|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
let _TextEncoder; |
|
let _TextDecoder; |
|
if (typeof TextEncoder === 'undefined') { |
|
_TextEncoder = require('text-encoding').TextEncoder; |
|
_TextDecoder = require('text-encoding').TextDecoder; |
|
} else { |
|
_TextEncoder = TextEncoder; |
|
_TextDecoder = TextDecoder; |
|
} |
|
|
|
|
|
|
|
|
|
const HTML_COMMENT_START = `<!${'-'.repeat(2)}`; |
|
const HTML_COMMENT_END = `${'-'.repeat(2)}>`; |
|
|
|
const regex = new RegExp( |
|
`${HTML_COMMENT_START}rotationCenter:(-?[\\d\\.]+):(-?[\\d\\.]+)${HTML_COMMENT_END}$` |
|
); |
|
|
|
const uint8ToBase64 = function(uint8) { |
|
let binary = ''; |
|
const chunkSize = 0x8000; |
|
for (let i = 0; i < uint8.length; i += chunkSize) { |
|
const chunk = uint8.subarray(i, i + chunkSize); |
|
binary += String.fromCharCode.apply(null, chunk); |
|
} |
|
return btoa(binary); |
|
} |
|
|
|
|
|
|
|
|
|
|
|
const generateCustomFontsCSS = (fonts) => { |
|
let fontCSS = ''; |
|
for (const font of fonts) { |
|
const base64 = uint8ToBase64(font.asset.data); |
|
|
|
|
|
let format = font.asset.dataFormat.toLowerCase(); |
|
if (format === 'otf') format = 'opentype'; |
|
if (format === 'ttf') format = 'truetype'; |
|
|
|
fontCSS += "@font-face {"; |
|
fontCSS += `font-family: "${font.family}";`; |
|
fontCSS += `src: url('data:font/${format};base64,${base64}') format('${format}');`; |
|
fontCSS += "}"; |
|
} |
|
|
|
return fontCSS; |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
const parseVectorMetadata = svgString => { |
|
|
|
const match = svgString.match(regex); |
|
if (!match) { |
|
return null; |
|
} |
|
|
|
const detectedX = +match[1]; |
|
const detectedY = +match[2]; |
|
if (Number.isNaN(detectedX) || Number.isNaN(detectedY)) { |
|
return null; |
|
} |
|
|
|
return [detectedX, detectedY]; |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
const exportCostume = (costume, optIncludeExtras) => { |
|
|
|
const originalData = costume.asset.data; |
|
|
|
if (costume.dataFormat !== 'svg') { |
|
return originalData; |
|
} |
|
|
|
let decodedData = new _TextDecoder().decode(originalData); |
|
|
|
|
|
decodedData = decodedData.replace(regex, ''); |
|
|
|
const centerX = costume.rotationCenterX; |
|
const centerY = costume.rotationCenterY; |
|
const extraData = `${HTML_COMMENT_START}rotationCenter:${centerX}:${centerY}${HTML_COMMENT_END}`; |
|
decodedData += extraData; |
|
|
|
if (optIncludeExtras && vm?.runtime?.fontManager?.fonts) { |
|
const fonts = vm.runtime.fontManager.fonts.filter(f => !f.system) |
|
.filter(f => decodedData.includes(`font-family=""${f.family}", ${f.fallback}"`)) |
|
|
|
const cssText = generateCustomFontsCSS(fonts); |
|
if (cssText) { |
|
const styleElement = `<style type="text/css">${cssText}</style>`; |
|
decodedData = decodedData.replace(new RegExp(`<svg[^>]*?>`), match => `${match}${styleElement}`); |
|
} |
|
} |
|
|
|
return new _TextEncoder().encode(decodedData); |
|
}; |
|
|
|
module.exports = { |
|
parseVectorMetadata, |
|
exportCostume |
|
}; |
|
|