1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
|
import { parse } from "wmap-parser";
import { renderToSVG, StageType } from "wmap-renderer-svg";
import DOMPurify from "isomorphic-dompurify";
////////////////////////////////////////////////////////////////////////////////
// Sourcing ////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Walks the lineup of items preceding $item and collects each
// .wmap-source's already-expanded text. Returns [] outside the wiki
// (no lineup to walk).
function lineup($item) {
if (typeof wiki === "undefined") return [];
const results = [];
const candidates = $(".item:lt(" + $(".item").index($item) + ")");
const sources = candidates.filter(".wmap-source");
for (const div of sources) {
results.push(div.wmapData());
}
return results;
}
// Replaces every bare "LINEUP" line with the concatenated text of every
// .wmap-source item earlier in the lineup, then returns the joined text.
// Each upstream wmapData() has already done its own expansion, so the
// recursion is implicit. The wmap-parser is tolerant of duplicates and
// unknown lines, so we don't pre-parse or dedupe here.
function expandLineup(text, $item) {
return text
.split("\n")
.map((line) =>
line.trim() === "LINEUP" ? lineup($item).join("\n") : line,
)
.join("\n");
}
// Finds the name for this map by walking the DOM to the nearest preceding
// heading on the same page. When multiple .wmap blocks share that
// heading, suffixes " #2", " #3", … in document order.
function findName($element) {
const page = $element.closest(".page");
if (!page) return "Unknown";
const headings = page.querySelectorAll("h1, h2, h3, h4, h5, h6");
let closestHeading = null;
for (const heading of headings) {
const elementFollowsHeading =
heading.compareDocumentPosition($element) &
Node.DOCUMENT_POSITION_FOLLOWING;
if (elementFollowsHeading) closestHeading = heading;
}
if (!closestHeading) return "Unknown";
const baseName = closestHeading.textContent.trim();
const wmaps = page.querySelectorAll(".wmap.item");
let position = 0;
for (const wmap of wmaps) {
const wmapFollowsHeading =
closestHeading.compareDocumentPosition(wmap) &
Node.DOCUMENT_POSITION_FOLLOWING;
if (!wmapFollowsHeading) continue;
position++;
if (wmap === $element) break;
}
return position <= 1 ? baseName : `${baseName} #${position}`;
}
// Default stage boundaries (in 0-1 component-coordinate units), matching
// wmap-renderer-svg's defaults [25, 50, 75] divided by 100.
const kDefaultStageBoundaries = [0.25, 0.5, 0.75];
const kStageNameToIndex = { i: 0, ii: 1, iii: 2 };
// Returns [b0, b1, b2] — the upper x boundaries of stages 1, 2, and 3.
// Falls back to defaults for any boundary the parser didn't override.
function stageBoundaries(map) {
const boundaries = [...kDefaultStageBoundaries];
for (const override of map.stages) {
const index = kStageNameToIndex[override.stage];
if (index !== undefined) boundaries[index] = override.value;
}
return boundaries;
}
// Maps an x coordinate to its 1-indexed evolution stage.
function stageFor(x, boundaries) {
if (x < boundaries[0]) return 1;
if (x < boundaries[1]) return 2;
if (x < boundaries[2]) return 3;
return 4;
}
// Pre-built per-stage description tables keyed by StageType.name. Stage N's
// table is at index N-1.
const kStageDescriptions = [1, 2, 3, 4].map((stage) => {
const descriptions = {};
for (const stageType of Object.values(StageType)) {
descriptions[stageType.name] = stageType.stages[stage - 1];
}
return descriptions;
});
// Creates the aspect data type out of the existing text.
// tAspectData := {
// +name: String,
// +graph: tAspectGraph
// }
// tAspectGraph := {
// nodes: Array<tAspectNode>,
// rels: Array<tAspectRelation>
// }
// tAspectNode := {
// type: String,
// in: Array<Number>,
// out: Array<Number>,
// props: Object<String, Any>
// }
// tAspectRelation := {
// type: String,
// from: Number,
// to: Number,
// props: Object<String, Any>
// }
function aspectData($element, text) {
const $item = $($element);
const map = parse(expandLineup(text, $item));
const boundaries = stageBoundaries(map);
const aspectNodes = [];
const rels = [];
const componentIndexByName = new Map();
for (const component of map.components) {
const index = aspectNodes.length;
componentIndexByName.set(component.label, index);
const stage = stageFor(component.coordinates[0], boundaries);
aspectNodes.push({
type: "component",
in: [],
out: [],
props: {
name: component.label,
position: component.coordinates,
evolutionStage: stage,
...kStageDescriptions[stage - 1],
},
});
}
for (const dep of map.dependencies) {
const from = componentIndexByName.get(dep.from);
const to = componentIndexByName.get(dep.to);
if (from === undefined || to === undefined) continue;
const forwardIndex = rels.length;
rels.push({ type: "depends on", from, to, props: {} });
aspectNodes[from].out.push(forwardIndex);
aspectNodes[to].in.push(forwardIndex);
}
for (const inertia of map.inertias) {
const targetIndex = componentIndexByName.get(inertia.component);
if (targetIndex === undefined) continue;
const inertiaIndex = aspectNodes.length;
aspectNodes.push({
type: "inertia",
in: [],
out: [],
props: { name: inertia.component },
});
const relIndex = rels.length;
rels.push({
type: "obstructs",
from: inertiaIndex,
to: targetIndex,
props: {},
});
aspectNodes[inertiaIndex].out.push(relIndex);
aspectNodes[targetIndex].in.push(relIndex);
}
for (const evolution of map.evolutions) {
const targetIndex = componentIndexByName.get(evolution.component);
if (targetIndex === undefined) continue;
const [targetX, targetY] = aspectNodes[targetIndex].props.position;
const newX = targetX + evolution.value;
const stage = stageFor(newX, boundaries);
const evolutionIndex = aspectNodes.length;
aspectNodes.push({
type: "evolution of",
in: [],
out: [],
props: {
name: evolution.component,
position: [newX, targetY],
evolutionStage: stage,
...kStageDescriptions[stage - 1],
},
});
const relIndex = rels.length;
rels.push({
type: "evolves from",
from: evolutionIndex,
to: targetIndex,
props: {},
});
aspectNodes[evolutionIndex].out.push(relIndex);
aspectNodes[targetIndex].in.push(relIndex);
}
return [
{
name: findName($element),
graph: { nodes: aspectNodes, rels },
},
];
}
// Returns this map's text with every LINEUP expanded, ready for upstream
// consumers to splice in. Kept as a string (not a parsed map) so the
// downstream wmap-parser only runs once at the top of the chain.
function wmapData(item, $item) {
return expandLineup(item.text, $item);
}
////////////////////////////////////////////////////////////////////////////////
// Internals ///////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
const internals = {
kStyleSheet: "/plugins/wmap/wmap.css",
kDimensions: {
full: {
map: {
mapWidth: 1300,
mapHeight: 1000,
padding: 42,
},
fonts: {},
},
thumbnail: {
map: {
mapWidth: 403,
mapHeight: 310,
padding: 15,
vertexWidth: 8,
vertexHeight: 8,
arrowHeadSize: 3,
stageHeight: 50,
},
fonts: {
axisLabel: 8,
vertexLabel: 9,
note: 9,
},
},
},
// Returns HTML that shows a message in the wiki.
message(text) {
return `
<div class="viewer" data-item="viewer" style="width:98%">
<div style="width:80%; padding:8px; color:gray; background-color:#eee; margin:0 auto; text-align:center">
<i>${text}</i>
</div>
</div>`;
},
// Creates a wmap PNG from text.
renderImage(source, dimensions) {
const parsedText = parse(source);
// Further Improvements. The zoomed version could have a drop down
// to show the different StageTypes and allow one to see the image
// with the different types.
// This could also potentially be in the toolbar that appears
// on hover to also show this in the download. It requires some
// thought on what the right interaction model would be.
return renderToSVG(parsedText, StageType.ACTIVITIES, {
theme: {
sizes: {
...dimensions.map,
},
fonts: {
...dimensions.fonts,
},
},
});
},
// Starts a download of the image.
download(filename, text) {
const svgWithNamespace = text.replace(
"<svg",
'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"',
);
const svgContent = '<?xml version="1.0" encoding="UTF-8"?>\n' + svgWithNamespace;
const blob = new Blob([svgContent], { type: "image/svg+xml" });
const url = URL.createObjectURL(blob);
const element = document.createElement("a");
element.setAttribute("href", url);
element.setAttribute("download", filename);
element.style.display = "none";
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
URL.revokeObjectURL(url);
},
// Replaces the image in a window. Intended for use in a dialog.
replaceImage(window, imageData) {
try {
const $container = window.document.querySelector("main");
$container.innerHTML = imageData;
} catch (error) {
console.error(
"wmap: Could not replace image. The DOM wasn't ready!",
error,
);
}
},
};
/**
* Runs once for each block. Do setup for the block before rendering.
*/
const emit = function emit($item) {
const hasStyleSheet = [...document.styleSheets].some((styleSheet) =>
styleSheet.href?.endsWith(internals.kStyleSheet),
);
if (!hasStyleSheet) {
console.log("Adding wmap stylesheet.");
const link = document.createElement("link");
link.rel = "stylesheet";
link.href = internals.kStyleSheet;
link.type = "text/css";
document.getElementsByTagName("head")[0].appendChild(link);
}
return $item.append(internals.message("Loading Wardley Map"));
};
/**
* Bind to events on the rendered block. Called once per block.
* Convention is that double click opens the editor.
*
* @param {JQuery} $item the HTML element representing the block.
* @param {Object} item the configuration for that particular object.
*/
const bind = function bind($item, item) {
$item.on("dblclick", () => {
return wiki.textEditor($item, item);
});
$item.on("click", "a", (event) => {
const { currentTarget } = event;
const action = currentTarget.dataset?.action;
if (!action) {
return;
}
event.stopPropagation();
event.preventDefault();
switch (action) {
case "download":
{
let imageData = internals.renderImage(
expandLineup(item.text, $item),
internals.kDimensions.full,
);
const slug = $item.parents(".page").attr("id");
internals.download(`${slug}.svg`, imageData);
}
break;
case "zoom":
{
const shouldOpenStandalone = !!event.shiftKey;
const target = shouldOpenStandalone ? "_blank" : "wmap";
const dialog = window.open(
"/plugins/wmap/dialog/#",
target,
"popup,height=600,width=800",
);
if (!dialog || dialog.closed) {
console.error("wmap: Failed to open dialog.");
return;
}
let imageData = internals.renderImage(
expandLineup(item.text, $item),
internals.kDimensions.full,
);
// We *MUST* check both readyState and href, because
// readyState will be complete when it first loads,
// and this will be an empty window.
if (
dialog.document.readyState === "complete" &&
dialog.document.location.href.includes(
"/plugins/wmap/dialog/",
)
) {
internals.replaceImage(dialog, imageData);
} else {
console.info("We not loaded");
dialog.addEventListener(
"load",
() => {
internals.replaceImage(dialog, imageData);
},
{ once: true },
);
}
}
break;
}
});
try {
// Register the source hooks before rendering so any sibling
// binding concurrently can resolve this item via lineup().
const root = $item.get(0);
root.classList.add("aspect-source");
root.classList.add("wmap-source");
root.aspectData = () => aspectData(root, item.text);
root.wmapData = () => wmapData(item, $item);
let thumbnailData = internals.renderImage(
expandLineup(item.text, $item),
internals.kDimensions.thumbnail,
);
$item.find(".viewer").html(`
<article class="wardley-map thumbnail">${thumbnailData}</article>
<nav class="actions">
<menu>
<li><a href="#" data-action="download" title="Download"><img width="18" height="18" alt="download" src='data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24" fill="grey"><g><rect fill="none" height="24" width="24"/></g><g><path d="M5,20h14v-2H5V20z M19,9h-4V3H9v6H5l7,7L19,9z"/></g></svg>'></a></li>
<li><a href="#" data-action="zoom" title="Zoom"><img width="18" height="18" alt="toggle zoom" src='data:image/svg+xml;charset=utf-8,<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" viewBox="0 0 24 24"><g><rect fill="none" height="24" width="24"/></g><g><g><g><path fill="grey" d="M15,3l2.3,2.3l-2.89,2.87l1.42,1.42L18.7,6.7L21,9V3H15z M3,9l2.3-2.3l2.87,2.89l1.42-1.42L6.7,5.3L9,3H3V9z M9,21 l-2.3-2.3l2.89-2.87l-1.42-1.42L5.3,17.3L3,15v6H9z M21,15l-2.3,2.3l-2.87-2.89l-1.42,1.42l2.89,2.87L15,21h6V15z"/></g></g></g></svg>'></a></li>
</menu>
</nav>
`);
$item.find('svg text:gt(7)').on('click', function(event) {
const title = this.innerHTML;
let $page = $item.parents('.page')
wiki.pageHandler.context = wiki.lineup.atKey($page.data('key')).getContext()
wiki.doInternalLink(title, event.shiftKey ? null : $page)
});
} catch (err) {
console.log("Failed to parse wardley map: ", err);
$item.html(internals.message(err.message));
}
};
/**
* On load, attempt to add the emit and bind functions to window, as these
* are called by the wiki plugin manager.
*/
if (typeof window !== "undefined" && window !== null) {
if (!window.plugins.wmap) {
window.plugins.wmap = { emit, bind };
}
}
const expand = function (text) {
return DOMPurify.sanitize(text);
};
export const wmap = typeof window === "undefined" ? { expand } : undefined;
|