overleaf/services/web/frontend/js/features/history/utils/label.ts
Miguel Serrano 92ade70601 Merge pull request #12933 from overleaf/ii-history-react-select-latest-version-when-all-labels-are-removed
[web] Fix history entries and labels selection issues

GitOrigin-RevId: 73b14ba15ab4f0d9ff5946b1159ae7d5912582dd
2023-05-09 08:04:00 +00:00

79 lines
2.1 KiB
TypeScript

import { orderBy, groupBy } from 'lodash'
import {
LoadedLabel,
Label,
PseudoCurrentStateLabel,
} from '../services/types/label'
import { Nullable } from '../../../../../types/utils'
export const isPseudoLabel = (
label: LoadedLabel
): label is PseudoCurrentStateLabel => {
return (label as PseudoCurrentStateLabel).isPseudoCurrentStateLabel === true
}
export const isLabel = (label: LoadedLabel): label is Label => {
return !isPseudoLabel(label)
}
const sortLabelsByVersionAndDate = (labels: LoadedLabel[]) => {
return orderBy(
labels,
['isPseudoCurrentStateLabel', 'version', 'created_at'],
['asc', 'desc', 'desc']
)
}
const deletePseudoCurrentStateLabelIfExistent = (labels: LoadedLabel[]) => {
if (labels.length && isPseudoLabel(labels[0])) {
const [, ...rest] = labels
return rest
}
return labels
}
const addPseudoCurrentStateLabelIfNeeded = (
labels: LoadedLabel[],
mostRecentVersion: Nullable<number>
) => {
if (!labels.length || labels[0].version !== mostRecentVersion) {
const pseudoCurrentStateLabel: PseudoCurrentStateLabel = {
id: '1',
isPseudoCurrentStateLabel: true,
version: mostRecentVersion,
created_at: new Date().toISOString(),
}
return [pseudoCurrentStateLabel, ...labels]
}
return labels
}
export const loadLabels = (
labels: Label[],
lastUpdateToV: Nullable<number>
) => {
const sortedLabels = sortLabelsByVersionAndDate(labels)
const labelsWithoutPseudoLabel =
deletePseudoCurrentStateLabelIfExistent(sortedLabels)
const labelsWithPseudoLabelIfNeeded = addPseudoCurrentStateLabelIfNeeded(
labelsWithoutPseudoLabel,
lastUpdateToV
)
return labelsWithPseudoLabelIfNeeded
}
export const getVersionWithLabels = (labels: Nullable<LoadedLabel[]>) => {
let versionWithLabels: { version: number; labels: LoadedLabel[] }[] = []
if (labels) {
const groupedLabelsHash = groupBy(labels, 'version')
versionWithLabels = Object.keys(groupedLabelsHash).map(key => ({
version: parseInt(key, 10),
labels: groupedLabelsHash[key],
}))
versionWithLabels = orderBy(versionWithLabels, ['version'], ['desc'])
}
return versionWithLabels
}