@luutuankiet/clipboard2markdown 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -79,6 +79,12 @@ Per diagram it writes `<name>.png` (scale 3, lowered until the image has at most
79
79
  c2m excalidraw --png flow.mmd # PNG + link + paste block
80
80
  ```
81
81
 
82
+ **Comics and doodles in a compact text format** (`c2m excalidraw <file>.c2m`, also `.sketch`): an agent writes about 20 lines (panels, stick figures, speech bubbles, boxes, arrows, a callout) and gets a laid-out comic in the house style, with no coordinates. The same link, PNG and paste block come out, and the lint runs on the result. A 3-panel strip is under 1,000 characters instead of roughly 7,600 characters of element JSON. Errors name the file, the line and a fix. Full grammar in `c2m excalidraw --help`, section SKETCH.
83
+
84
+ ```bash
85
+ c2m excalidraw --strict --png comic.c2m # panel "Title" / me: figure @left / me says "Hi" / a -> b "label"
86
+ ```
87
+
82
88
  **Lint and `--strict`** (every input): the finished scene is checked for a node sticking out of its subgraph frame, overlapping nodes, a literal `<br>` shown as text, unbound or floating arrows, text wider than its box, and text that would print under 8 pt at page width (468 pt, change with `--page-pt`). Findings print as `warning: lint ...` lines. `--strict` turns any error into exit 1 with no PNG and no link; `c2m lint <file>...` (or `c2m excalidraw --lint-only`) only checks. Mermaid input also turns `<br>` into line breaks, redraws `flowchart LR` / `graph LR` as TD (with a warning) and fits subgraph frames around their nodes.
83
89
 
84
90
  ```bash
package/bin/excalidraw.js CHANGED
@@ -7,6 +7,7 @@
7
7
  import { mkdirSync, readFileSync, writeFileSync } from 'fs';
8
8
  import { basename, dirname, resolve } from 'path';
9
9
  import { buildSkeleton } from '../src/diagrams/skeleton.js';
10
+ import { sketchToSkeleton, SKETCH_EXT } from '../src/sketch.js';
10
11
  import { saveScene } from '../src/diagrams/share-link.js';
11
12
  import { sceneToMermaid } from '../src/diagrams/scene-to-mermaid.js';
12
13
  import { lintScene, formatFinding, hasErrors, ALL_CLASSES, PAGE_PT } from '../src/lint.js';
@@ -23,6 +24,7 @@ Usage:
23
24
  draw into a working copy's images folder
24
25
  c2m excalidraw <file.mmd> a Mermaid diagram instead (see MERMAID below)
25
26
  c2m excalidraw <shot.json> an annotated screenshot (see DOODLE below)
27
+ c2m excalidraw <file.c2m> a comic or doodle in the compact text format (see SKETCH below)
26
28
  c2m excalidraw --strict ... refuse to draw or upload when the lint finds an error
27
29
  c2m lint <file>... check only, any input: exit 1 on an error finding
28
30
  (same as c2m excalidraw --lint-only <file>...)
@@ -219,6 +221,26 @@ DOODLE (annotated screenshot: a JSON object with "image" and "notes")
219
221
  picture (excalidraw.com stores pictures apart from the link), so every
220
222
  doodle warns; the PNG is the deliverable.
221
223
 
224
+ SKETCH (a comic or quick doodle in a compact text format: file.c2m or file.sketch)
225
+ One statement per line; indent = inside the preceding panel. # starts a comment.
226
+ Use it for strips and small explainers: it lays everything out for you (no
227
+ coordinates), so a 3-panel comic is about 20 lines instead of 150 of JSON.
228
+ strip [N cols] optional first line: panel grid width (default 2)
229
+ title "text" optional heading above the strip
230
+ panel "Title" [note "caption"] starts a panel; the statements below belong to it
231
+ grid R x C optional: lay the panel's boxes in R rows x C columns
232
+ id: figure [sad|happy] [@left|@right] ["Label"] stick figure with a name tag
233
+ id: box "Text" [marker] rectangle; \\n breaks a line
234
+ a -> b ["label"] [marker] arrow bound to two ids (labels are placed apart)
235
+ id says "text" [marker] speech bubble above that figure/box
236
+ id thinks "text" [marker] thought bubble (cloud tail)
237
+ stat "text" [marker] bold callout line at the panel bottom
238
+ note "text" small caption line inside the panel
239
+ markers: accent (blue), bad (red), good (green); anything else stays white.
240
+ Keep to <= 3 filled shapes and 2 colours per panel (lint g warns beyond that).
241
+ Errors name the line number and say how to fix it. Put the picture in the PNG:
242
+ c2m excalidraw --png <dir> --strict comic.c2m
243
+
222
244
  NOT SUPPORTED
223
245
  frames, freedraw, editing an existing link (use c2m diagrams edit for that),
224
246
  writing .excalidraw files, pictures in share links.
@@ -279,6 +301,7 @@ async function buildInputRaw(target, io) {
279
301
  var mermaid = await import('../src/mermaid-input.js');
280
302
  return Object.assign({ fence: 'mermaid' }, await mermaid.mermaidToScene(text));
281
303
  }
304
+ if (SKETCH_EXT.test(target)) return Object.assign({ fence: 'mermaid' }, toScene(sketchToSkeleton(text, target)));
282
305
  var input = parseJson(text);
283
306
  var doodle = await import('../src/doodle.js');
284
307
  if (doodle.isDoodleSpec(input)) {
@@ -314,13 +337,13 @@ function parseJson(text) {
314
337
  }
315
338
 
316
339
  function sceneName(target) {
317
- return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid)$/i, '');
340
+ return target === '-' ? 'diagram' : basename(target).replace(/\.(json|excalidraw|mmd|mermaid|c2m|sketch)$/i, '');
318
341
  }
319
342
 
320
343
  // `--png` takes an optional folder: the next argument is the folder unless it
321
344
  // looks like an input (-, *.json, *.excalidraw) or an option.
322
345
  function looksLikeInput(a) {
323
- return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid)$/i.test(a);
346
+ return a === '-' || a.startsWith('--') || /\.(json|excalidraw|mmd|mermaid|c2m|sketch)$/i.test(a);
324
347
  }
325
348
 
326
349
  // Returns the exit code. `io.fetch`, `io.stdin` and `io.env` exist for tests.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@luutuankiet/clipboard2markdown",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Convert rich clipboard HTML from Jira, Confluence, Slack and Google apps into clean Markdown, and back.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/sketch.js ADDED
@@ -0,0 +1,388 @@
1
+ // Compact comic / doodle format -> element array for the skeleton builder.
2
+ //
3
+ // An agent writes a few lines of text (see SKETCH in bin/excalidraw.js); this
4
+ // module parses them, lays everything out (no coordinates are ever written) and
5
+ // returns the same shorthand element array `c2m excalidraw` already accepts.
6
+ // From there the normal path runs unchanged: skeleton builder, lint, PNG, link.
7
+ //
8
+ // Look: everything is a white fill with a black stroke. Colour comes only from
9
+ // the markers `accent` (one blue, "look here"), `bad` (red) and `good` (green).
10
+ // Pure: no file or network access.
11
+
12
+ const FS = 16; // every text is 16 px; the scene is about 540 px wide, so it prints at about 14.5 pt
13
+ const CW = 0.68; // px per char per font px, equal to TEXT_METRICS.charWidth in diagrams/edit.js
14
+ const LH = 1.25; // line height
15
+ const PW = 256; // panel width
16
+ const PGAP = 32; // gap between panels
17
+ const M = 12; // margin inside a panel
18
+ const TAIL = 34; // gap between a bubble and its speaker's head
19
+ const SECTION = 18; // gap between sections of a panel
20
+ const INK = '#1e1e1e';
21
+ export const MARKERS = {
22
+ accent: { fill: '#a5d8ff', ink: '#1971c2' },
23
+ bad: { fill: '#ffc9c9', ink: '#e03131' },
24
+ good: { fill: '#b2f2bb', ink: '#2f9e44' },
25
+ };
26
+ const MOODS = ['ok', 'sad', 'happy'];
27
+ const SLOTS = ['@left', '@right', '@center'];
28
+
29
+ export const SKETCH_EXT = /\.(c2m|sketch)$/i;
30
+
31
+ function fail(file, line, text, msg, fix) {
32
+ var where = (file || 'input') + ':' + line;
33
+ throw new Error(where + ': ' + msg + (text ? '\n ' + String(text).trim() : '') + (fix ? '\n fix: ' + fix : ''));
34
+ }
35
+
36
+ // ---- parser ---------------------------------------------------------------
37
+
38
+ function tokenize(src) {
39
+ var out = [], re = /"((?:[^"\\]|\\.)*)"|->|:|#.*|[^\s":]+/g, m;
40
+ while ((m = re.exec(src))) {
41
+ if (m[0][0] === '#') break;
42
+ if (m[1] !== undefined) out.push({ q: true, v: m[1].replace(/\\(.)/g, function (_, c) { return c === 'n' ? '\n' : c; }) });
43
+ else out.push({ q: false, v: m[0] });
44
+ }
45
+ return out;
46
+ }
47
+
48
+ export function parseSketch(source, file) {
49
+ var doc = { cols: 2, title: null, body: [], panels: [], bodyGrid: 0 };
50
+ var panel = null;
51
+ String(source).split(/\r?\n/).forEach(function (raw, idx) {
52
+ var line = idx + 1;
53
+ var tk = tokenize(raw);
54
+ if (!tk.length) return;
55
+ var indented = /^\s/.test(raw);
56
+ var err = function (msg, fix) { fail(file, line, raw, msg, fix); };
57
+ var word = function (i) { return tk[i] && !tk[i].q ? tk[i].v : null; };
58
+ var str = function (i, what) {
59
+ if (!tk[i] || !tk[i].q) err('expected a quoted ' + what + ' here', 'write the text in double quotes, e.g. "Report"');
60
+ return tk[i].v;
61
+ };
62
+ // trailing markers and slots, in any order
63
+ var rest = function (from, allow) {
64
+ var o = { marker: null, slot: null, mood: null, words: [] };
65
+ for (var i = from; i < tk.length; i++) {
66
+ var w = word(i);
67
+ if (w && MARKERS[w]) { if (o.marker) err('two colour markers on one line (' + o.marker + ', ' + w + ')', 'use only one of accent, bad, good'); o.marker = w; }
68
+ else if (w && SLOTS.indexOf(w) >= 0 && allow.slot) o.slot = w.slice(1);
69
+ else if (w && MOODS.indexOf(w) >= 0 && allow.mood) o.mood = w;
70
+ else o.words.push(tk[i]);
71
+ }
72
+ return o;
73
+ };
74
+
75
+ var first = word(0);
76
+ if (!indented || !panel) {
77
+ if (indented && !panel && first !== 'strip' && first !== 'panel') {
78
+ // an indented line before any panel is just a body line
79
+ }
80
+ }
81
+ var target = indented && panel ? panel.stmts : doc.body;
82
+ if (!indented) panel = null;
83
+
84
+ if (first === 'strip') {
85
+ var n = Number(word(1));
86
+ if (!(n >= 1 && n <= 4)) err('strip needs a column count from 1 to 4', 'write: strip 2 cols (2 columns fit a 468 pt page at 14 pt text)');
87
+ doc.cols = n; return;
88
+ }
89
+ if (first === 'title') { doc.title = str(1, 'title'); return; }
90
+ if (first === 'panel') {
91
+ var r = rest(2, {});
92
+ panel = { title: str(1, 'panel title'), note: null, stmts: [], line: line };
93
+ if (r.words.length) {
94
+ if (r.words[0].v !== 'note' || !r.words[1] || !r.words[1].q || r.words.length > 2) err('after the panel title only note "caption" is allowed', 'write: panel "Title" note "One-line caption."');
95
+ panel.note = r.words[1].v;
96
+ }
97
+ doc.panels.push(panel); return;
98
+ }
99
+ if (first === 'grid') {
100
+ var g = Number(word(1));
101
+ if (!(g >= 1 && g <= 4)) err('grid needs a column count from 1 to 4', 'write: grid 2 cols');
102
+ (panel && indented ? panel : doc).grid = g; return;
103
+ }
104
+ if (first === 'stat' || first === 'text' || first === 'note') {
105
+ var rs = rest(2, {});
106
+ if (rs.words.length) err('unexpected text after the quoted string: ' + rs.words.map(function (t) { return t.v; }).join(' '), 'quote the whole text once; add \\n for a line break');
107
+ target.push({ kind: first === 'note' ? 'note' : 'stat', text: str(1, 'text'), marker: rs.marker, line: line }); return;
108
+ }
109
+ if (tk.some(function (t) { return !t.q && /->./.test(t.v) || !t.q && /.->/.test(t.v); })) err('write -> with a space on each side', 'e.g. a -> b "label"');
110
+ var ai = tk.findIndex(function (t) { return !t.q && t.v === '->'; });
111
+ if (ai >= 0) {
112
+ if (ai !== 1 || !word(0) || !word(2)) err('an arrow is written: from -> to ["label"] [accent|bad|good]', 'e.g. rpt -> db "query"');
113
+ var re = rest(3, {}), label = '';
114
+ if (re.words.length) {
115
+ var ws = re.words;
116
+ if (ws[0].v === ':' && !ws[0].q) label = ws.slice(1).map(function (t) { return t.v; }).join(' ');
117
+ else if (ws.length === 1 && ws[0].q) label = ws[0].v;
118
+ else err('unexpected text after the arrow target', 'label an arrow with : text or "text"');
119
+ }
120
+ target.push({ kind: 'edge', from: word(0), to: word(2), label: label, marker: re.marker, line: line }); return;
121
+ }
122
+ var w0 = word(0), w1 = word(1);
123
+ if (w1 === 'says' || w1 === 'thinks') {
124
+ var rb = rest(3, {});
125
+ if (rb.words.length) err('unexpected text after the quoted string', 'one quoted string, \\n for line breaks');
126
+ target.push({ kind: 'bubble', who: w0, think: w1 === 'thinks', text: str(2, 'speech'), marker: rb.marker, line: line }); return;
127
+ }
128
+ if (w0 && tk[1] && !tk[1].q && tk[1].v === ':') {
129
+ var kind = word(2);
130
+ if (kind === 'figure') {
131
+ var rf = rest(3, { slot: true, mood: true });
132
+ var name = '';
133
+ if (rf.words.length) { if (rf.words.length > 1 || !rf.words[0].q) err('a figure takes at most one quoted name', 'write: me: figure happy @left "You"'); name = rf.words[0].v; }
134
+ target.push({ kind: 'figure', id: w0, mood: rf.mood || 'ok', slot: rf.slot, name: name, marker: rf.marker, line: line }); return;
135
+ }
136
+ if (kind === 'box') {
137
+ var rx = rest(3, {});
138
+ if (rx.words.length !== 1 || !rx.words[0].q) err('a box needs one quoted label', 'write: db: box "Source\\nDB" good');
139
+ target.push({ kind: 'box', id: w0, label: rx.words[0].v, marker: rx.marker, line: line }); return;
140
+ }
141
+ err('unknown kind "' + kind + '" after "' + w0 + ':"', 'use figure or box');
142
+ }
143
+ err('cannot read this line', 'statements: strip N cols | title "t" | panel "t" [note "c"] | id: figure | id: box "l" | id says "t" | a -> b "l" | stat "t" | note "t" | grid N cols');
144
+ });
145
+ doc.panels.forEach(function (p) {
146
+ if (!p.stmts.length) fail(file, p.line, '', 'panel "' + p.title + '" has no statements', 'indent its figures, boxes and bubbles under the panel line with two spaces');
147
+ });
148
+ if (!doc.panels.length && !doc.body.length) fail(file, 1, '', 'nothing to draw', 'start with: strip 2 cols then panel "Title"');
149
+ return doc;
150
+ }
151
+
152
+ // ---- layout ---------------------------------------------------------------
153
+
154
+ function wrap(text, maxChars) {
155
+ return String(text).split('\n').map(function (para) {
156
+ var lines = [], cur = '';
157
+ para.split(/\s+/).filter(Boolean).forEach(function (w) {
158
+ if (!cur) cur = w;
159
+ else if ((cur + ' ' + w).length <= maxChars) cur += ' ' + w;
160
+ else { lines.push(cur); cur = w; }
161
+ });
162
+ lines.push(cur);
163
+ return lines.join('\n');
164
+ }).join('\n');
165
+ }
166
+ function chars(px) { return Math.max(4, Math.floor(px / (CW * FS))); }
167
+ function size(text) {
168
+ var ls = String(text).split('\n');
169
+ return { w: Math.ceil(Math.max.apply(null, ls.map(function (l) { return l.length; })) * CW * FS), h: Math.ceil(ls.length * LH * FS), n: ls.length };
170
+ }
171
+
172
+ function Maker(prefix) {
173
+ var n = 0, els = [];
174
+ return {
175
+ els: els,
176
+ id: function (p) { n++; return prefix + p + n; },
177
+ push: function (e) { els.push(e); return e; },
178
+ };
179
+ }
180
+
181
+ function shift(els, dx, dy) {
182
+ els.forEach(function (e) { if (typeof e.x === 'number') { e.x += dx; e.y += dy; } });
183
+ }
184
+
185
+ function layoutBody(stmts, W, scope, grid, file) {
186
+ var mk = Maker(scope + 'e');
187
+ var P = function (id) { return scope + id; };
188
+ var figs = stmts.filter(function (s) { return s.kind === 'figure'; });
189
+ var bubbles = stmts.filter(function (s) { return s.kind === 'bubble'; });
190
+ var boxes = stmts.filter(function (s) { return s.kind === 'box'; });
191
+ var edges = stmts.filter(function (s) { return s.kind === 'edge'; });
192
+ var stats = stmts.filter(function (s) { return s.kind === 'stat'; });
193
+ var notes = stmts.filter(function (s) { return s.kind === 'note'; });
194
+ var ids = {};
195
+ stmts.forEach(function (s) {
196
+ if (s.id) {
197
+ if (ids[s.id]) fail(file, s.line, '', 'id "' + s.id + '" is declared twice in this ' + (scope ? 'panel' : 'file'), 'rename one; ids only need to be unique inside their panel');
198
+ ids[s.id] = s;
199
+ }
200
+ });
201
+
202
+ // figure slots
203
+ var used = {};
204
+ figs.forEach(function (f) { if (f.slot) { if (used[f.slot]) fail(file, f.line, '', 'two figures in @' + f.slot, 'give each figure its own @left, @right or @center'); used[f.slot] = 1; } });
205
+ var order = figs.length === 3 ? ['left', 'center', 'right'] : ['left', 'right', 'center'];
206
+ figs.forEach(function (f) { if (!f.slot) { f.slot = order.filter(function (s) { return !used[s]; })[0]; if (!f.slot) fail(file, f.line, '', 'more than 3 figures in one panel', 'split the scene into two panels'); used[f.slot] = 1; } });
207
+ figs.forEach(function (f) {
208
+ f.nameText = f.name ? wrap(f.name, 12) : '';
209
+ f.hw = Math.max(40, f.nameText ? Math.ceil(size(f.nameText).w / 2) + 2 : 0);
210
+ f.cx = f.slot === 'left' ? M + f.hw : f.slot === 'right' ? W - M - f.hw : W / 2;
211
+ });
212
+ var speakers = {};
213
+ bubbles.forEach(function (b) {
214
+ var f = ids[b.who];
215
+ if (!f || f.kind !== 'figure') fail(file, b.line, '', '"' + b.who + '" is not a figure here', 'declare it first: ' + b.who + ': figure @left "Name" (declared here: ' + (Object.keys(ids).join(', ') || 'nothing') + ')');
216
+ if (speakers[b.who]) fail(file, b.line, '', '"' + b.who + '" already has a bubble in this panel', 'one bubble per figure; merge the two into one with \\n');
217
+ speakers[b.who] = 1; b.fig = f;
218
+ });
219
+
220
+ var y = 0, bw, ink;
221
+ // 1. bubbles, stacked in statement order, each leaning toward its speaker
222
+ var two = bubbles.length > 1;
223
+ var maxBW = two ? W - 80 : W - 2 * M;
224
+ bubbles.forEach(function (b) {
225
+ var f = b.fig, k = b.think ? Math.SQRT2 : 1;
226
+ var text = wrap(b.text, chars((maxBW / k) - 20));
227
+ var s = size(text);
228
+ b.text2 = text;
229
+ b.w = Math.ceil((s.w + 20) * k) + (b.think ? 8 : 0);
230
+ b.h = Math.ceil((s.h + 20) * k);
231
+ b.x = f.slot === 'left' ? M : f.slot === 'right' ? W - M - b.w : Math.round((W - b.w) / 2);
232
+ b.y = y;
233
+ y += b.h + 30;
234
+ });
235
+ if (bubbles.length) y = y - 30 + TAIL;
236
+ var figTop = y;
237
+
238
+ // 2. figures and their tails
239
+ bubbles.forEach(function (b) {
240
+ var f = b.fig, col = b.marker && MARKERS[b.marker];
241
+ var by = b.y + b.h, tx = Math.max(b.x + 14, Math.min(b.x + b.w - 14, f.cx)), tipY = figTop - 6;
242
+ mk.push({ id: P(b.who + '_' + (b.think ? 'thinks' : 'says')), type: b.think ? 'ellipse' : 'rectangle', x: b.x, y: b.y, width: b.w, height: b.h,
243
+ backgroundColor: col ? col.fill : '#ffffff', label: { text: b.text2, fontSize: FS } });
244
+ if (b.think) {
245
+ [[0.62, 9], [0.8, 6], [0.95, 4]].forEach(function (d) {
246
+ var py = by + (tipY - by) * d[0];
247
+ mk.push({ id: mk.id('dot'), type: 'line', x: tx + (f.cx - tx) * d[0], y: py, points: [[0, 0], [1, 0]], strokeWidth: d[1] });
248
+ });
249
+ } else {
250
+ mk.push({ id: mk.id('tail'), type: 'line', x: tx - 9, y: by, points: [[0, 0], [f.cx - tx + 9, tipY - by], [18, 0]], strokeWidth: 2 });
251
+ }
252
+ });
253
+ var figH = 0;
254
+ figs.forEach(function (f) {
255
+ var col = f.marker && MARKERS[f.marker], cx = f.cx, t = figTop, sw = 3;
256
+ mk.push({ id: P(f.id + '_head'), type: 'ellipse', x: cx - 17, y: t, width: 34, height: 34, strokeWidth: sw, backgroundColor: col ? col.fill : '#ffffff' });
257
+ [-6, 6].forEach(function (dx) { mk.push({ id: mk.id('eye'), type: 'line', x: cx + dx, y: t + 14, points: [[0, 0], [1, 0]], strokeWidth: 5 }); });
258
+ var mouth = f.mood === 'happy' ? [[0, 0], [8, 7], [16, 0]] : f.mood === 'sad' ? [[0, 7], [8, 0], [16, 7]] : [[0, 0], [16, 0]];
259
+ mk.push({ id: mk.id('mouth'), type: 'line', x: cx - 8, y: t + 23, points: mouth, strokeWidth: 2 });
260
+ mk.push({ id: mk.id('torso'), type: 'line', x: cx, y: t + 34, points: [[0, 0], [0, 44]], strokeWidth: sw });
261
+ mk.push({ id: mk.id('arm'), type: 'line', x: cx, y: t + 46, points: [[0, 0], [-30, 22]], strokeWidth: sw });
262
+ mk.push({ id: mk.id('arm'), type: 'line', x: cx, y: t + 46, points: [[0, 0], [30, -14]], strokeWidth: sw });
263
+ mk.push({ id: mk.id('leg'), type: 'line', x: cx, y: t + 78, points: [[0, 0], [-22, 38]], strokeWidth: sw });
264
+ mk.push({ id: mk.id('leg'), type: 'line', x: cx, y: t + 78, points: [[0, 0], [22, 38]], strokeWidth: sw });
265
+ var h = 120;
266
+ if (f.nameText) {
267
+ var s = size(f.nameText);
268
+ mk.push({ id: mk.id('name'), type: 'text', x: cx - s.w / 2, y: t + 122, text: f.nameText, fontSize: FS, textAlign: 'center' });
269
+ h = 122 + s.h;
270
+ }
271
+ figH = Math.max(figH, h);
272
+ });
273
+ if (figs.length) y = figTop + figH + SECTION;
274
+ else if (bubbles.length) y = figTop;
275
+
276
+ // 3. boxes and the arrows between them
277
+ if (boxes.length) {
278
+ boxes.forEach(function (b) {
279
+ var s = size(b.label);
280
+ b.w = Math.max(80, s.w + 24); b.h = Math.max(52, s.h + 24);
281
+ });
282
+ var bwMax = Math.max.apply(null, boxes.map(function (b) { return b.w; }));
283
+ var bhMax = Math.max.apply(null, boxes.map(function (b) { return b.h; }));
284
+ var rx = M, rw = W - 2 * M, side = null;
285
+ var sides = figs.map(function (f) { return f.slot; }).filter(function (s, i, a) { return a.indexOf(s) === i; });
286
+ if (figs.length && sides.length === 1 && sides[0] !== 'center' && !grid) {
287
+ var edgeL = Math.max.apply(null, figs.map(function (f) { return f.cx + f.hw; })) + 10;
288
+ var edgeR = Math.min.apply(null, figs.map(function (f) { return f.cx - f.hw; })) - 10;
289
+ var r0 = sides[0] === 'left' ? edgeL : M, r1 = sides[0] === 'left' ? W - M : edgeR;
290
+ var room = (r1 - r0) - bwMax / 2 - 10;
291
+ var labelsFit = edges.every(function (e) { var s = size(wrap(e.label || 'x', chars(room))); return s.n <= 3; });
292
+ if (bwMax <= r1 - r0 && labelsFit) { side = sides[0]; rx = r0; rw = r1 - r0; }
293
+ }
294
+ var n = boxes.length, cols = grid || (side ? 1 : (n * bwMax + (n - 1) * 90 <= rw ? n : 1));
295
+ cols = Math.min(cols, n);
296
+ var labelH = 0;
297
+ edges.forEach(function (e) { if (e.label) labelH = Math.max(labelH, size(wrap(e.label, chars(side ? rw - bwMax / 2 - 10 : 130))).h); });
298
+ var gy = Math.max(64, labelH ? labelH + 28 : 0);
299
+ var gx = cols > 1 ? Math.max(90, Math.min(130, (rw - cols * bwMax) / (cols - 1))) : 0;
300
+ var totalW = cols * bwMax + (cols - 1) * gx;
301
+ var x0 = side === 'left' ? rx : side === 'right' ? rx + rw - totalW : rx + (rw - totalW) / 2;
302
+ boxes.forEach(function (b, i) {
303
+ var c = i % cols, r = Math.floor(i / cols), col = b.marker && MARKERS[b.marker];
304
+ b.w = bwMax; b.h = bhMax;
305
+ b.x = Math.round(x0 + c * (bwMax + gx)); b.y = Math.round(y + r * (bhMax + gy));
306
+ mk.push({ id: P(b.id), type: 'rectangle', x: b.x, y: b.y, width: b.w, height: b.h, backgroundColor: col ? col.fill : '#ffffff', label: { text: b.label, fontSize: FS } });
307
+ });
308
+ var rows = Math.ceil(n / cols);
309
+ edges.forEach(function (e) {
310
+ var a = ids[e.from], b = ids[e.to];
311
+ [[e.from, a], [e.to, b]].forEach(function (p) {
312
+ if (!p[1] || p[1].kind !== 'box') fail(file, e.line, '', '"' + p[0] + '" is not a box here', 'arrows join boxes; declared boxes here: ' + (boxes.map(function (x) { return x.id; }).join(', ') || 'none'));
313
+ });
314
+ var col = e.marker && MARKERS[e.marker];
315
+ mk.push({ id: P(e.from + '_to_' + e.to), type: 'arrow', start: { id: P(e.from) }, end: { id: P(e.to) }, strokeColor: col ? col.ink : INK, strokeWidth: 2 });
316
+ if (e.label) {
317
+ var ax = (a.x + a.w / 2 + b.x + b.w / 2) / 2, ay = (a.y + a.h / 2 + b.y + b.h / 2) / 2;
318
+ var vertical = Math.abs(a.x - b.x) < 4, horizontal = Math.abs(a.y - b.y) < 4;
319
+ var txt, s;
320
+ if (horizontal) {
321
+ var gapW = Math.abs(b.x - a.x) - bwMax;
322
+ txt = wrap(e.label, chars(Math.max(gapW - 8, 60))); s = size(txt);
323
+ mk.push({ id: mk.id('lbl'), type: 'text', x: ax - s.w / 2, y: ay - 8 - s.h, text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: 'center' });
324
+ } else {
325
+ var rightRoom = (rx + rw) - (ax + 8), leftRoom = (ax - 8) - rx;
326
+ var onRight = side === 'right' ? false : rightRoom >= leftRoom;
327
+ txt = wrap(e.label, chars(onRight ? rightRoom : leftRoom)); s = size(txt);
328
+ mk.push({ id: mk.id('lbl'), type: 'text', x: onRight ? ax + 14 : ax - 14 - s.w, y: ay - s.h / 2 - (vertical ? 0 : 6), text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: onRight ? 'left' : 'right' });
329
+ }
330
+ }
331
+ });
332
+ y += rows * bhMax + (rows - 1) * gy + SECTION;
333
+ } else if (edges.length) {
334
+ fail(file, edges[0].line, '', 'arrow with no boxes in this ' + (scope ? 'panel' : 'file'), 'declare the boxes first: a: box "A"');
335
+ }
336
+
337
+ // 4. free text and the caption, centred
338
+ stats.concat(notes).forEach(function (t) {
339
+ var col = t.marker && MARKERS[t.marker], txt = wrap(t.text, chars(W - 2 * M)), s = size(txt);
340
+ mk.push({ id: mk.id('txt'), type: 'text', x: Math.round((W - s.w) / 2), y: y, text: txt, fontSize: FS, strokeColor: col ? col.ink : INK, textAlign: 'center' });
341
+ y += s.h + 10;
342
+ });
343
+ return { els: mk.els, h: Math.max(0, y - SECTION + 10) };
344
+ }
345
+
346
+ // Parsed document -> element array.
347
+ export function sketchToElements(doc, file) {
348
+ var out = [];
349
+ var cols = Math.min(doc.cols, Math.max(1, doc.panels.length));
350
+ var width = doc.panels.length ? cols * PW + (cols - 1) * PGAP : 520;
351
+ var y = 0;
352
+ if (doc.title) {
353
+ var t = wrap(doc.title, chars(width)), s = size(t);
354
+ out.push({ id: 'title', type: 'text', x: Math.round((width - s.w) / 2), y: 0, text: t, fontSize: FS, textAlign: 'center' });
355
+ y = s.h + 18;
356
+ }
357
+ if (doc.body.length) {
358
+ var body = layoutBody(doc.body, width, '', doc.grid, file);
359
+ shift(body.els, 0, y); out = out.concat(body.els); y += body.h + 24;
360
+ }
361
+ var rows = [];
362
+ doc.panels.forEach(function (p, i) { (rows[Math.floor(i / cols)] = rows[Math.floor(i / cols)] || []).push(i); });
363
+ rows.forEach(function (row) {
364
+ var laid = row.map(function (i) {
365
+ var p = doc.panels[i];
366
+ var head = wrap(p.title, chars(PW - 2 * M)), hs = size(head);
367
+ var stmts = p.stmts.slice();
368
+ if (p.note) stmts.push({ kind: 'note', text: p.note, marker: null, line: p.line });
369
+ var body = layoutBody(stmts, PW, 'p' + (i + 1) + '_', p.grid, file);
370
+ return { head: head, hs: hs, body: body, top: hs.h + 22, num: i };
371
+ });
372
+ var H = Math.max.apply(null, laid.map(function (l) { return l.top + l.body.h + 16; }));
373
+ laid.forEach(function (l, c) {
374
+ var ox = c * (PW + PGAP), p = 'p' + (l.num + 1) + '_';
375
+ out.push({ id: p + 'frame', type: 'rectangle', x: ox, y: y, width: PW, height: H, strokeWidth: 3 });
376
+ out.push({ id: p + 'title', type: 'text', x: ox + Math.round((PW - l.hs.w) / 2), y: y + 9, text: l.head, fontSize: FS, textAlign: 'center' });
377
+ out.push({ id: p + 'rule', type: 'line', x: ox, y: y + l.top - 4, points: [[0, 0], [PW, 0]], strokeWidth: 2 });
378
+ shift(l.body.els, ox, y + l.top + 8);
379
+ out = out.concat(l.body.els);
380
+ });
381
+ y += H + PGAP;
382
+ });
383
+ return out;
384
+ }
385
+
386
+ export function sketchToSkeleton(source, file) {
387
+ return sketchToElements(parseSketch(source, file), file);
388
+ }