mue/src/modules/helpers/background/widget.js

103 lines
3.0 KiB
JavaScript

// since there is so much code in the component, we have moved it to a separate file
export function videoCheck(url) {
return (
url.startsWith('data:video/') ||
url.endsWith('.mp4') ||
url.endsWith('.webm') ||
url.endsWith('.ogg')
);
}
export function offlineBackground() {
const offlineImages = require('./offlineImages.json');
// Get all photographers from the keys in offlineImages.json
const photographers = Object.keys(offlineImages);
const photographer = photographers[Math.floor(Math.random() * photographers.length)];
const randomImage =
offlineImages[photographer].photo[
Math.floor(Math.random() * offlineImages[photographer].photo.length)
];
const object = {
url: `./offline-images/${randomImage}.webp`,
photoInfo: {
offline: true,
credit: photographer,
},
};
localStorage.setItem('currentBackground', JSON.stringify(object));
return object;
}
function gradientStyleBuilder({ type, angle, gradient }) {
// Note: Append the gradient for additional browser support.
const steps = gradient?.map((v) => `${v.colour} ${v.stop}%`);
const grad = `background: ${type}-gradient(${type === 'linear' ? `${angle}deg,` : ''}${steps})`;
return {
type: 'colour',
style: `background:${gradient[0]?.colour};${grad}`,
};
}
export function getGradient() {
const customBackgroundColour = localStorage.getItem('customBackgroundColour') || {
angle: '180',
gradient: [{ colour: '#ffb032', stop: 0 }],
type: 'linear',
};
let gradientSettings = '';
try {
gradientSettings = JSON.parse(customBackgroundColour);
} catch (e) {
const hexColorRegex = /#[0-9a-fA-F]{6}/s;
if (hexColorRegex.exec(customBackgroundColour)) {
// Colour used to be simply a hex colour or a NULL value before it was a JSON object. This automatically upgrades the hex colour value to the new standard. (NULL would not trigger an exception)
gradientSettings = {
type: 'linear',
angle: '180',
gradient: [{ colour: customBackgroundColour, stop: 0 }],
};
localStorage.setItem('customBackgroundColour', JSON.stringify(gradientSettings));
}
}
if (typeof gradientSettings === 'object' && gradientSettings !== null) {
return gradientStyleBuilder(gradientSettings);
}
}
export function randomColourStyleBuilder(type) {
// randomColour based on https://stackoverflow.com/a/5092872
const randomColour = () =>
'#000000'.replace(/0/g, () => {
return (~~(Math.random() * 16)).toString(16);
});
let style = `background:${randomColour()};`;
if (type === 'random_gradient') {
const directions = [
'to right',
'to left',
'to bottom',
'to top',
'to bottom right',
'to bottom left',
'to top right',
'to top left',
];
style = `background:linear-gradient(${
directions[Math.floor(Math.random() * directions.length)]
}, ${randomColour()}, ${randomColour()});`;
}
return {
type: 'colour',
style,
};
}