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

去掉mode

parent 88105e4b
......@@ -5,7 +5,7 @@
*/
var { getTree } = require("./psd-tree");
var { walkNode, trimCustom, getPageStyle, getXYBySign } = require("./utils");
var { walkNode, trimCustom } = require("./utils");
var path = require('path');
var Color = require('color');
var generateUUID = require('uuid/v4');
......@@ -30,7 +30,7 @@
async function compilePsdToJson(psdFile, options) {
const { mode, assetsPath } = options;
const { assetsPath } = options;
if (!assetsPath) {
console.log("没有指定assets目录");
}
......@@ -60,51 +60,40 @@
console.warn(`${page.name}不合法,请保持设计稿根目录为全部文件夹形式`);
} else {
const { x, y, width, height } = page;
//如果没有选择适配的情况下,不设置页面的属性,方便给予节点相对布局
let styleObj = mode == 'none' ? {} : { width, height, ...getPageStyle(mode, x, y) };
let viewNode = {
const viewNode = {
name: folderName,
nodeType: 'Div',
properties: {
attrs: {},
props:{
className: `${folderName}`
},
expression:{},
style: {
...styleObj
}
width, height, left: x, top: y, position: "absolute"
},
attrs: {
},
className: ""
},
uuid: generateUUID(),
children: []
};
viewRoot.children.push(viewNode);
}
await walkNode(page, async (node, parent) => {
let { name } = node;
name = trimCustom(name);
const { x, y, width, height, origin: { layer, layer: { typeTool, solidColor } } } = node;
const layout = getXYBySign(name, x, y, width, height, mode);
let properties = {
attrs: {},
props:{
className: `${name}`
},
expression:{},
style: {
width, height, ...layout
width, height, left: x, top: y, position: "absolute"
},
attrs: {
}
},
className: ""
};
let viewNode = {
name: name.split('|')[0], //如果设置了适配的话,作为名字截取掉
name,
properties,
uuid: generateUUID(),
};
......@@ -170,8 +159,8 @@
if (!fs.existsSync(imgPath)) {
fs.mkdirsSync(imgPath);
}
src = path.join(imgPath, '/' + viewNode.name + ext);
properties.attrs.src = viewNode.name + ext;
src = path.join(imgPath, '/' + name + ext);
properties.attrs.src = name + ext;
properties.attrs.folderName = folderName;
buffer = await savePng(img, src).catch(e => {
console.log(`${src}下载失败`);
......@@ -183,7 +172,7 @@
if (buffer) {
assets.push({
name: viewNode.name,
name,
src,
folderName
});
......@@ -224,9 +213,15 @@
return data;
}
/**
* 单页解析
* @param {*} node
* @param {*} parent
* @param {*} folderName
*/
async function compilePage(node, parent, folderName, assetsPath) {
}
function savePng(png, output) {
return new Promise((resolve, reject) => {
......@@ -264,4 +259,5 @@
module.exports = {
compilePsdToJson
}
\ No newline at end of file
}
\ No newline at end of file
/**
*
* 本地化解析psd
* 添加了mode选项的备份
*
*/
var { getTree } = require("./psd-tree");
var { walkNode, trimCustom, getPageStyle, getXYBySign } = 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', },
};
async function compilePsdToJson(psdFile, options) {
const { mode, assetsPath } = options;
if (!assetsPath) {
console.log("没有指定assets目录");
}
const tree = await getTree(psdFile);
let viewRoot = {
name: path.basename(psdFile, '.psd'),
nodeType: 'Div',
uuid: generateUUID(),
children: []
};
const assets = [];
const pageList = tree.children || [];
const isHadErrorPage = pageList.filter(page => !page.children);
if (isHadErrorPage.length) {
console.warn(`${isHadErrorPage[0].name}不合法,请保持设计稿根目录为全部文件夹形式`);
return {
error: true,
errorName: isHadErrorPage[0].name
}
}
const pr = pageList.map(async (page, index) => {
let folderName = page.name || `未命名页面${Math.random().toFixed(2) * 100}`;
folderName = trimCustom(folderName);
if (!page.children) {
console.warn(`${page.name}不合法,请保持设计稿根目录为全部文件夹形式`);
} else {
const { x, y, width, height } = page;
//如果没有选择适配的情况下,不设置页面的属性,方便给予节点相对布局
let styleObj = mode == 'none' ? {} : { width, height, ...getPageStyle(mode, x, y) };
let viewNode = {
name: folderName,
nodeType: 'Div',
properties: {
attrs: {},
props:{
className: `${folderName}`
},
expression:{},
style: {
...styleObj
}
},
uuid: generateUUID(),
children: []
};
viewRoot.children.push(viewNode);
}
await walkNode(page, async (node, parent) => {
let { name } = node;
name = trimCustom(name);
const { x, y, width, height, origin: { layer, layer: { typeTool, solidColor } } } = node;
const layout = getXYBySign(name, x, y, width, height, mode);
let properties = {
attrs: {},
props:{
className: `${name}`
},
expression:{},
style: {
width, height, ...layout
},
attrs: {
}
};
let viewNode = {
name: name.split('|')[0], //如果设置了适配的话,作为名字截取掉
properties,
uuid: generateUUID(),
};
let dealLater = true;
if (typeTool) {
let fontInfo = typeTool();
properties.attrs.text = fontInfo.textValue;
const colors = fontInfo.colors();
// console.log("node::", node)
// console.log("fontInfo::", fontInfo.export())
let fsize = computeFontSize(fontInfo)
properties.style.fontSize = parseInt(fsize);//字体取整
//字体取整情况下有可能导致宽度不够,默认扩大10像素
viewNode.properties.style.width += 10;
viewNode.properties.style.lineHeight = `${height}`;
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();
let imgPath = assetsPath;
// console.log("folderName::",folderName);
//如果是一级页面的话,那么根据页面创建路径
if (folderName) {
imgPath = path.join(assetsPath, folderName);
}
if (!fs.existsSync(imgPath)) {
fs.mkdirsSync(imgPath);
}
src = path.join(imgPath, '/' + viewNode.name + ext);
properties.attrs.src = viewNode.name + ext;
properties.attrs.folderName = folderName;
buffer = await savePng(img, src).catch(e => {
console.log(`${src}下载失败`);
});
} catch (e) {
console.log("下载图片失败:", e);
}
if (buffer) {
assets.push({
name: viewNode.name,
src,
folderName
});
}
}
}
let viewParent = parent.view || viewRoot.children[index];
if (!viewParent.hasOwnProperty('children')) {
viewParent.children = [];
}
// console.log("viewNode:", viewNode);
viewParent.children.push(viewNode);
node.view = viewNode;
});
})
await Promise.all(pr);
if (viewRoot.children && viewRoot.children.length) {
viewRoot.children.map(item => {
item.viewType = "Component";//'Page' // 由于弹窗比较多,所以默认是弹窗
})
}
let data = {
pluginVersion: "0.0.1",
reference: "psd",
fileName: path.basename(psdFile, '.psd'),
assets,
view: { children: viewRoot.children },
};
// console.log("data...", JSON.stringify(data));
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);
});
});
}
const computeFontSize = (fontinfo, defValue = 24) => {
const sizes = fontinfo.sizes();
let size;
if (sizes && sizes[0]) {
if (fontinfo.transform.yy !== 1) {
size = Math.round((sizes[0] * fontinfo.transform.yy) * 100) * 0.01;
} else { // transform.yy为1时,sizes[0]的值就是字体显示大小的值,不需要计算
size = sizes[0].toFixed();
}
} else {
size = defValue; // 默认
}
return size;
}
module.exports = {
compilePsdToJson
}
\ No newline at end of file
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