Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 36 additions & 16 deletions js/calcData/data.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getPoet, getCity, getGovs } from "./getters.js";
import { getPoet, getCity, getGovs, getDates } from "./getters.js";

/**
* Hydrates the raw CSV rows (ids and coordinates become numbers, dates become
Expand Down Expand Up @@ -136,7 +136,7 @@ function derive(csvs, lookups) {
linesByBornCityId: groupById(lines, line => line.bornCityId, identity),
linesByActiveCityId: groupById(lines, line => line.activeCityId, identity),
travelPoets: createTravelPoets(lines, lookups),
travelCities: createTravelCities(lines, lookups),
travelCities: createTravelCities(lines),
regionsForInterface: createRegionsForInterface(csvs)
};
}
Expand Down Expand Up @@ -191,9 +191,12 @@ function groupById(rows, idOf, valueOf) {
*/
function sortPoetCities(lookups, poetCities) {
poetCities.sort((a, b) => {
const poetA = getPoet(lookups, a.poetId);
const poetB = getPoet(lookups, b.poetId);
return sortAlphabetically(poetA.poetname, poetB.poetname);
// A row cannot be dropped from a comparator, so an unresolvable poet sorts
// under the empty name — which sortAlphabetically puts at the end, with the
// Greek ones. getPoet has already reported the id.
const nameA = getPoet(lookups, a.poetId)?.poetname ?? "";
const nameB = getPoet(lookups, b.poetId)?.poetname ?? "";
return sortAlphabetically(nameA, nameB);
});
}

Expand Down Expand Up @@ -284,13 +287,18 @@ function createGenresByGenreId(genres) {
}

/**
* Poets with no row in poets.csv are left out: a control bar button is a name
* and nothing else, so there is nothing to render for one, and getPoet has
* already reported the id.
* @param {Iterable<number>} poetIds
* @param {Lookups} lookups
* @returns {FilterOption[]}
*/
function createAlphabetizedListOfPoetsFromIds(poetIds, lookups) {
return Array.from(poetIds)
.map(poetId => ({ id: poetId, name: getPoet(lookups, poetId).poetDetailName }))
.map(poetId => getPoet(lookups, poetId))
.filter(poet => poet !== undefined)
.map(poet => ({ id: poet.poetId, name: poet.poetDetailName }))
.sort((a, b) => sortAlphabetically(a.name, b.name));
}

Expand Down Expand Up @@ -356,15 +364,21 @@ function createTravelPoets(lines, lookups) {
}

/**
* Read off the lines rather than looked up again. createLines() only builds a
* line once both of its cities have resolved, so every city named here is one
* the line is already holding — there is no second chance for the lookup to
* fail, and no unnamed button to guard against.
* @param {Line[]} lines
* @param {Lookups} lookups
* @returns {FilterOption[]}
*/
function createTravelCities(lines, lookups) {
const cityIds = new Set(lines.flatMap(line => [line.bornCityId, line.activeCityId]));
return Array.from(cityIds)
.map(cityId => ({ id: cityId, name: getCity(lookups, cityId).cityname }))
.sort((a, b) => sortAlphabetically(a.name, b.name));
function createTravelCities(lines) {
/** @type {Map<number, string>} */
const nameByCityId = new Map();
for (const line of lines) {
nameByCityId.set(line.bornCityId, line.bornCity.cityname);
nameByCityId.set(line.activeCityId, line.activeCity.cityname);
}
return Array.from(nameByCityId, ([id, name]) => ({ id, name })).sort((a, b) => sortAlphabetically(a.name, b.name));
}

/**
Expand Down Expand Up @@ -423,15 +437,21 @@ function createLines(csvs, lookups) {
const poetId = parseInt(poetIdStr);
const poet = poets[poetId];
if (poet.bornPcs.length === 0 || poet.activePcs.length === 0) {
const poetDetailName = getPoet(lookups, poetId).poetDetailName;
poetsWithUnknownTravel.push({ id: poetId, name: poetDetailName });
// As in createAlphabetizedListOfPoetsFromIds(): a poet with no row in
// poets.csv has no name to put on a button, so gets no button.
const unknownTravelPoet = getPoet(lookups, poetId);
if (unknownTravelPoet) poetsWithUnknownTravel.push({ id: poetId, name: unknownTravelPoet.poetDetailName });
} else {
for (const bornPc of poet.bornPcs) {
for (const activePc of poet.activePcs) {
const dotted = bornPc.dotted === "dotted" || activePc.dotted === "dotted";
const fromCity = getCity(lookups, bornPc.cityId);
const toCity = getCity(lookups, activePc.cityId);
const poetDates = lookups.datesByPoetId[poetId];
// A line is two endpoints. Without both there is nothing to draw, so
// this pair is dropped and the rest of the poet's travel still is;
// getCity has already reported whichever id did not resolve.
if (!fromCity || !toCity) continue;
const dotted = bornPc.dotted === "dotted" || activePc.dotted === "dotted";
const poetDates = getDates(lookups, poetId);
const bornGovIds = [
...new Set(
getGovs(lookups, bornPc.cityId)
Expand Down
36 changes: 31 additions & 5 deletions js/calcData/getters.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
import { assertUnreachable } from "../assertUnreachable.js";

/**
* The poet a row points at, or undefined if the id resolves to nothing.
*
* Undefined is in the return type because it is a value this really returns: a
* poetId in poets_cities.csv that poets.csv does not have is a data bug the
* referential-integrity tests are there to catch, but the code should report it
* and carry on rather than take the map down with it. Callers are expected to
* drop whatever they were building for that id; the log below is the report.
* @param {Lookups} lookups
* @param {number} poetId
* @returns {Poet}
* @returns {Poet | undefined}
*/
export function getPoet(lookups, poetId) {
const poet = lookups.poetsById[poetId];
Expand All @@ -22,9 +29,11 @@ export function getGenres(lookups, poetId) {
}

/**
* The city a row points at, or undefined if the id resolves to nothing. See
* getPoet() for why undefined is in the type.
* @param {Lookups} lookups
* @param {number} cityId
* @returns {City}
* @returns {City | undefined}
*/
export function getCity(lookups, cityId) {
const city = lookups.citiesById[cityId];
Expand All @@ -45,6 +54,22 @@ export function getGovs(lookups, cityId) {
return [];
}

/**
* The years attested for a poet, or an empty list if dates.csv has no row for
* them — in which case they are already invisible on the map, because
* getDateFilterFn() compares against the minDate and maxDate these produce.
* @param {Lookups} lookups
* @param {number} poetId
* @returns {number[]}
*/
export function getDates(lookups, poetId) {
if (lookups.datesByPoetId[poetId]) {
return lookups.datesByPoetId[poetId];
}
console.log(`poetId ${poetId} does not exist in datesByPoetId`);
return [];
}

/** The filters the places control bar offers. */
/** @type {PlacesFilterType[]} */
export const PLACES_FILTER_TYPES = ["relationship", "poet", "genre"];
Expand Down Expand Up @@ -122,9 +147,10 @@ function parseFilter(selectedId, allowed, mapName) {
* they replaced was saving nothing worth the four fields it added to four types
* — fields the rows did not have until the priming pass ran.
*
* The empty-string fallbacks are for data that is missing rather than absent:
* warnAboutIncompletePoets() reports it at startup, and this keeps a popup
* rendering a blank line instead of the word "undefined".
* The empty-string fallbacks cover both a poet whose fields are blank and a
* poetId with no poet behind it at all: warnAboutIncompletePoets() and getPoet()
* report each of those at startup, and this keeps a popup rendering a blank line
* instead of the word "undefined".
* @param {Lookups} lookups
* @param {number} poetId
* @returns {PoetDisplay}
Expand Down
4 changes: 4 additions & 0 deletions js/renderMap/calcCommon.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ import { getPoet } from "../calcData/getters.js";
export function getDateFilterFn(data, state) {
return obj => {
const poet = getPoet(data, obj.poetId);
// A poet the lookup cannot resolve has no dates, and a poet with no dates
// is already invisible here whatever the slider says: this is the same
// answer, given without reading fields off nothing.
if (!poet) return false;
return poet.maxDate >= state.minDate && poet.minDate <= state.maxDate;
};
}
36 changes: 28 additions & 8 deletions tests/helpers/loadData.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,18 @@ export function loadRawCsvs() {
}

/**
* The CSVs run through the real initializeData(), i.e. the same object the
* browser builds before it draws anything. Use this for behaviour assertions.
* Runs fn with alert() and console.log() collected rather than printed, and
* hands back what it returned alongside what it said.
*
* The app reports missing lookups by calling alert() and console.log(), neither
* of which should ever fire against good data, so both are captured and handed
* back for assertion rather than printed.
* @returns {{ data: Data, alerts: string[], logs: string[] }}
* Those two are how the app reports an id that resolves to nothing, and neither
* should ever fire against good data — so capturing them is both what lets a
* test assert on the report and what keeps a test that provokes one on purpose
* from printing it into the TAP output.
* @template T
* @param {() => T} fn
* @returns {{ result: T, alerts: string[], logs: string[] }}
*/
export function loadInitializedData() {
export function captureReports(fn) {
/** @type {string[]} */
const alerts = [];
/** @type {string[]} */
Expand All @@ -63,13 +66,30 @@ export function loadInitializedData() {
console.log = (/** @type {unknown[]} */ ...args) => logs.push(args.join(" "));

try {
return { data: initializeData(loadRawCsvs()), alerts, logs };
return { result: fn(), alerts, logs };
} finally {
globals.alert = realAlert;
console.log = realLog;
}
}

/**
* The CSVs run through the real initializeData(), i.e. the same object the
* browser builds before it draws anything. Use this for behaviour assertions.
*
* Takes the raw CSVs so that a test can break one row on purpose and watch what
* startup does with it — the only way to reach the missing-id paths, since the
* referential-integrity tests exist to keep the real files off them. Pass a
* fresh loadRawCsvs(): hydrate() parses the rows in place, so they are not
* reusable between calls.
* @param {RawCsvs} [raw] defaults to the CSVs as they sit on disk
* @returns {{ data: Data, alerts: string[], logs: string[] }}
*/
export function loadInitializedData(raw = loadRawCsvs()) {
const { result, alerts, logs } = captureReports(() => initializeData(raw));
return { data: result, alerts, logs };
}

/** The whole slider range, i.e. what a map shows before anything is dragged. */
export const ALL_DATES = { minDate: -800, maxDate: -400 };

Expand Down
92 changes: 91 additions & 1 deletion tests/initializeData.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@

import { test, describe } from "node:test";
import assert from "node:assert/strict";
import { loadInitializedData } from "./helpers/loadData.js";
import { loadInitializedData, loadRawCsvs, captureReports, stateFor } from "./helpers/loadData.js";
import { sortAlphabetically } from "../js/calcData/data.js";
import { PLACES_FILTER_TYPES, GEO_FILTER_TYPES, TRAVEL_FILTER_TYPES, selectedIdOf } from "../js/calcData/getters.js";
import { getDateFilterFn } from "../js/renderMap/calcCommon.js";
import { defaultMapState } from "../js/interface/interface.js";
import { createPlacesInterfaceHtml } from "../js/interface/placesInterface.js";
import { createTravelInterfaceHtml } from "../js/interface/travelInterface.js";
Expand All @@ -31,6 +32,95 @@ describe("initializeData runs clean", () => {
});
});

// ---------------------------------------------------------------------------
// What startup does with an id that resolves to nothing.
//
// Against the real CSVs this is unreachable, which is what the referential
// integrity tests in data-integrity.test.js are for — and the reason getPoet()
// and getCity() could claim to always return a row for as long as they did. So
// these break one row on purpose and assert the behaviour the console.log in
// each getter was written for: the row is dropped and reported, and everything
// else is still built. See issue #369.
// ---------------------------------------------------------------------------

describe("an id that resolves to nothing costs one row, not the map", () => {
const MISSING = 99999;

/** The id poets.csv gives a poet, as the string a raw row holds. */
const rawPoetIdByName = (/** @type {RawCsvs} */ raw, /** @type {string} */ name) => {
const poet = raw.poets.find(rawPoet => rawPoet.poetname === name);
assert.ok(poet, `no poet named ${name}`);
return poet.poetId;
};

test("a poet named in poets_cities.csv but absent from poets.csv", () => {
// Alcman travels, so moving every one of his rows onto an id poets.csv does
// not have reaches all three startup paths that read a poet: the sort of
// poets_cities, the travel poet list, and the dates behind a travel line.
const raw = loadRawCsvs();
const alcmanId = rawPoetIdByName(raw, "Alcman");
const moved = raw.poetCities.filter(pc => pc.poetId === alcmanId);
assert.ok(moved.length > 0, "expected Alcman to have poets_cities rows");
for (const pc of moved) pc.poetId = String(MISSING);

const { data: broken, logs: brokenLogs } = loadInitializedData(raw);

assert.ok(
brokenLogs.includes(`poetId ${MISSING} does not exist in poetsById`),
"the unresolved poetId should be reported"
);
assert.ok(
brokenLogs.includes(`poetId ${MISSING} does not exist in datesByPoetId`),
"a poet with no row also has no dates, which should be reported too"
);

// The rest of the map is untouched: only Alcman leaves the control bar.
assert.ok(broken.lines.length > 0);
assert.ok(broken.travelCities.length > 0);
assert.ok(!broken.travelPoets.some(option => option.id === MISSING));
assert.ok(!broken.travelPoets.some(option => option.id === Number(alcmanId)));
for (const { id: poetId } of [...broken.travelPoets, ...broken.poetsWithUnknownTravel]) {
assert.ok(broken.poetsById[poetId], `control bar offers unknown poetId ${poetId}`);
}

// His lines survive initializeData, since both of their cities are real,
// but nothing draws them: every render path filters through
// getDateFilterFn(), which has no dates to admit them by.
const orphaned = broken.lines.filter(line => line.poetId === MISSING);
assert.ok(orphaned.length > 0);
const inDateRange = getDateFilterFn(broken, stateFor("travelMode", "all_0"));
const { result: anyDrawn } = captureReports(() => orphaned.some(inDateRange));
assert.ok(!anyDrawn, "a poet with no dates should be off the map at every date");
});

test("a city named in poets_cities.csv but absent from cities.csv", () => {
// Alcman is reported born in both Sparta and Sardis. Break the Sardis row
// and the Sardis -> Sparta line cannot be drawn, but Sparta -> Sparta still
// is: the pair is dropped, not the poet.
const raw = loadRawCsvs();
const alcmanId = rawPoetIdByName(raw, "Alcman");
const sardis = raw.poetCities.find(pc => pc.poetId === alcmanId && pc.cityname === "Sardis");
assert.ok(sardis, "expected Alcman to have a Sardis row");
sardis.cityId = String(MISSING);

const { data: broken, logs: brokenLogs } = loadInitializedData(raw);

assert.ok(
brokenLogs.includes(`cityId ${MISSING} does not exist in citiesById`),
"the unresolved cityId should be reported"
);

const journeys = broken.linesByPoetId[Number(alcmanId)].map(
line => `${line.bornCity.cityname} -> ${line.activeCity.cityname}`
);
assert.deepEqual(journeys, ["Sparta -> Sparta"]);
assert.ok(!broken.travelCities.some(option => option.id === MISSING));
for (const { id: cityId } of broken.travelCities) {
assert.ok(broken.citiesById[cityId], `control bar offers unknown cityId ${cityId}`);
}
});
});

describe("hydration", () => {
test("every field the types declare numeric really is one, on every row", () => {
// Written out by hand rather than read from NUMERIC_CSV_FIELDS, which would
Expand Down
Loading