sketch-json-parse
Version:
sketch-json解析
79 lines (78 loc) • 3.51 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTypeFace = void 0;
const utils_1 = require("../common/utils");
const const_1 = require("../common/const");
/**
* 基础属性解析
* @param layer
*/
const parseTypeFace = (layer) => {
const { attributedString, style } = layer;
if (!attributedString) {
return [];
}
const { string: textContent, // 文本内容
attributes // 分段样式
} = attributedString;
// 分段处理
const typefaces = attributes.map(({ location, length, attributes }) => {
var _a, _b, _c, _d, _e, _f, _g;
let { name: fontFamily, // 获取字体类型
size: fontSize, // 获取字体大小
} = (_a = attributes.MSAttributedStringFontAttribute) === null || _a === void 0 ? void 0 : _a.attributes;
/**
* fontFamily处理
* 1.PingFang-SCPingFang SC 针对PingFang-SC和PingFang SC在web端不生效的问题,进行修正处理
*
*/
fontFamily = fontFamily ? fontFamily.replace(/PingFang-SC|PingFang SC/, 'PingFangSC') : '';
// 获取字体重量, 默认 Regular;
const val = fontFamily.split('-').pop();
const fontWeight = fontFamily.split('-').length >= 2 && const_1.fontWeightTypes.includes(val.toLowerCase()) ? val : '';
// 获取字体颜色 默认:{ red: 0, green: 0,blue: 0,alpha: 1 }
const { red, green, blue, alpha, swatchID } = attributes.MSAttributedStringColorAttribute || { red: 0, green: 0, blue: 0, alpha: 1, _class: 'color' };
const color = (0, utils_1.transSketchColor)({ red, green, blue, alpha, swatchID });
// 获取字间距
const letterSpacing = attributes.kerning || 0;
/**
* 获取行间距
* 1. maximumLineHeight存在,则取maximumLineHeight值
* 2. maximumLineHeight不存在,则根据字体映射出对应的默认行高
*/
const lineHeight = ((_b = attributes.paragraphStyle) === null || _b === void 0 ? void 0 : _b.maximumLineHeight) ? (_c = attributes.paragraphStyle) === null || _c === void 0 ? void 0 : _c.maximumLineHeight : const_1.fontSizeLineHeightMap[fontSize];
// 获取段间距
const paragraphSpacing = ((_d = attributes.paragraphStyle) === null || _d === void 0 ? void 0 : _d.paragraphSpacing) || 0;
/**
* 获取字体水平居中方式
* 0 水平左对齐
* 1 水平居中对齐
* 2 水平右对齐
* 3 水平两端对齐
*/
const alignment = ((_e = attributes.paragraphStyle) === null || _e === void 0 ? void 0 : _e.alignment) !== undefined ? +((_f = attributes.paragraphStyle) === null || _f === void 0 ? void 0 : _f.alignment) : 0;
/**
* 获取字体垂直居中方式
* 0 垂直顶部对齐
* 1 垂直居中对齐
* 2 垂直底部对齐
*/
const verticalAlignment = (_g = style.textStyle) === null || _g === void 0 ? void 0 : _g.verticalAlignment;
// 获取该段文本内容
const content = textContent.substring(location, location + length);
return {
fontFamily,
fontWeight,
alignment,
verticalAlignment,
color,
fontSize,
letterSpacing,
lineHeight,
paragraphSpacing,
content
};
});
return typefaces;
};
exports.parseTypeFace = parseTypeFace;