-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
249 lines (205 loc) · 7.32 KB
/
index.js
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
const Psd = require('psd');
const { Svg, Path, PathDefinition, Point, Color, Group, GenericElement, Use } = require('./classes');
const { PathRecordType, StrokeLineAlignment, StrokeLineCapType, StrokeLineJoinType } = require('./types');
const { reverse, rotate, roundOff } = require('./utils');
exports.convertFile = convertFile;
exports.convertToSvg = convertToSvg;
function convertFile(path) {
let psd = Psd.fromFile(path);
let ok = psd.parse();
if (!ok) {
throw new Error('Failed to parse PSD');
}
return convertToSvg(psd);
}
function convertToSvg(psd) {
let header = psd.tree().psd.header;
let width = header.width;
let height = header.height;
let state = new ConversionState();
let nodes = convertNode(psd.tree(), state, { width, height });
return new Svg(width, height, nodes);
}
function convertNode(node, state, params) {
if (node.isRoot()) {
return convertChildren(node.children(), state, params);
}
let name = node.get('name').trim().replace(/\s+/g, '_').toLowerCase();
let hidden = node.hidden();
let opacity = roundOff(node.get('opacity') / 255, 2);
if (node.isGroup()) {
let groupNum = ++state.groupCount;
let children = convertChildren(node.children(), state, params);
return new Group({ id: `G${groupNum}_${name}`, hidden, opacity }, children);
}
let vectorMask = node.get('vectorMask');
if (vectorMask == null) {
return null;
}
let layerNum = ++state.layerCount;
let vectorData = node.get('vectorStroke');
let solidColor = node.get('solidColor');
let fill = vectorData != null && !vectorData.data.fillEnabled
? null
: solidColor == null
? Color.Black
: new Color(solidColor.r, solidColor.g, solidColor.b);
let stroke = vectorData == null || !vectorData.data.strokeEnabled
? null
: getStroke(vectorData.data);
let subpaths = getSubpaths(vectorMask, params.width, params.height);
if (stroke == null || stroke.alignment === 'center') {
return new Path({ id: `L${layerNum}_${name}`, hidden, opacity, fill: fill ?? 'none', stroke }, subpaths);
} else if (stroke.alignment === 'inside') {
state.maskCount++;
let pathId = `M${state.maskCount}_path`;
let maskId = `M${state.maskCount}_inner_stroke_mask`;
let newStroke = Object.assign(stroke, { width: stroke.width * 2 } );
let elems = [
new GenericElement('defs', {}, [
new Path({ id: pathId }, subpaths),
new GenericElement('mask', { id: maskId }, [
new Use(pathId, { fill: Color.White }),
]),
]),
new Use(pathId, { fill: fill ?? 'none', stroke: newStroke, mask: maskId }),
];
return new Group({ id: `L${layerNum}_${name}`, hidden, opacity }, elems);
} else if (stroke.alignment === 'outside') {
state.maskCount++;
let pathId = `M${state.maskCount}_path`;
let maskId = `M${state.maskCount}_outer_stroke_mask`;
let newStroke = Object.assign(stroke, { width: stroke.width * 2 } );
let elems = [
new GenericElement('defs', {}, [
new Path({ id: pathId }, subpaths),
new GenericElement('mask', { id: maskId }, [
new GenericElement('rect', { width: params.width, height: params.height, fill: Color.White }),
new Use(pathId, { fill: Color.Black }),
]),
]),
new Use(pathId, { fill: 'none', stroke: newStroke, mask: maskId }),
];
if (fill != null) {
elems.push(new Use(pathId, { fill }));
}
return new Group({ id: `L${layerNum}_${name}`, hidden, opacity }, elems);
} else {
throw new Error('Unknown stroke alignment: ' + stroke.alignment);
}
}
function convertChildren(children, state, params) {
let nodes = [];
// reverse because PSD and SVG have opposite layer ordering
for (let n of reverse(children)) {
let result = convertNode(n, state, params);
if (result != null) {
nodes.push(result);
}
}
return nodes;
}
function getStroke(strokeData) {
let strokeColor = strokeData.strokeStyleContent['Clr '];
let strokeWidth = strokeData.strokeStyleLineWidth.value;
let strokeDash = strokeData.strokeStyleLineDashSet.map(dash => dash.value * strokeWidth);
return {
width: strokeWidth,
color: new Color(strokeColor['Rd '], strokeColor['Grn '], strokeColor['Bl ']),
alignment: getStrokeAlignment(strokeData.strokeStyleLineAlignment),
lineCap: getLineCap(strokeData.strokeStyleLineCapType),
lineJoin: getLineJoin(strokeData.strokeStyleLineJoinType),
dash: strokeDash.length <= 0 ? null : strokeDash,
};
}
function getSubpaths(vectorMask, width, height) {
let pathRecords = vectorMask.paths;
let subpaths = [];
for (let i = 0; i < pathRecords.length; i++) {
let rec = pathRecords[i];
switch (rec.recordType) {
case PathRecordType.ClosedSubpathLength:
case PathRecordType.OpenSubpathLength:
let isClosed = rec.recordType === PathRecordType.ClosedSubpathLength;
let points = collectPoints(pathRecords.slice(i + 1, i + 1 + rec.numPoints))
.map(p => new Point(roundOff(p.x * width, 4), roundOff(p.y * height, 4)));
subpaths.push(buildPathDefinition(isClosed, points));
i += rec.numPoints;
break;
case PathRecordType.PathFillRule:
case PathRecordType.Clipboard:
case PathRecordType.InitialFillRule:
continue;
default:
throw new Error('Unexpected path record type: ' + rec.recordType);
}
}
return subpaths;
}
function collectPoints(knots) {
let points = [];
for (let k of knots) {
points.push(new Point(k.precedingHoriz, k.precedingVert));
points.push(new Point(k.anchorHoriz, k.anchorVert));
points.push(new Point(k.leavingHoriz, k.leavingVert));
}
return rotate(points);
}
function buildPathDefinition(isClosed, points) {
let def = new PathDefinition();
def.move(points[0]);
points = rotate(points);
if (!isClosed) {
points = points.slice(0, points.length - 3);
}
for (let i = 0; i < points.length; i += 3) {
def.cubicCurve(points[i], points[i + 1], points[i + 2]);
}
if (isClosed) {
def.close();
}
return def;
}
function getStrokeAlignment(alignData) {
switch (alignData.value) {
case StrokeLineAlignment.Center:
return 'center';
case StrokeLineAlignment.Inside:
return 'inside';
case StrokeLineAlignment.Outside:
return 'outside';
default:
throw new Error('Unknown stroke alignment: ' + alignData.value);
}
}
function getLineCap(capData) {
switch (capData.value) {
case StrokeLineCapType.Butt:
return 'butt';
case StrokeLineCapType.Round:
return 'round';
case StrokeLineCapType.Square:
return 'square';
default:
throw new Error('Unknown stroke line cap type: ' + capData.value);
}
}
function getLineJoin(joinData) {
switch (joinData.value) {
case StrokeLineJoinType.Miter:
return 'miter';
case StrokeLineJoinType.Round:
return 'round';
case StrokeLineJoinType.Bevel:
return 'bevel';
default:
throw new Error('Unknown stroke line join type: ' + joinData.value);
}
}
class ConversionState {
constructor() {
this.layerCount = 0;
this.groupCount = 0;
this.maskCount = 0;
}
}