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
12 changes: 9 additions & 3 deletions apps/navigator/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,21 @@ import { useFetched } from './useFetched';
import { useUrlState } from './useUrlState';

type SpaceListItem = { name: string };
type MapViewsResponse = { definitions: MapViewDefinition[]; errors: { path: string; message: string }[] };

export function App() {
const { spaceName, mapViewId, focus, values, setSpaceName, setMapViewId, setFocus, setValue } = useUrlState();
const [selectedNode, setSelectedNode] = useState<SpaceNode>();
const [unattachedPanelOpen, setUnattachedPanelOpen] = useState(false);

const spaceList = useFetched('/api/spaces', fetchJson<SpaceListItem[]>);
const allDefinitions = useFetched('/api/map-views', fetchJson<MapViewDefinition[]>);
const allDefinitions = useFetched('/api/map-views', fetchJson<MapViewsResponse>);
// The whole space, unfiltered: gives the schema (to pick map views) and the nodes validation results attach to.
const fullSpace = useFetched(spaceName ? spaceUrl(spaceName) : undefined, fetchSpace);

const applicableDefinitions = useMemo(
() => mapViewsForSchema(allDefinitions.data ?? [], fullSpace.data?.schemaId),
[allDefinitions.data, fullSpace.data?.schemaId],
() => mapViewsForSchema(allDefinitions.data?.definitions ?? [], fullSpace.data?.schemaId),
[allDefinitions.data?.definitions, fullSpace.data?.schemaId],
);
const activeDefinition = applicableDefinitions.find((d) => d.id === mapViewId) ?? applicableDefinitions[0];
// Settle on the map view actually drawn, so the URL names it and a stale or missing `view` is replaced.
Expand Down Expand Up @@ -114,6 +115,11 @@ export function App() {
{error}
</p>
)}
{allDefinitions.data?.errors.map((e) => (
<p key={e.path} className="error" role="alert">
{e.message}
</p>
))}
{fullSpace.data && !activeDefinition && (
<p className="notice muted">No map view applies to this space's schema.</p>
)}
Expand Down
4 changes: 3 additions & 1 deletion apps/navigator/src/server/sctx-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export function sctxApi(): Plugin {
});
server.middlewares.use('/api/map-views', (_req, res) => {
try {
sendJson(res, 200, loadMapViewDefinitions(loadConfig()));
const errors: { path: string; message: string }[] = [];
const definitions = loadMapViewDefinitions(loadConfig(), { onError: (e) => errors.push(e) });
sendJson(res, 200, { definitions, errors });
} catch (err) {
sendError(res, err);
}
Expand Down
10 changes: 7 additions & 3 deletions packages/map-views/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@ const CONFIG_PLUGINS_DIR = 'plugins';

/**
* Every map view definition available with `config`, found as docs/definitions.md describes.
* Throws on the first invalid definition, including one outside its namespace or with a duplicate `$id`.
* Throws on the first invalid definition unless `onError` is provided, in which case invalid
* definitions are reported to `onError` and skipped so valid definitions still load.
*
* `configDir` is the root of the main config file; it defaults to where structured-context finds it.
*/
export function loadMapViewDefinitions(config: Config, options: { configDir?: string } = {}): MapViewDefinition[] {
export function loadMapViewDefinitions(
config: Config,
options: { configDir?: string; onError?: (error: { path: string; message: string }) => void } = {},
): MapViewDefinition[] {
const configDir = options.configDir ?? resolveConfigPath().root;
const configDirs = [...new Set([configDir, ...config.spaces.flatMap((s) => (s.sourceDir ? [s.sourceDir] : []))])];

Expand All @@ -34,7 +38,7 @@ export function loadMapViewDefinitions(config: Config, options: { configDir?: st
}),
];

return readDefinitionFolders(folders);
return readDefinitionFolders(folders, { onError: options.onError });
}

/** Plugin short name → root directory, for plugins in a config root's plugins folder or named by the config. */
Expand Down
25 changes: 17 additions & 8 deletions packages/map-views/src/node/read-definitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,27 @@ export type DefinitionSource = { kind: 'core' } | { kind: 'plugin'; plugin: stri

/**
* Definitions in `folders` and this package's embedded ones, each checked against the namespace of its source.
* Throws on the first invalid definition or a repeated id.
* Throws on the first invalid definition or a repeated id unless `onError` is provided, in which case
* invalid definitions are reported to `onError` and skipped so valid definitions still load.
*/
export function readDefinitionFolders(folders: { dir: string; source: DefinitionSource }[]): MapViewDefinition[] {
export function readDefinitionFolders(
folders: { dir: string; source: DefinitionSource }[],
options: { onError?: (error: { path: string; message: string }) => void } = {},
): MapViewDefinition[] {
const foundAt = new Map<string, string>();
const definitions: MapViewDefinition[] = [];
const add = (label: string, text: string, source: DefinitionSource) => {
const definition = parseMapViewDefinition(label, text);
assertIdNamespace(definition.id, source, label);
const existing = foundAt.get(definition.id);
if (existing) throw new Error(`Map view id "${definition.id}" is defined by both ${existing} and ${label}.`);
foundAt.set(definition.id, label);
definitions.push(definition);
try {
const definition = parseMapViewDefinition(label, text);
assertIdNamespace(definition.id, source, label);
const existing = foundAt.get(definition.id);
if (existing) throw new Error(`Map view id "${definition.id}" is defined by both ${existing} and ${label}.`);
foundAt.set(definition.id, label);
definitions.push(definition);
} catch (err) {
if (!options.onError) throw err;
options.onError({ path: label, message: err instanceof Error ? err.message : String(err) });
}
};

for (const [file, text] of Object.entries(BUNDLED_DEFINITIONS))
Expand Down
13 changes: 13 additions & 0 deletions packages/map-views/tests/load-definitions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,17 @@ describe('loadMapViewDefinitions', () => {
const config: Config = { spaces: [{ name: 's', path: '.', sourceDir: join(root, 'included') }] };
expect(() => ids(config)).toThrow(/"sctx-map-view:\/\/a" is defined by both/);
});

test('with onError, reports invalid definitions and still loads valid ones', () => {
write('config/.sctx/map-views/bad.json5', '{ $id: "sctx-map-view://bad", regions: [] }');
write('config/.sctx/map-views/good.json5', definition('sctx-map-view://good'));
const errors: { path: string; message: string }[] = [];
const loaded = loadMapViewDefinitions(noSpaces, {
configDir: join(root, 'config'),
onError: (e) => errors.push(e),
});
expect(loaded.map((d) => d.id)).toEqual([...bundled(), 'sctx-map-view://good']);
expect(errors).toHaveLength(1);
expect(errors[0]!.path).toEndWith('bad.json5');
});
});