paper.js/src/core/PaperScript.js

280 lines
7.7 KiB
JavaScript
Raw Normal View History

2011-03-06 19:50:44 -05:00
/*
* Paper.js
*
2011-03-06 19:50:44 -05:00
* This file is part of Paper.js, a JavaScript Vector Graphics Library,
* based on Scriptographer.org and designed to be largely API compatible.
2011-03-07 20:41:50 -05:00
* http://paperjs.org/
2011-03-06 19:50:44 -05:00
* http://scriptographer.org/
*
2011-03-06 19:50:44 -05:00
* Copyright (c) 2011, Juerg Lehni & Jonathan Puckey
* http://lehni.org/ & http://jonathanpuckey.com/
*
2011-07-01 06:17:45 -04:00
* Distributed under the MIT license. See LICENSE file for details.
*
2011-03-07 20:41:50 -05:00
* All rights reserved.
2011-03-06 19:50:44 -05:00
*/
/**
* @name PaperScript
* @namespace
*/
var PaperScript = this.PaperScript = new function() {
/*#*/ include('../../lib/parse-js-min.js');
2011-03-07 06:10:45 -05:00
// Math Operators
var operators = {
'+': 'add',
'-': 'subtract',
'*': 'multiply',
'/': 'divide',
'%': 'modulo',
'==': 'equals',
'!=': 'equals'
};
function $eval(left, operator, right) {
var handler = operators[operator];
if (left && left[handler]) {
var res = left[handler](right);
return operator === '!=' ? !res : res;
}
switch (operator) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
case '%': return left % right;
case '==': return left == right;
case '!=': return left != right;
default:
throw new Error('Implement Operator: ' + operator);
}
}
2011-03-07 06:10:45 -05:00
// Sign Operators
var signOperators = {
'-': 'negate'
};
2011-03-03 20:22:08 -05:00
function $sign(operator, value) {
var handler = signOperators[operator];
2011-03-03 20:22:08 -05:00
if (value && value[handler]) {
return value[handler]();
}
switch (operator) {
2011-03-03 20:22:08 -05:00
case '+': return +value;
case '-': return -value;
default:
throw new Error('Implement Sign Operator: ' + operator);
}
}
// AST Helpers
function isDynamic(exp) {
var type = exp[0];
return type != 'num' && type != 'string';
}
function handleOperator(operator, left, right) {
2011-03-03 20:23:47 -05:00
// Only replace operators with calls to $operator if the left hand side
// is potentially an object.
if (operators[operator] && isDynamic(left)) {
2011-03-03 20:23:47 -05:00
// Replace with call to $operator(left, operator, right):
return ['call', ['name', '$eval'],
[left, ['string', operator], right]];
}
}
/**
* Compiles PaperScript code into JavaScript code.
*
* @name PaperScript.compile
* @function
* @param {String} code The PaperScript code.
* @return {String} The compiled PaperScript as JavaScript code.
*/
function compile(code) {
// Use parse-js to translate the code into a AST structure which is then
// walked and parsed for operators to overload. The resulting AST is
// translated back to code and evaluated.
var ast = parse_js.parse(code),
walker = parse_js.ast_walker(),
walk = walker.walk;
ast = walker.with_walkers({
'binary': function(operator, left, right) {
// Handle simple mathematical operators here:
return handleOperator(operator, left = walk(left),
right = walk(right))
// Always return a new AST for this node, since we have
// processed left and right int he call above!
|| [this[0], operator, left, right];
},
'assign': function(operator, left, right) {
// Handle assignments like +=, -=, etc:
// Check if the assignment operator needs to be handled by paper
// if so, convert the assignment to a simple = and use result of
// of handleOperator on the right hand side.
var res = handleOperator(operator, left = walk(left),
right = walk(right));
return res
? [this[0], true, left, res]
// Always return a new AST for the same reason as in binary
: [this[0], operator, left, right];
},
'unary-prefix': function(operator, exp) {
if (signOperators[operator] && isDynamic(exp)) {
return ['call', ['name', '$sign'],
[['string', operator], walk(exp)]];
}
}
}, function() {
return walk(ast);
});
return parse_js.gen_code(ast, {
beautify: true
});
}
/**
* Evaluates parsed PaperScript code in the passed {@link PaperScope}
* object. It also installs handlers automatically for us.
*
* @name PaperScript.evaluate
* @function
* @param {String} code The PaperScript code.
* @param {PaperScript} scope The scope in which the code is executed.
* @return {Object} The result of the code evaluation.
*/
function evaluate(code, scope) {
// Set currently active scope.
paper = scope;
2012-09-01 13:27:38 -04:00
var view = scope.project && scope.project.view,
res;
// Define variables for potential handlers, so eval() calls below to
// fetch their values do not require try-catch around them.
// Use with(){} in order to make the scope the current 'global' scope
// instead of window.
with (scope) {
// Within this, use a function scope, so local variables to not try
2011-05-16 06:19:47 -04:00
// and set themselves on the scope object.
(function() {
2011-12-27 10:05:02 -05:00
var onEditOptions, onSelect, onDeselect, onReselect,
onMouseDown, onMouseUp, onMouseDrag, onMouseMove,
onKeyDown, onKeyUp, onFrame, onResize;
res = eval(compile(code));
// Only look for tool handlers if something resembling their
// name is contained in the code.
if (/on(?:Key|Mouse)(?:Up|Down|Move|Drag)/.test(code)) {
Base.each(Tool.prototype._events, function(key) {
var value = eval(key);
if (value) {
// Use the getTool accessor that handles auto tool
// creation for us:
scope.getTool()[key] = value;
}
});
}
if (view) {
view.setOnResize(onResize);
// Fire resize event directly, so any user
// defined resize handlers are called.
view.fire('resize', {
size: view.size,
delta: new Point()
});
view.setOnFrame(onFrame);
// Automatically draw view at the end.
view.draw();
2011-05-15 18:37:40 -04:00
}
}).call(scope);
}
return res;
}
/*#*/ if (options.browser) {
// Code borrowed from Coffee Script:
function request(url, scope) {
2011-04-26 10:16:05 -04:00
var xhr = new (window.ActiveXObject || XMLHttpRequest)(
'Microsoft.XMLHTTP');
xhr.open('GET', url, true);
2011-05-06 08:29:21 -04:00
if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
return evaluate(xhr.responseText, scope);
}
};
return xhr.send(null);
}
function load() {
var scripts = document.getElementsByTagName('script');
for (var i = 0, l = scripts.length; i < l; i++) {
var script = scripts[i];
// Only load this script if it not loaded already.
// Support both text/paperscript and text/x-paperscript:
if (/^text\/(?:x-|)paperscript$/.test(script.type)
&& !script.getAttribute('data-paper-ignore')) {
// Produce a new PaperScope for this script now. Scopes are
// cheap so let's not worry about the initial one that was
// already created.
// Define an id for each PaperScript, so its scope can be
// retrieved through PaperScope.get().
// If a canvas id is provided, pass it on to the PaperScope
// so a project is created for it now.
var scope = new PaperScope(script);
scope.setup(PaperScript.getAttribute(script, 'canvas'));
if (script.src) {
// If we're loading from a source, request that first and then
// run later.
request(script.src, scope);
} else {
// We can simply get the code form the script tag.
evaluate(script.innerHTML, scope);
}
// Mark script as loaded now.
script.setAttribute('data-paper-ignore', true);
}
}
}
DomEvent.add(window, { load: load });
// Produces helpers to e.g. check for both 'canvas' and 'data-paper-canvas'
// attributes:
function handleAttribute(name) {
name += 'Attribute';
return function(el, attr) {
return el[name](attr) || el[name]('data-paper-' + attr);
};
}
return {
compile: compile,
evaluate: evaluate,
load: load,
getAttribute: handleAttribute('get'),
hasAttribute: handleAttribute('has')
};
/*#*/ } else { // !options.browser
return {
compile: compile,
evaluate: evaluate
};
/*#*/ } // !options.browser
};
// Export load directly:
this.load = PaperScript.load;