-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
557 lines (488 loc) · 18 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>squareplanner</title>
<style>
body {
font-family: monospace;
}
.output {
width: 100%;
margin-top: 16px;
}
.textarea {
width: 100%;
height: 230px;
font-family: monospace;
resize: none;
}
.textarea:disabled {
border: 0px;
color: #000;
background-color: #fff;
}
@media print {
.output {
margin-top: 0px !important;
break-inside: avoid !important;
}
.textarea {
display: none !important;
}
.print-spec {
margin-bottom: 0.5cm;
display: block !important;
font-size: 0.25cm !important;
}
}
.print-spec {
display: none;
}
.part {
border: 1px solid black;
font-size: 1em;
padding: 4px;
}
.part-red {
color: red;
}
.part-green {
color: green;
}
.part-blue {
color: blue;
}
.part-name {
font-weight: bold;
}
.peripherical-part .part-name {
margin-right: 8px;
}
.peripherical-part {
font-size: 0.75em;
padding: 1px;
}
.main-part .part-name {
display: block;
margin-bottom: 4px;
}
.measurements {
font-size: 0.8em;
}
.top {
background-color: black;
color: white;
padding-top: 0px;
margin-bottom: -4px;
z-index: 1000;
}
.bottom {
background-color: #ddd;
}
</style>
<script>
var scale = 5;
var columnSpacing = 3;
var lock = false;
var updateTimeout;
var colorMap = {
"red": "part-red",
"green": "part-green",
"blue": "part-blue",
"vermelho": "part-red",
"verde": "part-green",
"azul": "part-blue",
}
var defaultSpec = `# Declare the basic measurements in the first line.
# Specify the columns in the second line. All elements specify width.
# From the third line onwards, specify the parts. First elements specify height.
# Use cm measurements or * specify automatic width/height.
# Use <, > and ^ to extend parts to the left, right or above.
# Press Ctrl+Alt+f to automatically format the specification.
cabinet 200cm x 92cm top 3cm bottom 15cm scale 5
50cm * * 20cm
* drawer door door drawer
* drawer ^ ^ drawer
* ^ ^ > drawer
* > drawer drawer <
`
class Part {
constructor(name, x, y) {
this.name = name;
this.fromX = parseInt(x);
this.toX = this.fromX + 1;
this.fromY = parseInt(y);
this.toY = this.fromY + 1;
}
extendX(dir) {
if (dir === "right") {
this.fromX--;
} else if (dir === "left") {
this.toX++;
}
}
extendY() {
this.toY++;
}
}
function splitWords(row) {
return row.trim().split(/\s+/)
}
function parseHeaderDecl(headerDecl) {
let words = splitWords(headerDecl);
let status = "waiting_width";
let dimension = /(\d+)(\s*)?/;
let header = {};
for (let word of words) {
let dim = word.match(dimension);
if (!dim || isNaN(dim[1])) {
if (status === "waiting_extras") {
if (word === "top" || word === "pedra") {
header.topName = word;
status = "waiting_top";
} else if (word === "bottom" || word === "base") {
header.bottomName = word;
status = "waiting_bottom";
} else if (word === "scale" || word === "escala") {
status = "waiting_scale";
}
}
continue;
} else {
dim = parseInt(dim[1]);
if (status === "waiting_width") {
header.width = dim;
status = "waiting_height";
} else if (status === "waiting_height") {
header.height = dim;
status = "waiting_extras";
} else if (status === "waiting_top") {
header.top = dim;
status = "waiting_extras";
} else if (status === "waiting_bottom") {
header.bottom = dim;
status = "waiting_extras";
} else if (status === "waiting_scale") {
header.scale = dim;
status = "waiting_extras";
}
continue;
}
}
return header;
}
function parseRowColumnDecl(decl) {
let dimensionRegex = /(\d+)[cm]?/;
decl = decl.map(part => {
if (part === "*") {
return "1fr";
} else {
let dim = part.match(dimensionRegex);
if (!dim || isNaN(dim[1])) {
throw new Error(`error parsing row or column declaration: ${part}`);
}
return `${dim[1] * scale}px`;
}
})
return decl.join(" ");
}
function parsePartsDecls(lines) {
let parts = []
// First-pass: resolve declared parts.
for (let y = 0; y < lines.length; y++) {
let line = []
for (let x = 0; x < lines[y].length; x++) {
let part = lines[y][x];
if (part === "^" || part === "<" || part === ">") {
line.push(part);
} else {
line.push(new Part(part, x, y));
}
}
parts.push(line);
}
// Second-pass: resolve references.
for (let y = 0; y < parts.length; y++) {
for (let x = 0; x < parts[y].length; x++) {
let part = parts[y][x];
if (part === "^") {
if (parts[y - 1] && parts[y - 1][x] instanceof Part) {
parts[y][x] = parts[y - 1][x];
// Only extend height again if left neighbor is not an
// extension of the same part already.
if (parts[y][x - 1] != parts[y][x]) {
parts[y][x].extendY();
}
} else {
parts[y][x] = undefined;
}
} else if (part === ">") {
if (parts[y][x + 1] instanceof Part) {
parts[y][x] = parts[y][x + 1];
parts[y][x].extendX("right");
} else {
parts[y][x] = undefined;
}
} else if (part === "<") {
if (parts[y][x - 1] instanceof Part) {
parts[y][x] = parts[y][x - 1];
// Only extend width again if upper neighbor is not
// an extension of the same part already.
if (!parts[y - 1] || parts[y - 1][x] != parts[y][x]) {
parts[y][x].extendX("left");
}
} else {
parts[y][x] = undefined;
}
}
}
}
// This-pass: consolidate.
let partsSet = [];
let maxWidth = 0;
for (let y = 0; y < parts.length; y++) {
if (parts[y].length > maxWidth) {
maxWidth = parts[y].length;
}
for (let x = 0; x < parts[y].length; x++) {
partsSet.push(parts[y][x])
}
}
partsSet = partsSet.filter(part => part !== undefined)
return {
width: maxWidth,
height: parts.length,
parts: new Set(partsSet),
};
}
function gen(header, cols, rows, parts) {
let container = document.createElement("div");
let yOffset = 0;
// top
let topRow = "";
if (header.top > 0) {
yOffset = 1;
container.innerHTML += `<div class="top part peripherical-part" style="
grid-column-start: 1;
grid-column-end: ${parts.width + 1};
grid-row-start: 1;
grid-row-end: 2"
data-name="${header.topName}"></div>`
topRow = `${header.top * scale}px`;
}
// bottom
let bottomRow = "";
if (header.bottom > 0) {
container.innerHTML += `<div class="bottom part peripherical-part" style="
grid-column-start: 1;
grid-column-end: ${parts.width + 1};
grid-row-start: ${parts.height + 1 + yOffset};
grid-row-end: ${parts.height + yOffset + 2}"
data-name="${header.bottomName}"></div>`
bottomRow = `${header.bottom * scale}px`;
}
// parts
for (let part of parts.parts) {
let [name, color] = part.name.split(":");
color = colorMap[color] || "";
container.innerHTML += `<div class="part main-part ${color}" style="
grid-column-start: ${part.fromX + 1};
grid-column-end: ${part.toX + 1};
grid-row-start: ${part.fromY + 1 + yOffset};
grid-row-end: ${part.toY + 1 + yOffset}"
data-name="${name}"></div>`
}
container.setAttribute("style", `
width: ${header.width * scale}px;
height: ${header.height * scale}px;
border: 1px solid black;
display: grid;
grid-template-columns: ${cols};
grid-template-rows: ${topRow} ${rows} ${bottomRow};
margin-left: auto;
margin-right: auto;
`);
let output = document.querySelector(".output")
output.innerHTML = "";
output.appendChild(container);
}
function parseAndGen(spec) {
let lines = spec.split("\n");
lines = lines.filter(line => line.trim().length > 0 && line.trim()[0] !== "#");
if (lines.length == 0) {
throw new Error("please provide a spec");
}
let header = parseHeaderDecl(lines[0])
// Make scale globally available to make our lives easier.
scale = header.scale;
if (!scale) {
scale = 5;
}
let colsDecl = splitWords(lines[1]);
let cols = parseRowColumnDecl(colsDecl)
let rowsDecls = [];
let partsDecls = lines.slice(2).map(splitWords).map(line => {
rowsDecls.push(line[0]);
return line.slice(1);
});
let rows = parseRowColumnDecl(rowsDecls);
if (partsDecls.length == 0) {
throw new Error("you need to have at least one line declaring parts");
}
let parts = parsePartsDecls(partsDecls);
gen(header, cols, rows, parts);
}
function format(spec) {
// Identify lines to format and tokenize them.
let linesToFormat = []
let lines = spec.split("\n");
let passedHeader = false;
for (let i = 0; i < lines.length; i++) {
let line = lines[i].trim()
if (line.startsWith("#") || line === "") {
continue
}
if (!passedHeader) {
passedHeader = true;
continue;
}
linesToFormat.push(i);
}
let tokenizedLines = []
for (line of linesToFormat) {
tokenizedLines.push(splitWords(lines[line]))
}
// Add a blank item to the first row (columns declaration) so that
// we format it along with other lines.
tokenizedLines[0].unshift("");
// Normalize number of columns in all rows.
let nColumns = 0;
for (line of tokenizedLines) {
if (line.length > nColumns) {
nColumns = line.length
}
}
for (line of tokenizedLines) {
if (line.length < nColumns) {
let fill = new Array(nColumns - line.length).fill("");
line.push(...fill);
}
}
// Calculate maximum width of each column.
let maxWidth = new Array(nColumns).fill(0);
for (line of tokenizedLines) {
for (let i = 0; i < line.length; i++) {
if (line[i].length > maxWidth[i]) {
maxWidth[i] = line[i].length;
}
}
}
// Adjust width to maximum width + columnSpacing.
for (line of tokenizedLines) {
for (let i = 0; i < line.length - 1; i++) {
let cur = line[i].length;
let add = maxWidth[i] - cur + columnSpacing;
line[i] = line[i] + " ".repeat(add);
}
}
// Place back the adjusted lines and return.
let i = 0;
for (line of linesToFormat) {
lines[line] = tokenizedLines[i++].join("");
}
return lines.join("\n");
}
function setTextArea(spec) {
document.querySelector(".textarea").value = spec;
document.querySelector(".print-spec").innerHTML = spec;
}
function update() {
let spec = document.querySelector(".textarea").value
if (spec.trim() === "") {
spec = defaultSpec;
setTextArea(spec);
}
if (spec == defaultSpec) {
window.location.hash = "";
} else {
let data = btoa(spec);
if (lock) {
data = "lock:" + data;
}
window.location.hash = data;
}
try {
parseAndGen(spec)
} catch (e) {
document.querySelector(".output").innerHTML = e;
console.error(e);
}
document.querySelectorAll(".part").forEach(part => {
let width = part.offsetWidth;
let height = part.offsetHeight;
// Discount the negative margin when dealing with the top part.
if (part.classList.contains("top")) {
height -= 4;
}
width = (new Number(width / scale)).toFixed(2);
height = (new Number(height / scale)).toFixed(2);
part.innerHTML = `
<span class='part-name'>${part.dataset.name}</span>
<span class='measurements'>${width} x ${height} cm</span>
`;
});
}
function throttledUpdate() {
if (updateTimeout) {
clearTimeout(updateTimeout);
}
updateTimeout = setTimeout(() => {
update();
updateTimeout = null;
}, 500);
}
function start() {
let spec = defaultSpec;
try {
let urlSpec = window.location.hash;
if (urlSpec[0] === "#") {
urlSpec = urlSpec.substring(1);
}
if (urlSpec.startsWith("lock:")) {
lock = true;
document.querySelector(".textarea").setAttribute("disabled", "");
urlSpec = urlSpec.substring(5);
} else {
lock = false;
document.querySelector(".textarea").removeAttribute("disabled");
}
if (urlSpec !== "") {
spec = atob(urlSpec);
}
} catch (e) {
// Nothing to do, ignore errors and keep default spec.
}
setTextArea(spec);
update();
}
document.addEventListener('keydown', event => {
if (event.ctrlKey && event.altKey && event.key === 'f') {
setTextArea(format(document.querySelector(".textarea").value));
}
if (event.ctrlKey && event.altKey && event.key === 'l') {
lock = !lock;
update();
}
});
</script>
</head>
<body onload="start()" onhashchange="start()">
<div class="controls">
<textarea name="textarea" class="textarea" onkeyup="throttledUpdate()"></textarea>
<pre class="print-spec"></pre>
</div>
<div class="output"></div>
</body>
</html>