Skip to content

Commit

Permalink
Just improve your old module and render it wonderfully nicer
Browse files Browse the repository at this point in the history
  • Loading branch information
Julien Michaud committed Nov 9, 2024
1 parent 4bdb406 commit 411e670
Show file tree
Hide file tree
Showing 4 changed files with 165 additions and 77 deletions.
43 changes: 43 additions & 0 deletions Model/Config/Source/Season.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
<?php
/**
* Copyright © OpenGento, All rights reserved.
* See LICENSE bundled with this library for license details.
*/
declare(strict_types=1);

namespace Opengento\Snowflake\Model\Config\Source;

use Magento\Framework\Data\OptionSourceInterface;

class Season implements OptionSourceInterface
{
public function toOptionArray(): array
{
return [
['value' => 'halloween', 'label' => __('Halloween')],
['value' => 'noel', 'label' => __('Noel')],
['value' => 'printemps', 'label' => __('Printemps')],
['value' => 'ete', 'label' => __('Été')],
['value' => 'automne', 'label' => __('Automne')],
['value' => 'fete_nationale', 'label' => __('Fête Nationale')],
['value' => 'nouvel_an', 'label' => __('Nouvel An')],
['value' => 'paques', 'label' => __('Pâques')],
['value' => 'saint_valentin', 'label' => __('Saint-Valentin')],
['value' => 'fete_travail', 'label' => __('Fête du Travail')],
['value' => 'fete_musique', 'label' => __('Fête de la Musique')],
['value' => 'hiver', 'label' => __('Hiver')],
['value' => 'carnaval', 'label' => __('Carnaval')],
['value' => 'saint_patrick', 'label' => __('Saint Patrick')],
['value' => 'hanoucca', 'label' => __('Hanoucca')],
['value' => 'ramadan', 'label' => __('Ramadan')],
['value' => 'diwali', 'label' => __('Diwali')],
['value' => 'chinese_new_year', 'label' => __('Nouvel An Chinois')],
['value' => 'fete_meres', 'label' => __('Fête des Mères')],
['value' => 'fete_peres', 'label' => __('Fête des Pères')],
['value' => 'action_de_grace', 'label' => __('Action de Grâce')],
['value' => 'fete_saucisse', 'label' => __('Fête à la Saucisse')],
['value' => 'apero_time', 'label' => __('l\'heure de l\'apéro')]
];
}

}
63 changes: 53 additions & 10 deletions ViewModel/Snowflake.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,24 +10,67 @@
use Magento\Framework\View\Element\Block\ArgumentInterface;
use Opengento\Snowflake\Model\Config\OpenWeather as OpenWeatherConfig;
use Opengento\Snowflake\Model\Config\Snowflake as SnowflakeConfig;
use Magento\Framework\Serialize\SerializerInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Store\Model\ScopeInterface;

final class Snowflake implements ArgumentInterface
{
private SnowflakeConfig $snowflakeConfig;
public function __construct(
private SerializerInterface $serializer,
private SnowflakeConfig $snowflakeConfig,
private OpenWeatherConfig $openWeatherConfig,
private ScopeConfigInterface $scopeConfig
) {}

private OpenWeatherConfig $openWeatherConfig;
public function getSeasonalIcons(): array
{
return [
'halloween' => ['🎃', '👻', '🦇'],
'noel' => ['❄️', '🎅', '🎄'],
'printemps' => ['🌷', '🐣', '☀️'],
'ete' => ['🌞', '🏖️', '🍉'],
'automne' => ['🍂', '🍁', '🎃'],
'fete_nationale' => ['🎆', '🇫🇷', '🥳'],
'nouvel_an' => ['🎇', '🎉', '🥂'],
'paques' => ['🐰', '🥚', '🐣'],
'saint_valentin' => ['💖', '🌹', '💕'],
'fete_travail' => ['⚒️', '🌻', '🛠️'],
'fete_musique' => ['🎵', '🎸', '🎤'],
'hiver' => ['❄️', '☃️', '🌨️'],
'printemps' => ['🌸', '🌷', '🦋'],
'ete' => ['🌞', '🍦', '🏄'],
'automne' => ['🍁', '🍂', '🍄'],
'halloween' => ['🎃', '🕸️', '👻'],
'noel' => ['🎄', '🎅', '🤶'],
'carnaval' => ['🎭', '🎊', '🤹'],
'saint_patrick' => ['☘️', '🍺', '🇮🇪'],
'hanoucca' => ['🕎', '', '🥯'],
'ramadan' => ['🌙', '🕌', '🕋'],
'diwali' => ['🪔', '🎆', '🌟'],
'chinese_new_year' => ['🐉', '🏮', '🧧'],
'fete_meres' => ['💐', '👩‍👧‍👦', '🌹'],
'fete_peres' => ['👔', '🍻', '🎣'],
'halloween' => ['🎃', '🦇', '🕸️'],
'action_de_grace' => ['🦃', '🥧', '🍂'],
'noel' => ['🎄', '🎁', '❄️'],
'nouvel_an_chinois' => ['🐲', '🧨', '🧧'],
'fete_saucisse' => ['🌭', '🍻', '🎉', '🕺', '🎶'],
'apero_time' => ['🍺', '🍹', '🍾']
];
}

public function __construct(
SnowflakeConfig $snowflakeConfig,
OpenWeatherConfig $openWeatherConfig
) {
$this->snowflakeConfig = $snowflakeConfig;
$this->openWeatherConfig = $openWeatherConfig;
public function getSelectedSeason(): string
{
return $this->scopeConfig->getValue('snowflake/general/season', ScopeInterface::SCOPE_STORE);
}

public function getSnowflakeChar(): string
public function getIconsForSelectedSeason(): string
{
return $this->snowflakeConfig->getSnowflakeChar();
$selectedSeason = $this->getSelectedSeason();
$seasonalIcons = $this->getSeasonalIcons();
$icons = $seasonalIcons[$selectedSeason] ?? [];
return $this->serializer->serialize($icons);
}

public function getSnowflakeVSpeed(): float
Expand Down
8 changes: 4 additions & 4 deletions etc/adminhtml/system.xml
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
<config_path>snowflake/general/enable</config_path>
<source_model>Magento\Config\Model\Config\Source\Enabledisable</source_model>
</field>
<field id="icon" translate="label comment" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Icon</label>
<comment><![CDATA[Icon to display as a snowflake ❄️, get <a href="https://emojipedia.org/" target="_blank">more emoji</a>.]]></comment>
<backend_model>Opengento\Snowflake\Model\Config\Backend\EmojiConverter</backend_model>
<field id="season" translate="label" type="select" sortOrder="15" showInDefault="1" showInWebsite="1" showInStore="1" canRestore="1">
<label>Season/Festival</label>
<source_model>Opengento\Snowflake\Model\Config\Source\Season</source_model>
<comment><![CDATA[Choose a season or festival for the icons.]]></comment>
<depends>
<field id="snowflake/general/enable">1</field>
</depends>
Expand Down
128 changes: 65 additions & 63 deletions view/frontend/templates/snowflake.phtml
Original file line number Diff line number Diff line change
Expand Up @@ -5,72 +5,68 @@
*/
declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Magento\Framework\View\Element\Template;
use Opengento\Snowflake\ViewModel\Snowflake;

/** @var Template $block */
/** @var Snowflake $viewModel */
$viewModel = $block->getData('viewModel');
/** @var ViewModelRegistry $viewModels */

/** @var Snowflake $snowflake */
$snowflake = $viewModels->require(Snowflake::class)
?>
<div id="snowflake_container"></div>

<script>
require([
'jquery',
'jquery/ui',
'domReady!'
], function($) {
document.addEventListener('DOMContentLoaded', function() {
"use strict";

<?php if ($viewModel->isForceSnow()): ?>
// Vérifiez si la neige de saucisses doit commencer
if (forceSnow()) {
letSnow();
<?php elseif ($viewModel->isApiEnabled()): ?>
let lat, lon, settings = {
"url": "<?= $viewModel->getIpLocatorApiUrl() ?>",
"method": "GET",
"timeout": 0
};
$.ajax(settings).done(function (response) {
[lat, lon] = response.loc.split(',');
$.ajax({
url: '<?= $block->getData('meteoUrl') ?>lat/' + lat + '/lon/' + lon,
type: "GET",
}).done(function (data) {
} else if (isApiEnabled()) {
fetch("<?= $snowflake->getIpLocatorApiUrl() ?>")
.then(response => response.json())
.then(data => {
let [lat, lon] = data.loc.split(',');
return fetch(`<?= $block->getData('meteoUrl') ?>lat/${lat}/lon/${lon}`);
})
.then(response => response.json())
.then(data => {
if (data.is_snowing) {
letSnow();
}
});
});
<?php endif; ?>
})
.catch(error => console.error('Error:', error));
}

function letSnow() {
let snowMax = <?= $viewModel->getSnowflakeQty() ?>;
let snowColor = ["#DDD", "#BBB", "#AAA", "#EEE", "#CCC"];
let snowEntity = "<?= $viewModel->getSnowflakeChar() ?>";
let snowVSpeed = <?= $viewModel->getSnowflakeVSpeed() ?>;
let snowHSpeed = <?= $viewModel->getSnowflakeHSpeed() ?>;
let snowRotSpeed = <?= $viewModel->getSnowflakeRotSpeed() ?>;
let snowMinSize = <?= $viewModel->getSnowflakeMinSize() ?>;
const snowMaxSize = <?= $viewModel->getSnowflakeMaxSize() ?>;
let snowMax = <?= $snowflake->getSnowflakeQty() ?>;
let snowEntities = <?= $snowflake->getIconsForSelectedSeason() ?>;
let snowVSpeed = <?= $snowflake->getSnowflakeVSpeed() ?>;
let snowHSpeed = <?= $snowflake->getSnowflakeHSpeed() ?>;
let snowRotSpeed = <?= $snowflake->getSnowflakeRotSpeed() ?>;
let snowMinSize = <?= $snowflake->getSnowflakeMinSize() ?>;
const snowMaxSize = <?= $snowflake->getSnowflakeMaxSize() ?>;
const snowRefresh = 50;
const snowMaxBlur = 3;
const snowMaxBlur = 0;
const snowStyles = "cursor: default; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; -o-user-select: none; user-select: none;";

let snow = [],
pos = [],
coords = [],
left = [],
marginBottom,
marginRight;
let snow = [];
let pos = [];
let coords = [];
let left = [];
let marginBottom;
let marginRight;

let newPositions = '';

for (let i = 0; i <= snowMax; i++) {
newPositions += ("<span id='flake" + i + "'" +
" style='" + snowStyles + "position:absolute;top:-" + snowMaxSize + "'>"
+ snowEntity + "</span>");
// Utiliser l'index modulo pour choisir une icône différente à chaque itération
let entity = snowEntities[i % snowEntities.length].trim(); // Utilisation de trim() pour éviter les espaces indésirables
newPositions += `<span id='flake${i}' style='${snowStyles} position:absolute; top:-${snowMaxSize}px;'>${entity}</span>`;
}
$('#snowflake_container').html(newPositions);
document.getElementById('snowflake_container').innerHTML = newPositions;

let snowSize = snowMaxSize - snowMinSize;
marginBottom = document.body.scrollHeight - 5;
Expand All @@ -80,23 +76,22 @@ $viewModel = $block->getData('viewModel');
coords[i] = 0;
left[i] = Math.random() * 15;
pos[i] = 0.03 + Math.random() / 10;
snow[i] = document.getElementById("flake" + i);
snow[i] = document.getElementById(`flake${i}`);
snow[i].style.fontFamily = "inherit";
let size = randomise(snowSize) + snowMinSize
let size = randomise(snowSize) + snowMinSize;
snow[i].size = size;
snow[i].speedFactor = snowMaxSize / size / 2;
snow[i].style.filter = "blur(" + (snowMaxBlur * ((snowMaxSize - size) / (snowMaxSize - snowMinSize))) / 2 + "px)";
snow[i].style.fontSize = snow[i].size + "px";
snow[i].style.color = snowColor[randomise(snowColor.length)];
snow[i].style.filter = `blur(${(snowMaxBlur * ((snowMaxSize - size) / (snowMaxSize - snowMinSize))) / 2}px)`;
snow[i].style.fontSize = `${size}px`;
snow[i].style.zIndex = 1000;
snow[i].style.textShadow = "1px 1px 5px #0000DD55";
snow[i].style.transform = "rotate(0deg)";
snow[i].vsink = snowVSpeed * snow[i].size / 5;
snow[i].hsink = snowHSpeed * snow[i].size / 5;
snow[i].posX = randomise(marginRight - snow[i].size);
snow[i].posY = randomise(2 * marginBottom - marginBottom - 2 * snow[i].size);
snow[i].style.left = snow[i].posX + "px";
snow[i].style.top = snow[i].posY + "px";
snow[i].vsink = snowVSpeed * size / 5;
snow[i].hsink = snowHSpeed * size / 5;
snow[i].posX = randomise(marginRight - size);
snow[i].posY = randomise(2 * marginBottom - marginBottom - 2 * size);
snow[i].style.left = `${snow[i].posX}px`;
snow[i].style.top = `${snow[i].posY}px`;

snow[i].rotationAngleStep = 0;
snow[i].rotationAngActual = 0;
Expand Down Expand Up @@ -125,31 +120,38 @@ $viewModel = $block->getData('viewModel');
coords[i] += pos[i];
snow[i].posY += snow[i].vsink;
snow[i].posX += snow[i].hsink * snow[i].speedFactor;
snow[i].style.left = snow[i].posX + left[i] * Math.sin(coords[i]) + "px";
snow[i].style.top = snow[i].posY + "px";
snow[i].style.left = `${snow[i].posX + left[i] * Math.sin(coords[i])}px`;
snow[i].style.top = `${snow[i].posY}px`;
snow[i].rotationAngActual += snow[i].rotationAngleStep;
snow[i].style.transform = "rotate(" + snow[i].rotationAngActual + "deg)";
snow[i].style.transform = `rotate(${snow[i].rotationAngActual}deg)`;

// if (snowVSpeed > 0 && (snow[i].posY >= marginBottom - 2 * snow[i].size || parseInt(snow[i].style.left) > (marginRight - 3 * left[i]))) {
if (snowVSpeed > 0 && (snow[i].posY >= marginBottom - 2 * snow[i].size)) {
if (snowVSpeed > 0 && snow[i].posY >= marginBottom - 2 * snow[i].size) {
snow[i].posX = randomise(marginRight - snow[i].size);
snow[i].posY = 0;
}
if (snowVSpeed < 0 && (snow[i].posY < 0)) {
snow[i].posY = document.body.scrollHeight - snow[i].size *2;
if (snowVSpeed < 0 && snow[i].posY < 0) {
snow[i].posY = document.body.scrollHeight - snow[i].size * 2;
}
if (snowHSpeed > 0 && (snow[i].posX >= marginRight - 2 * snow[i].size)) {
if (snowHSpeed > 0 && snow[i].posX >= marginRight - 2 * snow[i].size) {
snow[i].posX = randomise(marginRight - snow[i].size);
snow[i].posY = 0;
}
if (snowHSpeed < 0 && (snow[i].posX < 0)) {
if (snowHSpeed < 0 && snow[i].posX < 0) {
snow[i].posY = document.body.clientWidth - snow[i].size * 2;
}
}
}

window.addEventListener('resize', resize);
window.setInterval(moveSnow, snowRefresh);
setInterval(moveSnow, snowRefresh);
}

function forceSnow() {
return <?= $snowflake->isForceSnow() ?>;
}

function isApiEnabled() {
return <?= $snowflake->isApiEnabled() ?>;
}
});
</script>

0 comments on commit 411e670

Please sign in to comment.