DecodeMarketing commited on
Commit
49bcc18
·
unverified ·
1 Parent(s): 9c71687

feat: export every attribute's network to PowerPoint from the HTML (#6)

Browse files

Teams exported one PNG per attribute by hand. The HTML now writes one
native slide per listed attribute (dots, names, lines; style C agreed
with JM) on the client's own master: DECODE/P&G, Henkel or REWE.

The masters stay out of the repo and the public Space: users pick the
"network masters" folder once, the browser remembers it.
scripts/make_network_masters.py builds the masters from the reporting
tool's frames.

.gitignore CHANGED
@@ -4,3 +4,8 @@ __pycache__/
4
  # Claude Code reviewer artifacts — session-local, never commit
5
  .decode-reviewer-clean
6
  .decode-reviewer-findings.md
 
 
 
 
 
 
4
  # Claude Code reviewer artifacts — session-local, never commit
5
  .decode-reviewer-clean
6
  .decode-reviewer-findings.md
7
+
8
+ # JM inputs and test outputs (client data) - never commit
9
+ Input/
10
+ *.pptx
11
+ test - *
Dockerfile CHANGED
@@ -11,7 +11,7 @@ RUN apt-get update && apt-get install -y \
11
  COPY requirements.txt ./
12
  RUN pip3 install -r requirements.txt
13
 
14
- COPY app.py config.py parse_excel.py build_network.py ./
15
 
16
  EXPOSE 8501
17
 
 
11
  COPY requirements.txt ./
12
  RUN pip3 install -r requirements.txt
13
 
14
+ COPY app.py config.py parse_excel.py build_network.py pptx_export.js pptx_export_ui.js ./
15
 
16
  EXPOSE 8501
17
 
build_network.py CHANGED
@@ -2,12 +2,21 @@
2
 
3
  import html
4
  import json
 
5
 
6
  import numpy as np
7
 
8
  from config import COLORS
9
 
10
 
 
 
 
 
 
 
 
 
11
  def _safe_json(obj):
12
  """JSON-encode and escape </script> sequences for safe embedding in HTML."""
13
  return json.dumps(obj).replace('</','<\\/')
@@ -125,6 +134,8 @@ def generate_network_html(network_data, threshold, max_l1_nodes,
125
  avg_corr=avg_corr,
126
  default_max_l1=default_max_l1,
127
  show_category_index=show_category_index,
 
 
128
  )
129
 
130
  stats = {
@@ -147,7 +158,7 @@ def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta,
147
  driver_list, nonrewards_list, threshold, min_corr,
148
  max_corr, attribute_count, reward_drivers,
149
  nonreward_drivers, corr_count, avg_corr,
150
- default_max_l1, show_category_index):
151
  """Build the standalone HTML string. Separated for readability."""
152
 
153
  # Escape all user-supplied strings for safe HTML embedding
@@ -160,6 +171,8 @@ def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta,
160
  meta_json = _safe_json(attr_meta)
161
  drivers_json = _safe_json(driver_list)
162
  nonrewards_json = _safe_json(nonrewards_list)
 
 
163
 
164
  return f"""<!DOCTYPE html>
165
  <html lang="en">
@@ -168,6 +181,7 @@ def _build_html_template(*, chart_title, header_title, sparse_corr, attr_meta,
168
  <title>{safe_title} — Association Network</title>
169
  <link type="text/css" href="https://unpkg.com/vis-network@9.1.9/dist/dist/vis-network.min.css" rel="stylesheet" />
170
  <script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
 
171
  <style>
172
  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
173
  body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }}
@@ -238,6 +252,19 @@ body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans
238
  .tab-btn {{ padding: 6px 14px; font-size: 12px; font-weight: 500; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; color: #555; transition: all 0.15s; }}
239
  .tab-btn:hover {{ background: #f0f0f0; }}
240
  .tab-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
 
 
 
 
 
 
 
 
 
 
 
 
 
241
 
242
  .details-panel {{ position: absolute; bottom: 0; left: 0; right: 0; z-index: 20; background: #fff; border-top: 1px solid #e0e0e0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08); transform: translateY(100%); transition: transform 0.25s ease; max-height: 45vh; overflow-y: auto; }}
243
  .details-panel.open {{ transform: translateY(0); }}
@@ -284,6 +311,8 @@ var THRESHOLD = {threshold};
284
  var MIN_CORR = {min_corr};
285
  var MAX_CORR = {max_corr};
286
  var SHOW_CAT_IDX = {'true' if show_category_index else 'false'};
 
 
287
 
288
  var COLORS = {{
289
  reward_color: '{COLORS["reward_color"]}',
@@ -793,6 +822,7 @@ document.addEventListener('DOMContentLoaded', function() {{
793
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
794
  Save PNG
795
  </button>
 
796
  <button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
797
  </div>
798
  <div class="details-panel" id="detailsPanel">
@@ -829,5 +859,13 @@ document.addEventListener('DOMContentLoaded', function() {{
829
  </div>
830
  </div>
831
 
 
 
 
 
 
 
 
 
832
  </body>
833
- </html>"""
 
2
 
3
  import html
4
  import json
5
+ from pathlib import Path
6
 
7
  import numpy as np
8
 
9
  from config import COLORS
10
 
11
 
12
+ def _export_js(name):
13
+ """The PowerPoint export's code, inlined into the HTML (one file, no server)."""
14
+ js = (Path(__file__).parent / name).read_text(encoding='utf-8')
15
+ if '</script' in js.lower():
16
+ raise ValueError(f'{name} must not contain "</script"')
17
+ return js
18
+
19
+
20
  def _safe_json(obj):
21
  """JSON-encode and escape </script> sequences for safe embedding in HTML."""
22
  return json.dumps(obj).replace('</','<\\/')
 
134
  avg_corr=avg_corr,
135
  default_max_l1=default_max_l1,
136
  show_category_index=show_category_index,
137
+ project={'client': client_name or '', 'country': country_name or '',
138
+ 'brand': brand_name or '', 'category': category_name or ''},
139
  )
140
 
141
  stats = {
 
158
  driver_list, nonrewards_list, threshold, min_corr,
159
  max_corr, attribute_count, reward_drivers,
160
  nonreward_drivers, corr_count, avg_corr,
161
+ default_max_l1, show_category_index, project=None):
162
  """Build the standalone HTML string. Separated for readability."""
163
 
164
  # Escape all user-supplied strings for safe HTML embedding
 
171
  meta_json = _safe_json(attr_meta)
172
  drivers_json = _safe_json(driver_list)
173
  nonrewards_json = _safe_json(nonrewards_list)
174
+ project_json = _safe_json(project or {})
175
+ title_json = _safe_json(chart_title)
176
 
177
  return f"""<!DOCTYPE html>
178
  <html lang="en">
 
181
  <title>{safe_title} — Association Network</title>
182
  <link type="text/css" href="https://unpkg.com/vis-network@9.1.9/dist/dist/vis-network.min.css" rel="stylesheet" />
183
  <script src="https://unpkg.com/vis-network@9.1.9/dist/vis-network.min.js"></script>
184
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
185
  <style>
186
  * {{ box-sizing: border-box; margin: 0; padding: 0; }}
187
  body {{ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: #f8f9fa; color: #333; }}
 
252
  .tab-btn {{ padding: 6px 14px; font-size: 12px; font-weight: 500; border: 1px solid #ddd; background: #fff; border-radius: 6px; cursor: pointer; color: #555; transition: all 0.15s; }}
253
  .tab-btn:hover {{ background: #f0f0f0; }}
254
  .tab-btn.active {{ background: #283273; color: #fff; border-color: #283273; }}
255
+ #pptxDialog {{ position: fixed; inset: 0; background: rgba(20,24,40,.35); display: none; align-items: center; justify-content: center; z-index: 900; }}
256
+ #pptxDialog .xp {{ background: #fff; width: 520px; max-width: calc(100vw - 32px); max-height: calc(100vh - 64px); overflow: auto; border-radius: 8px; box-shadow: 0 10px 40px rgba(0,0,0,.25); padding: 20px 22px; font-size: 13px; line-height: 1.5; color: #222; }}
257
+ #pptxDialog h2 {{ font-size: 15px; margin: 0 0 2px; }}
258
+ #pptxDialog .sub {{ color: #666; margin: 0 0 14px; }}
259
+ #pptxDialog .row {{ margin: 0 0 12px; }}
260
+ #pptxDialog label {{ display: block; font-weight: 600; margin: 10px 0 4px; }}
261
+ #pptxDialog input, #pptxDialog select {{ width: 100%; padding: 5px 7px; font: inherit; border: 1px solid #ccc; border-radius: 4px; }}
262
+ #pptxDialog .warn {{ color: #8a5a00; background: #fff6e0; padding: 6px 8px; border-radius: 4px; margin-top: 12px; }}
263
+ #pptxDialog .status {{ color: #555; margin-top: 12px; min-height: 1.5em; }}
264
+ #pptxDialog .btns {{ display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }}
265
+ #pptxDialog button {{ padding: 6px 14px; font: inherit; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }}
266
+ #pptxDialog button.primary {{ background: #283273; color: #fff; border-color: #283273; }}
267
+ #pptxDialog button:disabled {{ opacity: .5; cursor: default; }}
268
 
269
  .details-panel {{ position: absolute; bottom: 0; left: 0; right: 0; z-index: 20; background: #fff; border-top: 1px solid #e0e0e0; box-shadow: 0 -4px 20px rgba(0,0,0,0.08); transform: translateY(100%); transition: transform 0.25s ease; max-height: 45vh; overflow-y: auto; }}
270
  .details-panel.open {{ transform: translateY(0); }}
 
311
  var MIN_CORR = {min_corr};
312
  var MAX_CORR = {max_corr};
313
  var SHOW_CAT_IDX = {'true' if show_category_index else 'false'};
314
+ var PROJECT = {project_json};
315
+ var CHART_TITLE = {title_json};
316
 
317
  var COLORS = {{
318
  reward_color: '{COLORS["reward_color"]}',
 
822
  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1px"><path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h4l2-3h6l2 3h4a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/></svg>
823
  Save PNG
824
  </button>
825
+ <button class="tab-btn" onclick="startPptxExport()" title="One slide per listed attribute, on the DECODE, Henkel or REWE master">PowerPoint</button>
826
  <button class="tab-btn" id="detailsBtn" onclick="toggleDetails()">Details</button>
827
  </div>
828
  <div class="details-panel" id="detailsPanel">
 
859
  </div>
860
  </div>
861
 
862
+ <input type="file" id="pptxMasterPick" accept=".pptx" multiple style="display:none">
863
+ <div id="pptxDialog"></div>
864
+ <script>
865
+ __PPTX_EXPORT_JS__
866
+ </script>
867
+ <script>
868
+ __PPTX_EXPORT_UI_JS__
869
+ </script>
870
  </body>
871
+ </html>""".replace('__PPTX_EXPORT_JS__', _export_js('pptx_export.js')).replace('__PPTX_EXPORT_UI_JS__', _export_js('pptx_export_ui.js'))
pptx_export.js ADDED
@@ -0,0 +1,759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* PowerPoint export of the association network - one slide per attribute.
2
+ ----------------------------------------------------------------------
3
+ Runs inside the generated HTML (build_network.py inlines this file) and in
4
+ the Node test (tests/test_pptx_export.js). Nothing here touches the page:
5
+ the page hands in the networks, a text-measuring function and the master
6
+ file the user picked; out comes the .pptx as bytes.
7
+
8
+ The master is one of the "network masters" (scripts/make_network_masters.py):
9
+ slide 1 = the template slide (net.card / net.area / net.legend / net.meta),
10
+ slide 2 = hidden, one picture per country flag ("flag DE | Germany").
11
+
12
+ Design agreed with JM (trial C, 2026-11-17; chosen 2026-11-23):
13
+ - dots, not boxes; dot size = category index (as the HTML's node size)
14
+ - the selected attribute dark in the middle, its name centred below or
15
+ above its dot on white; every other name and dot equally strong
16
+ - no box behind the other names; lines kept off the names by the layout
17
+ - 12pt, else 10pt when the names do not fit
18
+ - title "Associative network <attribute>" with the attribute in italics
19
+ */
20
+ (function (root) {
21
+ 'use strict';
22
+
23
+ var COLORS = {
24
+ reward: 'E03E3E', nonreward: '2B7AB2', driver: '2B2B2B',
25
+ text: '1A1A1A', text2: '6E6E6E', text3: '555555', index: '888888', legend: '333333'
26
+ };
27
+ var EMU = 12700; // per point
28
+ var IN = 72; // points per inch (the layout's constants are inches)
29
+
30
+ // ---------------------------------------------------------------- labels
31
+ function wrap(text) { // the HTML's own rule (wrapLabel)
32
+ var words = String(text).split(/\s+/);
33
+ if (words.length <= 2) return [text];
34
+ var lines = [], line = '';
35
+ words.forEach(function (w) {
36
+ if (line && line.length + w.length + 1 > 15) { lines.push(line); line = w; }
37
+ else line = line ? line + ' ' + w : w;
38
+ });
39
+ if (line) lines.push(line);
40
+ return lines;
41
+ }
42
+
43
+ function labelLines(n, showIdx) {
44
+ if (n.level === 0) return [n.name + (showIdx ? ' (' + n.cat + ')' : '')];
45
+ var l = wrap(n.name);
46
+ return showIdx ? l.concat(['(' + n.cat + ')']) : l;
47
+ }
48
+
49
+ // ---------------------------------------------------------------- layout
50
+ // All positions in inches inside the slide; area = {x, y, w, h} in inches.
51
+
52
+ function permutations(arr) {
53
+ if (arr.length <= 1) return [arr.slice()];
54
+ var out = [];
55
+ arr.forEach(function (x, i) {
56
+ var rest = arr.slice(0, i).concat(arr.slice(i + 1));
57
+ permutations(rest).forEach(function (p) { out.push([x].concat(p)); });
58
+ });
59
+ return out;
60
+ }
61
+
62
+ function parentsOf(nodes, edges, by) {
63
+ var parents = {};
64
+ nodes.forEach(function (n) { parents[n.name] = []; });
65
+ edges.forEach(function (e) { if (by[e.a].level === 1) parents[e.b].push(e.a); });
66
+ return parents;
67
+ }
68
+
69
+ /* Sector start: every direct link gets a slice of the ellipse, its own further
70
+ links sit outside it in the same slice; links shared by two direct links sit
71
+ between them; then boxes are nudged apart. */
72
+ function sectorStart(nodes, edges, seed, A) {
73
+ var cx = A.x + A.w / 2, cy = A.y + A.h / 2;
74
+ var by = {}; nodes.forEach(function (n) { by[n.name] = n; });
75
+ var parents = parentsOf(nodes, edges, by);
76
+ var l1 = nodes.filter(function (n) { return n.level === 1; }).map(function (n) { return n.name; });
77
+ var l2 = nodes.filter(function (n) { return n.level === 2; }).map(function (n) { return n.name; });
78
+ function score(order) {
79
+ var pos = {}; order.forEach(function (nm, i) { pos[nm] = i; });
80
+ var s = 0;
81
+ l2.forEach(function (c) {
82
+ var ps = parents[c];
83
+ for (var i = 0; i < ps.length; i++) for (var j = i + 1; j < ps.length; j++) {
84
+ var d = Math.abs(pos[ps[i]] - pos[ps[j]]); d = Math.min(d, order.length - d); s += d - 1;
85
+ }
86
+ });
87
+ return s;
88
+ }
89
+ var order = l1.slice();
90
+ if (l1.length > 2) {
91
+ var best = null;
92
+ permutations(l1.slice(1)).forEach(function (p) {
93
+ var o = [l1[0]].concat(p), sc = score(o);
94
+ if (best === null || sc < best[0]) best = [sc, o];
95
+ });
96
+ order = best[1];
97
+ }
98
+ var own = {}, weight = {}, tot = 0;
99
+ order.forEach(function (p) {
100
+ own[p] = l2.filter(function (c) { return parents[c].length === 1 && parents[c][0] === p; });
101
+ weight[p] = 1 + own[p].length; tot += weight[p];
102
+ });
103
+ var ang = {}, span = {}, a0 = -Math.PI / 2 + seed * 0.21;
104
+ order.forEach(function (p) {
105
+ var w = 2 * Math.PI * weight[p] / tot;
106
+ span[p] = [a0, a0 + w]; ang[p] = a0 + w / 2; a0 += w;
107
+ });
108
+ var RX1 = 0.22 * A.w, RY1 = 0.23 * A.h, RX2 = 0.445 * A.w, RY2 = 0.445 * A.h;
109
+ nodes[0].x = cx; nodes[0].y = cy;
110
+ order.forEach(function (p) {
111
+ by[p].x = cx + RX1 * Math.cos(ang[p]); by[p].y = cy + RY1 * Math.sin(ang[p]);
112
+ var kids = own[p], lo = span[p][0], hi = span[p][1];
113
+ kids.forEach(function (c, k) {
114
+ var a = lo + (hi - lo) * (k + 1) / (kids.length + 1);
115
+ by[c].x = cx + RX2 * Math.cos(a); by[c].y = cy + RY2 * Math.sin(a);
116
+ });
117
+ });
118
+ l2.forEach(function (c) {
119
+ var ps = parents[c];
120
+ if (ps.length > 1) {
121
+ var sx = 0, sy = 0;
122
+ ps.forEach(function (p) { sx += Math.sin(ang[p]); sy += Math.cos(ang[p]); });
123
+ var a = Math.atan2(sx, sy);
124
+ by[c].x = cx + 0.5 * (RX1 + RX2) * Math.cos(a); by[c].y = cy + 0.5 * (RY1 + RY2) * Math.sin(a);
125
+ }
126
+ });
127
+ // nudge apart: overlapping boxes, and boxes on someone else's line
128
+ var pad = 0.10;
129
+ for (var it = 0; it < 800; it++) {
130
+ var moved = false, i, j;
131
+ for (i = 0; i < nodes.length; i++) for (j = i + 1; j < nodes.length; j++) {
132
+ var a = nodes[i], b = nodes[j];
133
+ var dx = b.x - a.x, dy = b.y - a.y;
134
+ var ox = (a.w + b.w) / 2 + pad - Math.abs(dx), oy = (a.h + b.h) / 2 + pad - Math.abs(dy);
135
+ if (ox > 0 && oy > 0) {
136
+ moved = true;
137
+ var ma = a.level === 0 ? 0 : 0.5, mb = b.level === 0 ? 0 : 0.5;
138
+ if (ma + mb === 0) continue;
139
+ var t = ma + mb; ma /= t; mb /= t;
140
+ if (ox * 1.5 < oy) { var s = sign(dx) * ox; a.x -= s * ma; b.x += s * mb; }
141
+ else { var s2 = sign(dy) * oy; a.y -= s2 * ma; b.y += s2 * mb; }
142
+ }
143
+ }
144
+ edges.forEach(function (e) {
145
+ var a = by[e.a], b = by[e.b];
146
+ nodes.forEach(function (n) {
147
+ if (n === a || n === b || n.level === 0) return;
148
+ var vx = b.x - a.x, vy = b.y - a.y, L2 = vx * vx + vy * vy || 1e-6;
149
+ var u = ((n.x - a.x) * vx + (n.y - a.y) * vy) / L2;
150
+ if (!(u > 0 && u < 1)) return;
151
+ var px = a.x + u * vx, py = a.y + u * vy, dx = n.x - px, dy = n.y - py;
152
+ if (Math.abs(dx) < n.w / 2 + 0.04 && Math.abs(dy) < n.h / 2 + 0.04) {
153
+ var d = Math.hypot(dx, dy) || 1e-6;
154
+ n.x += 0.03 * dx / d; n.y += 0.03 * dy / d; moved = true;
155
+ }
156
+ });
157
+ });
158
+ nodes.forEach(function (n) { clampBox(n, A); });
159
+ if (!moved) break;
160
+ }
161
+ }
162
+
163
+ function sign(v) { return v < 0 ? -1 : 1; }
164
+
165
+ function clampBox(n, A) {
166
+ n.x = Math.min(Math.max(n.x, A.x + n.w / 2), A.x + A.w - n.w / 2);
167
+ n.y = Math.min(Math.max(n.y, A.y + n.h / 2), A.y + A.h - n.h / 2);
168
+ }
169
+
170
+ /* Fruchterman-Reingold from given start positions - the same steps as
171
+ networkx.spring_layout (trial D was made with it), then rescaled to [-1, 1]. */
172
+ function springRelax(nodes, edges, pos, k, iterations) {
173
+ var n = nodes.length, idx = {}, i, j;
174
+ nodes.forEach(function (nd, i2) { idx[nd.name] = i2; });
175
+ var Aw = []; for (i = 0; i < n; i++) { Aw.push(new Array(n).fill(0)); }
176
+ edges.forEach(function (e) {
177
+ var w = 0.6 + e.val / 40, a = idx[e.a], b = idx[e.b];
178
+ Aw[a][b] = w; Aw[b][a] = w; // undirected, last weight wins (as networkx)
179
+ });
180
+ var xs = pos.map(function (p) { return p[0]; }), ys = pos.map(function (p) { return p[1]; });
181
+ var t = Math.max(Math.max.apply(null, xs) - Math.min.apply(null, xs),
182
+ Math.max.apply(null, ys) - Math.min.apply(null, ys)) * 0.1;
183
+ var dt = t / (iterations + 1);
184
+ for (var it = 0; it < iterations; it++) {
185
+ var disp = [];
186
+ for (i = 0; i < n; i++) {
187
+ var dxs = 0, dys = 0;
188
+ for (j = 0; j < n; j++) {
189
+ if (i === j) continue;
190
+ var dx = pos[i][0] - pos[j][0], dy = pos[i][1] - pos[j][1];
191
+ var d = Math.max(Math.hypot(dx, dy), 0.01);
192
+ var f = k * k / (d * d) - Aw[i][j] * d / k;
193
+ dxs += dx * f; dys += dy * f;
194
+ }
195
+ disp.push([dxs, dys]);
196
+ }
197
+ var err = 0;
198
+ for (i = 0; i < n; i++) {
199
+ var len = Math.hypot(disp[i][0], disp[i][1]);
200
+ if (len < 0.01) len = 0.1;
201
+ var mx = disp[i][0] * t / len, my = disp[i][1] * t / len;
202
+ pos[i][0] += mx; pos[i][1] += my; err += Math.hypot(mx, my);
203
+ }
204
+ t -= dt;
205
+ if (err / n < 1e-4) break;
206
+ }
207
+ var mxx = 0, myy = 0;
208
+ pos.forEach(function (p) { mxx += p[0]; myy += p[1]; });
209
+ mxx /= n; myy /= n;
210
+ var lim = 0;
211
+ pos.forEach(function (p) { p[0] -= mxx; p[1] -= myy; lim = Math.max(lim, Math.abs(p[0]), Math.abs(p[1])); });
212
+ if (lim > 0) pos.forEach(function (p) { p[0] /= lim; p[1] /= lim; });
213
+ return pos;
214
+ }
215
+
216
+ var GAP = 0.06; // dot -> label, inches
217
+
218
+ function placeLabels(nodes, cx, cy) {
219
+ nodes.forEach(function (n) {
220
+ var d = n.d;
221
+ if (n.fixedSide) n.side = n.fixedSide;
222
+ else if (n.level === 0) n.side = 'below';
223
+ else {
224
+ var dx = n.x - cx, dy = (n.y - cy) * 2.4;
225
+ n.side = dx >= 0 ? 'right' : 'left';
226
+ if (Math.abs(dx) < Math.abs(dy) * 0.35) n.side = dy > 0 ? 'below' : 'above';
227
+ }
228
+ if (n.side === 'right') { n.lx = n.x + d / 2 + GAP; n.ly = n.y - n.lh / 2; }
229
+ else if (n.side === 'left') { n.lx = n.x - d / 2 - GAP - n.lw; n.ly = n.y - n.lh / 2; }
230
+ else if (n.side === 'below') { n.lx = n.x - n.lw / 2; n.ly = n.y + d / 2 + 0.01; }
231
+ else { n.lx = n.x - n.lw / 2; n.ly = n.y - d / 2 - 0.01 - n.lh; }
232
+ });
233
+ }
234
+
235
+ function bbox(n) {
236
+ var d = n.d;
237
+ return [Math.min(n.x - d / 2, n.lx), Math.min(n.y - d / 2, n.ly),
238
+ Math.max(n.x + d / 2, n.lx + n.lw), Math.max(n.y + d / 2, n.ly + n.lh)];
239
+ }
240
+
241
+ /* One attempt: sector start -> spring -> nudge dots + names apart.
242
+ Returns the score: 1 per collision, 0.3 per line running through a name. */
243
+ function attempt(nodes, edges, seed, A) {
244
+ var by = {}; nodes.forEach(function (n) { by[n.name] = n; });
245
+ nodes.forEach(function (n) { n.w = n.lw + n.d; n.h = n.lh; });
246
+ sectorStart(nodes, edges, seed, A);
247
+ var cx = A.x + A.w / 2, cy = A.y + A.h / 2, norm = A.w / 2.04;
248
+ var pos = nodes.map(function (n) { return [(n.x - cx) / norm, (n.y - cy) / norm]; });
249
+ springRelax(nodes, edges, pos, 1.1 / Math.sqrt(nodes.length), 25 + 10 * seed);
250
+ var r = pos[0];
251
+ var pts = pos.map(function (p) { return [p[0] - r[0], p[1] - r[1]]; });
252
+ var mx = Math.max.apply(null, pts.map(function (p) { return Math.abs(p[0]); })) || 1;
253
+ var my = Math.max.apply(null, pts.map(function (p) { return Math.abs(p[1]); })) || 1;
254
+ nodes.forEach(function (n, i) {
255
+ n.x = cx + pts[i][0] / mx * A.w / 2 * 0.80;
256
+ n.y = cy + pts[i][1] / my * A.h / 2 * 0.82;
257
+ });
258
+ var x1 = A.x + A.w, y1 = A.y + A.h;
259
+ var N = nodes.length, E = edges.map(function (e) { return [by[e.a], by[e.b]]; });
260
+ var B0 = new Float64Array(N), B1 = new Float64Array(N), B2 = new Float64Array(N), B3 = new Float64Array(N);
261
+ function boxes() {
262
+ for (var q = 0; q < N; q++) {
263
+ var n = nodes[q], d2 = n.d / 2;
264
+ B0[q] = Math.min(n.x - d2, n.lx); B1[q] = Math.min(n.y - d2, n.ly);
265
+ B2[q] = Math.max(n.x + d2, n.lx + n.lw); B3[q] = Math.max(n.y + d2, n.ly + n.lh);
266
+ }
267
+ }
268
+ for (var it = 0; it < 900; it++) {
269
+ placeLabels(nodes, cx, cy);
270
+ boxes();
271
+ var moved = false, i, j, k;
272
+ for (i = 0; i < N; i++) for (j = i + 1; j < N; j++) {
273
+ var ox = Math.min(B2[i], B2[j]) - Math.max(B0[i], B0[j]) + 0.08;
274
+ if (ox <= 0) continue;
275
+ var oy = Math.min(B3[i], B3[j]) - Math.max(B1[i], B1[j]) + 0.06;
276
+ if (oy <= 0) continue;
277
+ var a = nodes[i], b = nodes[j];
278
+ moved = true;
279
+ var wa = a.level === 0 ? 0 : 1, wb = b.level === 0 ? 0 : 1, t = wa + wb;
280
+ wa /= t; wb /= t;
281
+ if (ox < oy * 1.3) {
282
+ var s = sign((B0[j] + B2[j]) - (B0[i] + B2[i])) * Math.min(ox, 0.05);
283
+ a.x -= s * wa; b.x += s * wb;
284
+ } else {
285
+ var s2 = sign((B1[j] + B3[j]) - (B1[i] + B3[i])) * Math.min(oy, 0.05);
286
+ a.y -= s2 * wa; b.y += s2 * wb;
287
+ }
288
+ }
289
+ for (k = 0; k < E.length; k++) {
290
+ var ea = E[k][0], eb = E[k][1];
291
+ var sx0 = Math.min(ea.x, eb.x) - 0.03, sx1 = Math.max(ea.x, eb.x) + 0.03;
292
+ var sy0 = Math.min(ea.y, eb.y) - 0.03, sy1 = Math.max(ea.y, eb.y) + 0.03;
293
+ var vx = eb.x - ea.x, vy = eb.y - ea.y, L2 = vx * vx + vy * vy || 1e-6;
294
+ for (i = 0; i < N; i++) {
295
+ var n = nodes[i];
296
+ if (n === ea || n === eb || n.level === 0) continue;
297
+ if (B2[i] < sx0 || B0[i] > sx1 || B3[i] < sy0 || B1[i] > sy1) continue; // nowhere near the line
298
+ var mx_ = (B0[i] + B2[i]) / 2, my_ = (B1[i] + B3[i]) / 2;
299
+ var u = ((mx_ - ea.x) * vx + (my_ - ea.y) * vy) / L2;
300
+ if (!(u > 0.03 && u < 0.97)) continue;
301
+ var px = ea.x + u * vx, py = ea.y + u * vy;
302
+ if (B0[i] - 0.03 < px && px < B2[i] + 0.03 && B1[i] - 0.03 < py && py < B3[i] + 0.03) {
303
+ var dx = mx_ - px, dy = my_ - py, dd = Math.hypot(dx, dy) || 1e-6;
304
+ n.x += 0.025 * dx / dd; n.y += 0.025 * dy / dd; moved = true;
305
+ }
306
+ }
307
+ }
308
+ boxes();
309
+ for (i = 0; i < N; i++) {
310
+ var m = nodes[i];
311
+ if (B0[i] < A.x) m.x += A.x - B0[i];
312
+ if (B2[i] > x1) m.x -= B2[i] - x1;
313
+ if (B1[i] < A.y) m.y += A.y - B1[i];
314
+ if (B3[i] > y1) m.y -= B3[i] - y1;
315
+ }
316
+ if (!moved) break;
317
+ }
318
+ placeLabels(nodes, cx, cy);
319
+ chooseSides(nodes, edges, by, A, cx, cy);
320
+ return defects(nodes, edges, by);
321
+ }
322
+
323
+ /* Each name goes on the side of its dot where no line - its own included -
324
+ runs through it, no other dot or name sits and it stays inside the area. */
325
+ var SIDES = ['right', 'left', 'below', 'above'];
326
+ function sideCost(n, nodes, edges, by, A) {
327
+ var bx = bbox(n), cost = 0;
328
+ var lab = [n.lx, n.ly, n.lx + n.lw, n.ly + n.lh];
329
+ 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 += 5;
330
+ nodes.forEach(function (o) {
331
+ if (o === n) return;
332
+ var bo = bbox(o);
333
+ 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;
334
+ });
335
+ edges.forEach(function (e) {
336
+ var a = by[e.a], b = by[e.b];
337
+ if (segHitsRect(a.x, a.y, b.x, b.y, lab)) cost += 1;
338
+ });
339
+ return cost;
340
+ }
341
+ function chooseSides(nodes, edges, by, A, cx, cy) {
342
+ for (var pass = 0; pass < 2; pass++) {
343
+ nodes.forEach(function (n) {
344
+ // the selected attribute's name stays centred on its dot: below or above (JM, 2026-11-23)
345
+ var keep = n.side, best = [sideCost(n, nodes, edges, by, A) - 0.01, keep];
346
+ (n.level === 0 ? ['below', 'above'] : SIDES).forEach(function (s) {
347
+ if (s === keep) return;
348
+ n.fixedSide = s; placeLabels([n], cx, cy);
349
+ var c = sideCost(n, nodes, edges, by, A);
350
+ if (c < best[0]) best = [c, s];
351
+ });
352
+ n.fixedSide = best[1]; placeLabels([n], cx, cy);
353
+ });
354
+ }
355
+ nodes.forEach(function (n) { n.fixedSide = null; });
356
+ }
357
+
358
+ /* Does the segment a-b cross the rectangle r = [x0, y0, x1, y1]? (Liang-Barsky) */
359
+ function segHitsRect(ax, ay, bx, by_, r) {
360
+ var t0 = 0, t1 = 1, dx = bx - ax, dy = by_ - ay;
361
+ var p = [-dx, dx, -dy, dy], q = [ax - r[0], r[2] - ax, ay - r[1], r[3] - ay];
362
+ for (var i = 0; i < 4; i++) {
363
+ if (p[i] === 0) { if (q[i] < 0) return false; continue; }
364
+ var t = q[i] / p[i];
365
+ if (p[i] < 0) { if (t > t1) return false; if (t > t0) t0 = t; }
366
+ else { if (t < t0) return false; if (t < t1) t1 = t; }
367
+ }
368
+ return t1 > t0 + 0.025 && t0 < 0.975; // as the old sampling: ends just at a dot don't count
369
+ }
370
+
371
+ function defects(nodes, edges, by) {
372
+ var bad = 0, i, j;
373
+ for (i = 0; i < nodes.length; i++) for (j = i + 1; j < nodes.length; j++) {
374
+ var ba = bbox(nodes[i]), bb = bbox(nodes[j]);
375
+ 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;
376
+ }
377
+ edges.forEach(function (e) {
378
+ var a = by[e.a], b = by[e.b];
379
+ nodes.forEach(function (n) {
380
+ if (n === a || n === b) return;
381
+ if (segHitsRect(a.x, a.y, b.x, b.y, bbox(n))) bad += 0.3;
382
+ });
383
+ });
384
+ return bad;
385
+ }
386
+
387
+ /* Lay out one network inside area (points). measure(text, pt, bold) -> width
388
+ in points. Returns {nodes, edges, pt, score}; positions in points. */
389
+ function layoutNetwork(net, areaPt, measure, opts) {
390
+ opts = opts || {};
391
+ var showIdx = opts.showIdx !== false, seeds = opts.seeds || 30;
392
+ // [selected + direct links, further links] in pt; the second pair is the fallback
393
+ // style 'C' (default, JM's choice): every name and dot equally strong.
394
+ // style 'D' (trial only): further links smaller, grey, paler.
395
+ var flat = opts.style !== 'D';
396
+ var sizes = flat ? [[12, 12], [10, 10]] : (opts.sizes || [[12, 10], [10, 10]]);
397
+ var A = { x: areaPt.x / IN, y: areaPt.y / IN, w: areaPt.w / IN, h: areaPt.h / IN };
398
+ // every field up front, one object shape (fast property access in the loops)
399
+ var nodes = net.nodes.map(function (n) {
400
+ return { name: n.name, level: n.level, cat: n.cat, reward: n.reward, x: 0, y: 0, d: 0, w: 0, h: 0,
401
+ lx: 0, ly: 0, lw: 0, lh: 0, pt: 0, lines: null, side: 'right', fixedSide: null };
402
+ });
403
+ var edges = net.edges;
404
+ var cats = nodes.map(function (n) { return n.cat; });
405
+ var cmin = Math.min.apply(null, cats), cmax = Math.max.apply(null, cats);
406
+ var result = null;
407
+ sizes.some(function (sz) {
408
+ var pt = sz[0];
409
+ nodes.forEach(function (n) {
410
+ var f = (n.cat - cmin) / Math.max(1, cmax - cmin);
411
+ 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;
412
+ n.lines = labelLines(n, showIdx);
413
+ n.pt = n.level <= 1 ? sz[0] : sz[1];
414
+ var bold = n.level <= 1;
415
+ var wmax = 0;
416
+ n.lines.forEach(function (t) { wmax = Math.max(wmax, measure(t, n.pt, bold && t.charAt(0) !== '(')); });
417
+ n.lw = wmax / IN + 0.02;
418
+ n.lh = n.lines.length * n.pt * 1.15 / IN + 0.02;
419
+ });
420
+ var best = null;
421
+ for (var seed = 0; seed < seeds; seed++) {
422
+ var sc = attempt(nodes, edges, seed, A);
423
+ if (best === null || sc < best[0]) best = [sc, seed];
424
+ if (sc === 0) break;
425
+ }
426
+ if (best[1] !== seeds - 1 || best[0] !== 0) attempt(nodes, edges, best[1], A);
427
+ result = { pt: pt, score: best[0], seed: best[1] };
428
+ return best[0] < 1; // 12pt unless names or dots really collide
429
+ });
430
+ nodes.forEach(function (n) {
431
+ ['x', 'y', 'd', 'lx', 'ly', 'lw', 'lh'].forEach(function (k) { n[k] *= IN; });
432
+ });
433
+ result.nodes = nodes; result.edges = edges; result.style = flat ? 'C' : 'D';
434
+ return result;
435
+ }
436
+
437
+ // ---------------------------------------------------------------- XML
438
+ function esc(s) {
439
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
440
+ }
441
+ function e(pt) { return Math.round(pt * EMU); }
442
+ function fill(rgb, alpha) {
443
+ return '<a:solidFill><a:srgbClr val="' + rgb + '">' +
444
+ (alpha != null && alpha < 1 ? '<a:alpha val="' + Math.round(alpha * 100000) + '"/>' : '') +
445
+ '</a:srgbClr></a:solidFill>';
446
+ }
447
+ function xfrm(x, y, w, h, flipH, flipV) {
448
+ return '<a:xfrm' + (flipH ? ' flipH="1"' : '') + (flipV ? ' flipV="1"' : '') + '><a:off x="' + e(x) + '" y="' + e(y) +
449
+ '"/><a:ext cx="' + e(w) + '" cy="' + e(h) + '"/></a:xfrm>';
450
+ }
451
+ function run(text, o) {
452
+ return '<a:r><a:rPr lang="en-US" sz="' + Math.round(o.pt * 100) + '"' + (o.b ? ' b="1"' : ' b="0"') +
453
+ (o.i ? ' i="1"' : '') + ' dirty="0">' + (o.color ? fill(o.color) : '') +
454
+ '<a:latin typeface="+mn-lt"/><a:cs typeface="+mn-lt"/></a:rPr><a:t>' + esc(text) + '</a:t></a:r>';
455
+ }
456
+
457
+ function dotXml(id, n, flat) {
458
+ var kind = n.reward ? COLORS.reward : COLORS.nonreward;
459
+ return '<p:sp><p:nvSpPr><p:cNvPr id="' + id + '" name="' + esc('dot ' + n.name) + '"/><p:cNvSpPr/><p:nvPr/></p:nvSpPr>' +
460
+ '<p:spPr>' + xfrm(n.x - n.d / 2, n.y - n.d / 2, n.d, n.d) + '<a:prstGeom prst="ellipse"><a:avLst/></a:prstGeom>' +
461
+ fill(n.level === 0 ? COLORS.driver : kind, n.level === 2 && !flat ? 0.55 : 1) +
462
+ '<a:ln w="' + e(1) + '">' + fill('FFFFFF') + '</a:ln></p:spPr>' +
463
+ '<p:txBody><a:bodyPr/><a:lstStyle/><a:p><a:endParaRPr lang="en-US" dirty="0"/></a:p></p:txBody></p:sp>';
464
+ }
465
+
466
+ function labelXml(id, n, flat) {
467
+ var algn = n.side === 'right' ? 'l' : n.side === 'left' ? 'r' : 'ctr';
468
+ var paras = n.lines.map(function (t) {
469
+ var idx = t.charAt(0) === '(';
470
+ return '<a:p><a:pPr algn="' + algn + '"><a:lnSpc><a:spcPct val="100000"/></a:lnSpc><a:spcBef><a:spcPts val="0"/></a:spcBef></a:pPr>' +
471
+ run(t, { pt: n.pt, b: n.level <= 1 && !idx, color: idx ? COLORS.index : n.level <= 1 ? COLORS.text : flat ? COLORS.text3 : COLORS.text2 }) + '</a:p>';
472
+ }).join('');
473
+ return '<p:sp><p:nvSpPr><p:cNvPr id="' + id + '" name="' + esc('label ' + n.name) + '"/><p:cNvSpPr txBox="1"/><p:nvPr/></p:nvSpPr>' +
474
+ // the selected attribute's name on white, so a line behind it never cuts through it
475
+ '<p:spPr>' + xfrm(n.lx, n.ly, n.lw, n.lh) + '<a:prstGeom prst="rect"><a:avLst/></a:prstGeom>' + (n.level === 0 ? fill('FFFFFF') : '<a:noFill/>') + '</p:spPr>' +
476
+ '<p:txBody><a:bodyPr wrap="none" lIns="0" tIns="0" rIns="0" bIns="0" anchor="ctr" anchorCtr="0"><a:noAutofit/></a:bodyPr><a:lstStyle/>' +
477
+ paras + '</p:txBody></p:sp>';
478
+ }
479
+
480
+ function lineXml(id, ed, a, b, minC, maxC, flat) {
481
+ var norm = maxC > minC ? (ed.val - minC) / (maxC - minC) : 0.5;
482
+ norm = Math.max(0, Math.min(1, norm));
483
+ var outer = b.level === 2 && !flat;
484
+ var w = outer ? 0.5 + norm * 3 : 0.75 + norm * 5;
485
+ var alpha = (0.35 + norm * 0.6) * (outer ? 0.55 : 1);
486
+ var x = Math.min(a.x, b.x), y = Math.min(a.y, b.y);
487
+ return '<p:cxnSp><p:nvCxnSpPr><p:cNvPr id="' + id + '" name="' + esc(ed.a + ' - ' + ed.b + ' (' + ed.val.toFixed(1) + ')') + '"/>' +
488
+ '<p:cNvCxnSpPr/><p:nvPr/></p:nvCxnSpPr><p:spPr>' +
489
+ xfrm(x, y, Math.abs(b.x - a.x), Math.abs(b.y - a.y), b.x < a.x, b.y < a.y) +
490
+ '<a:prstGeom prst="line"><a:avLst/></a:prstGeom><a:ln w="' + e(w) + '" cap="rnd">' +
491
+ fill(a.reward ? COLORS.reward : COLORS.nonreward, alpha) + '</a:ln></p:spPr></p:cxnSp>';
492
+ }
493
+
494
+ // ---------------------------------------------------------------- package
495
+ var NS = {
496
+ p: 'http://schemas.openxmlformats.org/presentationml/2006/main',
497
+ a: 'http://schemas.openxmlformats.org/drawingml/2006/main',
498
+ r: 'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
499
+ rel: 'http://schemas.openxmlformats.org/package/2006/relationships',
500
+ ct: 'http://schemas.openxmlformats.org/package/2006/content-types'
501
+ };
502
+
503
+ function parse(xml, P) { return new P().parseFromString(xml, 'application/xml'); }
504
+ function kids(el, ns, local) {
505
+ var out = [];
506
+ for (var c = el.firstChild; c; c = c.nextSibling) if (c.nodeType === 1 && c.namespaceURI === ns && c.localName === local) out.push(c);
507
+ return out;
508
+ }
509
+ function all(el, ns, local) { return Array.prototype.slice.call(el.getElementsByTagNameNS(ns, local)); }
510
+ function relsPath(part) { var i = part.lastIndexOf('/'); return part.slice(0, i) + '/_rels/' + part.slice(i + 1) + '.rels'; }
511
+ function resolve(fromPart, target) {
512
+ var parts = fromPart.split('/'); parts.pop();
513
+ target.split('/').forEach(function (t) { if (t === '..') parts.pop(); else if (t !== '.') parts.push(t); });
514
+ return parts.join('/');
515
+ }
516
+
517
+ function shapeName(sp) {
518
+ var c = all(sp, NS.p, 'cNvPr')[0];
519
+ return c ? c.getAttribute('name') : '';
520
+ }
521
+ function phType(sp) {
522
+ var ph = all(sp, NS.p, 'ph')[0];
523
+ return ph ? (ph.getAttribute('type') || 'body') : null;
524
+ }
525
+ function spText(sp) { return all(sp, NS.a, 't').map(function (t) { return t.textContent; }).join(''); }
526
+
527
+ /* Replace a shape's text by runs, keeping the first paragraph's properties and
528
+ the first run's properties (font, size, colour stay the master's). */
529
+ function setRuns(doc, sp, runs) {
530
+ var body = all(sp, NS.p, 'txBody')[0];
531
+ if (!body) return;
532
+ var paras = kids(body, NS.a, 'p');
533
+ var keepP = paras.length ? kids(paras[0], NS.a, 'pPr')[0] : null;
534
+ var r0 = paras.length ? all(paras[0], NS.a, 'rPr')[0] : null;
535
+ paras.forEach(function (p) { body.removeChild(p); });
536
+ var p = doc.createElementNS(NS.a, 'a:p');
537
+ if (keepP) p.appendChild(keepP.cloneNode(true));
538
+ runs.forEach(function (r) {
539
+ var re = doc.createElementNS(NS.a, 'a:r');
540
+ var rp = r0 ? r0.cloneNode(true) : doc.createElementNS(NS.a, 'a:rPr');
541
+ if (!rp.getAttribute('lang')) rp.setAttribute('lang', 'en-US');
542
+ if (r.i) rp.setAttribute('i', '1'); else rp.removeAttribute('i');
543
+ if (r.pt) rp.setAttribute('sz', String(Math.round(r.pt * 100)));
544
+ if (r.color) {
545
+ kids(rp, NS.a, 'solidFill').forEach(function (f) { rp.removeChild(f); });
546
+ var sf = doc.createElementNS(NS.a, 'a:solidFill'), clr = doc.createElementNS(NS.a, 'a:srgbClr');
547
+ clr.setAttribute('val', r.color); sf.appendChild(clr);
548
+ // a:solidFill goes after a:ln (if any), before the fonts
549
+ var ln = kids(rp, NS.a, 'ln')[0];
550
+ rp.insertBefore(sf, ln ? ln.nextSibling : rp.firstChild);
551
+ }
552
+ re.appendChild(rp);
553
+ var t = doc.createElementNS(NS.a, 'a:t'); t.textContent = r.text;
554
+ re.appendChild(t);
555
+ p.appendChild(re);
556
+ });
557
+ body.appendChild(p);
558
+ }
559
+ function imageSize(bytes) {
560
+ var b = bytes;
561
+ 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];
562
+ if (b[0] === 0xFF && b[1] === 0xD8) {
563
+ var i = 2;
564
+ while (i < b.length) {
565
+ if (b[i] !== 0xFF) { i++; continue; }
566
+ var m = b[i + 1], len = b[i + 2] << 8 | b[i + 3];
567
+ 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]];
568
+ i += 2 + len;
569
+ }
570
+ }
571
+ if (b[0] === 0x47 && b[1] === 0x49) return [b[6] | b[7] << 8, b[8] | b[9] << 8];
572
+ return null;
573
+ }
574
+
575
+ /* Read a picked master: checks it is a network master, returns what the
576
+ export dialog needs (frame, flags) and keeps the zip for build(). */
577
+ /* "12:10,10:10" -> [[12, 10], [10, 10]] (net.meta `sizes`) */
578
+ function sizesOf(M) {
579
+ var s = (M.meta && M.meta.sizes) || '12:10,10:10';
580
+ return s.split(',').map(function (p) { return p.split(':').map(Number); });
581
+ }
582
+
583
+ function openMaster(JSZip, data, env) {
584
+ return JSZip.loadAsync(data).then(function (zip) {
585
+ var M = { zip: zip, env: env };
586
+ return zip.file('ppt/presentation.xml').async('string').then(function (pres) {
587
+ M.pres = pres;
588
+ return zip.file('ppt/_rels/presentation.xml.rels').async('string');
589
+ }).then(function (prels) {
590
+ M.prels = prels;
591
+ var pdoc = parse(M.pres, env.DOMParser), rdoc = parse(prels, env.DOMParser);
592
+ var rid2t = {};
593
+ all(rdoc, NS.rel, 'Relationship').forEach(function (r) { rid2t[r.getAttribute('Id')] = r.getAttribute('Target'); });
594
+ M.slides = all(pdoc, NS.p, 'sldId').map(function (s) {
595
+ return 'ppt/' + rid2t[s.getAttributeNS(NS.r, 'id')].replace(/^\//, '').replace(/^ppt\//, '');
596
+ });
597
+ 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".');
598
+ return Promise.all([zip.file(M.slides[0]).async('string'), zip.file(relsPath(M.slides[0])).async('string'),
599
+ zip.file(M.slides[1]).async('string'), zip.file(relsPath(M.slides[1])).async('string')]);
600
+ }).then(function (x) {
601
+ M.tpl = x[0]; M.tplRels = x[1];
602
+ var tdoc = parse(M.tpl, env.DOMParser);
603
+ var meta = null;
604
+ 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(''); }); });
605
+ if (!meta) throw new Error('This is not a network master (no network template slide). Please pick a file from "Input\\network masters".');
606
+ M.meta = {};
607
+ meta.forEach(function (l) { var i = l.indexOf('='); if (i > 0) M.meta[l.slice(0, i)] = l.slice(i + 1); });
608
+ all(tdoc, NS.p, 'sp').forEach(function (sp) {
609
+ var nm = shapeName(sp);
610
+ if (nm === 'net.area' || nm === 'net.legend') {
611
+ var off = all(sp, NS.a, 'off')[0], ext = all(sp, NS.a, 'ext')[0];
612
+ 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 };
613
+ }
614
+ });
615
+ // the flags: picture name "flag DE | Germany" -> media part
616
+ var fdoc = parse(x[2], env.DOMParser), frels = parse(x[3], env.DOMParser), rid2t = {};
617
+ all(frels, NS.rel, 'Relationship').forEach(function (r) { rid2t[r.getAttribute('Id')] = r.getAttribute('Target'); });
618
+ M.flags = [];
619
+ all(fdoc, NS.p, 'pic').forEach(function (pic) {
620
+ var m = /^flag ([A-Z]{2}) \| (.*)$/.exec(shapeName(pic));
621
+ var blip = all(pic, NS.a, 'blip')[0];
622
+ if (m && blip) M.flags.push({ code: m[1], name: m[2], part: resolve(M.slides[1], rid2t[blip.getAttributeNS(NS.r, 'embed')]) });
623
+ });
624
+ return M;
625
+ });
626
+ });
627
+ }
628
+
629
+ /* Guess the flag from the project's country (code or English name) - only a
630
+ suggestion; the dialog shows it and the user confirms or changes it. */
631
+ function suggestFlag(M, country) {
632
+ var c = String(country || '').trim().toLowerCase();
633
+ if (!c) return '';
634
+ c = { uk: 'gb', 'great britain': 'gb', england: 'gb', usa: 'us', 'united states': 'us' }[c] || c;
635
+ var hit = M.flags.filter(function (f) { return f.code.toLowerCase() === c || f.name.toLowerCase() === c; })[0];
636
+ return hit ? hit.code : '';
637
+ }
638
+
639
+ /* Build the deck. settings: {sample, flag (code or ''), footer, legendRuns};
640
+ nets: [{attr, net}] already laid out by layoutNetwork. */
641
+ function buildDeck(M, nets, settings, minC, maxC) {
642
+ var zip = M.zip, env = M.env, P = env.DOMParser, S = env.XMLSerializer;
643
+ var flag = settings.flag ? M.flags.filter(function (f) { return f.code === settings.flag; })[0] : null;
644
+ var footnote = M.meta.footnote === '1'; // Henkel, REWE: "Base: ..." line
645
+ var legendPt = +M.meta.legend_pt || 8;
646
+ var ctDoc, presDoc = parse(M.pres, P), prelDoc = parse(M.prels, P);
647
+ var flagBytes = null;
648
+ return zip.file('[Content_Types].xml').async('string').then(function (ct) {
649
+ ctDoc = parse(ct, P);
650
+ return flag ? zip.file(flag.part).async('uint8array') : null;
651
+ }).then(function (fb) {
652
+ flagBytes = fb;
653
+ var existing = Object.keys(zip.files).filter(function (f) { return /^ppt\/slides\/slide\d+\.xml$/.test(f); })
654
+ .map(function (f) { return +/(\d+)\.xml$/.exec(f)[1]; });
655
+ var nextNo = Math.max.apply(null, existing) + 1;
656
+ var sldIdLst = all(presDoc, NS.p, 'sldIdLst')[0];
657
+ var maxId = 255;
658
+ all(presDoc, NS.p, 'sldId').forEach(function (s) { maxId = Math.max(maxId, +s.getAttribute('id')); });
659
+ var relRoot = prelDoc.documentElement, maxRid = 0;
660
+ all(prelDoc, NS.rel, 'Relationship').forEach(function (r) { var m = /^rId(\d+)$/.exec(r.getAttribute('Id')); if (m) maxRid = Math.max(maxRid, +m[1]); });
661
+ // drop template + flags slides from the show (their parts go below)
662
+ var oldIds = all(presDoc, NS.p, 'sldId');
663
+ var oldRids = oldIds.map(function (s) { return s.getAttributeNS(NS.r, 'id'); });
664
+ oldIds.forEach(function (s) { sldIdLst.removeChild(s); });
665
+ all(prelDoc, NS.rel, 'Relationship').forEach(function (r) { if (oldRids.indexOf(r.getAttribute('Id')) >= 0) relRoot.removeChild(r); });
666
+
667
+ nets.forEach(function (item, k) {
668
+ var no = nextNo + k, part = 'ppt/slides/slide' + no + '.xml';
669
+ var doc = parse(M.tpl, P), rdoc = parse(M.tplRels, P);
670
+ var tree = all(doc, NS.p, 'spTree')[0];
671
+ var maxShape = 1;
672
+ all(doc, NS.p, 'cNvPr').forEach(function (c) { maxShape = Math.max(maxShape, +c.getAttribute('id') || 0); });
673
+ var id = maxShape + 1;
674
+ // texts and pictures of the frame
675
+ Array.prototype.slice.call(tree.childNodes).forEach(function (sp) {
676
+ if (sp.nodeType !== 1) return;
677
+ var nm = shapeName(sp), ph = phType(sp);
678
+ if (nm === 'net.meta' || nm === 'net.area') { tree.removeChild(sp); return; }
679
+ if (ph === 'title') setRuns(doc, sp, [{ text: 'Associative network ' }, { text: item.attr, i: true }]);
680
+ // by name first: on REWE the base line is itself a text placeholder
681
+ else if (nm === 'update_sample') setRuns(doc, sp, [{ text: footnote ? 'Base: ' + settings.sample : settings.sample }]);
682
+ else if (ph === 'body') setRuns(doc, sp, [{ text: 'Associative Network' }]);
683
+ else if (ph === 'ftr' && settings.footer) setRuns(doc, sp, [{ text: settings.footer }]);
684
+ else if (nm === 'net.legend') setRuns(doc, sp, settings.legendRuns.map(function (r) { return { text: r.text, color: r.color, pt: legendPt }; }));
685
+ else if (nm === 'viz.logo') {
686
+ if (!flag) { tree.removeChild(sp); return; }
687
+ var blip = all(sp, NS.a, 'blip')[0];
688
+ var rel = rdoc.createElementNS(NS.rel, 'Relationship');
689
+ rel.setAttribute('Id', 'rIdFlag'); rel.setAttribute('Type', NS.r + '/image');
690
+ rel.setAttribute('Target', '../media/' + flag.part.split('/').pop());
691
+ rdoc.documentElement.appendChild(rel);
692
+ blip.setAttributeNS(NS.r, 'r:embed', 'rIdFlag');
693
+ var dims = imageSize(flagBytes);
694
+ if (dims && dims[0] && dims[1]) { // width kept, height by the flag's aspect, about the slot's centre
695
+ var off = all(sp, NS.a, 'off')[0], ext = all(sp, NS.a, 'ext')[0];
696
+ var cx = +ext.getAttribute('cx'), cy = +ext.getAttribute('cy'), y = +off.getAttribute('y');
697
+ var h = Math.round(cx * dims[1] / dims[0]);
698
+ off.setAttribute('y', String(Math.round(y + cy / 2 - h / 2))); ext.setAttribute('cy', String(h));
699
+ }
700
+ }
701
+ });
702
+ // the network: lines, then dots, then names - on top of the card
703
+ var net = item.net, by = {}, xml = [];
704
+ net.nodes.forEach(function (n) { by[n.name] = n; });
705
+ var flat = net.style === 'C';
706
+ net.edges.forEach(function (ed) { xml.push(lineXml(id++, ed, by[ed.a], by[ed.b], minC, maxC, flat)); });
707
+ net.nodes.forEach(function (n) { xml.push(dotXml(id++, n, flat)); });
708
+ net.nodes.forEach(function (n) { xml.push(labelXml(id++, n, flat)); });
709
+ var frag = parse('<p:spTree xmlns:p="' + NS.p + '" xmlns:a="' + NS.a + '" xmlns:r="' + NS.r + '">' + xml.join('') + '</p:spTree>', P);
710
+ Array.prototype.slice.call(frag.documentElement.childNodes).forEach(function (c) { tree.appendChild(doc.importNode(c, true)); });
711
+ zip.file(part, new S().serializeToString(doc));
712
+ zip.file(relsPath(part), new S().serializeToString(rdoc));
713
+ var ov = ctDoc.createElementNS(NS.ct, 'Override');
714
+ ov.setAttribute('PartName', '/' + part);
715
+ ov.setAttribute('ContentType', 'application/vnd.openxmlformats-officedocument.presentationml.slide+xml');
716
+ ctDoc.documentElement.appendChild(ov);
717
+ var rid = 'rId' + (++maxRid);
718
+ var r = prelDoc.createElementNS(NS.rel, 'Relationship');
719
+ r.setAttribute('Id', rid); r.setAttribute('Type', NS.r + '/slide'); r.setAttribute('Target', 'slides/slide' + no + '.xml');
720
+ relRoot.appendChild(r);
721
+ var sid = presDoc.createElementNS(NS.p, 'p:sldId');
722
+ sid.setAttribute('id', String(++maxId)); sid.setAttributeNS(NS.r, 'r:id', rid);
723
+ sldIdLst.appendChild(sid);
724
+ });
725
+ // remove the template and the flags slides
726
+ M.slides.forEach(function (part) {
727
+ zip.remove(part); zip.remove(relsPath(part));
728
+ all(ctDoc, NS.ct, 'Override').forEach(function (o) { if (o.getAttribute('PartName') === '/' + part) ctDoc.documentElement.removeChild(o); });
729
+ });
730
+ zip.file('ppt/presentation.xml', new S().serializeToString(presDoc));
731
+ zip.file('ppt/_rels/presentation.xml.rels', new S().serializeToString(prelDoc));
732
+ zip.file('[Content_Types].xml', new S().serializeToString(ctDoc));
733
+ // flag pictures nobody shows any more leave the file
734
+ var relFiles = Object.keys(zip.files).filter(function (f) { return /\.rels$/.test(f); });
735
+ return Promise.all(relFiles.map(function (f) { return zip.file(f).async('string'); })).then(function (texts) {
736
+ var used = {};
737
+ texts.forEach(function (t, i) {
738
+ var re = /Target="([^"]+)"/g, m;
739
+ while ((m = re.exec(t))) used[resolve(relFiles[i].replace('/_rels/', '/').replace(/\.rels$/, ''), m[1])] = 1;
740
+ });
741
+ M.flags.forEach(function (f) { if (!used[f.part]) zip.remove(f.part); });
742
+ return zip.generateAsync({ type: env.outputType || 'blob', compression: 'DEFLATE',
743
+ mimeType: 'application/vnd.openxmlformats-officedocument.presentationml.presentation' });
744
+ });
745
+ });
746
+ }
747
+
748
+ function legendRuns(showIdx) {
749
+ return [{ text: '● ', color: COLORS.reward }, { text: 'emotional ', color: COLORS.legend },
750
+ { text: '● ', color: COLORS.nonreward }, { text: 'functional ', color: COLORS.legend },
751
+ { text: (showIdx ? 'dot size & (…) = category index' : 'dot size = category index') +
752
+ ' · line thickness = strength of connection', color: COLORS.legend }];
753
+ }
754
+
755
+ var api = { sizesOf: sizesOf, wrap: wrap, layoutNetwork: layoutNetwork, openMaster: openMaster, suggestFlag: suggestFlag,
756
+ buildDeck: buildDeck, legendRuns: legendRuns, imageSize: imageSize };
757
+ if (typeof module !== 'undefined' && module.exports) module.exports = api;
758
+ else root.NetPptx = api;
759
+ })(this);
pptx_export_ui.js ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* The PowerPoint button of the generated HTML: find the network masters,
2
+ confirm master / sample / flag / footer, get one slide per attribute
3
+ (pptx_export.js).
4
+ The masters live in one fixed folder (auto report\Input\network masters).
5
+ A web page cannot open a folder on its own, so the user picks it ONCE; the
6
+ browser remembers it (Edge/Chrome) and only asks to allow access again.
7
+ Browsers without that ability (e.g. Firefox) pick the master file each time.
8
+ Uses the page's own data and rules: attrMeta, buildNetwork, getMaxL1,
9
+ isReward, SHOW_CAT_IDX, MIN_CORR, MAX_CORR, PROJECT, CHART_TITLE. */
10
+ (function () {
11
+ 'use strict';
12
+ var FOLDER = 'auto report\\Input\\network masters';
13
+ var masters = []; // [{file, frame, bytes, M}] - what was found
14
+
15
+ function $(id) { return document.getElementById(id); }
16
+ function escH(s) { return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;'); }
17
+ function label(frame) { return frame === 'DECODE' ? 'DECODE / P&G' : frame; }
18
+
19
+ // the attributes exactly as the list on the left shows them (filter, search, sort)
20
+ function listedAttributes() {
21
+ return Array.prototype.map.call(document.querySelectorAll('#sidebarList .attr-row'), function (r) {
22
+ return +r.getAttribute('data-index');
23
+ });
24
+ }
25
+
26
+ function networkOf(idx, maxL1) {
27
+ var data = buildNetwork(idx, maxL1);
28
+ return {
29
+ nodes: data.nodes.map(function (n) { return { name: n.id, level: n.level, cat: n.value, reward: isReward(n.id) }; }),
30
+ edges: data.edges.map(function (e) { return { a: e.from, b: e.to, val: e.value }; })
31
+ };
32
+ }
33
+
34
+ function measurer(font) {
35
+ var ctx = document.createElement('canvas').getContext('2d');
36
+ return function (text, pt, bold) {
37
+ ctx.font = (bold ? 'bold ' : '') + pt + 'pt "' + font + '", Arial, sans-serif';
38
+ return ctx.measureText(text).width * 0.75; // px -> pt
39
+ };
40
+ }
41
+
42
+ function footerDefault(frame) {
43
+ var parts = [PROJECT.client, PROJECT.brand, PROJECT.category, PROJECT.country].filter(Boolean).join(' ');
44
+ var year = String(new Date().getFullYear());
45
+ return frame === 'DECODE' ? ['DECODE Marketingberatung GmbH', parts, year].filter(Boolean).join(' | ')
46
+ : [parts, year].filter(Boolean).join(' | ');
47
+ }
48
+
49
+ // ------------------------------------------------ the remembered folder
50
+ function db() {
51
+ return new Promise(function (ok, no) {
52
+ var r = indexedDB.open('network-pptx-export', 1);
53
+ r.onupgradeneeded = function () { r.result.createObjectStore('folder'); };
54
+ r.onsuccess = function () { ok(r.result); };
55
+ r.onerror = function () { no(r.error); };
56
+ });
57
+ }
58
+ function remembered() {
59
+ return db().then(function (d) {
60
+ return new Promise(function (ok) {
61
+ var q = d.transaction('folder').objectStore('folder').get('masters');
62
+ q.onsuccess = function () { ok(q.result || null); };
63
+ q.onerror = function () { ok(null); };
64
+ });
65
+ }).catch(function () { return null; });
66
+ }
67
+ function remember(handle) {
68
+ return db().then(function (d) {
69
+ var t = d.transaction('folder', 'readwrite');
70
+ if (handle) t.objectStore('folder').put(handle, 'masters'); else t.objectStore('folder').delete('masters');
71
+ }).catch(function () {});
72
+ }
73
+
74
+ function allowed(h) {
75
+ if (!h) return Promise.resolve(null);
76
+ return h.queryPermission({ mode: 'read' }).then(function (p) {
77
+ return p === 'granted' ? p : h.requestPermission({ mode: 'read' });
78
+ }).then(function (p) { return p === 'granted' ? h : null; }).catch(function () { return null; });
79
+ }
80
+
81
+ function pickFolder() {
82
+ return window.showDirectoryPicker({ id: 'network-masters', mode: 'read' }).then(function (h) { remember(h); return h; });
83
+ }
84
+
85
+ function mastersIn(h) {
86
+ var it = h.values(), found = [];
87
+ function next() {
88
+ return it.next().then(function (r) {
89
+ if (r.done) return found;
90
+ if (r.value.kind === 'file' && /^Network master .+\.pptx$/i.test(r.value.name)) found.push(r.value);
91
+ return next();
92
+ });
93
+ }
94
+ return next().then(function (entries) {
95
+ return Promise.all(entries.map(function (e) { return e.getFile(); }));
96
+ });
97
+ }
98
+
99
+ function load(files) {
100
+ return Promise.all(files.map(function (f) {
101
+ return f.arrayBuffer().then(function (buf) {
102
+ return NetPptx.openMaster(JSZip, buf, { DOMParser: DOMParser, XMLSerializer: XMLSerializer }).then(function (M) {
103
+ return { file: f.name, frame: M.meta.frame, bytes: buf, M: M };
104
+ });
105
+ }).catch(function () { return null; }); // not a network master: left out
106
+ })).then(function (list) {
107
+ return list.filter(Boolean).sort(function (a, b) {
108
+ return (a.frame === 'DECODE' ? '' : a.frame).localeCompare(b.frame === 'DECODE' ? '' : b.frame);
109
+ });
110
+ });
111
+ }
112
+
113
+ function opened(list, where) {
114
+ if (!list.length) {
115
+ remember(null);
116
+ return alert('No network master found' + (where ? ' in "' + where + '"' : '') + '.\n' +
117
+ 'Please click PowerPoint again and pick the folder "' + FOLDER + '".');
118
+ }
119
+ masters = list;
120
+ showDialog(defaultMaster());
121
+ }
122
+
123
+ // the client's own master if there is one (PROJECT.client), else DECODE
124
+ function defaultMaster() {
125
+ var c = String(PROJECT.client || '').toLowerCase(), i;
126
+ for (i = 0; i < masters.length; i++) if (c && c.indexOf(masters[i].frame.toLowerCase()) >= 0) return i;
127
+ for (i = 0; i < masters.length; i++) if (masters[i].frame === 'DECODE') return i;
128
+ return 0;
129
+ }
130
+
131
+ window.startPptxExport = function (otherFolder) {
132
+ if (!window.showDirectoryPicker) { // no folder access in this browser: pick the file(s)
133
+ var input = $('pptxMasterPick');
134
+ input.value = '';
135
+ return input.click();
136
+ }
137
+ var where = '';
138
+ (otherFolder ? Promise.resolve(null) : remembered().then(allowed)).then(function (h) {
139
+ return h || pickFolder();
140
+ }).then(function (h) {
141
+ where = h.name;
142
+ return mastersIn(h);
143
+ }).then(load).then(function (list) { opened(list, where); }).catch(function (err) {
144
+ if (err && err.name === 'AbortError') return; // the user closed the folder window
145
+ alert('The network masters could not be read: ' + (err.message || err));
146
+ });
147
+ };
148
+
149
+ function onPicked(ev) {
150
+ var files = Array.prototype.slice.call(ev.target.files || []);
151
+ if (files.length) load(files).then(function (list) { opened(list, ''); });
152
+ }
153
+
154
+ // ------------------------------------------------ the dialog
155
+ function showDialog(mi, keep) {
156
+ var m = masters[mi], M = m.M;
157
+ var attrs = listedAttributes(), maxL1 = getMaxL1();
158
+ var flagOpts = '<option value="">- no flag -</option>' + M.flags.slice().sort(function (a, b) { return a.name.localeCompare(b.name); })
159
+ .map(function (f) { return '<option value="' + f.code + '">' + escH(f.name) + ' (' + f.code + ')</option>'; }).join('');
160
+ var fontOk = !document.fonts || document.fonts.check('12pt "' + M.meta.font + '"');
161
+ var masterOpts = masters.map(function (x, i) {
162
+ return '<option value="' + i + '"' + (i === mi ? ' selected' : '') + '>' + escH(label(x.frame)) + '</option>';
163
+ }).join('');
164
+ var box = $('pptxDialog');
165
+ box.innerHTML =
166
+ '<div class="xp">' +
167
+ '<h2>PowerPoint</h2>' +
168
+ '<p class="sub">' + escH(m.file) + (window.showDirectoryPicker ? ' &middot; <a href="#" id="xpFolder">other folder</a>' : '') + '</p>' +
169
+ '<div class="row"><b>' + attrs.length + ' attributes</b> as listed on the left; the network shows ' +
170
+ '<b>' + maxL1 + ' connections</b> each (the Connections setting).</div>' +
171
+ '<label>Master</label><select id="xpMaster">' + masterOpts + '</select>' +
172
+ '<label>Sample</label><input id="xpSample" value="Total">' +
173
+ '<label>Country flag</label><select id="xpFlag">' + flagOpts + '</select>' +
174
+ '<label>Footer</label><input id="xpFooter" value="' + escH(footerDefault(M.meta.frame)) + '">' +
175
+ (fontOk ? '' : '<p class="warn">The font "' + escH(M.meta.font) + '" is not installed on this PC. The slides still use it, ' +
176
+ 'but names may sit a little closer together than planned.</p>') +
177
+ '<p class="status" id="xpStatus"></p>' +
178
+ '<div class="btns"><button id="xpCancel">Cancel</button><button id="xpGo" class="primary">Create PowerPoint</button></div>' +
179
+ '</div>';
180
+ box.style.display = 'flex';
181
+ $('xpFlag').value = NetPptx.suggestFlag(M, PROJECT.country);
182
+ if (keep) { $('xpSample').value = keep.sample; $('xpFlag').value = keep.flag; } // switching the master keeps these
183
+ $('xpMaster').onchange = function () {
184
+ showDialog(+this.value, { sample: $('xpSample').value, flag: $('xpFlag').value });
185
+ };
186
+ if ($('xpFolder')) $('xpFolder').onclick = function (ev) { ev.preventDefault(); closeDialog(); window.startPptxExport(true); };
187
+ $('xpCancel').onclick = closeDialog;
188
+ $('xpGo').onclick = function () { run(m, attrs, maxL1); };
189
+ if (!attrs.length) { $('xpGo').disabled = true; $('xpStatus').textContent = 'No attribute is listed on the left (check the filter).'; }
190
+ }
191
+
192
+ function closeDialog() { var b = $('pptxDialog'); b.style.display = 'none'; b.innerHTML = ''; }
193
+
194
+ function run(m, attrs, maxL1) {
195
+ var M = m.M;
196
+ var settings = { sample: $('xpSample').value.trim() || 'Total', flag: $('xpFlag').value,
197
+ footer: $('xpFooter').value.trim(), legendRuns: NetPptx.legendRuns(SHOW_CAT_IDX) };
198
+ $('xpGo').disabled = true; $('xpCancel').disabled = true; $('xpMaster').disabled = true;
199
+ var status = $('xpStatus'), measure = measurer(M.meta.font), sizes = NetPptx.sizesOf(M);
200
+ var nets = [], small = [], k = 0;
201
+ function step() {
202
+ if (k < attrs.length) {
203
+ var idx = attrs[k], name = attrMeta[idx].name;
204
+ status.textContent = 'Laying out ' + (k + 1) + ' of ' + attrs.length + ': ' + name;
205
+ var net = NetPptx.layoutNetwork(networkOf(idx, maxL1), M.area, measure, { showIdx: SHOW_CAT_IDX, sizes: sizes });
206
+ if (net.pt !== 12) small.push(name);
207
+ nets.push({ attr: name, net: net });
208
+ k++;
209
+ setTimeout(step, 0); // let the page breathe between slides
210
+ return;
211
+ }
212
+ status.textContent = 'Writing the PowerPoint...';
213
+ // a fresh copy of the master for every export (building changes it)
214
+ NetPptx.openMaster(JSZip, m.bytes, { DOMParser: DOMParser, XMLSerializer: XMLSerializer }).then(function (fresh) {
215
+ return NetPptx.buildDeck(fresh, nets, settings, MIN_CORR, MAX_CORR);
216
+ }).then(function (blob) {
217
+ var a = document.createElement('a');
218
+ a.href = URL.createObjectURL(blob);
219
+ a.download = CHART_TITLE + '_Associative networks_' + M.meta.frame + '.pptx';
220
+ document.body.appendChild(a); a.click(); a.remove();
221
+ status.innerHTML = 'Done: ' + nets.length + ' slides, saved to your Downloads.' +
222
+ (small.length ? ' ' + small.length + ' at the smaller size (' + sizes[1][0] + 'pt) because the names did not fit' +
223
+ (small.length <= 10 ? ': ' + escH(small.join(', ')) : '') + '.' : '');
224
+ $('xpCancel').disabled = false; $('xpCancel').textContent = 'Close';
225
+ }).catch(function (err) { status.textContent = 'Something went wrong: ' + (err.message || err); $('xpCancel').disabled = false; });
226
+ }
227
+ step();
228
+ }
229
+
230
+ document.addEventListener('DOMContentLoaded', function () {
231
+ $('pptxMasterPick').addEventListener('change', onPicked);
232
+ });
233
+ })();
scripts/make_network_masters.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Build the two "network masters" the HTML's PowerPoint export reads.
3
+
4
+ The export (in the generated HTML) never ships a client's master: the user picks
5
+ one of these files when exporting. Each is made from the reporting tool's own
6
+ slide frame, so a network slide sits exactly where the tool's charts sit:
7
+
8
+ slide 1 the network template slide - title, header, footer, date, slide
9
+ number, Sample box (DECODE) or base footnote (Henkel), flag, and:
10
+ net.card the white card (DECODE only; JM's trial, 2026-11-17)
11
+ net.area where the network is drawn (invisible, removed on export)
12
+ net.legend the legend line under the network
13
+ net.meta what the export needs to know (invisible, removed)
14
+ slide 2 hidden - every country flag, one picture per country, named
15
+ "flag <CODE> | <english name>" (from the tool's flag deck)
16
+
17
+ Run it again whenever the reporting tool's frame or flag deck changes:
18
+
19
+ python scripts/make_network_masters.py <auto report folder>
20
+
21
+ It reads tool/app/templates/DECODE_grid_library.pptx (DECODE frame, also P&G)
22
+ clients/Henkel/frame.pptx (Henkel frame)
23
+ Henkel_reports_countrymaps_flags.pptx (flags)
24
+ clients/REWE/frame.pptx (REWE frame)
25
+ and writes Input/network masters/Network master DECODE.pptx
26
+ Input/network masters/Network master Henkel.pptx
27
+ Input/network masters/Network master REWE.pptx
28
+ """
29
+ import io
30
+ import re
31
+ import sys
32
+ from pathlib import Path
33
+
34
+ from pptx import Presentation
35
+ from pptx.dml.color import RGBColor
36
+ from pptx.enum.shapes import MSO_SHAPE
37
+ from pptx.oxml.ns import qn
38
+
39
+ VERSION = "1"
40
+
41
+ # What survives from the tool's frame slide. Everything else (axis titles,
42
+ # quadrant tags, Index badge, factor icon, scale, spec.* style samples) is a
43
+ # grid's, not the network's.
44
+ KEEP_PLACEHOLDERS = {"TITLE", "BODY", "FOOTER", "DATE", "SLIDE_NUMBER"}
45
+ KEEP_NAMES = {"label_sample", "update_sample", "viz.logo"}
46
+
47
+ FRAMES = {
48
+ "DECODE": {
49
+ "source": Path("tool/app/templates/DECODE_grid_library.pptx"),
50
+ # JM's trial slide (2026-11-17, "trial C" page 2): white card and legend
51
+ "card": (26.4, 153.7, 884.1, 320.3),
52
+ "area_inset": (14.0, 10.0), # pt inside the card, left/right and top/bottom
53
+ "legend": (32.4, 476.0, 648.0, 14.0),
54
+ "legend_pt": 8, # the frame's own legend size (spec.legend.text)
55
+ "footnote": False,
56
+ },
57
+ "Henkel": {
58
+ "source": Path("clients/Henkel/frame.pptx"),
59
+ "card": None, # Henkel: no card (JM, 2026-10-15)
60
+ "area": "viz.card", # the network takes the card's region
61
+ "legend": "viz.legend",
62
+ "legend_pt": 7,
63
+ "footnote": True, # the base goes in update_sample: "Base: ..."
64
+ },
65
+ "REWE": {
66
+ "source": Path("clients/REWE/frame.pptx"),
67
+ "card": None, # REWE: plain cards (tool profile look.plain_cards)
68
+ "area": "viz.chart", # below the subline (viz.cardline1)
69
+ "legend": "viz.legend",
70
+ "legend_span": "viz.chart", # REWE: legend under the chart, centred (JM, 2026-11-18)
71
+ "legend_align": "ctr",
72
+ "legend_pt": 8,
73
+ "footnote": True, # the base goes in update_sample: "Base: ..."
74
+ # the subline starts after the tool's chart icon; a network slide has no icon
75
+ "move": {"viz.cardline1": (43.0, None, 873.0, None)},
76
+ },
77
+ }
78
+ FLAG_DECK = Path("Henkel_reports_countrymaps_flags.pptx")
79
+ OUT_DIR = Path("Input/network masters")
80
+
81
+
82
+ def emu(pt):
83
+ return round(pt * 12700)
84
+
85
+
86
+ def rect_of(shape):
87
+ return tuple(v / 12700 for v in (shape.left, shape.top, shape.width, shape.height))
88
+
89
+
90
+ def theme_font(slide):
91
+ master = slide.slide_layout.slide_master
92
+ for rel in master.part.rels.values():
93
+ if rel.reltype.endswith("/theme"):
94
+ xml = rel.target_part.blob.decode("utf-8", "ignore")
95
+ m = re.search(r'<a:minorFont>\s*<a:latin typeface="([^"]*)"', xml)
96
+ if m:
97
+ return m.group(1)
98
+ return "Arial"
99
+
100
+
101
+ def drop(shape):
102
+ el = shape._element
103
+ el.getparent().remove(el)
104
+
105
+
106
+ def invisible_box(slide, name, rect, text=""):
107
+ tb = slide.shapes.add_textbox(*(emu(v) for v in rect))
108
+ tb.name = name
109
+ tb.text_frame.text = text
110
+ return tb
111
+
112
+
113
+ def flags_from(deck_path):
114
+ """[(code, english name, blob, ext)] - the picture sitting just above each
115
+ "(XX)" label, scored as the reporting tool does (assets.flag_blob)."""
116
+ prs = Presentation(deck_path)
117
+ pat = re.compile(r"^(.*?)\(\s*([A-Za-z]{2,3})\b", re.DOTALL)
118
+ seen, out = set(), []
119
+ for s in prs.slides:
120
+ pics = [sh for sh in s.shapes if sh.shape_type == 13 and sh.top is not None]
121
+ for lab in s.shapes:
122
+ if not getattr(lab, "has_text_frame", False):
123
+ continue
124
+ m = pat.match(lab.text_frame.text.strip())
125
+ if not m or len(m.group(2)) != 2:
126
+ continue
127
+ code = m.group(2).upper()
128
+ name = re.sub(r"\s+", " ", m.group(1)).strip()
129
+ if code in seen or "flags of the world" in name.lower():
130
+ continue
131
+ cand = sorted([(abs((p.left + p.width / 2) - (lab.left + lab.width / 2))
132
+ + abs((p.top + p.height) - lab.top), i, p)
133
+ for i, p in enumerate(pics) if p.top < lab.top])
134
+ if cand:
135
+ img = cand[0][2].image
136
+ seen.add(code)
137
+ out.append((code, name, img.blob, img.ext))
138
+ return sorted(out)
139
+
140
+
141
+ def build(root, client, cfg, flags):
142
+ prs = Presentation(root / cfg["source"])
143
+ if len(prs.slides) != 1:
144
+ raise SystemExit(f"{cfg['source']}: expected ONE frame slide, found {len(prs.slides)}")
145
+ slide = prs.slides[0]
146
+ by_name = {sh.name: sh for sh in slide.shapes}
147
+
148
+ # regions read off the frame before anything is removed
149
+ if cfg.get("area"):
150
+ area = rect_of(by_name[cfg["area"]])
151
+ else:
152
+ x, y, w, h = cfg["card"]
153
+ ix, iy = cfg["area_inset"]
154
+ area = (x + ix, y + iy, w - 2 * ix, h - 2 * iy)
155
+ legend = rect_of(by_name[cfg["legend"]]) if isinstance(cfg["legend"], str) else cfg["legend"]
156
+ if cfg.get("legend_span"):
157
+ sx, _, sw, _ = rect_of(by_name[cfg["legend_span"]])
158
+ legend = (sx, legend[1], sw, legend[3])
159
+
160
+ for name, rect in cfg.get("move", {}).items():
161
+ sh = by_name[name]
162
+ for attr, v in zip(("left", "top", "width", "height"), rect):
163
+ if v is not None:
164
+ setattr(sh, attr, emu(v))
165
+
166
+ for sh in list(slide.shapes):
167
+ if sh.is_placeholder:
168
+ if sh.placeholder_format.type.name in KEEP_PLACEHOLDERS:
169
+ continue
170
+ elif sh.name in KEEP_NAMES:
171
+ continue
172
+ drop(sh)
173
+
174
+ # the notes page of the frame (the tool's style notes) does not travel
175
+ for rid, rel in list(slide.part.rels.items()):
176
+ if rel.reltype.endswith("/notesSlide"):
177
+ slide.part.drop_rel(rid)
178
+
179
+ font = theme_font(slide)
180
+ if cfg["card"]:
181
+ card = slide.shapes.add_shape(MSO_SHAPE.ROUNDED_RECTANGLE, *(emu(v) for v in cfg["card"]))
182
+ card.name = "net.card"
183
+ card.adjustments[0] = 0.02997
184
+ card.fill.solid()
185
+ card.fill.fore_color.rgb = RGBColor(0xFF, 0xFF, 0xFF)
186
+ card.line.fill.background()
187
+ card.shadow.inherit = False
188
+ # behind everything else that is drawn on the slide
189
+ sp_tree = card._element.getparent()
190
+ sp_tree.remove(card._element)
191
+ first = next(i for i, el in enumerate(sp_tree) if el.tag in (qn("p:sp"), qn("p:pic"), qn("p:grpSp"), qn("p:cxnSp")))
192
+ sp_tree.insert(first, card._element)
193
+
194
+ invisible_box(slide, "net.area", area)
195
+ lg = invisible_box(slide, "net.legend", legend)
196
+ lg.text_frame.margin_left = lg.text_frame.margin_right = 0
197
+ lg.text_frame.margin_top = lg.text_frame.margin_bottom = 0
198
+ if cfg.get("legend_align") == "ctr":
199
+ from pptx.enum.text import PP_ALIGN
200
+ lg.text_frame.paragraphs[0].alignment = PP_ALIGN.CENTER
201
+ meta = {
202
+ "network-master": VERSION, "frame": client, "font": font,
203
+ "legend_pt": cfg["legend_pt"], "footnote": "1" if cfg["footnote"] else "0",
204
+ "slide_w": round(prs.slide_width / 12700, 2), "slide_h": round(prs.slide_height / 12700, 2),
205
+ }
206
+ invisible_box(slide, "net.meta", (0, prs.slide_height / 12700 + 20, 300, 60),
207
+ "\n".join(f"{k}={v}" for k, v in meta.items()))
208
+
209
+ # slide 2, hidden: the flags
210
+ blank = min(slide.slide_layout.slide_master.slide_layouts, key=lambda l: len(l.placeholders))
211
+ fs = prs.slides.add_slide(blank)
212
+ for ph in list(fs.placeholders):
213
+ drop(ph)
214
+ fs._element.set("show", "0")
215
+ for i, (code, name, blob, ext) in enumerate(flags):
216
+ pic = fs.shapes.add_picture(io.BytesIO(blob), emu(20 + (i % 16) * 40), emu(20 + (i // 16) * 30), emu(32))
217
+ pic.name = f"flag {code} | {name}"
218
+ out = root / OUT_DIR / f"Network master {client}.pptx"
219
+ out.parent.mkdir(parents=True, exist_ok=True)
220
+ prs.save(out)
221
+ return out, meta, area, legend
222
+
223
+
224
+ def main(argv):
225
+ if len(argv) != 2:
226
+ print(__doc__)
227
+ return 2
228
+ root = Path(argv[1])
229
+ flags = flags_from(root / FLAG_DECK)
230
+ print(f"{len(flags)} flags read from {FLAG_DECK}")
231
+ for client, cfg in FRAMES.items():
232
+ out, meta, area, legend = build(root, client, cfg, flags)
233
+ print(f"{client}: {out}\n font {meta['font']}, slide {meta['slide_w']} x {meta['slide_h']} pt, "
234
+ f"network area {tuple(round(v, 1) for v in area)}, legend {tuple(round(v, 1) for v in legend)}")
235
+ return 0
236
+
237
+
238
+ if __name__ == "__main__":
239
+ sys.exit(main(sys.argv))