Commit d15f8b34 authored by 张九刚's avatar 张九刚

修改解析格式

parent 7cd69d39
......@@ -89,3 +89,4 @@ typings/
# DynamoDB Local files
.dynamodb/
.history
{
"name": "psd-parse-web",
"version": "1.0.2",
"version": "1.0.3",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
......
{
"name": "psd-parse-web",
"version": "1.0.3",
"version": "1.0.4",
"main": "src/index.js",
"module": "dist/index.es.js",
"license": "MIT",
......
/**
*
* 本地化解析psd
*
*/
var { getTree } = require("./psd-tree");
var { walkNode } = require("./utils");
var path = require('path');
var Color = require('color');
var generateUUID = require('uuid/v4');
var fs = require("fs-extra");
var hash = require('object-hash');
var zlib = require('zlib');
const relativePosPrefixMap = {
l: { field: 'left', },
t: { field: 'top', },
r: { field: 'right', },
b: { field: 'bottom', },
h: { field: 'horizonCenter', },
v: { field: 'verticalCenter', },
wp: { field: 'width', },
hp: { field: 'height', },
lp: { field: 'left', },
tp: { field: 'top', },
rp: { field: 'right', },
bp: { field: 'bottom', },
};
const offsetAll = 176;
async function compilePsdToJson(psdFile, options) {
console.log("psdFile:", psdFile);
const { assetsPath } = options;
if (!assetsPath) {
console.log("没有指定assets目录");
}
const tree = await getTree(psdFile);
const { mode = 'none', singleView = true } = options;
let offset = { x: 0, y: 0 };
let cutSize = { x: 0, y: 0 };
if (mode !== 'none') {
cutSize.y = offsetAll;
}
switch (mode) {
case 'top':
offset.y = offsetAll;
break;
case 'center':
offset.y = offsetAll / 2;
break;
}
const isCenter = mode === 'center';
let viewRoot = {
name: path.basename(psdFile, '.psd'),
nodeType: 'Div',
uuid: generateUUID(),
};
const assets = [];
const imageHashMap = {};
let { width: stageWidthOrigin, height: stageHeightOrigin } = tree;
const stageWidth = stageWidthOrigin - cutSize.x || 0;
const stageHeight = stageHeightOrigin - cutSize.y || 0;
await walkNode(tree, async function (node, parent) {
let { name } = node;
const { x, y, width, height, opacity, display, origin: { layer, layer: { typeTool, solidColor } } } = node;
let properties = {
style: {
width, height, opacity, display,
},
attrs: {
},
className: ""
};
const isSecondLayer = singleView && !parent.origin.parent || !singleView && parent.origin.parent && !parent.origin.parent.parent;
const shouldVerticalCenter = isSecondLayer && isCenter;
const { width: parentWidth, height: parentHeight } = parent;
if (name.includes('|') || shouldVerticalCenter) {
try {
let arr = name.split('|');
name = arr[0];
let paramsStr = arr[1];
let relativePos;
if (paramsStr) {
let params = paramsStr.split(';');
relativePos = params[0];
} else if (shouldVerticalCenter) {
relativePos = 'v';
}
if (relativePos) {
let items = relativePos.split(',');
for (let item of items) {
let result = item.match(/[a-zA-Z]+/);
if (!result) {
continue;
}
let prefix = result[0];
let mapItem = relativePosPrefixMap[prefix];
if (mapItem) {
let { field, } = mapItem;
let value = item.substr(prefix.length);
let hasValue = value.length > 0;
let fieldChar = prefix[0];
if (!hasValue) {
switch (fieldChar) {
case 'l':
value = x - offset.x;
break;
case 't':
value = y - offset.y;
break;
case 'r':
value = stageWidth - (x - offset.x) - width;
break;
case 'b':
value = stageHeight - (y - offset.y) - height;
break;
case 'h':
value = x + width / 2 - stageWidthOrigin / 2;
break;
case 'v':
value = y + height / 2 - stageHeightOrigin / 2;
break;
}
}
let isPercent = prefix.endsWith('p');
if (isPercent) {
if (!hasValue) {
switch (fieldChar) {
case 'l':
case 'r':
value /= stageWidth;
break;
case 't':
case 'b':
value /= stageHeight;
break;
}
value = Math.floor(value * 100);
}
value += '%';
} else {
value = parseFloat(value);
if (isNaN(value)) {
value = 0;
}
}
properties.style[field] = value;
}
}
}
} catch (e) {
console.log(e);
}
}
let viewNode = {
name,
properties,
uuid: generateUUID(),
};
let dealLater = true;
if (x !== 0) {
if (!properties.style.left) {
properties.style.left = x - (isSecondLayer ? offset.x : 0);
}
}
if (y !== 0) {
if (!properties.style.top) {
properties.style.top = y - (isSecondLayer ? offset.y : 0);
}
}
properties.style.position = "absolute"
// properties.style.transformOrigin = "0px 0px 0px";
// viewNode.rect = {
// x: properties.style.left ? properties.style.left : 0,
// y: properties.style.top ? properties.style.top : 0,
// width: properties.style.width,
// height: properties.style.height
// }
if (typeTool) {
let fontInfo = typeTool();
properties.attrs.text = fontInfo.textValue;
const sizes = fontInfo.sizes();
const colors = fontInfo.colors();
let fsize = sizes ? sizes[0] || 20 : 20;
properties.style.fontSize = parseInt(fsize);//字体取整
let [r, g, b, a] = colors[0];
properties.style.color = `rgba(${r}, ${g}, ${b}, ${a / 255})`;
viewNode.nodeType = 'Label';
dealLater = false;
} else if (solidColor && layer.vectorMask) {
let paths = layer.vectorMask().paths;
if (paths[2].numPoints === 4) {
let isRect = true;
for (let i = 3; i < paths.length; i++) {
if (paths[i].recordType !== 2) {
isRect = false;
break;
}
}
if (isRect) {
viewNode.nodeType = 'Div';
const { r, g, b } = solidColor();
properties.style.backgroundColor = `rgba(${r}, ${g}, ${b}, 1)`;
dealLater = false;
}
}
}
if (dealLater) {
if (node.hasOwnProperty('children')) {
viewNode.nodeType = 'Div';
} else {
viewNode.nodeType = 'Image';
const ext = '.png';
let buffer;
let src = '';
try {
let img = node.origin.toPng();
if (!fs.existsSync(assetsPath)) {
fs.mkdirsSync(assetsPath);
}
src = path.join(assetsPath, '/' + name + ext);
properties.attrs.src = name + ext;
buffer = await savePng(img, src).catch(e => {
console.log(`${src}下载失败`);
});
} catch (e) {
console.log("下载图片失败:", e);
}
if (buffer) {
assets.push({
name,
src
});
}
}
}
let viewParent = parent.view || viewRoot;
if (!viewParent.hasOwnProperty('children')) {
viewParent.children = [];
}
viewParent.children.push(viewNode);
node.view = viewNode;
});
if (viewRoot.children && viewRoot.children.length) {
viewRoot.children.map(item => {
item.viewType = 'Page'
})
}
let data = {
pluginVersion: "0.0.1",
reference: "psd",
fileName: path.basename(psdFile, '.psd'),
assets,
view: viewRoot,
};
return data;
}
function savePng(png, output) {
return new Promise((resolve, reject) => {
let buffer, buffers = [];
png.pack()
.on('error', reject)
.on('data', (data) => buffers.push(data))
.on('end', () => {
buffer = Buffer.concat(buffers)
})
.pipe(fs.createWriteStream(output))
.on('finish', () => {
resolve(buffer);
});
});
}
module.exports = {
compilePsdToJson
}
\ No newline at end of file
......@@ -4,9 +4,11 @@
const { getTree } = require('./psd-tree');
const { execute } = require("./zeroing");
const { compilePsdToJson } = require('./compilelocal');
module.exports = {
getTree,
execute
execute,
compilePsdToJson
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment