jekyll-image-links 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,468 @@
1
+ (function () {
2
+ "use strict";
3
+
4
+ const ROOT_SELECTOR = '[data-jil-root="true"]';
5
+ const config = window.__JIL_CONFIG__ || {};
6
+
7
+ function getHoverPopup() {
8
+ const api = window.JekyllHoverPopup;
9
+ if (!api || typeof api.openLink !== "function" || typeof api.openContent !== "function") {
10
+ return null;
11
+ }
12
+ return api;
13
+ }
14
+
15
+ function useHoverPopup() {
16
+ if (config.useHoverPopup === false) return false;
17
+ return !!getHoverPopup();
18
+ }
19
+
20
+ function init() {
21
+ document.querySelectorAll("[data-jil-map]").forEach(initMapHost);
22
+ }
23
+
24
+ function initMapHost(host) {
25
+ if (host.dataset.jilReady === "true") return;
26
+ host.dataset.jilReady = "true";
27
+
28
+ const mapData = JSON.parse(host.dataset.jilMap);
29
+ const inline = host.dataset.jilInline !== "false";
30
+ const viewer = host.dataset.jilViewer !== "false";
31
+ const labels = host.dataset.jilLabels === "true";
32
+ const img = host.querySelector(".jil-map-image");
33
+
34
+ if (!img) return;
35
+
36
+ if (labels) renderLabels(host, mapData, img);
37
+ if (inline) bindInlineClicks(host, mapData, img);
38
+ if (viewer) addViewerButton(host, mapData);
39
+ }
40
+
41
+ function renderLabels(host, mapData, img) {
42
+ const overlay = document.createElement("div");
43
+ overlay.className = "jil-label-layer";
44
+ host.appendChild(overlay);
45
+
46
+ const update = () => {
47
+ overlay.innerHTML = "";
48
+ const geom = getMapGeometry(img, mapData);
49
+ if (!geom || !geom.width || !geom.height) return;
50
+
51
+ overlay.style.left = `${geom.offsetX}px`;
52
+ overlay.style.top = `${geom.offsetY}px`;
53
+ overlay.style.width = `${geom.width}px`;
54
+ overlay.style.height = `${geom.height}px`;
55
+
56
+ mapData.regions.forEach((region) => {
57
+ const center = polygonCenter(region.points);
58
+ if (!center) return;
59
+
60
+ const left = (center[0] / mapData.width) * 100;
61
+ const top = (center[1] / mapData.height) * 100;
62
+ const label = region.label || region.title || "";
63
+ if (!label) return;
64
+
65
+ const link = document.createElement("a");
66
+ link.className = "jil-label";
67
+ link.href = region.href;
68
+ link.textContent = label;
69
+ link.style.left = `${left}%`;
70
+ link.style.top = `${top}%`;
71
+ link.title = region.title || label;
72
+ overlay.appendChild(link);
73
+ });
74
+ };
75
+
76
+ if (img.complete) update();
77
+ img.addEventListener("load", update);
78
+ window.addEventListener("resize", update);
79
+ if (typeof ResizeObserver !== "undefined") {
80
+ const observer = new ResizeObserver(update);
81
+ observer.observe(host);
82
+ observer.observe(img);
83
+ }
84
+ }
85
+
86
+ function bindInlineClicks(host, mapData, img) {
87
+ host.classList.add("jil-inline");
88
+ img.addEventListener("click", (event) => {
89
+ const point = imagePointFromEvent(img, mapData, event);
90
+ const region = firstIntersectedRegion(mapData.regions, point);
91
+ if (!region) return;
92
+
93
+ event.preventDefault();
94
+ openRegion(region, event);
95
+ });
96
+
97
+ img.addEventListener("mousemove", (event) => {
98
+ const point = imagePointFromEvent(img, mapData, event);
99
+ const region = firstIntersectedRegion(mapData.regions, point);
100
+ img.style.cursor = region ? "pointer" : "";
101
+ });
102
+ }
103
+
104
+ function addViewerButton(host, mapData) {
105
+ const figure = host.closest(".jil-figure");
106
+ if (!figure) return;
107
+
108
+ const caption = figure.querySelector(".jil-caption");
109
+ const toolbar = document.createElement("div");
110
+ toolbar.className = "jil-toolbar";
111
+
112
+ const button = document.createElement("button");
113
+ button.type = "button";
114
+ button.className = "jil-viewer-button btn btn-outline";
115
+ button.textContent = mapData.title ? `Open ${mapData.title}` : "Open map viewer";
116
+ button.addEventListener("click", (event) => openViewer(mapData, event));
117
+ toolbar.appendChild(button);
118
+
119
+ if (caption) {
120
+ caption.insertAdjacentElement("afterend", toolbar);
121
+ } else {
122
+ host.insertAdjacentElement("afterend", toolbar);
123
+ }
124
+ }
125
+
126
+ function openViewer(mapData, event) {
127
+ const panel = buildViewerPanel(mapData);
128
+ const jhp = useHoverPopup() ? getHoverPopup() : null;
129
+
130
+ if (jhp) {
131
+ jhp.openContent({
132
+ title: mapData.title || "Map viewer",
133
+ pageUrl: mapData.src,
134
+ content: panel.root,
135
+ clientX: event.clientX,
136
+ clientY: event.clientY,
137
+ isPermanent: true,
138
+ maxWidth: "min(96vw, 1200px)",
139
+ });
140
+ return;
141
+ }
142
+
143
+ const backdrop = document.createElement("div");
144
+ backdrop.className = "jil-viewer-backdrop";
145
+ backdrop.setAttribute("role", "dialog");
146
+ backdrop.setAttribute("aria-modal", "true");
147
+ backdrop.setAttribute("aria-label", mapData.title || "Map viewer");
148
+ backdrop.appendChild(panel.root);
149
+ document.body.appendChild(backdrop);
150
+ panel.focusClose();
151
+ backdrop.addEventListener("click", (evt) => {
152
+ if (evt.target === backdrop) backdrop.remove();
153
+ });
154
+ backdrop.addEventListener("keydown", (evt) => {
155
+ if (evt.key === "Escape") backdrop.remove();
156
+ });
157
+ }
158
+
159
+ function buildViewerPanel(mapData) {
160
+ const root = document.createElement("div");
161
+ root.className = "jil-viewer-panel jil-viewer-in-popup";
162
+
163
+ const header = document.createElement("div");
164
+ header.className = "jil-viewer-header";
165
+
166
+ const title = document.createElement("div");
167
+ title.className = "jil-viewer-title";
168
+ title.textContent = mapData.title || "Map viewer";
169
+
170
+ const closeBtn = document.createElement("button");
171
+ closeBtn.type = "button";
172
+ closeBtn.className = "jil-viewer-close btn btn-outline";
173
+ closeBtn.textContent = "Close";
174
+ closeBtn.hidden = true;
175
+
176
+ header.append(title, closeBtn);
177
+
178
+ const controls = document.createElement("div");
179
+ controls.className = "jil-viewer-controls";
180
+
181
+ const zoomOut = makeButton("Zoom out");
182
+ const zoomIn = makeButton("Zoom in");
183
+ const zoomReset = makeButton("Reset zoom");
184
+ const zoomFit = makeButton("Zoom to fit");
185
+ controls.append(zoomOut, zoomIn, zoomReset, zoomFit);
186
+
187
+ const scroll = document.createElement("div");
188
+ scroll.className = "jil-viewer-scroll";
189
+
190
+ const canvas = document.createElement("canvas");
191
+ canvas.className = "jil-viewer-canvas";
192
+ scroll.appendChild(canvas);
193
+
194
+ root.append(header, controls, scroll);
195
+
196
+ const state = {
197
+ zoom: 1,
198
+ image: null,
199
+ };
200
+
201
+ const paint = () => {
202
+ if (!state.image) return;
203
+ const width = Math.round(mapData.width * state.zoom);
204
+ const height = Math.round(mapData.height * state.zoom);
205
+ canvas.width = width;
206
+ canvas.height = height;
207
+
208
+ const ctx = canvas.getContext("2d");
209
+ ctx.clearRect(0, 0, width, height);
210
+ ctx.drawImage(state.image, 0, 0, width, height);
211
+
212
+ mapData.regions.forEach((region) => {
213
+ ctx.beginPath();
214
+ region.points.forEach((point, index) => {
215
+ const x = point[0] * state.zoom;
216
+ const y = point[1] * state.zoom;
217
+ if (index === 0) ctx.moveTo(x, y);
218
+ else ctx.lineTo(x, y);
219
+ });
220
+ ctx.closePath();
221
+ ctx.fillStyle = "rgba(51, 122, 183, 0.35)";
222
+ ctx.strokeStyle = "rgba(51, 122, 183, 0.95)";
223
+ ctx.lineWidth = 2;
224
+ ctx.fill();
225
+ ctx.stroke();
226
+ });
227
+ };
228
+
229
+ const setZoom = (value) => {
230
+ state.zoom = clamp(value, 0.1, 8);
231
+ paint();
232
+ };
233
+
234
+ const fitZoom = () => {
235
+ const maxWidth = scroll.clientWidth || mapData.width;
236
+ const maxHeight = scroll.clientHeight || mapData.height;
237
+ setZoom(Math.min(maxWidth / mapData.width, maxHeight / mapData.height, 1));
238
+ scroll.scrollTop = 0;
239
+ scroll.scrollLeft = 0;
240
+ };
241
+
242
+ zoomOut.addEventListener("click", () => setZoom(state.zoom / 1.25));
243
+ zoomIn.addEventListener("click", () => setZoom(state.zoom * 1.25));
244
+ zoomReset.addEventListener("click", () => {
245
+ setZoom(1);
246
+ scroll.scrollTop = 0;
247
+ scroll.scrollLeft = 0;
248
+ });
249
+ zoomFit.addEventListener("click", fitZoom);
250
+
251
+ canvas.addEventListener("click", (event) => {
252
+ const point = canvasPointFromEvent(canvas, state.zoom, event);
253
+ const region = firstIntersectedRegion(mapData.regions, point);
254
+ if (!region) return;
255
+ event.preventDefault();
256
+ openRegion(region, event);
257
+ });
258
+
259
+ canvas.addEventListener("mousemove", (event) => {
260
+ const point = canvasPointFromEvent(canvas, state.zoom, event);
261
+ const region = firstIntersectedRegion(mapData.regions, point);
262
+ canvas.style.cursor = region ? "pointer" : "grab";
263
+ });
264
+
265
+ let dragStart = null;
266
+ canvas.addEventListener("mousedown", (event) => {
267
+ if (event.button !== 2) return;
268
+ event.preventDefault();
269
+ dragStart = {
270
+ x: event.clientX,
271
+ y: event.clientY,
272
+ scrollLeft: scroll.scrollLeft,
273
+ scrollTop: scroll.scrollTop,
274
+ };
275
+ canvas.style.cursor = "grabbing";
276
+ });
277
+
278
+ window.addEventListener("mouseup", () => {
279
+ dragStart = null;
280
+ canvas.style.cursor = "grab";
281
+ });
282
+
283
+ window.addEventListener("mousemove", (event) => {
284
+ if (!dragStart) return;
285
+ scroll.scrollLeft = dragStart.scrollLeft + (dragStart.x - event.clientX);
286
+ scroll.scrollTop = dragStart.scrollTop + (dragStart.y - event.clientY);
287
+ });
288
+
289
+ canvas.addEventListener("contextmenu", (event) => event.preventDefault());
290
+
291
+ scroll.addEventListener("wheel", (event) => {
292
+ if (!event.ctrlKey && !event.metaKey) return;
293
+ event.preventDefault();
294
+ setZoom(state.zoom * (event.deltaY < 0 ? 1.1 : 0.9));
295
+ }, { passive: false });
296
+
297
+ const image = new Image();
298
+ image.onload = () => {
299
+ state.image = image;
300
+ fitZoom();
301
+ };
302
+ image.src = mapData.src;
303
+
304
+ return {
305
+ root,
306
+ focusClose: () => closeBtn.focus(),
307
+ };
308
+ }
309
+
310
+ function makeButton(label) {
311
+ const button = document.createElement("button");
312
+ button.type = "button";
313
+ button.className = "btn btn-outline";
314
+ button.textContent = label;
315
+ return button;
316
+ }
317
+
318
+ async function openRegion(region, event) {
319
+ if (event.shiftKey) {
320
+ window.open(region.href, "_blank", "noopener,noreferrer");
321
+ return;
322
+ }
323
+
324
+ const jhp = useHoverPopup() ? getHoverPopup() : null;
325
+ if (jhp) {
326
+ event.preventDefault();
327
+ await jhp.openLink({
328
+ href: region.href,
329
+ title: region.title || region.label || region.href,
330
+ clientX: event.clientX,
331
+ clientY: event.clientY,
332
+ isPermanent: true,
333
+ });
334
+ return;
335
+ }
336
+
337
+ window.location.href = region.href;
338
+ }
339
+
340
+ function imagePointFromEvent(img, mapData, event) {
341
+ const rect = img.getBoundingClientRect();
342
+ const geom = getMapGeometry(img, mapData);
343
+ if (!geom || !geom.width || !geom.height) {
344
+ return [0, 0];
345
+ }
346
+
347
+ const relX = (event.clientX - rect.left - geom.offsetX) / geom.width;
348
+ const relY = (event.clientY - rect.top - geom.offsetY) / geom.height;
349
+ return [
350
+ Math.round(relX * mapData.width),
351
+ Math.round(relY * mapData.height),
352
+ ];
353
+ }
354
+
355
+ function getMapGeometry(img, mapData) {
356
+ const rect = img.getBoundingClientRect();
357
+ const mapW = mapData.width;
358
+ const mapH = mapData.height;
359
+ if (!rect.width || !rect.height || !mapW || !mapH) {
360
+ return null;
361
+ }
362
+
363
+ const objectFit = window.getComputedStyle(img).objectFit || "fill";
364
+ const mapAspect = mapW / mapH;
365
+
366
+ if (objectFit === "fill") {
367
+ return {
368
+ offsetX: 0,
369
+ offsetY: 0,
370
+ width: rect.width,
371
+ height: rect.height,
372
+ };
373
+ }
374
+
375
+ const boxAspect = rect.width / rect.height;
376
+ let width;
377
+ let height;
378
+
379
+ if (objectFit === "cover") {
380
+ if (boxAspect > mapAspect) {
381
+ height = rect.height;
382
+ width = height * mapAspect;
383
+ } else {
384
+ width = rect.width;
385
+ height = width / mapAspect;
386
+ }
387
+ } else {
388
+ if (boxAspect > mapAspect) {
389
+ height = rect.height;
390
+ width = height * mapAspect;
391
+ } else {
392
+ width = rect.width;
393
+ height = width / mapAspect;
394
+ }
395
+ }
396
+
397
+ return {
398
+ offsetX: (rect.width - width) / 2,
399
+ offsetY: (rect.height - height) / 2,
400
+ width,
401
+ height,
402
+ };
403
+ }
404
+
405
+ function canvasPointFromEvent(canvas, zoom, event) {
406
+ const rect = canvas.getBoundingClientRect();
407
+ const x = (event.clientX - rect.left) / zoom;
408
+ const y = (event.clientY - rect.top) / zoom;
409
+ return [Math.round(x), Math.round(y)];
410
+ }
411
+
412
+ function firstIntersectedRegion(regions, point) {
413
+ return regions.find((region) => pointInPolygon(region.points, point)) || null;
414
+ }
415
+
416
+ function pointInPolygon(points, point) {
417
+ const [x, y] = point;
418
+ let count = 0;
419
+ for (let i = 0; i < points.length; i += 1) {
420
+ const a = { x: points[i][0], y: points[i][1] };
421
+ const b = { x: points[(i + 1) % points.length][0], y: points[(i + 1) % points.length][1] };
422
+ if (isWest(a, b, x, y)) count += 1;
423
+ }
424
+ return count % 2 === 1;
425
+ }
426
+
427
+ function isWest(a, b, x, y) {
428
+ if (a.y <= b.y) {
429
+ if (y <= a.y || y > b.y || (x >= a.x && x >= b.x)) return false;
430
+ if (x < a.x && x < b.x) return true;
431
+ return (y - a.y) / (x - a.x) > (b.y - a.y) / (b.x - a.x);
432
+ }
433
+ return isWest(b, a, x, y);
434
+ }
435
+
436
+ function polygonCenter(points) {
437
+ let x = 0;
438
+ let y = 0;
439
+ points.forEach((point) => {
440
+ x += point[0];
441
+ y += point[1];
442
+ });
443
+ return [x / points.length, y / points.length];
444
+ }
445
+
446
+ function clamp(value, min, max) {
447
+ return Math.min(max, Math.max(min, value));
448
+ }
449
+
450
+ function start() {
451
+ if (!document.querySelector(ROOT_SELECTOR)) return;
452
+
453
+ const run = () => init();
454
+
455
+ if (document.querySelector('[data-hover-popup-root="true"]') && !getHoverPopup()) {
456
+ window.setTimeout(run, 0);
457
+ return;
458
+ }
459
+
460
+ run();
461
+ }
462
+
463
+ if (document.readyState === "loading") {
464
+ document.addEventListener("DOMContentLoaded", start);
465
+ } else {
466
+ start();
467
+ }
468
+ })();
@@ -0,0 +1,17 @@
1
+ module Jekyll
2
+ module ImageLinks
3
+ class AssetFile < Jekyll::StaticFile
4
+ def initialize(site, base, dir, name, source_path:)
5
+ super(site, base, dir, name)
6
+ @source_path = source_path
7
+ end
8
+
9
+ def write(dest)
10
+ dest_path = destination(dest)
11
+ FileUtils.mkdir_p(File.dirname(dest_path))
12
+ FileUtils.cp(@source_path, dest_path)
13
+ true
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,34 @@
1
+ module Jekyll
2
+ module ImageLinks
3
+ class Generator < Jekyll::Generator
4
+ safe true
5
+ priority :low
6
+
7
+ def generate(site)
8
+ cfg = (site.config["image_links"] || {})
9
+ return if cfg["enabled"] == false
10
+
11
+ assets_path = cfg["assets_path"] || "/assets/jekyll-image-links"
12
+ assets_path = "/#{assets_path}" unless assets_path.start_with?("/")
13
+
14
+ asset_dir = File.expand_path("../../../assets/jekyll-image-links", __dir__)
15
+
16
+ files = {
17
+ "image_links.js" => File.join(asset_dir, "image_links.js"),
18
+ "image_links.css" => File.join(asset_dir, "image_links.css"),
19
+ }
20
+
21
+ files.each do |name, source_path|
22
+ next unless File.file?(source_path)
23
+ site.static_files << AssetFile.new(
24
+ site,
25
+ site.source,
26
+ assets_path.sub(%r{\A/}, ""),
27
+ name,
28
+ source_path: source_path
29
+ )
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,61 @@
1
+ module Jekyll
2
+ module ImageLinks
3
+ module Hooks
4
+ def self.register!
5
+ Jekyll::Hooks.register(%i[pages documents], :post_render) do |doc|
6
+ site = doc.site
7
+ cfg = (site.config["image_links"] || {})
8
+ next if cfg["enabled"] == false
9
+ next unless doc.respond_to?(:output_ext) && doc.output_ext == ".html"
10
+
11
+ html = doc.output.to_s
12
+ next unless html.include?('data-jil-image-map="true"') || MapRenderer.portable_markup?(html)
13
+
14
+ assets_path = cfg["assets_path"] || "/assets/jekyll-image-links"
15
+ assets_path = "/#{assets_path}" unless assets_path.start_with?("/")
16
+
17
+ begin
18
+ html = MapRenderer.enhance_html(html, site: site, page: doc, cfg: cfg)
19
+ doc.output = inject_assets(html, assets_path: assets_path, site: site, cfg: cfg)
20
+ rescue StandardError => e
21
+ Jekyll.logger.warn("jekyll-image-links:", "Failed to process #{doc.relative_path}: #{e.class}: #{e.message}")
22
+ end
23
+ end
24
+ end
25
+
26
+ def self.build_jil_config(site, cfg)
27
+ return { useHoverPopup: false } if cfg["use_hover_popup"] == false
28
+ return { useHoverPopup: true } if cfg["use_hover_popup"] == true
29
+
30
+ hover_cfg = site.config["hover_popup"] || {}
31
+ return { useHoverPopup: false } if hover_cfg["enabled"] == false
32
+
33
+ # Auto: omit useHoverPopup and detect window.JekyllHoverPopup at runtime.
34
+ {}
35
+ end
36
+
37
+ def self.inject_assets(html, assets_path:, site:, cfg:)
38
+ return html unless html.include?('data-jil-image-map="true"')
39
+ return html if html.include?('data-jil-root="true"')
40
+
41
+ jil_config = build_jil_config(site, cfg)
42
+
43
+ tags = <<~HTML
44
+ <script>
45
+ window.__JIL_CONFIG__ = #{jil_config.to_json};
46
+ </script>
47
+ <link rel="stylesheet" href="#{assets_path}/image_links.css" />
48
+ <script defer src="#{assets_path}/image_links.js" data-jil-root="true"></script>
49
+ HTML
50
+
51
+ if html.include?("</body>")
52
+ html.sub("</body>", "#{tags}\n</body>")
53
+ else
54
+ "#{html}\n#{tags}\n"
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
60
+
61
+ Jekyll::ImageLinks::Hooks.register!