Skip to content

Open source alternative to Semrush and Ahrefs

Let readers zoom and pan the rank-grid map in local-seo reports (#1053)

Ben Senescu2d8236a4fd5d
diff --git a/src/report-widgets/rank-grid.ts b/src/report-widgets/rank-grid.ts
index 75ee0856..95f80186 100644
--- a/src/report-widgets/rank-grid.ts
+++ b/src/report-widgets/rank-grid.ts
@@ -8,9 +8,10 @@ import {
} from "../shared/report-map";
// The rank-grid report widget: turns a declarative block a skill wrote into
-// the Maps grid, the way local rank trackers draw it. The view is fixed on the
-// grid, like a rank tracker's report: no zoom, no panning. This bundle
-// is the only script a report may run (see src/shared/report-sandbox.ts), so
+// the Maps grid, the way local rank trackers draw it. The view opens fitted to
+// the grid; readers can zoom and pan within the area the map grant covers, and
+// a button brings the fitted view back. This bundle is the only script a
+// report may run (see src/shared/report-sandbox.ts), so
// it reads data from the page and never evaluates anything found there.
//
// The block it looks for:
@@ -69,6 +70,8 @@ const STYLE = `
.osw .leaflet-container{font-family:inherit}
.osw-logo img{display:block;width:59px;height:18px}
.osw .leaflet-control-attribution{font-size:11px}
+.osw-fit button{display:block;height:30px;padding:0 10px;border:0;border-radius:4px;background:#fff;color:#0a0a0a;font-family:inherit;font-size:12px;font-weight:600;line-height:30px;cursor:pointer}
+.osw-fit button:hover{background:#f4f4f4}
.osw-fallback{display:none}
@media print{.osw{display:none}.osw-fallback{display:block}}
`;
@@ -204,9 +207,26 @@ function addGoogleAttribution(map: L.Map, grant: string) {
refresh();
}
+// A button under the zoom control that brings back the fitted view.
+function addFitControl(map: L.Map, fit: () => void) {
+ const FitControl = L.Control.extend({
+ onAdd: () => {
+ const bar = el("div", "leaflet-bar osw-fit");
+ const button = el("button", undefined, "Fit grid");
+ button.type = "button";
+ button.title = "Zoom to the whole grid";
+ L.DomEvent.disableClickPropagation(bar);
+ button.addEventListener("click", fit);
+ bar.appendChild(button);
+ return bar;
+ },
+ });
+ new FitControl({ position: "topleft" }).addTo(map);
+}
+
function render(figure: HTMLElement, cfg: RankGridConfig, grant: string) {
- // The proxy only serves tiles at the grant's zooms, inside its area. Both
- // are sized for this widget's fitted view at any width.
+ // The proxy only serves tiles at the grant's zooms, in and just around its
+ // area, so the map's zoom and panning stay inside both.
const granted = readMapGrant(grant);
if (!granted) return;
const wrap = el("div", "osw");
@@ -248,34 +268,37 @@ function render(figure: HTMLElement, cfg: RankGridConfig, grant: string) {
return ranks.reduce((s, r) => s + r, 0) / ranks.length;
};
+ const { area } = granted;
const map = L.map(mapEl, {
minZoom: granted.minZoom,
maxZoom: granted.maxZoom,
- zoomSnap: 0.5,
- zoomControl: false,
- dragging: false,
- touchZoom: false,
- doubleClickZoom: false,
- scrollWheelZoom: false,
+ // Panning stops at the granted area: there are no tiles past it.
+ maxBounds: [
+ [area.south, area.west],
+ [area.north, area.east],
+ ],
+ maxBoundsViscosity: 1,
boxZoom: false,
- keyboard: false,
+ // The wheel scrolls the report until the reader clicks into the map.
+ scrollWheelZoom: false,
attributionControl: true,
});
map.attributionControl.setPrefix(false);
+ map.on("focus", () => map.scrollWheelZoom.enable());
+ map.on("blur", () => map.scrollWheelZoom.disable());
// The whole grid in the middle of the map with room around it. Refit when
- // the map's size changes, so a narrow column never clips the outer points,
- // and when a popup closes, since opening one may have panned the map.
- const fit = () =>
+ // the map's size changes, so a narrow column never clips the outer points.
+ const fit = (animate = false) =>
map.fitBounds(bounds, {
padding: [REPORT_MAP_PADDING, REPORT_MAP_PADDING],
- animate: false,
+ animate,
});
fit();
new ResizeObserver(() => {
map.invalidateSize({ animate: false });
fit();
}).observe(mapEl);
- map.on("popupclose", fit);
+ addFitControl(map, () => fit(true));
L.tileLayer(`/report-map/${grant}/{z}/{x}/{y}`).addTo(map);
addGoogleAttribution(map, grant);
@@ -369,13 +392,46 @@ function render(figure: HTMLElement, cfg: RankGridConfig, grant: string) {
draw(cfg.keywords.length > 1 ? ALL : cfg.keywords[0].keyword);
}
+// The server signs one grant per grid, its area centered on the grid. Grids
+// close together can each sit inside the other's area, so the one centered
+// nearest this grid is the one signed for it.
+function grantFor(cfg: RankGridConfig, grants: string[]) {
+ const points = cfg.keywords.flatMap((k) => k.points);
+ if (points.length === 0) return undefined;
+ const lats = points.map((p) => p.lat);
+ const lngs = points.map((p) => p.lng);
+ const south = Math.min(...lats);
+ const north = Math.max(...lats);
+ const west = Math.min(...lngs);
+ const east = Math.max(...lngs);
+ let best: { grant: string; distance: number } | undefined;
+ for (const grant of grants) {
+ const area = readMapGrant(grant)?.area;
+ if (
+ !area ||
+ area.south > south ||
+ area.north < north ||
+ area.west > west ||
+ area.east < east
+ )
+ continue;
+ const distance =
+ Math.abs(area.south + area.north - south - north) +
+ Math.abs(area.west + area.east - west - east);
+ if (!best || distance < best.distance) best = { grant, distance };
+ }
+ return best?.grant;
+}
+
// The tag is `defer`, so the document is parsed by now, and currentScript is
// still this tag.
function boot() {
const script = document.currentScript;
- const grant =
- script instanceof HTMLScriptElement ? script.dataset.mapGrant : undefined;
- if (!grant) return;
+ const grants =
+ script instanceof HTMLScriptElement
+ ? (script.dataset.mapGrants ?? "").split(" ").filter(Boolean)
+ : [];
+ if (grants.length === 0) return;
const figures = document.querySelectorAll<HTMLElement>(
'figure[data-widget="rank-grid"]',
);
@@ -386,7 +442,8 @@ function boot() {
for (const figure of figures) {
const data = figure.querySelector('script[type="application/json"]');
const cfg = data?.textContent ? parseConfig(data.textContent) : null;
- if (!cfg) continue;
+ const grant = cfg ? grantFor(cfg, grants) : undefined;
+ if (!cfg || !grant) continue;
render(figure, cfg, grant);
}
}
diff --git a/src/routes/r/$reportId.ts b/src/routes/r/$reportId.ts
index dae10dc1..ef02ce72 100644
--- a/src/routes/r/$reportId.ts
+++ b/src/routes/r/$reportId.ts
@@ -5,7 +5,7 @@ import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve"
import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";
import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";
import { asAppError } from "@/server/lib/errors";
-import { createReportMapGrant } from "@/server/features/reports/reportMapGrant";
+import { createReportMapGrants } from "@/server/features/reports/reportMapGrant";
import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";
// The report viewer: the stored document, served byte for byte from the app's
@@ -86,7 +86,7 @@ async function handleReportRequest(
return reportDocumentResponse(html, {
print,
cacheControl: "private, no-store",
- mapGrant: await createReportMapGrant(html),
+ mapGrants: await createReportMapGrants(html),
});
}
diff --git a/src/routes/report-map/$grant/$z/$x/$y.ts b/src/routes/report-map/$grant/$z/$x/$y.ts
index 9ef047f1..4f82518b 100644
--- a/src/routes/report-map/$grant/$z/$x/$y.ts
+++ b/src/routes/report-map/$grant/$z/$x/$y.ts
@@ -10,7 +10,7 @@ import { REPORT_MAP_MAX_ZOOM } from "@/shared/report-map";
// Map tiles for the rank-grid report widget. No session: a shared report's
// reader has none, and the sandboxed frame sends no cookies anyway. The
// signed grant in the path is the authorization, and it only covers the area
-// around the report's grid at the zooms its fitted view uses (see
+// around the report's grid at a few zooms either side of its fitted view (see
// reportMapGrant.ts).
//
// A raw-Response route with no `component`, so it stays out of the client
diff --git a/src/routes/s/$token/raw.ts b/src/routes/s/$token/raw.ts
index b3d02c1c..0e83ad42 100644
--- a/src/routes/s/$token/raw.ts
+++ b/src/routes/s/$token/raw.ts
@@ -6,7 +6,7 @@ import {
sharesEnabled,
} from "@/server/features/reports/shareAccess";
import { captureServerEvent } from "@/server/lib/posthog";
-import { createReportMapGrant } from "@/server/features/reports/reportMapGrant";
+import { createReportMapGrants } from "@/server/features/reports/reportMapGrant";
import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";
import { sharePath } from "@/shared/report-share";
@@ -118,7 +118,7 @@ async function handleSharedReportRequest(
return reportDocumentResponse(html, {
cacheControl: EDGE_CACHE_CONTROL,
noindex: true,
- mapGrant: await createReportMapGrant(html),
+ mapGrants: await createReportMapGrants(html),
});
}
diff --git a/src/server/features/reports/reportMapGrant.test.ts b/src/server/features/reports/reportMapGrant.test.ts
index 67b6208d..7cc76c77 100644
--- a/src/server/features/reports/reportMapGrant.test.ts
+++ b/src/server/features/reports/reportMapGrant.test.ts
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
- createReportMapGrant,
+ createReportMapGrants,
grantCoversTile,
verifyReportMapGrant,
} from "./reportMapGrant";
@@ -28,7 +28,7 @@ describe("report map grants", () => {
});
it("covers the report's grid and nothing far from it", async () => {
- const grant = await createReportMapGrant(reportWithGrid);
+ const [grant] = await createReportMapGrants(reportWithGrid);
const scope = await verifyReportMapGrant(grant ?? "");
expect(scope).not.toBeNull();
@@ -38,18 +38,43 @@ describe("report map grants", () => {
expect(grantCoversTile(tileAt(39.95, -75.16), scope)).toBe(false);
});
- it("covers only the zooms a fitted view of the grid uses", async () => {
- const grant = await createReportMapGrant(reportWithGrid);
+ it("stops a few zooms past the fitted view", async () => {
+ const [grant] = await createReportMapGrants(reportWithGrid);
const scope = await verifyReportMapGrant(grant ?? "");
expect(scope).not.toBeNull();
if (!scope) return;
- // The grid is ~4 km across, so street level is far past any fitted view.
+ // The grid is ~4 km across, so it fits around zoom 13 and building level
+ // is out of reach.
+ expect(grantCoversTile(tileAt(40.44, -79.99, 16), scope)).toBe(true);
expect(grantCoversTile(tileAt(40.44, -79.99, 18), scope)).toBe(false);
});
+ it("gives each grid its own grant, zoomable to that grid", async () => {
+ // A second location ~35 km north: one grant sized to both would stop
+ // every map zoomed out far enough to show the pair.
+ const twoLocations = reportWithGrid.replace(
+ "</body>",
+ reportWithGrid
+ .slice(
+ reportWithGrid.indexOf("<figure"),
+ reportWithGrid.indexOf("</body>"),
+ )
+ .replaceAll("40.4", "40.7") + "</body>",
+ );
+ const grants = await createReportMapGrants(twoLocations);
+ const scopes = await Promise.all(grants.map(verifyReportMapGrant));
+
+ expect(scopes).toHaveLength(2);
+ const [pittsburgh, north] = scopes;
+ if (!pittsburgh || !north) throw new Error("grant did not verify");
+ expect(grantCoversTile(tileAt(40.44, -79.99, 15), pittsburgh)).toBe(true);
+ expect(grantCoversTile(tileAt(40.74, -79.99, 15), north)).toBe(true);
+ expect(grantCoversTile(tileAt(40.74, -79.99, 15), pittsburgh)).toBe(false);
+ });
+
it("rejects a grant whose area was widened", async () => {
- const grant = (await createReportMapGrant(reportWithGrid)) ?? "";
+ const [grant = ""] = await createReportMapGrants(reportWithGrid);
const widened = grant.replace(/^[^~]+/, "-80");
expect(await verifyReportMapGrant(widened)).toBeNull();
@@ -58,6 +83,6 @@ describe("report map grants", () => {
it("issues no grant without a Maps key", async () => {
vi.stubEnv("GOOGLE_MAPS_API_KEY", "");
- expect(await createReportMapGrant(reportWithGrid)).toBeNull();
+ expect(await createReportMapGrants(reportWithGrid)).toEqual([]);
});
});
diff --git a/src/server/features/reports/reportMapGrant.ts b/src/server/features/reports/reportMapGrant.ts
index 00709c65..c58bb240 100644
--- a/src/server/features/reports/reportMapGrant.ts
+++ b/src/server/features/reports/reportMapGrant.ts
@@ -19,12 +19,22 @@ import {
// copied out of a report stops working.
const GRANT_TTL_SECONDS = 24 * 60 * 60;
-// Around the grid, enough to fill the widget's fixed view on a wide screen:
-// one and a half times the grid's size on every side, and never less than
-// ~3 km.
+// Around the grid, room to pan: one and a half times the grid's size on every
+// side, and never less than ~3 km. The widget keeps its view inside this area.
const PAD_GRID_SPANS = 1.5;
const MIN_PAD_DEGREES = 0.03;
+// How far a reader can zoom from the fitted view: out far enough to place the
+// grid in its town, in close enough to read street names around a point.
+const ZOOM_OUT_LEVELS = 2;
+const ZOOM_IN_LEVELS = 2;
+
+// Zoomed out, the view can be bigger than the area, so tiles within this many
+// tiles of it are served too: half the widest view is about two tiles, with
+// room to spare. The widget keeps its view inside the area wherever the view
+// fits in it, so only zoomed-out views ever reach into this margin.
+const MARGIN_TILES = 4;
+
// The space the widget fits the grid into, from a phone to a wide report
// column. The height is fixed by the widget's CSS.
const MIN_FIT_PX = 160;
@@ -83,8 +93,9 @@ function widgetBlocks(html: string) {
return blocks;
}
-function gridPoints(html: string) {
- const points: Array<{ lat: number; lng: number }> = [];
+// The points of each rank grid in the report, one list per figure.
+function gridsInReport(html: string) {
+ const grids: Array<Array<{ lat: number; lng: number }>> = [];
for (const block of widgetBlocks(html)) {
let data: unknown;
try {
@@ -94,9 +105,10 @@ function gridPoints(html: string) {
}
const parsed = widgetPointsSchema.safeParse(data);
if (!parsed.success) continue;
- for (const keyword of parsed.data.keywords) points.push(...keyword.points);
+ const points = parsed.data.keywords.flatMap((keyword) => keyword.points);
+ if (points.length > 0) grids.push(points);
}
- return points;
+ return grids;
}
function mapGrantScope(
@@ -110,6 +122,7 @@ function mapGrantScope(
const east = Math.max(...lngs);
const padLat = Math.max((north - south) * PAD_GRID_SPANS, MIN_PAD_DEGREES);
const padLng = Math.max((east - west) * PAD_GRID_SPANS, MIN_PAD_DEGREES);
+ const fitted = fittedZoomRange({ south, west, north, east });
return {
area: {
south: south - padLat,
@@ -117,7 +130,8 @@ function mapGrantScope(
north: north + padLat,
east: east + padLng,
},
- ...fittedZoomRange({ south, west, north, east }),
+ minZoom: Math.max(0, fitted.minZoom - ZOOM_OUT_LEVELS),
+ maxZoom: Math.min(REPORT_MAP_MAX_ZOOM, fitted.maxZoom + ZOOM_IN_LEVELS),
};
}
@@ -129,8 +143,7 @@ function mercatorY(lat: number) {
/**
* The tile zooms the widget can land on when it fits the grid into its view
- * (Leaflet's fitBounds), across every view size it can have. The widget's view
- * is fixed, so these few levels are all it ever loads.
+ * (Leaflet's fitBounds), across every view size it can have.
*/
function fittedZoomRange(grid: MapArea) {
// The grid's size in pixels at zoom 0, where the world is 256 across.
@@ -171,24 +184,34 @@ async function mapsKey() {
return (await getOptionalEnvValue("GOOGLE_MAPS_API_KEY"))?.trim() || null;
}
-/** A grant for the area the report's rank grids cover, or null for none. */
-export async function createReportMapGrant(html: string) {
+/**
+ * One grant per distinct rank grid in the report, empty for none. Each grid
+ * gets its own: a report covering several locations would otherwise share one
+ * grant sized to all of them, and its zooms would hold every map far out.
+ */
+export async function createReportMapGrants(html: string) {
const apiKey = await mapsKey();
- if (!apiKey) return null;
- const points = gridPoints(html);
- if (points.length === 0) return null;
- const scope = mapGrantScope(points);
+ if (!apiKey) return [];
const expiresAt = Math.floor(Date.now() / 1000) + GRANT_TTL_SECONDS;
- const payload = [
- scope.area.south.toFixed(5),
- scope.area.west.toFixed(5),
- scope.area.north.toFixed(5),
- scope.area.east.toFixed(5),
- scope.minZoom,
- scope.maxZoom,
- expiresAt,
- ].join("~");
- return `${payload}~${await sign(payload, apiKey)}`;
+ const payloads = new Set(
+ gridsInReport(html).map((points) => {
+ const scope = mapGrantScope(points);
+ return [
+ scope.area.south.toFixed(5),
+ scope.area.west.toFixed(5),
+ scope.area.north.toFixed(5),
+ scope.area.east.toFixed(5),
+ scope.minZoom,
+ scope.maxZoom,
+ expiresAt,
+ ].join("~");
+ }),
+ );
+ return Promise.all(
+ [...payloads].map(
+ async (payload) => `${payload}~${await sign(payload, apiKey)}`,
+ ),
+ );
}
/** What a grant covers, or null when it is forged or expired. */
@@ -224,16 +247,19 @@ function tileLatitude(y: number, zoom: number) {
return (180 / Math.PI) * Math.atan(Math.sinh(n));
}
-/** Whether a grant covers a web-mercator tile: one of its zooms, in its area. */
+/**
+ * Whether a grant covers a web-mercator tile: one of its zooms, in its area or
+ * within MARGIN_TILES of it.
+ */
export function grantCoversTile(
tile: { z: number; x: number; y: number },
{ area, minZoom, maxZoom }: MapGrantScope,
) {
if (tile.z < minZoom || tile.z > maxZoom) return false;
- const west = (tile.x / 2 ** tile.z) * 360 - 180;
- const east = ((tile.x + 1) / 2 ** tile.z) * 360 - 180;
- const north = tileLatitude(tile.y, tile.z);
- const south = tileLatitude(tile.y + 1, tile.z);
+ const west = ((tile.x - MARGIN_TILES) / 2 ** tile.z) * 360 - 180;
+ const east = ((tile.x + 1 + MARGIN_TILES) / 2 ** tile.z) * 360 - 180;
+ const north = tileLatitude(tile.y - MARGIN_TILES, tile.z);
+ const south = tileLatitude(tile.y + 1 + MARGIN_TILES, tile.z);
return (
west < area.east &&
east > area.west &&
diff --git a/src/shared/report-map.ts b/src/shared/report-map.ts
index eed893e0..6247894c 100644
--- a/src/shared/report-map.ts
+++ b/src/shared/report-map.ts
@@ -1,11 +1,11 @@
// The map behind the rank-grid report widget: Google Maps tiles, proxied
// through /report-map so no key reaches a reader. A report is sandboxed and
// may be read by anyone holding a share link, so the proxy cannot ask who is
-// reading. Instead the document response carries a signed grant naming the
-// one area the report's grid covers and the few zoom levels a fitted view of
-// it can land on, and the proxy serves those tiles only. Shared by the server,
-// which signs and checks grants, and by the widget, which fits its fixed view
-// inside the grant.
+// reading. Instead the document response carries a signed grant per rank grid,
+// naming the area around that grid and the few zoom levels either side of a
+// fitted view of it, and the proxy serves those tiles only. Shared by the
+// server, which signs and checks grants, and by the widget, which keeps its
+// zoom and panning inside the grant.
/** The closest zoom the map offers: street level, not building level. */
export const REPORT_MAP_MAX_ZOOM = 18;
diff --git a/src/shared/report-sandbox.test.ts b/src/shared/report-sandbox.test.ts
index 107c2389..d12db79b 100644
--- a/src/shared/report-sandbox.test.ts
+++ b/src/shared/report-sandbox.test.ts
@@ -31,7 +31,7 @@ describe("report-sandbox", () => {
it("injects the widget script under the response nonce", async () => {
const response = reportDocumentResponse(
'<!doctype html><html><body><script>alert(1)</script><script src="x" </body></html>',
- { cacheControl: "no-store", mapGrant: "grant" },
+ { cacheControl: "no-store", mapGrants: ["grant"] },
);
const html = await response.text();
const csp = response.headers.get("Content-Security-Policy") ?? "";
@@ -41,7 +41,7 @@ describe("report-sandbox", () => {
expect(csp).toContain("sandbox allow-scripts");
expect(
html.startsWith(
- `<!doctype html><script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grant="grant" defer></script>`,
+ `<!doctype html><script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grants="grant" defer></script>`,
),
).toBe(true);
expect(html.split(`nonce="${nonce}"`).length).toBe(2);
diff --git a/src/shared/report-sandbox.ts b/src/shared/report-sandbox.ts
index f76fe743..d16037dd 100644
--- a/src/shared/report-sandbox.ts
+++ b/src/shared/report-sandbox.ts
@@ -125,9 +125,9 @@ function withPrintScript(html: string): string {
* closed doctype gets the tag first of all, which is just as safe; a doctype
* left unclosed swallows the tag entirely, and the widget simply never boots.
*/
-function withWidgetScript(html: string, nonce: string, mapGrant: string) {
- // The grant is path-safe (see readMapGrant), so it needs no escaping here.
- const tag = `<script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grant="${mapGrant}" defer></script>`;
+function withWidgetScript(html: string, nonce: string, mapGrants: string[]) {
+ // Grants are path-safe (see readMapGrant), so they need no escaping here.
+ const tag = `<script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grants="${mapGrants.join(" ")}" defer></script>`;
const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
if (!doctype) return tag + html;
const end = doctype.index + doctype[0].length;
@@ -147,16 +147,14 @@ export function reportDocumentResponse(
print?: boolean;
cacheControl: string;
noindex?: boolean;
- /** From createReportMapGrant: lets the rank-grid widget draw its map. */
- mapGrant?: string | null;
+ /** From createReportMapGrants: let the rank-grid widget draw its maps. */
+ mapGrants?: string[];
},
): Response {
// The widget only loads where it has a map to draw.
- const nonce = options.mapGrant ? crypto.randomUUID() : undefined;
- const document =
- nonce && options.mapGrant
- ? withWidgetScript(html, nonce, options.mapGrant)
- : html;
+ const mapGrants = options.mapGrants ?? [];
+ const nonce = mapGrants.length > 0 ? crypto.randomUUID() : undefined;
+ const document = nonce ? withWidgetScript(html, nonce, mapGrants) : html;
return new Response(options.print ? withPrintScript(document) : document, {
status: 200,
headers: {