Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Last active April 9, 2020 10:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iconifyit/08ef6e4ebabaca98be5e79bacbef2327 to your computer and use it in GitHub Desktop.
Save iconifyit/08ef6e4ebabaca98be5e79bacbef2327 to your computer and use it in GitHub Desktop.
Experimental code sending JSX message to com.adobe.svgwriter (internal CEP extension). Not currently working.
/*-------------------------------------------------------------------------------------------------------------------------*/
/**
* Adds JSON library support for engines that do not include it natively.
*/
"object"!=typeof JSON&&(JSON={}),function(){"use strict";function f(t){return 10>t?"0"+t:t}function quote(t){
return escapable.lastIndex=0,escapable.test(t)?'"'+t.replace(escapable,function(t){var e=meta[t];
return"string"==typeof e?e:"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+t+'"'}
function str(t,e){var n,r,o,f,u,i=gap,p=e[t];switch(p&&"object"==typeof p&&"function"==typeof p.toJSON&&(p=p.toJSON(t)),
"function"==typeof rep&&(p=rep.call(e,t,p)),typeof p){case"string":return quote(p);case"number":return isFinite(p)?String(p):"null";
case"boolean":case"null":return String(p);case"object":if(!p)return"null";if(gap+=indent,u=[],"[object Array]"===Object.prototype.toString.apply(p)){
for(f=p.length,n=0;f>n;n+=1)u[n]=str(n,p)||"null";return o=0===u.length?"[]":gap?"[\n"+gap+u.join(",\n"+gap)+"\n"+i+"]":"["+u.join(",")+"]",gap=i,o}
if(rep&&"object"==typeof rep)for(f=rep.length,n=0;f>n;n+=1)"string"==typeof rep[n]&&(r=rep[n],o=str(r,p),o&&u.push(quote(r)+(gap?": ":":")+o));
else for(r in p)Object.prototype.hasOwnProperty.call(p,r)&&(o=str(r,p),o&&u.push(quote(r)+(gap?": ":":")+o));return o=0===u.length?"{}":gap?"{\n"+gap+
u.join(",\n"+gap)+"\n"+i+"}":"{"+u.join(",")+"}",gap=i,o}}"function"!=typeof Date.prototype.toJSON&&(Date.prototype.toJSON=function(){
return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+
f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null},String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){
return this.valueOf()});var cx,escapable,gap,indent,meta,rep;"function"!=typeof JSON.stringify&&
(escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},JSON.stringify=function(t,e,n){var r;
if(gap="",indent="","number"==typeof n)for(r=0;n>r;r+=1)indent+=" ";else"string"==typeof n&&(indent=n);if(rep=e,
e&&"function"!=typeof e&&("object"!=typeof e||"number"!=typeof e.length))throw new Error("JSON.stringify");return str("",{"":t})}),
"function"!=typeof JSON.parse&&(cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
JSON.parse=function(text,reviver){function walk(t,e){var n,r,o=t[e];if(o&&"object"==typeof o)for(n in o)Object.prototype.hasOwnProperty.call(o,n)&&
(r=walk(o,n),void 0!==r?o[n]=r:delete o[n]);return reviver.call(t,e,o)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&
(text=text.replace(cx,function(t){return"\\u"+("0000"+t.charCodeAt(0).toString(16)).slice(-4)})),
/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]")
.replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;
throw new SyntaxError("JSON.parse")})}();
/*-------------------------------------------------------------------------------------------------------------------------*/
/**
* Write a file to disc.
* @param {string} path The file path to write to
* @param {string} txt The text to write to the file
* @param {bool} replace Whether to replace the file if it already exists
* @returns {void}
*/
JSON.write = function( path, txt, replace ) {
var OSType = $.os.search(/windows/i) != -1 ? "WINDOWS" : "MAC" ;
try {
var file = new File( path );
if (replace && file.exists) {
file.remove();
file = new File( path );
}
file.open("e", "TEXT", "????");
file.seek(0,2);
file.lineFeed = 'macintosh';
if (OSType == 'WINDOWS') {
file.lineFeed = 'windows';
}
file.writeln(txt);
file.close();
}
catch(ex) {
try { file.close(); }
catch(ex) {/* Exit Gracefully*/}
}
};
/**
* Reads the contents of a file.
* @param {File} fp A file object.
* @returns {string}
*/
JSON.read = function(fp) {
var data = '';
try {
fp.open('r', undefined, undefined);
data = fp.read();
fp.close();
}
catch(e) {
try { fp.close() } catch (e) {}
/* Exit gracefully for now */
}
return data;
};
String.prototype.escapeSpecialChars = function () {
return this.replace(/\\/g, "\\\\")
.replace(/\"/g, "\\\"")
.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r");
};
// ****************** The Real Magic is below **************************
try {
app.sendScriptMessage("SvgFileFormat", "exportSVG", JSON.stringify({
jsonFormatOptions : {
embed: 'embed',
artboards : 'selected',
convertToOutline : false,
svgPath : '000-svgwriter.svg',
logPath : '000-svgwriter.svg.log'
},
svgWriterOptions : {
trimToArtboards : false,
constrainToDocBounds : false,
precision : 3,
isResponsive : false,
minify : false,
styling : 'attribute',
preserveAspectRatio : 'none',
idType : 'regular'
}
}).escapeSpecialChars() );
}
catch(e) { alert(e) }
@C4MS
Copy link

C4MS commented Apr 9, 2020

works fine when using valid absolute paths, tested it on a CEP panel not JSX

let fileName = '/Users/ME/Downloads/Export.svg';

let options = {
    jsonFormatOptions: {
        embed : "embed",
        artboards : "artboard",
        convertToOutline : false,
        svgPath : fileName,
        logPath : fileName + ".log",
    },
    svgWriterOptions: {
        trimToArtBounds : true,
        constrainToDocBounds : false,
        precision : 3,
        isResponsive : true,
        minify : 'minify',
        styling : "attribute",
        preserveAspectRatio : true,
        idType : "minimal",
    }
}

let escapedOptions = JSON.stringify(options).escapeSpecialChars();

let command = `app.sendScriptMessage("SvgFileFormat", "exportSVG", "${escapedOptions}")`;

csInterface.evalScript(command, response => {
    if (response !== "ok") {
        alert(response);
    }
});

@iconifyit
Copy link
Author

Oh, nice. I will give that a try. What's sad is, I barely remember posting this, ha ha. But thanks for the addition.

@iconifyit
Copy link
Author

Another thing I'm curious about is running this through a service worker so it doesn't tie up the UI. So just let the exports run in the background and let the user move onto whatever they need to do.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment