Skip to content

Commit

Permalink
feat: Improve styling of SVG map
Browse files Browse the repository at this point in the history
  • Loading branch information
ptbrowne committed Feb 17, 2023
1 parent c15eda0 commit fc3e062
Showing 1 changed file with 76 additions and 8 deletions.
84 changes: 76 additions & 8 deletions website/src/pages/api/v0.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,48 @@ const cors = initMiddleware(
})
);

const truthy = <T>(x: T): x is Exclude<T, undefined | null> => {
return Boolean(x);
};

const makeMapshaperStyleCommands = (
shapeStyles: Record<
string,
null | {
fill?: string;
stroke?: string;
}
>
) => {
return Object.entries(shapeStyles)
.map(([shapeName, style]) => {
if (style === null) {
return style;
}
return `-style target='${shapeName}' ${Object.entries(style)
.map(([propName, propValue]) => {
return `${propName}='${propValue}'`;
})
.join(" ")}`;
})
.filter(truthy);
};

const getShapeZIndex = (shape: string) => {
if (shape.includes("country")) {
return 3;
} else if (shape.includes("cantons")) {
return 2;
} else if (shape.includes("lakes")) {
return 1;
}
return 0;
};

const shapeIndexComparator = (a: string, b: string) => {
const za = getShapeZIndex(a);
const zb = getShapeZIndex(b);
return za === zb ? 0 : za < zb ? -1 : 1;
};

export default async function handler(
Expand All @@ -45,17 +83,47 @@ export default async function handler(
}

const cwd = process.cwd();
const shpFilenames = [...options.shapes]
.map((shapeName) => {
return path.join(cwd, "public", "swiss-maps", year, `${shapeName}.shp`);
})
.sort(shapeIndexComparator);

const hasCantons = shapes.has("cantons");
const hasMunicipalities = shapes.has("municipalities");
const hasLakes = shapes.has("lakes");

const shapeStyles = {
country: {
fill: hasCantons || hasMunicipalities ? "transparent" : "#eee",
stroke: "#111",
},
lakes: hasLakes
? {
fill: "#a1d0f7",
}
: null,
cantons: hasCantons
? {
fill: hasMunicipalities ? "transparent" : "#eee",
stroke: "#666",
}
: null,
municipalities: hasMunicipalities
? {
fill: "#eee",
stroke: hasCantons ? "#bbb" : "#666",
}
: null,
};

const styleCommands = makeMapshaperStyleCommands(shapeStyles);

const output = await generate({
...options,
shpFilenames: [...options.shapes].map((shapeName) => {
return path.join(cwd, "public", "swiss-maps", year, `${shapeName}.shp`);
}),
shpFilenames: shpFilenames,
mapshaperCommands: [
// svg coloring, otherwise is all bblack
shapes.has("cantons")
? `-style fill='#e6e6e6' stroke='#999' target='cantons'`
: "",
shapes.has("lakes") ? `-style fill='#a1d0f7' target='lakes'` : "",
...styleCommands,
`-o output.${format} format=${format} target=*`,
],
});
Expand Down

0 comments on commit fc3e062

Please sign in to comment.