debian-mirror-gitlab/app/assets/javascripts/emoji/components/utils.js

69 lines
1.9 KiB
JavaScript
Raw Normal View History

2021-04-17 20:07:23 +05:30
import { chunk, memoize, uniq } from 'lodash';
2022-04-04 11:22:00 +05:30
import { getCookie, setCookie } from '~/lib/utils/common_utils';
2021-04-17 20:07:23 +05:30
import { initEmojiMap, getEmojiCategoryMap } from '~/emoji';
import {
EMOJIS_PER_ROW,
EMOJI_ROW_HEIGHT,
CATEGORY_ROW_HEIGHT,
FREQUENTLY_USED_KEY,
FREQUENTLY_USED_COOKIE_KEY,
} from '../constants';
export const generateCategoryHeight = (emojisLength) =>
emojisLength * EMOJI_ROW_HEIGHT + CATEGORY_ROW_HEIGHT;
export const getFrequentlyUsedEmojis = () => {
2022-04-04 11:22:00 +05:30
const savedEmojis = getCookie(FREQUENTLY_USED_COOKIE_KEY);
2021-04-17 20:07:23 +05:30
if (!savedEmojis) return null;
const emojis = chunk(uniq(savedEmojis.split(',')), 9);
return {
frequently_used: {
emojis,
top: 0,
height: generateCategoryHeight(emojis.length),
},
};
};
export const addToFrequentlyUsed = (emoji) => {
const frequentlyUsedEmojis = uniq(
2022-04-04 11:22:00 +05:30
(getCookie(FREQUENTLY_USED_COOKIE_KEY) || '')
2021-04-17 20:07:23 +05:30
.split(',')
.filter((e) => e)
.concat(emoji),
);
2022-04-04 11:22:00 +05:30
setCookie(FREQUENTLY_USED_COOKIE_KEY, frequentlyUsedEmojis.join(','));
2021-04-17 20:07:23 +05:30
};
export const hasFrequentlyUsedEmojis = () => getFrequentlyUsedEmojis() !== null;
export const getEmojiCategories = memoize(async () => {
await initEmojiMap();
const categories = await getEmojiCategoryMap();
const frequentlyUsedEmojis = getFrequentlyUsedEmojis();
let top = frequentlyUsedEmojis
? frequentlyUsedEmojis.frequently_used.top + frequentlyUsedEmojis.frequently_used.height
: 0;
return Object.freeze(
Object.keys(categories)
.filter((c) => c !== FREQUENTLY_USED_KEY)
.reduce((acc, category) => {
const emojis = chunk(categories[category], EMOJIS_PER_ROW);
const height = generateCategoryHeight(emojis.length);
const newAcc = {
...acc,
[category]: { emojis, height, top },
};
top += height;
return newAcc;
}, frequentlyUsedEmojis || {}),
);
});