-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathdef_tools.ts
351 lines (311 loc) · 9.36 KB
/
def_tools.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
import {AttributesDefTool, IdHelper} from './def_tool.ts';
import {Attributes, AttributesBuilder, createElement} from './elements.ts';
import * as figures from './figures.ts';
import {generateId} from './ids.ts';
import {Piece, PiecePartArg} from './pieces.ts';
import {Transform} from './transform.ts';
import {OrArray} from './util.ts';
interface AttributesAndId {
attributes?: Attributes;
id?: string;
}
type PiecesArg = OrArray<PiecePartArg | undefined>;
type PiecesAttributesAndId<P extends string = "pieces"> = AttributesAndId & {
[key in P]: PiecesArg;
}
type PartialPieceAttributesAndId<P extends string> =
PiecesArg | PiecesAttributesAndId<P>;
function isPiecesArg<P extends string>(
arg: PartialPieceAttributesAndId<P>, piecesPath: P): arg is PiecesArg {
return !(arg && Object.getPrototypeOf(arg) === Object.prototype &&
Object.hasOwn(arg, piecesPath));
}
function piecesAttributesAndIdFromPartial<P extends string>(
arg: PartialPieceAttributesAndId<P>, piecesPath: P): PiecesAttributesAndId {
if (isPiecesArg(arg, piecesPath))
return {pieces: arg};
const {attributes, id, [piecesPath]: pieces} = arg;
return {attributes, id, pieces};
}
/**
* Creates a clip path AttributesDefTool, used to restrict the painting region of a Piece.
*
* Usage example:
*
* myPiece.useDefTool(createClipPath({...}))
*
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath
*/
export function createClipPath(path: PiecesArg): AttributesDefTool;
/**
* Creates a clip path AttributesDefTool, used to restrict the painting region of a Piece.
*
* Usage example:
*
* myPiece.useDefTool(createClipPath({...}))
*
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/clipPath
*/
export function createClipPath(args: {
paths: PiecePartArg,
attributes?: Attributes,
id?: string,
}): AttributesDefTool;
export function createClipPath(arg: PartialPieceAttributesAndId<"paths">) {
const {pieces, attributes, id} = piecesAttributesAndIdFromPartial(arg, "paths");
return Piece.createElement({
tagName: "clipPath",
children: pieces,
attributes,
}).asDefTool(id).useByAttribute("clip-path");
}
export interface MaskPartAttributes {
/** Whether to include fill. */
fill?: boolean;
/** Whether to include stroke, optionally with stroke width. */
stroke?: boolean | number;
}
function applyMaskPartAttributes(
maskPiece: Piece,
color: string, {
fill = true,
stroke,
}: MaskPartAttributes = {},
) {
const attributes: AttributesBuilder = {};
if (fill === false)
attributes.fill = "none";
else if (fill === true)
attributes.fill = color;
if (stroke) {
attributes.stroke = color;
if (typeof stroke === "number")
attributes.strokeWidth = stroke;
}
return maskPiece.setAttributes(attributes);
}
const DEFAULT_EVERYTHING_MASK_SIDE = 1e6;
function everythingRect(side: number) {
return figures.rectangle({centered: true, side});
}
/**
* An object representing a mask.
*
* Usage example:
*
* myPiece.useDefTool(Mask.incl(...).excl(...))
*
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/mask
*/
export class Mask implements AttributesDefTool {
static readonly NOTHING = new Mask(Piece.EMPTY, {}, "mask_nothing");
static readonly EVERYTHING = Mask.incl(everythingRect(DEFAULT_EVERYTHING_MASK_SIDE))
.setId("mask_everything");
private genId;
protected constructor(
readonly mask: Piece,
private readonly attributes: Attributes | undefined,
private readonly id: string | undefined,
) {
this.genId = id;
}
static everything(everythingSide?: number) {
return everythingSide ? Mask.incl(everythingRect(everythingSide)) : Mask.EVERYTHING;
}
static incl(includePart: Piece, maskPartAttributes?: MaskPartAttributes) {
return Mask.NOTHING.incl(includePart, maskPartAttributes);
}
static excl(excludePart: Piece, {
everythingSide,
...maskPartAttributes
}: {everythingSide?: number} & MaskPartAttributes = {}) {
return Mask.everything(everythingSide).excl(excludePart, maskPartAttributes);
}
static create(mask: Piece, {attributes, id}: {
attributes?: Attributes,
id?: string,
} = {}) {
return new Mask(mask, attributes, id);
}
add(maskPart: Piece) {
return new Mask(this.mask.add(maskPart), this.attributes, undefined);
}
incl(includePart: Piece, maskPartAttributes?: MaskPartAttributes) {
return this.add(applyMaskPartAttributes(includePart, "white", maskPartAttributes));
}
excl(excludePart: Piece, maskPartAttributes?: MaskPartAttributes) {
return this.add(applyMaskPartAttributes(excludePart, "black", maskPartAttributes));
}
setAttributes(attributes: Attributes) {
return new Mask(this.mask, {...this.attributes, ...attributes}, undefined);
}
setId(id: string) {
return new Mask(this.mask, this.attributes, id);
}
getDefs() {
return [createElement({
tagName: "mask",
attributes: {id: this.getId()},
children: this.mask.getElements(),
})];
}
asAttributes() {
return {mask: new IdHelper(this.getId()).url};
}
private getId() {
if (!this.genId)
this.genId = generateId("mask");
return this.genId;
}
}
/**
* Value of a coordinate, expressed as the fraction of size.
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/radialGradient
*/
export type GradientCoordFrac = number;
export type GradientFracPoint = readonly [GradientCoordFrac | undefined, GradientCoordFrac | undefined];
export interface GradientStopValue {
readonly color?: string;
readonly opacity?: number;
}
export interface GradientStop extends GradientStopValue {
readonly offset: number;
}
export type GradientStops = GradientStop[];
export interface GradientStopFunc {
(offset: number): GradientStopValue | undefined;
}
const DEFAULT_NUM_STOPS_FOR_FUNC = 11;
export interface GradientStopsFuncWithRange {
startOffset?: number;
endOffset?: number;
numStops?: number;
offsetStep?: number;
func: GradientStopFunc;
}
export type PartialGradientStops =
| GradientStops
| [GradientStopValue, GradientStopValue]
| GradientStopFunc
| GradientStopsFuncWithRange;
export function gradientStopsFromPartial(arg: PartialGradientStops): GradientStops {
if (Array.isArray(arg)) {
function isGradientStops(arg: GradientStops | [GradientStopValue, GradientStopValue]):
arg is GradientStops {
return arg.length !== 2 || Object.hasOwn(arg[0], "offset");
}
if (isGradientStops(arg))
return arg;
return [0, 1].map(offset => ({offset, ...arg[offset]}));
}
const {
startOffset = 0,
endOffset = 1,
numStops = DEFAULT_NUM_STOPS_FOR_FUNC,
offsetStep = (endOffset - startOffset) / (numStops - 1),
func,
} = typeof arg === "function" ? {func: arg} satisfies GradientStopsFuncWithRange : arg;
if (offsetStep <= 0)
throw new Error(`Expected positive offset step, got ${offsetStep}`);
const stops = [];
for (let offset = startOffset; offset <= endOffset + 1e-9; offset += offsetStep) {
const value = func(offset);
if (value)
stops.push({offset, ...value});
}
return stops;
}
const NO_POINT: GradientFracPoint = [undefined, undefined];
function createStopElement({offset, color, opacity}: GradientStop) {
return Piece.createElement({
tagName: "stop",
attributes: {
offset,
stopColor: color,
stopOpacity: opacity,
},
});
}
/**
* Creates a linear gradient GenericDefTool, usable as fill or stroke.
*
* Usage example:
*
* myPiece.useDefTool(createLinearGradient({...}), "stroke")
*
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/linearGradient
*/
export function createLinearGradient({
stops,
spread,
from = NO_POINT,
to = NO_POINT,
transform,
attributes,
id,
}: {
stops: PartialGradientStops,
spread?: "pad" | "reflect" | "repeat",
from?: GradientFracPoint,
to?: GradientFracPoint,
transform?: Transform,
} & AttributesAndId) {
return Piece.createElement({
tagName: "linearGradient",
children: gradientStopsFromPartial(stops).map(createStopElement),
attributes: {
spreadMethod: spread,
x1: from[0],
y1: from[1],
x2: to[0],
y2: to[1],
gradientTransform: transform?.svgTransform,
...attributes,
},
}).asDefTool(id);
}
export interface RadialGradientEnd {
readonly center?: GradientFracPoint;
readonly radius?: GradientCoordFrac;
}
/**
* Creates a radial gradient GenericDefTool, usable as fill or stroke.
*
* Usage example:
*
* myPiece.useDefTool(createRadialGradient({...}), "fill")
*
* @see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/radialGradient
*/
export function createRadialGradient({
stops,
spread,
circle = {},
from = {},
transform,
attributes,
id,
}: {
stops: PartialGradientStops,
spread?: "pad" | "reflect" | "repeat",
circle?: RadialGradientEnd,
from?: RadialGradientEnd,
transform?: Transform,
} & AttributesAndId) {
return Piece.createElement({
tagName: "radialGradient",
children: gradientStopsFromPartial(stops).map(createStopElement),
attributes: {
spreadMethod: spread,
cx: circle.center?.[0],
cy: circle.center?.[1],
r: circle.radius,
fx: from.center?.[0],
fy: from.center?.[1],
fr: from.radius,
gradientTransform: transform?.svgTransform,
...attributes,
},
}).asDefTool(id);
}