/* PowerPoint export of the association network - one slide per attribute. ---------------------------------------------------------------------- Runs inside the generated HTML (build_network.py inlines this file) and in the Node test (tests/test_pptx_export.js). Nothing here touches the page: the page hands in the networks, a text-measuring function and the master file the user picked; out comes the .pptx as bytes. The master is one of the "network masters" (scripts/make_network_masters.py): slide 1 = the template slide (net.card / net.area / net.legend / net.meta), slide 2 = hidden, one picture per country flag ("flag DE | Germany"). Design agreed with JM (trial C, 2026-11-17; chosen 2026-11-23): - dots, not boxes; dot size = category index (as the HTML's node size) - the selected attribute dark in the middle, its name centred below or above its dot on white; every other name and dot equally strong - no box behind the other names; lines kept off the names by the layout - 12pt, else 10pt when the names do not fit - title "Associative network " with the attribute in italics */ (function (root) { 'use strict'; var COLORS = { reward: 'E03E3E', nonreward: '2B7AB2', driver: '2B2B2B', text: '1A1A1A', text2: '6E6E6E', text3: '555555', index: '888888', legend: '333333' }; var EMU = 12700; // per point var IN = 72; // points per inch (the layout's constants are inches) // ---------------------------------------------------------------- labels function wrap(text) { // the HTML's own rule (wrapLabel) var words = String(text).split(/\s+/); if (words.length <= 2) return [text]; var lines = [], line = ''; words.forEach(function (w) { if (line && line.length + w.length + 1 > 15) { lines.push(line); line = w; } else line = line ? line + ' ' + w : w; }); if (line) lines.push(line); return lines; } function labelLines(n, showIdx) { if (n.level === 0) return [n.name + (showIdx ? ' (' + n.cat + ')' : '')]; var l = wrap(n.name); return showIdx ? l.concat(['(' + n.cat + ')']) : l; } // ---------------------------------------------------------------- layout // All positions in inches inside the slide; area = {x, y, w, h} in inches. function permutations(arr) { if (arr.length <= 1) return [arr.slice()]; var out = []; arr.forEach(function (x, i) { var rest = arr.slice(0, i).concat(arr.slice(i + 1)); permutations(rest).forEach(function (p) { out.push([x].concat(p)); }); }); return out; } function parentsOf(nodes, edges, by) { var parents = {}; nodes.forEach(function (n) { parents[n.name] = []; }); edges.forEach(function (e) { if (by[e.a].level === 1) parents[e.b].push(e.a); }); return parents; } /* Sector start: every direct link gets a slice of the ellipse, its own further links sit outside it in the same slice; links shared by two direct links sit between them; then boxes are nudged apart. */ function sectorStart(nodes, edges, seed, A) { var cx = A.x + A.w / 2, cy = A.y + A.h / 2; var by = {}; nodes.forEach(function (n) { by[n.name] = n; }); var parents = parentsOf(nodes, edges, by); var l1 = nodes.filter(function (n) { return n.level === 1; }).map(function (n) { return n.name; }); var l2 = nodes.filter(function (n) { return n.level === 2; }).map(function (n) { return n.name; }); function score(order) { var pos = {}; order.forEach(function (nm, i) { pos[nm] = i; }); var s = 0; l2.forEach(function (c) { var ps = parents[c]; for (var i = 0; i < ps.length; i++) for (var j = i + 1; j < ps.length; j++) { var d = Math.abs(pos[ps[i]] - pos[ps[j]]); d = Math.min(d, order.length - d); s += d - 1; } }); return s; } var order = l1.slice(); if (l1.length > 2) { var best = null; permutations(l1.slice(1)).forEach(function (p) { var o = [l1[0]].concat(p), sc = score(o); if (best === null || sc < best[0]) best = [sc, o]; }); order = best[1]; } var own = {}, weight = {}, tot = 0; order.forEach(function (p) { own[p] = l2.filter(function (c) { return parents[c].length === 1 && parents[c][0] === p; }); weight[p] = 1 + own[p].length; tot += weight[p]; }); var ang = {}, span = {}, a0 = -Math.PI / 2 + seed * 0.21; order.forEach(function (p) { var w = 2 * Math.PI * weight[p] / tot; span[p] = [a0, a0 + w]; ang[p] = a0 + w / 2; a0 += w; }); var RX1 = 0.22 * A.w, RY1 = 0.23 * A.h, RX2 = 0.445 * A.w, RY2 = 0.445 * A.h; nodes[0].x = cx; nodes[0].y = cy; order.forEach(function (p) { by[p].x = cx + RX1 * Math.cos(ang[p]); by[p].y = cy + RY1 * Math.sin(ang[p]); var kids = own[p], lo = span[p][0], hi = span[p][1]; kids.forEach(function (c, k) { var a = lo + (hi - lo) * (k + 1) / (kids.length + 1); by[c].x = cx + RX2 * Math.cos(a); by[c].y = cy + RY2 * Math.sin(a); }); }); l2.forEach(function (c) { var ps = parents[c]; if (ps.length > 1) { var sx = 0, sy = 0; ps.forEach(function (p) { sx += Math.sin(ang[p]); sy += Math.cos(ang[p]); }); var a = Math.atan2(sx, sy); by[c].x = cx + 0.5 * (RX1 + RX2) * Math.cos(a); by[c].y = cy + 0.5 * (RY1 + RY2) * Math.sin(a); } }); // nudge apart: overlapping boxes, and boxes on someone else's line var pad = 0.10; for (var it = 0; it < 800; it++) { var moved = false, i, j; for (i = 0; i < nodes.length; i++) for (j = i + 1; j < nodes.length; j++) { var a = nodes[i], b = nodes[j]; var dx = b.x - a.x, dy = b.y - a.y; var ox = (a.w + b.w) / 2 + pad - Math.abs(dx), oy = (a.h + b.h) / 2 + pad - Math.abs(dy); if (ox > 0 && oy > 0) { moved = true; var ma = a.level === 0 ? 0 : 0.5, mb = b.level === 0 ? 0 : 0.5; if (ma + mb === 0) continue; var t = ma + mb; ma /= t; mb /= t; if (ox * 1.5 < oy) { var s = sign(dx) * ox; a.x -= s * ma; b.x += s * mb; } else { var s2 = sign(dy) * oy; a.y -= s2 * ma; b.y += s2 * mb; } } } edges.forEach(function (e) { var a = by[e.a], b = by[e.b]; nodes.forEach(function (n) { if (n === a || n === b || n.level === 0) return; var vx = b.x - a.x, vy = b.y - a.y, L2 = vx * vx + vy * vy || 1e-6; var u = ((n.x - a.x) * vx + (n.y - a.y) * vy) / L2; if (!(u > 0 && u < 1)) return; var px = a.x + u * vx, py = a.y + u * vy, dx = n.x - px, dy = n.y - py; if (Math.abs(dx) < n.w / 2 + 0.04 && Math.abs(dy) < n.h / 2 + 0.04) { var d = Math.hypot(dx, dy) || 1e-6; n.x += 0.03 * dx / d; n.y += 0.03 * dy / d; moved = true; } }); }); nodes.forEach(function (n) { clampBox(n, A); }); if (!moved) break; } } function sign(v) { return v < 0 ? -1 : 1; } function clampBox(n, A) { n.x = Math.min(Math.max(n.x, A.x + n.w / 2), A.x + A.w - n.w / 2); n.y = Math.min(Math.max(n.y, A.y + n.h / 2), A.y + A.h - n.h / 2); } /* Fruchterman-Reingold from given start positions - the same steps as networkx.spring_layout (trial D was made with it), then rescaled to [-1, 1]. */ function springRelax(nodes, edges, pos, k, iterations) { var n = nodes.length, idx = {}, i, j; nodes.forEach(function (nd, i2) { idx[nd.name] = i2; }); var Aw = []; for (i = 0; i < n; i++) { Aw.push(new Array(n).fill(0)); } edges.forEach(function (e) { var w = 0.6 + e.val / 40, a = idx[e.a], b = idx[e.b]; Aw[a][b] = w; Aw[b][a] = w; // undirected, last weight wins (as networkx) }); var xs = pos.map(function (p) { return p[0]; }), ys = pos.map(function (p) { return p[1]; }); var t = Math.max(Math.max.apply(null, xs) - Math.min.apply(null, xs), Math.max.apply(null, ys) - Math.min.apply(null, ys)) * 0.1; var dt = t / (iterations + 1); for (var it = 0; it < iterations; it++) { var disp = []; for (i = 0; i < n; i++) { var dxs = 0, dys = 0; for (j = 0; j < n; j++) { if (i === j) continue; var dx = pos[i][0] - pos[j][0], dy = pos[i][1] - pos[j][1]; var d = Math.max(Math.hypot(dx, dy), 0.01); var f = k * k / (d * d) - Aw[i][j] * d / k; dxs += dx * f; dys += dy * f; } disp.push([dxs, dys]); } var err = 0; for (i = 0; i < n; i++) { var len = Math.hypot(disp[i][0], disp[i][1]); if (len < 0.01) len = 0.1; var mx = disp[i][0] * t / len, my = disp[i][1] * t / len; pos[i][0] += mx; pos[i][1] += my; err += Math.hypot(mx, my); } t -= dt; if (err / n < 1e-4) break; } var mxx = 0, myy = 0; pos.forEach(function (p) { mxx += p[0]; myy += p[1]; }); mxx /= n; myy /= n; var lim = 0; pos.forEach(function (p) { p[0] -= mxx; p[1] -= myy; lim = Math.max(lim, Math.abs(p[0]), Math.abs(p[1])); }); if (lim > 0) pos.forEach(function (p) { p[0] /= lim; p[1] /= lim; }); return pos; } var GAP = 0.06; // dot -> label, inches function placeLabels(nodes, cx, cy) { nodes.forEach(function (n) { var d = n.d; if (n.fixedSide) n.side = n.fixedSide; else if (n.level === 0) n.side = 'below'; else { var dx = n.x - cx, dy = (n.y - cy) * 2.4; n.side = dx >= 0 ? 'right' : 'left'; if (Math.abs(dx) < Math.abs(dy) * 0.35) n.side = dy > 0 ? 'below' : 'above'; } if (n.side === 'right') { n.lx = n.x + d / 2 + GAP; n.ly = n.y - n.lh / 2; } else if (n.side === 'left') { n.lx = n.x - d / 2 - GAP - n.lw; n.ly = n.y - n.lh / 2; } else if (n.side === 'below') { n.lx = n.x - n.lw / 2; n.ly = n.y + d / 2 + 0.01; } else { n.lx = n.x - n.lw / 2; n.ly = n.y - d / 2 - 0.01 - n.lh; } }); } function bbox(n) { var d = n.d; return [Math.min(n.x - d / 2, n.lx), Math.min(n.y - d / 2, n.ly), Math.max(n.x + d / 2, n.lx + n.lw), Math.max(n.y + d / 2, n.ly + n.lh)]; } /* One attempt: sector start -> spring -> nudge dots + names apart. Returns the score: 1 per collision, 0.3 per line running through a name. */ function attempt(nodes, edges, seed, A) { var by = {}; nodes.forEach(function (n) { by[n.name] = n; }); nodes.forEach(function (n) { n.w = n.lw + n.d; n.h = n.lh; }); sectorStart(nodes, edges, seed, A); var cx = A.x + A.w / 2, cy = A.y + A.h / 2, norm = A.w / 2.04; var pos = nodes.map(function (n) { return [(n.x - cx) / norm, (n.y - cy) / norm]; }); springRelax(nodes, edges, pos, 1.1 / Math.sqrt(nodes.length), 25 + 10 * seed); var r = pos[0]; var pts = pos.map(function (p) { return [p[0] - r[0], p[1] - r[1]]; }); var mx = Math.max.apply(null, pts.map(function (p) { return Math.abs(p[0]); })) || 1; var my = Math.max.apply(null, pts.map(function (p) { return Math.abs(p[1]); })) || 1; nodes.forEach(function (n, i) { n.x = cx + pts[i][0] / mx * A.w / 2 * 0.80; n.y = cy + pts[i][1] / my * A.h / 2 * 0.82; }); var x1 = A.x + A.w, y1 = A.y + A.h; var N = nodes.length, E = edges.map(function (e) { return [by[e.a], by[e.b]]; }); var B0 = new Float64Array(N), B1 = new Float64Array(N), B2 = new Float64Array(N), B3 = new Float64Array(N); function boxes() { for (var q = 0; q < N; q++) { var n = nodes[q], d2 = n.d / 2; B0[q] = Math.min(n.x - d2, n.lx); B1[q] = Math.min(n.y - d2, n.ly); B2[q] = Math.max(n.x + d2, n.lx + n.lw); B3[q] = Math.max(n.y + d2, n.ly + n.lh); } } for (var it = 0; it < 900; it++) { placeLabels(nodes, cx, cy); boxes(); var moved = false, i, j, k; for (i = 0; i < N; i++) for (j = i + 1; j < N; j++) { var ox = Math.min(B2[i], B2[j]) - Math.max(B0[i], B0[j]) + 0.08; if (ox <= 0) continue; var oy = Math.min(B3[i], B3[j]) - Math.max(B1[i], B1[j]) + 0.06; if (oy <= 0) continue; var a = nodes[i], b = nodes[j]; moved = true; var wa = a.level === 0 ? 0 : 1, wb = b.level === 0 ? 0 : 1, t = wa + wb; wa /= t; wb /= t; if (ox < oy * 1.3) { var s = sign((B0[j] + B2[j]) - (B0[i] + B2[i])) * Math.min(ox, 0.05); a.x -= s * wa; b.x += s * wb; } else { var s2 = sign((B1[j] + B3[j]) - (B1[i] + B3[i])) * Math.min(oy, 0.05); a.y -= s2 * wa; b.y += s2 * wb; } } for (k = 0; k < E.length; k++) { var ea = E[k][0], eb = E[k][1]; var sx0 = Math.min(ea.x, eb.x) - 0.03, sx1 = Math.max(ea.x, eb.x) + 0.03; var sy0 = Math.min(ea.y, eb.y) - 0.03, sy1 = Math.max(ea.y, eb.y) + 0.03; var vx = eb.x - ea.x, vy = eb.y - ea.y, L2 = vx * vx + vy * vy || 1e-6; for (i = 0; i < N; i++) { var n = nodes[i]; if (n === ea || n === eb || n.level === 0) continue; if (B2[i] < sx0 || B0[i] > sx1 || B3[i] < sy0 || B1[i] > sy1) continue; // nowhere near the line var mx_ = (B0[i] + B2[i]) / 2, my_ = (B1[i] + B3[i]) / 2; var u = ((mx_ - ea.x) * vx + (my_ - ea.y) * vy) / L2; if (!(u > 0.03 && u < 0.97)) continue; var px = ea.x + u * vx, py = ea.y + u * vy; if (B0[i] - 0.03 < px && px < B2[i] + 0.03 && B1[i] - 0.03 < py && py < B3[i] + 0.03) { var dx = mx_ - px, dy = my_ - py, dd = Math.hypot(dx, dy) || 1e-6; n.x += 0.025 * dx / dd; n.y += 0.025 * dy / dd; moved = true; } } } boxes(); for (i = 0; i < N; i++) { var m = nodes[i]; if (B0[i] < A.x) m.x += A.x - B0[i]; if (B2[i] > x1) m.x -= B2[i] - x1; if (B1[i] < A.y) m.y += A.y - B1[i]; if (B3[i] > y1) m.y -= B3[i] - y1; } if (!moved) break; } placeLabels(nodes, cx, cy); chooseSides(nodes, edges, by, A, cx, cy); keepInside(nodes, A); return defects(nodes, edges, by); } /* Each name goes on the side of its dot where no line - its own included - runs through it, no other dot or name sits and it stays inside the area. */ var SIDES = ['right', 'left', 'below', 'above']; function sideCost(n, nodes, edges, by, A) { var bx = bbox(n), cost = 0; var lab = [n.lx, n.ly, n.lx + n.lw, n.ly + n.lh]; if (bx[0] < A.x - 0.01 || bx[2] > A.x + A.w + 0.01 || bx[1] < A.y - 0.01 || bx[3] > A.y + A.h + 0.01) cost += 50; // a name never leaves the area nodes.forEach(function (o) { if (o === n) return; var bo = bbox(o); if (Math.min(bx[2], bo[2]) > Math.max(bx[0], bo[0]) && Math.min(bx[3], bo[3]) > Math.max(bx[1], bo[1])) cost += 3; }); edges.forEach(function (e) { var a = by[e.a], b = by[e.b]; if (segHitsRect(a.x, a.y, b.x, b.y, lab)) cost += 1; }); return cost; } function chooseSides(nodes, edges, by, A, cx, cy) { for (var pass = 0; pass < 2; pass++) { nodes.forEach(function (n) { // the selected attribute's name stays centred on its dot: below or above (JM, 2026-11-23) var keep = n.side, best = [sideCost(n, nodes, edges, by, A) - 0.01, keep]; (n.level === 0 ? ['below', 'above'] : SIDES).forEach(function (s) { if (s === keep) return; n.fixedSide = s; placeLabels([n], cx, cy); var c = sideCost(n, nodes, edges, by, A); if (c < best[0]) best = [c, s]; }); n.fixedSide = best[1]; placeLabels([n], cx, cy); }); } nodes.forEach(function (n) { n.fixedSide = null; }); } /* Last step: a dot whose name still sticks out of the area moves in, name and all (JM 2026-11-30: names ran into the legend and the subline). */ function keepInside(nodes, A) { nodes.forEach(function (n) { var b = bbox(n), dx = 0, dy = 0; if (b[0] < A.x) dx = A.x - b[0]; else if (b[2] > A.x + A.w) dx = A.x + A.w - b[2]; if (b[1] < A.y) dy = A.y - b[1]; else if (b[3] > A.y + A.h) dy = A.y + A.h - b[3]; n.x += dx; n.lx += dx; n.y += dy; n.ly += dy; }); } /* Does the segment a-b cross the rectangle r = [x0, y0, x1, y1]? (Liang-Barsky) */ function segHitsRect(ax, ay, bx, by_, r) { var t0 = 0, t1 = 1, dx = bx - ax, dy = by_ - ay; var p = [-dx, dx, -dy, dy], q = [ax - r[0], r[2] - ax, ay - r[1], r[3] - ay]; for (var i = 0; i < 4; i++) { if (p[i] === 0) { if (q[i] < 0) return false; continue; } var t = q[i] / p[i]; if (p[i] < 0) { if (t > t1) return false; if (t > t0) t0 = t; } else { if (t < t0) return false; if (t < t1) t1 = t; } } return t1 > t0 + 0.025 && t0 < 0.975; // as the old sampling: ends just at a dot don't count } function defects(nodes, edges, by) { var bad = 0, i, j; for (i = 0; i < nodes.length; i++) for (j = i + 1; j < nodes.length; j++) { var ba = bbox(nodes[i]), bb = bbox(nodes[j]); if (Math.min(ba[2], bb[2]) > Math.max(ba[0], bb[0]) && Math.min(ba[3], bb[3]) > Math.max(ba[1], bb[1])) bad += 1; } edges.forEach(function (e) { var a = by[e.a], b = by[e.b]; nodes.forEach(function (n) { if (n === a || n === b) return; if (segHitsRect(a.x, a.y, b.x, b.y, bbox(n))) bad += 0.3; }); }); return bad; } /* Lay out one network inside area (points). measure(text, pt, bold) -> width in points. Returns {nodes, edges, pt, score}; positions in points. */ function layoutNetwork(net, areaPt, measure, opts) { opts = opts || {}; var showIdx = opts.showIdx !== false, seeds = opts.seeds || 30; // [selected + direct links, further links] in pt; the second pair is the fallback // style 'C' (default, JM's choice): every name and dot equally strong. // style 'D' (trial only): further links smaller, grey, paler. var flat = opts.style !== 'D'; var sizes = flat ? [[12, 12], [10, 10]] : (opts.sizes || [[12, 10], [10, 10]]); var A = { x: areaPt.x / IN, y: areaPt.y / IN, w: areaPt.w / IN, h: areaPt.h / IN }; // every field up front, one object shape (fast property access in the loops) var nodes = net.nodes.map(function (n) { return { name: n.name, level: n.level, cat: n.cat, reward: n.reward, x: 0, y: 0, d: 0, w: 0, h: 0, lx: 0, ly: 0, lw: 0, lh: 0, pt: 0, lines: null, side: 'right', fixedSide: null }; }); var edges = net.edges; var cats = nodes.map(function (n) { return n.cat; }); var cmin = Math.min.apply(null, cats), cmax = Math.max.apply(null, cats); var result = null; sizes.some(function (sz) { var pt = sz[0]; nodes.forEach(function (n) { var f = (n.cat - cmin) / Math.max(1, cmax - cmin); n.d = n.level === 0 ? 0.42 : flat ? 0.14 + 0.16 * f : n.level === 1 ? 0.18 + 0.16 * f : 0.10 + 0.12 * f; n.lines = labelLines(n, showIdx); n.pt = n.level <= 1 ? sz[0] : sz[1]; var bold = n.level <= 1; var wmax = 0; n.lines.forEach(function (t) { wmax = Math.max(wmax, measure(t, n.pt, bold && t.charAt(0) !== '(')); }); n.lw = wmax / IN + 0.02; n.lh = n.lines.length * n.pt * 1.15 / IN + 0.02; }); var best = null; for (var seed = 0; seed < seeds; seed++) { var sc = attempt(nodes, edges, seed, A); if (best === null || sc < best[0]) best = [sc, seed]; if (sc === 0) break; } if (best[1] !== seeds - 1 || best[0] !== 0) attempt(nodes, edges, best[1], A); result = { pt: pt, score: best[0], seed: best[1] }; return best[0] < 1; // 12pt unless names or dots really collide }); nodes.forEach(function (n) { ['x', 'y', 'd', 'lx', 'ly', 'lw', 'lh'].forEach(function (k) { n[k] *= IN; }); }); result.nodes = nodes; result.edges = edges; result.style = flat ? 'C' : 'D'; return result; } // ---------------------------------------------------------------- XML function esc(s) { return String(s).replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); } function e(pt) { return Math.round(pt * EMU); } function fill(rgb, alpha) { return '' + (alpha != null && alpha < 1 ? '' : '') + ''; } function xfrm(x, y, w, h, flipH, flipV) { return ''; } function run(text, o) { return '' + (o.color ? fill(o.color) : '') + '' + esc(text) + ''; } function dotXml(id, n, flat) { var kind = n.reward ? COLORS.reward : COLORS.nonreward; return '' + '' + xfrm(n.x - n.d / 2, n.y - n.d / 2, n.d, n.d) + '' + fill(n.level === 0 ? COLORS.driver : kind, n.level === 2 && !flat ? 0.55 : 1) + '' + fill('FFFFFF') + '' + ''; } function labelXml(id, n, flat) { var algn = n.side === 'right' ? 'l' : n.side === 'left' ? 'r' : 'ctr'; var paras = n.lines.map(function (t) { var idx = t.charAt(0) === '('; return '' + run(t, { pt: n.pt, b: n.level <= 1 && !idx, color: idx ? COLORS.index : n.level <= 1 ? COLORS.text : flat ? COLORS.text3 : COLORS.text2 }) + ''; }).join(''); return '' + // the selected attribute's name on white, so a line behind it never cuts through it '' + xfrm(n.lx, n.ly, n.lw, n.lh) + '' + (n.level === 0 ? fill('FFFFFF') : '') + '' + '' + paras + ''; } function lineXml(id, ed, a, b, minC, maxC, flat) { var norm = maxC > minC ? (ed.val - minC) / (maxC - minC) : 0.5; norm = Math.max(0, Math.min(1, norm)); var outer = b.level === 2 && !flat; var w = outer ? 0.5 + norm * 3 : 0.75 + norm * 5; var alpha = (0.35 + norm * 0.6) * (outer ? 0.55 : 1); var x = Math.min(a.x, b.x), y = Math.min(a.y, b.y); return '' + '' + xfrm(x, y, Math.abs(b.x - a.x), Math.abs(b.y - a.y), b.x < a.x, b.y < a.y) + '' + fill(a.reward ? COLORS.reward : COLORS.nonreward, alpha) + ''; } // ---------------------------------------------------------------- package var NS = { p: 'http://schemas.openxmlformats.org/presentationml/2006/main', a: 'http://schemas.openxmlformats.org/drawingml/2006/main', r: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships', rel: 'http://schemas.openxmlformats.org/package/2006/relationships', ct: 'http://schemas.openxmlformats.org/package/2006/content-types' }; function parse(xml, P) { return new P().parseFromString(xml, 'application/xml'); } function kids(el, ns, local) { var out = []; for (var c = el.firstChild; c; c = c.nextSibling) if (c.nodeType === 1 && c.namespaceURI === ns && c.localName === local) out.push(c); return out; } function all(el, ns, local) { return Array.prototype.slice.call(el.getElementsByTagNameNS(ns, local)); } function relsPath(part) { var i = part.lastIndexOf('/'); return part.slice(0, i) + '/_rels/' + part.slice(i + 1) + '.rels'; } function resolve(fromPart, target) { var parts = fromPart.split('/'); parts.pop(); target.split('/').forEach(function (t) { if (t === '..') parts.pop(); else if (t !== '.') parts.push(t); }); return parts.join('/'); } function shapeName(sp) { var c = all(sp, NS.p, 'cNvPr')[0]; return c ? c.getAttribute('name') : ''; } function phType(sp) { var ph = all(sp, NS.p, 'ph')[0]; return ph ? (ph.getAttribute('type') || 'body') : null; } function spText(sp) { return all(sp, NS.a, 't').map(function (t) { return t.textContent; }).join(''); } /* Replace a shape's text by runs, keeping the first paragraph's properties and the first run's properties (font, size, colour stay the master's). */ function setRuns(doc, sp, runs) { var body = all(sp, NS.p, 'txBody')[0]; if (!body) return; var paras = kids(body, NS.a, 'p'); var keepP = paras.length ? kids(paras[0], NS.a, 'pPr')[0] : null; var r0 = paras.length ? all(paras[0], NS.a, 'rPr')[0] : null; paras.forEach(function (p) { body.removeChild(p); }); var p = doc.createElementNS(NS.a, 'a:p'); if (keepP) p.appendChild(keepP.cloneNode(true)); runs.forEach(function (r) { var re = doc.createElementNS(NS.a, 'a:r'); var rp = r0 ? r0.cloneNode(true) : doc.createElementNS(NS.a, 'a:rPr'); if (!rp.getAttribute('lang')) rp.setAttribute('lang', 'en-US'); if (r.i) rp.setAttribute('i', '1'); else rp.removeAttribute('i'); if (r.pt) rp.setAttribute('sz', String(Math.round(r.pt * 100))); if (r.color) { kids(rp, NS.a, 'solidFill').forEach(function (f) { rp.removeChild(f); }); var sf = doc.createElementNS(NS.a, 'a:solidFill'), clr = doc.createElementNS(NS.a, 'a:srgbClr'); clr.setAttribute('val', r.color); sf.appendChild(clr); // a:solidFill goes after a:ln (if any), before the fonts var ln = kids(rp, NS.a, 'ln')[0]; rp.insertBefore(sf, ln ? ln.nextSibling : rp.firstChild); } re.appendChild(rp); var t = doc.createElementNS(NS.a, 'a:t'); t.textContent = r.text; re.appendChild(t); p.appendChild(re); }); body.appendChild(p); } function imageSize(bytes) { var b = bytes; if (b[0] === 0x89 && b[1] === 0x50) return [(b[16] << 24 | b[17] << 16 | b[18] << 8 | b[19]) >>> 0, (b[20] << 24 | b[21] << 16 | b[22] << 8 | b[23]) >>> 0]; if (b[0] === 0xFF && b[1] === 0xD8) { var i = 2; while (i < b.length) { if (b[i] !== 0xFF) { i++; continue; } var m = b[i + 1], len = b[i + 2] << 8 | b[i + 3]; if (m >= 0xC0 && m <= 0xCF && m !== 0xC4 && m !== 0xC8 && m !== 0xCC) return [b[i + 7] << 8 | b[i + 8], b[i + 5] << 8 | b[i + 6]]; i += 2 + len; } } if (b[0] === 0x47 && b[1] === 0x49) return [b[6] | b[7] << 8, b[8] | b[9] << 8]; return null; } /* Read a picked master: checks it is a network master, returns what the export dialog needs (frame, flags) and keeps the zip for build(). */ /* "12:10,10:10" -> [[12, 10], [10, 10]] (net.meta `sizes`) */ function sizesOf(M) { var s = (M.meta && M.meta.sizes) || '12:10,10:10'; return s.split(',').map(function (p) { return p.split(':').map(Number); }); } function openMaster(JSZip, data, env) { return JSZip.loadAsync(data).then(function (zip) { var M = { zip: zip, env: env }; return zip.file('ppt/presentation.xml').async('string').then(function (pres) { M.pres = pres; return zip.file('ppt/_rels/presentation.xml.rels').async('string'); }).then(function (prels) { M.prels = prels; var pdoc = parse(M.pres, env.DOMParser), rdoc = parse(prels, env.DOMParser); var rid2t = {}; all(rdoc, NS.rel, 'Relationship').forEach(function (r) { rid2t[r.getAttribute('Id')] = r.getAttribute('Target'); }); M.slides = all(pdoc, NS.p, 'sldId').map(function (s) { return 'ppt/' + rid2t[s.getAttributeNS(NS.r, 'id')].replace(/^\//, '').replace(/^ppt\//, ''); }); if (M.slides.length !== 2) throw new Error('This is not a network master (it has ' + M.slides.length + ' slides, a network master has 2). Please pick a file from "Input\\network masters".'); return Promise.all([zip.file(M.slides[0]).async('string'), zip.file(relsPath(M.slides[0])).async('string'), zip.file(M.slides[1]).async('string'), zip.file(relsPath(M.slides[1])).async('string')]); }).then(function (x) { M.tpl = x[0]; M.tplRels = x[1]; var tdoc = parse(M.tpl, env.DOMParser); var meta = null; all(tdoc, NS.p, 'sp').forEach(function (sp) { if (shapeName(sp) === 'net.meta') meta = all(sp, NS.a, 'p').map(function (p) { return all(p, NS.a, 't').map(function (t) { return t.textContent; }).join(''); }); }); if (!meta) throw new Error('This is not a network master (no network template slide). Please pick a file from "Input\\network masters".'); M.meta = {}; meta.forEach(function (l) { var i = l.indexOf('='); if (i > 0) M.meta[l.slice(0, i)] = l.slice(i + 1); }); all(tdoc, NS.p, 'sp').forEach(function (sp) { var nm = shapeName(sp); if (nm === 'net.area' || nm === 'net.legend') { var off = all(sp, NS.a, 'off')[0], ext = all(sp, NS.a, 'ext')[0]; M[nm === 'net.area' ? 'area' : 'legend'] = { x: +off.getAttribute('x') / EMU, y: +off.getAttribute('y') / EMU, w: +ext.getAttribute('cx') / EMU, h: +ext.getAttribute('cy') / EMU }; } }); // the flags: picture name "flag DE | Germany" -> media part var fdoc = parse(x[2], env.DOMParser), frels = parse(x[3], env.DOMParser), rid2t = {}; all(frels, NS.rel, 'Relationship').forEach(function (r) { rid2t[r.getAttribute('Id')] = r.getAttribute('Target'); }); M.flags = []; all(fdoc, NS.p, 'pic').forEach(function (pic) { var m = /^flag ([A-Z]{2}) \| (.*)$/.exec(shapeName(pic)); var blip = all(pic, NS.a, 'blip')[0]; if (m && blip) M.flags.push({ code: m[1], name: m[2], part: resolve(M.slides[1], rid2t[blip.getAttributeNS(NS.r, 'embed')]) }); }); return M; }); }); } /* Guess the flag from the project's country (code or English name) - only a suggestion; the dialog shows it and the user confirms or changes it. */ function suggestFlag(M, country) { var c = String(country || '').trim().toLowerCase(); if (!c) return ''; c = { uk: 'gb', 'great britain': 'gb', england: 'gb', usa: 'us', 'united states': 'us' }[c] || c; var hit = M.flags.filter(function (f) { return f.code.toLowerCase() === c || f.name.toLowerCase() === c; })[0]; return hit ? hit.code : ''; } /* Build the deck. settings: {sample, flag (code or ''), footer, legendRuns}; nets: [{attr, net}] already laid out by layoutNetwork. */ function buildDeck(M, nets, settings, minC, maxC) { var zip = M.zip, env = M.env, P = env.DOMParser, S = env.XMLSerializer; var flag = settings.flag ? M.flags.filter(function (f) { return f.code === settings.flag; })[0] : null; var footnote = M.meta.footnote === '1'; // Henkel, REWE: "Base: ..." line var legendPt = +M.meta.legend_pt || 8; var ctDoc, presDoc = parse(M.pres, P), prelDoc = parse(M.prels, P); var flagBytes = null; return zip.file('[Content_Types].xml').async('string').then(function (ct) { ctDoc = parse(ct, P); return flag ? zip.file(flag.part).async('uint8array') : null; }).then(function (fb) { flagBytes = fb; var existing = Object.keys(zip.files).filter(function (f) { return /^ppt\/slides\/slide\d+\.xml$/.test(f); }) .map(function (f) { return +/(\d+)\.xml$/.exec(f)[1]; }); var nextNo = Math.max.apply(null, existing) + 1; var sldIdLst = all(presDoc, NS.p, 'sldIdLst')[0]; var maxId = 255; all(presDoc, NS.p, 'sldId').forEach(function (s) { maxId = Math.max(maxId, +s.getAttribute('id')); }); var relRoot = prelDoc.documentElement, maxRid = 0; all(prelDoc, NS.rel, 'Relationship').forEach(function (r) { var m = /^rId(\d+)$/.exec(r.getAttribute('Id')); if (m) maxRid = Math.max(maxRid, +m[1]); }); // drop template + flags slides from the show (their parts go below) var oldIds = all(presDoc, NS.p, 'sldId'); var oldRids = oldIds.map(function (s) { return s.getAttributeNS(NS.r, 'id'); }); oldIds.forEach(function (s) { sldIdLst.removeChild(s); }); all(prelDoc, NS.rel, 'Relationship').forEach(function (r) { if (oldRids.indexOf(r.getAttribute('Id')) >= 0) relRoot.removeChild(r); }); nets.forEach(function (item, k) { var no = nextNo + k, part = 'ppt/slides/slide' + no + '.xml'; var doc = parse(M.tpl, P), rdoc = parse(M.tplRels, P); var tree = all(doc, NS.p, 'spTree')[0]; var maxShape = 1; all(doc, NS.p, 'cNvPr').forEach(function (c) { maxShape = Math.max(maxShape, +c.getAttribute('id') || 0); }); var id = maxShape + 1; // texts and pictures of the frame Array.prototype.slice.call(tree.childNodes).forEach(function (sp) { if (sp.nodeType !== 1) return; var nm = shapeName(sp), ph = phType(sp); if (nm === 'net.meta' || nm === 'net.area') { tree.removeChild(sp); return; } if (ph === 'title') setRuns(doc, sp, [{ text: 'Associative network ' }, { text: item.attr, i: true }]); // by name first: on REWE the base line is itself a text placeholder else if (nm === 'update_sample') setRuns(doc, sp, [{ text: footnote ? 'Base: ' + settings.sample : settings.sample }]); else if (ph === 'body') setRuns(doc, sp, [{ text: 'Associative Network' }]); else if (ph === 'ftr' && settings.footer) setRuns(doc, sp, [{ text: settings.footer }]); else if (nm === 'net.legend') setRuns(doc, sp, settings.legendRuns.map(function (r) { return { text: r.text, color: r.color, pt: legendPt }; })); else if (nm === 'viz.logo') { if (!flag) { tree.removeChild(sp); return; } var blip = all(sp, NS.a, 'blip')[0]; var rel = rdoc.createElementNS(NS.rel, 'Relationship'); rel.setAttribute('Id', 'rIdFlag'); rel.setAttribute('Type', NS.r + '/image'); rel.setAttribute('Target', '../media/' + flag.part.split('/').pop()); rdoc.documentElement.appendChild(rel); blip.setAttributeNS(NS.r, 'r:embed', 'rIdFlag'); var dims = imageSize(flagBytes); if (dims && dims[0] && dims[1]) { // width kept, height by the flag's aspect, about the slot's centre var off = all(sp, NS.a, 'off')[0], ext = all(sp, NS.a, 'ext')[0]; var cx = +ext.getAttribute('cx'), cy = +ext.getAttribute('cy'), y = +off.getAttribute('y'); var h = Math.round(cx * dims[1] / dims[0]); off.setAttribute('y', String(Math.round(y + cy / 2 - h / 2))); ext.setAttribute('cy', String(h)); } } }); // the network: lines, then dots, then names - on top of the card var net = item.net, by = {}, xml = []; net.nodes.forEach(function (n) { by[n.name] = n; }); var flat = net.style === 'C'; net.edges.forEach(function (ed) { xml.push(lineXml(id++, ed, by[ed.a], by[ed.b], minC, maxC, flat)); }); net.nodes.forEach(function (n) { xml.push(dotXml(id++, n, flat)); }); net.nodes.forEach(function (n) { xml.push(labelXml(id++, n, flat)); }); var frag = parse('' + xml.join('') + '', P); Array.prototype.slice.call(frag.documentElement.childNodes).forEach(function (c) { tree.appendChild(doc.importNode(c, true)); }); zip.file(part, new S().serializeToString(doc)); zip.file(relsPath(part), new S().serializeToString(rdoc)); var ov = ctDoc.createElementNS(NS.ct, 'Override'); ov.setAttribute('PartName', '/' + part); ov.setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml'); ctDoc.documentElement.appendChild(ov); var rid = 'rId' + (++maxRid); var r = prelDoc.createElementNS(NS.rel, 'Relationship'); r.setAttribute('Id', rid); r.setAttribute('Type', NS.r + '/slide'); r.setAttribute('Target', 'slides/slide' + no + '.xml'); relRoot.appendChild(r); var sid = presDoc.createElementNS(NS.p, 'p:sldId'); sid.setAttribute('id', String(++maxId)); sid.setAttributeNS(NS.r, 'r:id', rid); sldIdLst.appendChild(sid); }); // remove the template and the flags slides M.slides.forEach(function (part) { zip.remove(part); zip.remove(relsPath(part)); all(ctDoc, NS.ct, 'Override').forEach(function (o) { if (o.getAttribute('PartName') === '/' + part) ctDoc.documentElement.removeChild(o); }); }); zip.file('ppt/presentation.xml', new S().serializeToString(presDoc)); zip.file('ppt/_rels/presentation.xml.rels', new S().serializeToString(prelDoc)); zip.file('[Content_Types].xml', new S().serializeToString(ctDoc)); // flag pictures nobody shows any more leave the file var relFiles = Object.keys(zip.files).filter(function (f) { return /\.rels$/.test(f); }); return Promise.all(relFiles.map(function (f) { return zip.file(f).async('string'); })).then(function (texts) { var used = {}; texts.forEach(function (t, i) { var re = /Target="([^"]+)"/g, m; while ((m = re.exec(t))) used[resolve(relFiles[i].replace('/_rels/', '/').replace(/\.rels$/, ''), m[1])] = 1; }); M.flags.forEach(function (f) { if (!used[f.part]) zip.remove(f.part); }); return zip.generateAsync({ type: env.outputType || 'blob', compression: 'DEFLATE', mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' }); }); }); } /* meta: the master's net.meta - term_emotional / term_functional are the client's own words from the reporting tool (Henkel: psychological). */ function legendRuns(showIdx, meta) { var emo = (meta && meta.term_emotional) || 'emotional', fun = (meta && meta.term_functional) || 'functional'; return [{ text: '● ', color: COLORS.reward }, { text: emo + ' ', color: COLORS.legend }, { text: '● ', color: COLORS.nonreward }, { text: fun + ' ', color: COLORS.legend }, { text: (showIdx ? 'dot size & (…) = category index' : 'dot size = category index') + ' · line thickness = strength of connection', color: COLORS.legend }]; } var api = { sizesOf: sizesOf, wrap: wrap, layoutNetwork: layoutNetwork, openMaster: openMaster, suggestFlag: suggestFlag, buildDeck: buildDeck, legendRuns: legendRuns, imageSize: imageSize }; if (typeof module !== 'undefined' && module.exports) module.exports = api; else root.NetPptx = api; })(this);