mirror of
https://github.com/shlinkio/shlink-web-client.git
synced 2024-12-23 01:20:24 +03:00
Simplified ColorGenerator and exposed method to set colors for a key
This commit is contained in:
parent
2650027c40
commit
878e336ba1
1 changed files with 24 additions and 15 deletions
|
@ -1,37 +1,46 @@
|
||||||
import Storage from './Storage';
|
import Storage from './Storage';
|
||||||
import PropTypes from 'prop-types';
|
import PropTypes from 'prop-types';
|
||||||
|
import { range } from 'ramda';
|
||||||
|
|
||||||
const buildRandomColor = () => {
|
const { floor, random } = Math;
|
||||||
const letters = '0123456789ABCDEF';
|
const letters = '0123456789ABCDEF';
|
||||||
let color = '#';
|
const buildRandomColor = () =>
|
||||||
for (let i = 0; i < 6; i++ ) {
|
`#${
|
||||||
color += letters[Math.floor(Math.random() * 16)];
|
range(0, 6)
|
||||||
}
|
.map(() => letters[floor(random() * 16)])
|
||||||
return color;
|
.join('')
|
||||||
};
|
}`;
|
||||||
|
|
||||||
export class ColorGenerator {
|
export class ColorGenerator {
|
||||||
constructor(storage) {
|
constructor(storage) {
|
||||||
this.storage = storage;
|
this.storage = storage;
|
||||||
this.colors = this.storage.get('colors') || {};
|
this.colors = this.storage.get('colors') || {};
|
||||||
|
|
||||||
|
this.getColorForKey = this.getColorForKey.bind(this);
|
||||||
|
this.setColorForKey = this.setColorForKey.bind(this);
|
||||||
}
|
}
|
||||||
|
|
||||||
getColorForKey = key => {
|
getColorForKey = key => {
|
||||||
let color = this.colors[key];
|
const color = this.colors[key];
|
||||||
if (color) {
|
|
||||||
return color;
|
|
||||||
}
|
|
||||||
|
|
||||||
// If a color has not been set yet, generate a random one and save it
|
// If a color has not been set yet, generate a random one and save it
|
||||||
color = buildRandomColor();
|
if (!color) {
|
||||||
this.colors[key] = color;
|
this.setColorForKey(key, buildRandomColor());
|
||||||
this.storage.set('colors', this.colors);
|
return this.getColorForKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
return color;
|
return color;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
setColorForKey = (key, color) => {
|
||||||
|
this.colors[key] = color;
|
||||||
|
this.storage.set('colors', this.colors);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const colorGeneratorType = PropTypes.shape({
|
export const colorGeneratorType = PropTypes.shape({
|
||||||
getColorForKey: PropTypes.func,
|
getColorForKey: PropTypes.func,
|
||||||
|
setColorForKey: PropTypes.func,
|
||||||
});
|
});
|
||||||
|
|
||||||
export default new ColorGenerator(Storage);
|
export default new ColorGenerator(Storage);
|
||||||
|
|
Loading…
Reference in a new issue