-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathsheet.ts
781 lines (735 loc) · 26.1 KB
/
sheet.ts
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
import {Attributes, createElement, createSVG, setAttributes} from './elements.ts';
import * as figures from './figures.ts';
import {Image} from './images.ts';
import {NO_LAYER} from './layers.ts';
import * as layouts from './layouts.ts';
import {getNameSizeSuffix, getSizeString, getSuffixedFileName} from './name.ts';
import {Medium, PartialRunOptions, PartialSheetOptions, RunOptions, SheetOptions, Side, runOptionsFromPartial, sheetOptionsFromPartial} from './options.ts';
import {BasicPiece, Defs, Piece, gather} from './pieces.ts';
import {Point} from './point.ts';
import {getPNGDataURI} from './svg_converter.ts';
import {saveSVG, saveSVGAsPNG} from './svg_saver.ts';
import {createText} from './text.ts';
import {OrArray, assert, flatten, flattenFilter, roundReasonably} from './util.ts';
import {PartialViewBox, PartialViewBoxMargin, ViewBox, extendViewBox, viewBoxFromPartial, viewBoxMarginFromPartial, viewBoxToString} from './view_box.ts';
const DEFAULT_SVG_BORDER_STYLE = "solid #00f4 1px";
type SVGBorderStyle = string | boolean;
function addBorder(
element: HTMLElement | SVGSVGElement, border: SVGBorderStyle) {
if (border)
element.style.border = border === true ? DEFAULT_SVG_BORDER_STYLE : border;
}
function createSaveButton({label, hint, save}: {
label?: string,
hint?: string,
save: () => void,
}) {
const button = document.createElement("button");
button.textContent = label || `Save`;
if (hint)
button.title = hint;
button.addEventListener("click", save);
return button;
}
interface PartialRunsSelectorInterface {
runs?: string[] | "all";
cornersMarker?: boolean | "auto";
reversingFrame?: boolean | "auto";
}
export type PartialRunsSelector = PartialRunsSelectorInterface | string[];
export interface RunsSelector {
runs: string[] | "all";
cornersMarker: boolean;
reversingFrame: boolean;
}
export type SaveFormat = "SVG" | "PNG";
export interface PartialLaserSVGParams {
format?: SaveFormat;
printsAsImages?: boolean;
runsSelector?: PartialRunsSelector;
}
export interface LaserSVGParams {
format: SaveFormat;
printsAsImages: boolean;
runsSelector: RunsSelector;
}
export type ButtonSaveFormat = SaveFormat | "both";
const DEFAULT_RUNS: PartialRunOptions[] = [{type: "print"}, {type: "cut"}];
export interface BasicSheetParams {
options?: PartialSheetOptions;
margin?: PartialViewBoxMargin;
viewBox?: PartialViewBox | "auto";
runs?: OrArray<PartialRunOptions>;
preserveRunsOrder?: boolean;
}
export interface SheetParams extends BasicSheetParams {
pieces: OrArray<BasicPiece | undefined>;
}
export function mergeSheetParams<S extends BasicSheetParams | undefined>(basic: OrArray<BasicSheetParams | undefined>, params: S):
S extends SheetParams ? SheetParams : BasicSheetParams {
let result: BasicSheetParams = {};
function merge<S extends BasicSheetParams>(params: S): S {
return {...result, ...params, options: {...result.options, ...params.options}};
}
for (const basicParams of flatten(basic))
if (basicParams)
result = merge(basicParams);
return (params ? merge(params) : result) as S extends SheetParams ? SheetParams : BasicSheetParams;
}
export class Sheet {
private readonly runHandles?: ReadonlyMap<string, SVGGElement>;
protected constructor(
readonly options: SheetOptions,
private readonly pieces: Piece,
readonly viewBox: ViewBox,
private readonly runOptions: ReadonlyMap<string, RunOptions>,
private readonly emptyRuns: ReadonlySet<string>,
private readonly preserveRunsOrder: boolean,
) {
this.runHandles = this.createHandles();
}
get name() {return this.options.name;}
static create({
options = {},
pieces,
margin = 1,
viewBox = "auto",
runs,
preserveRunsOrder = false,
}: SheetParams) {
const sheetOptions = sheetOptionsFromPartial(options);
const fullPieces = gather(flattenFilter(pieces));
const fullMargin = viewBoxMarginFromPartial(margin);
const box = viewBox === "auto" ? fullPieces.getBoundingBox(fullMargin) :
extendViewBox(viewBoxFromPartial(viewBox), margin);
const allRuns = flatten(runs || DEFAULT_RUNS);
const runOptionsMap = new Map<string, RunOptions>();
const emptyRuns = new Set<string>();
for (const opts of allRuns) {
const runOptions = runOptionsFromPartial(sheetOptions, opts);
if (runOptionsMap.has(runOptions.id))
throw new Error(`Duplicate run id: ${JSON.stringify(runOptions.id)}`);
runOptionsMap.set(runOptions.id, runOptions);
if (!fullPieces.selectLayers(...runOptions.layers).getElements().length)
emptyRuns.add(runOptions.id);
}
return new Sheet(
sheetOptions,
fullPieces,
box,
runOptionsMap,
emptyRuns,
preserveRunsOrder,
);
}
private getRunOptions(id: string) {
const runOptions = this.runOptions.get(id);
if (!runOptions)
throw new Error(`No run with id ${JSON.stringify(id)}`);
return runOptions;
}
private getRunPiece({runOptions, medium}: {
runOptions: RunOptions,
medium: Medium,
}) {
let pieces = this.pieces.selectLayers(...runOptions.layers);
if (medium === "laser") {
if (runOptions.posCorrectionMillimeters && this.options.millimetersPerUnit !== undefined) {
const [dxMm, dyMm] = runOptions.posCorrectionMillimeters;
pieces = pieces.translate(
-dxMm / this.options.millimetersPerUnit, -dyMm / this.options.millimetersPerUnit);
}
if (runOptions.side === "back")
pieces = pieces.flipX(this.viewBox.minX + this.viewBox.width / 2);
if (this.options.cornersMarker.enable && runOptions.includeCornersMarker)
pieces = gather(pieces, this.getCornersMarkerRawPiece(medium));
}
return {
defs: pieces,
runGroup: pieces.asG({
id: runOptions.id,
...runOptions.styleAttributes[medium],
}),
};
}
private getCornersMarkerRawPiece(medium: Medium) {
const {minX, minY, width, height} = this.viewBox;
let cornersMarker;
if (this.options.cornersMarker.type === "circles")
cornersMarker = gather(
figures.circle({center: [minX + width, minY + height], radius: 0}),
figures.circle({center: [minX, minY], radius: 0}),
);
else if (this.options.cornersMarker.type === "lines")
cornersMarker = gather(
figures.line([minX, minY], [minX + 1e-9, minY]),
figures.line([minX + width, minY + height], [minX + width - 1e-9, minY + height]),
);
else
cornersMarker = this.options.cornersMarker.type satisfies never;
return cornersMarker.asG({
class: this.options.cornersMarker.id,
...this.options.cornersMarker.styleAttributes[medium],
});
}
private getCornersMarker(medium: Medium) {
const {id} = this.options.cornersMarker;
return {
id,
group: this.getCornersMarkerRawPiece(medium),
};
}
private getReversingFrame(medium: Medium) {
const {id} = this.options.reversingFrame;
return {
id,
group: figures.rectangle(this.viewBox).asG(
{id, ...this.options.reversingFrame.styleAttributes[medium]}),
};
}
getRunIds() {
return [...this.runOptions.keys()];
}
private getNonEmptyRunIds() {
return this.getRunIds().filter(id => !this.emptyRuns.has(id));
}
private runsSelectorFromPartial({
medium,
runsSelector = {},
}: {
medium?: Medium,
runsSelector?: PartialRunsSelector,
} = {}): RunsSelector {
let runsSelectorInterface: PartialRunsSelectorInterface;
if (Array.isArray(runsSelector))
runsSelectorInterface = {runs: runsSelector};
else
runsSelectorInterface = runsSelector;
const {
runs = "all",
cornersMarker = "auto",
reversingFrame = "auto",
} = runsSelectorInterface;
const fullRuns = this.runsOrAll(runs);
function assertMedium() {
if (!medium)
throw new Error(`Specifying medium is required when using "auto"`);
return medium;
}
if (reversingFrame === true && !this.options.reversingFrame.enable)
throw new Error(`Cannot specify reversingFrame:true when ` +
`reversing frame is not enabled in sheet options`);
if (cornersMarker === true && !this.options.cornersMarker.enable)
throw new Error(`Cannot specify cornersMarker:true when ` +
`corners marker is not enabled in sheet options`);
const fullReversingFrame = reversingFrame === "auto" ?
this.options.reversingFrame.enable && assertMedium() === "laser" &&
fullRuns.some(id => this.getRunOptions(id).side === "back") :
reversingFrame;
const fullCornersMarker = cornersMarker === "auto" ?
this.options.cornersMarker.enable && !fullReversingFrame && assertMedium() === "laser" &&
!fullRuns.some(id => this.getRunOptions(id).includeCornersMarker) :
cornersMarker;
return {
runs: runs === "all" ? "all" : fullRuns,
cornersMarker: fullCornersMarker,
reversingFrame: fullReversingFrame,
};
}
private runsOrAll(runs: RunsSelector["runs"]) {
return runs === "all" ? this.getNonEmptyRunIds() : [...new Set(runs)];
}
private getRunsTypes({runs, reversingFrame}: RunsSelector): {cut: boolean, print: boolean} {
const result = {cut: false, print: false};
for (const run of this.runsOrAll(runs))
result[this.getRunOptions(run).type] = true;
if (reversingFrame)
result.cut = true;
return result;
}
laserSVGParamsFromPartial({
format = "SVG",
printsAsImages = false,
runsSelector,
}: PartialLaserSVGParams = {}): LaserSVGParams {
return {
format,
printsAsImages,
runsSelector: this.runsSelectorFromPartial({medium: "laser", runsSelector}),
};
}
private async getRawSVG({
medium,
printsAsImages = false,
runsSelector = {},
}: {
medium: Medium,
printsAsImages?: boolean,
runsSelector?: PartialRunsSelector,
}): Promise<SVGSVGElement> {
const {runs, cornersMarker, reversingFrame} =
this.runsSelectorFromPartial({medium, runsSelector});
const runsData: {
id: string,
defs?: Defs,
group: SVGGElement,
extraAttributes?: Attributes,
sibling?: SVGElement,
}[] = [];
for (const id of this.runsOrAll(runs)) {
const runOptions = this.getRunOptions(id);
let defs;
let group;
if (runOptions.type === "print" && printsAsImages) {
// TODO: Consider converting pieces to PNG separately, at declared levels.
group = (await Image.fromURL(await getPNGDataURI(
await this.getRawSVG({
medium,
printsAsImages: false,
runsSelector: {
runs: [id],
cornersMarker,
reversingFrame,
},
}), this.options.resolution),
{
scaling: {
width: this.viewBox.width,
height: this.viewBox.height,
},
}))
.translate(this.viewBox.minX, this.viewBox.minY)
.asG({id: runOptions.id});
} else
({defs, runGroup: group} = this.getRunPiece({runOptions, medium}));
runsData.push({id, defs, group});
}
if (cornersMarker)
runsData.push(this.getCornersMarker(medium));
if (reversingFrame)
runsData.push(this.getReversingFrame(medium));
const {laserRunsOptions} = this.options;
if (medium === "laser") {
if (laserRunsOptions.colorCodes)
for (const runData of runsData)
runData.extraAttributes = {
fill: laserRunsOptions.colorCodes.get(runData.id),
};
if (this.runHandles)
for (const runData of runsData)
runData.sibling = this.runHandles.get(runData.id);
}
const defsElement = gather(runsData.map(({defs}) => defs)).getDefsElement();
const groups = runsData.map(({id, group, extraAttributes, sibling}) => {
if (extraAttributes || sibling) {
setAttributes(group, {id: undefined});
return createElement({
tagName: "g",
attributes: {
...extraAttributes,
id,
},
children: [sibling, group],
});
}
return group;
});
return createSVG({
viewBox: this.viewBox,
millimetersPerUnit: medium === "laser" ? this.options.millimetersPerUnit : undefined,
children: [defsElement, ...groups],
})
}
private createHandles(): ReadonlyMap<string, SVGGElement> | undefined {
const {handles} = this.options.laserRunsOptions;
if (!handles)
return undefined;
const ids = this.getHandleRuns();
if (ids.length < 2)
return undefined;
const wid = this.viewBox.width / ids.length;
const baseWid = 100;
const margin = 2;
const handleViewBox = extendViewBox(viewBoxFromPartial({
width: baseWid,
height: 15,
...handles === "above" ? {maxY: 0} :
handles === "below" ? {minY: 0} :
handles satisfies never,
}), -margin);
const textAttribs = {size: 5, font: "monospace"};
return new Map(ids.map(({runId, type}, index) => {
const grabAreaSize = handleViewBox.height - 4;
const grabAreaGaps = 0.5;
const grabArea = layouts.layout({
count: grabAreaSize / grabAreaGaps + 1,
pieceFunc: i => figures.line([grabAreaSize, 0]).moveUp(i * grabAreaGaps),
}).translate(2 * margin, -2 * margin);
const typeText = createText(type, textAttribs).normalise({
target: handleViewBox,
align: {x: "right", y: "center"},
}, {margin: 1});
const idText = createText(runId, textAttribs).normalise({
target: extendViewBox(handleViewBox, {
left: -grabAreaSize - margin,
right: -typeText.getBoundingBox().width,
}),
align: {y: "center"},
}, {margin: 1});
return [
runId,
gather(
figures.rectangle(handleViewBox).setAttributes({
fill: this.options.laserRunsOptions.colorCodes ? undefined : "black",
}),
grabArea.setAttributes({stroke: "black"}),
gather(
idText,
typeText,
).setAttributes({fill: "black"}),
).setAttributes({stroke: "none"})
.moveRight(index * baseWid)
.scale(wid / baseWid)
.translate(this.viewBox.minX, this.viewBox.minY)
.moveDown(handles === "below" ? this.viewBox.height : 0)
.setAttributes({id: `${runId}-handle`})
.asG(),
];
}));
}
private getHandleRuns() {
const result = [];
for (const partialRunsSelector of this.getRunsInNaturalOrder()) {
const runsSelector = this.runsSelectorFromPartial({
medium: "laser",
runsSelector: partialRunsSelector,
});
if (runsSelector.runs !== "all") {
if (runsSelector.runs.length)
for (const run of runsSelector.runs) {
const runOptions = assert(this.runOptions.get(run));
result.push({
runId: run,
type: (runOptions.side === "back" ? "-" : "") + runOptions.type[0],
});
}
if (runsSelector.reversingFrame)
result.push({
runId: this.options.reversingFrame.id,
type: "#",
});
}
}
return result;
}
/**
* Generates an `<svg>` element with the preview of this Sheet.
* If the runs selector is specified, the SVG will only contain the specified runs.
*/
async getPreviewSVG({
runsSelector,
showPointOnDblClick = true,
border = true,
}: {
runsSelector?: PartialRunsSelector,
showPointOnDblClick?: boolean,
border?: SVGBorderStyle,
} = {}) {
const fullRunsSelector = this.runsSelectorFromPartial({medium: "preview", runsSelector});
const svg = await this.getRawSVG({medium: "preview", runsSelector: fullRunsSelector});
addBorder(svg, border);
const titleElement = createElement({
tagName: "title",
children: this.name ? `${this.name} (${this.getSizeString()})` : this.getSizeString(),
});
svg.insertAdjacentElement("afterbegin", titleElement);
if (showPointOnDblClick)
svg.addEventListener("dblclick", (event) => {
event.preventDefault();
document.getSelection()?.empty();
const elem = event.currentTarget as HTMLElement;
const point: Point = [
this.viewBox.minX + event.offsetX / elem.clientWidth * this.viewBox.width,
this.viewBox.minY + event.offsetY / elem.clientHeight * this.viewBox.height,
];
console.log("Point:", point);
setTimeout(() => {
alert(`Point: [${point.map(c => roundReasonably(c, {significantDigits: 4})).join(", ")}]`);
});
});
return svg;
}
getSizeString() {
return getSizeString(this.viewBox.width, this.options.millimetersPerUnit) + "×" +
getSizeString(this.viewBox.height, this.options.millimetersPerUnit);
}
/**
* Generates an `<svg>` element suitable for loading in the laser cutter software.
* If the runs selector is specified, the SVG will only contain the specified runs.
* If `printsAsImages` is specified, all the print layers are actually pre-rendered images,
* which is helpful if the laser cutter software doesn't implement all the features of SVG.
*/
async getLaserSVG({printsAsImages, runsSelector}: {
printsAsImages?: boolean,
runsSelector?: PartialRunsSelector,
} = {}) {
return await this.getRawSVG({medium: "laser", printsAsImages, runsSelector});
}
private getSVGName({
runsSelector: {runs, reversingFrame},
printsAsImages,
}: {
runsSelector: RunsSelector,
printsAsImages: boolean,
}) {
const fileName = [
this.options.fileName,
...runs === "all" ? [] : [...runs, reversingFrame && this.options.reversingFrame.id],
printsAsImages && "prerendered",
].filter(Boolean).join("__");
const suffix = this.options.includeSizeInName ?
getNameSizeSuffix(this.viewBox, this.options.millimetersPerUnit) : undefined;
return getSuffixedFileName(fileName, suffix);
}
/**
* Saves the laser SVG file as a file.
* @see {@link Sheet.getLaserSVG}
*/
async saveLaserSVG(params: PartialLaserSVGParams = {}) {
const {format, printsAsImages, runsSelector} = this.laserSVGParamsFromPartial(params);
const svg = await this.getLaserSVG({printsAsImages, runsSelector});
const name = this.getSVGName({
runsSelector: this.runsSelectorFromPartial({medium: "laser", runsSelector}),
printsAsImages,
});
if (format === "SVG")
saveSVG({name, svg});
else if (format === "PNG")
await saveSVGAsPNG({
name,
svg,
conversionParams: this.options.resolution,
});
else {
return format satisfies never;
}
}
private getFormatLabel(format: SaveFormat) {
return `.${format.toLowerCase()}`;
}
private getSaveButtonLabel({format, runsSelector: {runs, reversingFrame}}: {
format: SaveFormat,
runsSelector: RunsSelector,
}) {
const text = [this.options.fileName];
if (runs !== "all") {
text.push(" (");
text.push([
runs.join(", "),
reversingFrame && "#",
].filter(Boolean).join(" "));
text.push(")");
}
if (format !== "SVG")
text.push(" ", this.getFormatLabel(format));
return text.join("");
}
/**
* Returns a `<button>` element which saves the SVG suitable for the laser cutter software
* on click.
* @see {@link Sheet.saveLaserSVG}
*/
getLaserSVGSaveButton({params = {}, label, hintLines = []}: {
params?: PartialLaserSVGParams,
label?: string,
hintLines?: string[],
} = {}) {
const {format, printsAsImages, runsSelector} = this.laserSVGParamsFromPartial(params);
return createSaveButton({
label: label || this.getSaveButtonLabel({format, runsSelector}),
hint: [
this.getSVGName({runsSelector, printsAsImages}),
...hintLines,
].join("\n"),
save: () => {
this.saveLaserSVG({format, printsAsImages, runsSelector});
},
});
}
getRunsInSpecifiedOrder(): PartialRunsSelector[] {
let lastSide: Side | undefined;
const result: PartialRunsSelector[] = [];
for (const {id, side} of this.runOptions.values()) {
if (!this.emptyRuns.has(id)) {
if (lastSide && side !== lastSide)
result.push({runs: [], reversingFrame: true});
lastSide = side;
result.push({runs: [id], reversingFrame: false});
}
}
return result;
}
/**
* If preserveRunsOrder was specified, the natural order is the same as the specified order.
* Otherwise returns all the runs defined in this Sheet in their natural order. The order is:
* - prints on the back side,
* - cuts on the back side (for scoring, as the main cut needs to be done on the front side),
* - the reversing frame - if there were any runs on the back,
* - prints on the front,
* - cuts on the front.
*/
getRunsInNaturalOrder(): PartialRunsSelector[] {
if (this.preserveRunsOrder)
return this.getRunsInSpecifiedOrder();
const allOptions = [...this.runOptions.values()];
const hasReverseSide = allOptions.some(({side}) => side === "back");
const toSingleRuns = (options: RunOptions[]): PartialRunsSelector[] => {
return options.filter(({id}) => !this.emptyRuns.has(id))
.map(({id}) => ({
runs: [id],
reversingFrame: false,
}));
};
function runsOnSide(side: Side) {
return toSingleRuns(["print", "cut"].flatMap(type =>
allOptions.filter(({type: t, side: s}) => t === type && s === side),
));
}
if (hasReverseSide)
return [
...runsOnSide("back"),
{runs: [], reversingFrame: true},
...runsOnSide("front"),
];
else
return runsOnSide("front");
}
/**
* Returns a `<div>` element with buttons for saving the laser SVG files, one per each
* runs selector, or a complete set of buttons if `"all"` is specified (the default).
* @see {@link Sheet.saveLaserSVG}
*/
getSaveLaserSVGButtons({
format = "SVG",
printsFormat = "both",
includePrintsAsImages = true,
runsSelectors = "all",
}: {
format?: ButtonSaveFormat,
printsFormat?: ButtonSaveFormat,
includePrintsAsImages?: boolean,
runsSelectors?: (PartialRunsSelector | "separator")[] | "all",
} = {}) {
const container = document.createElement("div");
container.textContent = `Files for the laser software:`;
const buttonsContainer = document.createElement("div");
container.append(buttonsContainer);
buttonsContainer.style.display = "flex";
buttonsContainer.style.flexWrap = "wrap";
function addItems(items: OrArray<HTMLElement>) {
const span = document.createElement("span");
span.style.margin = "2px";
let first = true;
for (const item of flatten(items)) {
if (first)
first = false;
else
item.style.marginLeft = "-1px";
item.style.minHeight = "2.2em";
span.append(item);
}
buttonsContainer.append(span);
}
function addSep() {
const sep = document.createElement("hr");
sep.style.margin = "2px";
buttonsContainer.append(sep);
}
if (runsSelectors === "all") {
const naturalOrder = this.getRunsInNaturalOrder();
runsSelectors = [{runs: "all"}];
if (naturalOrder.length > 1)
runsSelectors.push("separator", ...naturalOrder);
}
for (const runsSelector of runsSelectors) {
if (runsSelector === "separator")
addSep();
else {
const buttons = [];
const fullRunsSelector = this.runsSelectorFromPartial({medium: "laser", runsSelector});
const {cut, print} = this.getRunsTypes(fullRunsSelector);
const fullFormat = print && !cut ? printsFormat : format;
const mainFormat = fullFormat === "both" ? "SVG" : fullFormat;
const hintLines = [];
if (fullRunsSelector.runs === "all")
hintLines.push(`All the laser runs`);
else {
if (fullRunsSelector.runs.length)
hintLines.push(`Laser runs: ${fullRunsSelector.runs.map(
run => JSON.stringify(run)).join(", ")}`);
if (fullRunsSelector.reversingFrame)
hintLines.push(`Reversing frame`);
}
buttons.push(this.getLaserSVGSaveButton({
params: {format: mainFormat, runsSelector},
hintLines: hintLines,
}));
if (includePrintsAsImages && print && mainFormat === "SVG")
buttons.push(this.getLaserSVGSaveButton({
params: {format: "SVG", printsAsImages: true, runsSelector},
label: `(pre)`,
hintLines: [`With pre-rendered print runs`, ...hintLines],
}));
if (fullFormat === "both")
buttons.push(this.getLaserSVGSaveButton({
params: {format: "PNG", runsSelector},
label: this.getFormatLabel("PNG"),
hintLines: [`Raster image`, ...hintLines],
}));
if (fullRunsSelector.runs === "all")
for (const button of buttons)
button.style.fontWeight = "bold";
addItems(buttons);
}
}
return container;
}
getUnusedLayers() {
const unusedLayers = new Set(this.pieces.getLayers());
for (const runOptions of this.runOptions.values())
for (const layer of runOptions.layers)
unusedLayers.delete(layer);
return [
...unusedLayers.delete(NO_LAYER) ? [NO_LAYER] : [],
...[...unusedLayers].sort(),
];
}
getUnusedLayersWarning() {
const unusedLayers = this.getUnusedLayers();
if (!unusedLayers.length)
return undefined;
function makeInlinePre(text: string) {
const span = document.createElement("span");
span.style.fontFamily = "monospace";
span.textContent = text;
return span;
}
const span = document.createElement("span");
span.style.color = "#9202ff";
span.textContent = `Warning: Some layers are not included in any runs: `;
let first = true;
for (const layer of unusedLayers) {
if (first)
first = false;
else
span.append(`, `);
span.append(makeInlinePre(layer === undefined ? `NO_LAYER` : JSON.stringify(layer)));
}
span.append(`.`);
return span;
}
toString() {
return `Sheet[${this.name}, options = ${JSON.stringify(this.options)}, ${this.pieces}, ` +
`viewBox = "${viewBoxToString(this.viewBox)}", runs = ${JSON.stringify(this.runOptions)}]`;
}
}