debian-mirror-gitlab/app/assets/javascripts/frequent_items/utils.js

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

66 lines
2 KiB
JavaScript
Raw Normal View History

2020-03-13 15:44:24 +05:30
import { GlBreakpointInstance as bp } from '@gitlab/ui/dist/utils';
2021-03-11 19:13:27 +05:30
import { take } from 'lodash';
2021-01-03 14:25:43 +05:30
import { sanitize } from '~/lib/dompurify';
2018-11-08 19:23:39 +05:30
import { FREQUENT_ITEMS, HOUR_IN_MS } from './constants';
2020-03-13 15:44:24 +05:30
export const isMobile = () => ['md', 'sm', 'xs'].includes(bp.getBreakpointSize());
2018-11-08 19:23:39 +05:30
2021-03-08 18:12:59 +05:30
export const getTopFrequentItems = (items) => {
2018-11-08 19:23:39 +05:30
if (!items) {
return [];
}
const frequentItemsCount = isMobile()
? FREQUENT_ITEMS.LIST_COUNT_MOBILE
: FREQUENT_ITEMS.LIST_COUNT_DESKTOP;
2021-03-08 18:12:59 +05:30
const frequentItems = items.filter((item) => item.frequency >= FREQUENT_ITEMS.ELIGIBLE_FREQUENCY);
2018-11-08 19:23:39 +05:30
if (!frequentItems || frequentItems.length === 0) {
return [];
}
frequentItems.sort((itemA, itemB) => {
// Sort all frequent items in decending order of frequency
// and then by lastAccessedOn with recent most first
if (itemA.frequency !== itemB.frequency) {
return itemB.frequency - itemA.frequency;
} else if (itemA.lastAccessedOn !== itemB.lastAccessedOn) {
return itemB.lastAccessedOn - itemA.lastAccessedOn;
}
return 0;
});
2020-04-08 14:13:33 +05:30
return take(frequentItems, frequentItemsCount);
2018-11-08 19:23:39 +05:30
};
export const updateExistingFrequentItem = (frequentItem, item) => {
2021-09-04 01:27:46 +05:30
// `frequentItem` comes from localStorage and it's possible it doesn't have a `lastAccessedOn`
const neverAccessed = !frequentItem.lastAccessedOn;
const shouldUpdate =
neverAccessed || Math.abs(item.lastAccessedOn - frequentItem.lastAccessedOn) / HOUR_IN_MS > 1;
2018-11-08 19:23:39 +05:30
return {
...item,
2021-09-04 01:27:46 +05:30
frequency: shouldUpdate ? frequentItem.frequency + 1 : frequentItem.frequency,
lastAccessedOn: shouldUpdate ? Date.now() : frequentItem.lastAccessedOn,
2018-11-08 19:23:39 +05:30
};
};
2020-02-01 01:16:34 +05:30
2021-03-08 18:12:59 +05:30
export const sanitizeItem = (item) => {
2020-03-28 13:19:24 +05:30
// Only sanitize if the key exists on the item
2021-03-08 18:12:59 +05:30
const maybeSanitize = (key) => {
2020-03-28 13:19:24 +05:30
if (!Object.prototype.hasOwnProperty.call(item, key)) {
return {};
}
2020-10-24 23:57:45 +05:30
return { [key]: sanitize(item[key].toString(), { ALLOWED_TAGS: [] }) };
2020-03-28 13:19:24 +05:30
};
return {
...item,
...maybeSanitize('name'),
...maybeSanitize('namespace'),
};
};