feat: optionally sort translation mappings by creation date
This commit is contained in:
34
src/lib/mapping-created-at.ts
Normal file
34
src/lib/mapping-created-at.ts
Normal file
@@ -0,0 +1,34 @@
|
||||
import type { ProjectRun } from "./velum-project";
|
||||
import type { PlaceholderMapping } from "../types";
|
||||
|
||||
/** Project snapshots are immutable: the first snapshot containing a matching entry dates its first Velum record. */
|
||||
export function projectMappingCreatedAt(runs: ProjectRun[], current: PlaceholderMapping): Record<string, string> {
|
||||
const createdAt: Record<string, string> = {};
|
||||
const seen = new Set<string>();
|
||||
for (const run of [...runs].sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt))) {
|
||||
for (const [key, entry] of Object.entries(run.mapping)) {
|
||||
const active = current[key];
|
||||
if (active && active.type === entry.type && active.original === entry.original && !seen.has(key)) {
|
||||
seen.add(key);
|
||||
// An imported snapshot records the migration time, not when its terms were first created.
|
||||
if (run.origin !== "imported" || run.revisedFrom) createdAt[key] = run.createdAt;
|
||||
}
|
||||
}
|
||||
}
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
/** Dated entries lead; legacy entries fall back to descending IDs within each category. */
|
||||
export function sortMappingRowsByCreatedAt<T extends { placeholder: string; type: string }>(
|
||||
rows: T[], createdAt: Record<string, string>,
|
||||
): T[] {
|
||||
const timestamp = (key: string) => {
|
||||
const value = Date.parse(createdAt[key] ?? "");
|
||||
return Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY;
|
||||
};
|
||||
const number = (key: string) => Number(/_(\d+)>?$/u.exec(key)?.[1] ?? -1);
|
||||
return [...rows].sort((a, b) => timestamp(b.placeholder) - timestamp(a.placeholder)
|
||||
|| a.type.localeCompare(b.type)
|
||||
|| number(b.placeholder) - number(a.placeholder)
|
||||
|| a.placeholder.localeCompare(b.placeholder));
|
||||
}
|
||||
Reference in New Issue
Block a user