code
stringlengths
2
1.05M
import { createStore, applyMiddleware, compose } from 'redux'; import { reducer } from './reducer'; import { combineEpics, createEpicMiddleware } from 'redux-observable'; import { testEpic } from './testEpic'; import { createRestEpic } from 'robs-fetch'; // Import the restEpic constructor. const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; export function createReduxStore() { // Add the restEpic to the rootEpic creation. const fetchEpic = createRestEpic({ credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }); const rootEpic = combineEpics(testEpic, fetchEpic); const epicMiddleware = createEpicMiddleware(rootEpic); const enhancers = composeEnhancers(applyMiddleware(epicMiddleware)); return createStore(reducer, enhancers); }
/** * The following features are still outstanding: animation as a * function, placement as a function, inside, support for more triggers than * just mouse enter/leave, html tooltips, and selector delegation. */ angular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] ) /** * The $tooltip service creates tooltip- and popover-like directives as well as * houses global options for them. */ .provider( '$tooltip', function () { // The default options tooltip and popover. var defaultOptions = { placement: 'top', animation: true, popupDelay: 0 }; // Default hide triggers for each show trigger var triggerMap = { 'mouseenter': 'mouseleave', 'click': 'click', 'focus': 'blur' }; // The options specified to the provider globally. var globalOptions = {}; /** * `options({})` allows global configuration of all tooltips in the * application. * * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) { * // place tooltips left instead of top by default * $tooltipProvider.options( { placement: 'left' } ); * }); */ this.options = function( value ) { angular.extend( globalOptions, value ); }; /** * This allows you to extend the set of trigger mappings available. E.g.: * * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' ); */ this.setTriggers = function setTriggers ( triggers ) { angular.extend( triggerMap, triggers ); }; /** * This is a helper function for translating camel-case to snake-case. */ function snake_case(name){ var regexp = /[A-Z]/g; var separator = '-'; return name.replace(regexp, function(letter, pos) { return (pos ? separator : '') + letter.toLowerCase(); }); } /** * Returns the actual instance of the $tooltip service. * TODO support multiple triggers */ this.$get = [ '$window', '$compile', '$timeout', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $document, $position, $interpolate ) { return function $tooltip ( type, prefix, defaultTriggerShow ) { var options = angular.extend( {}, defaultOptions, globalOptions ); /** * Returns an object of show and hide triggers. * * If a trigger is supplied, * it is used to show the tooltip; otherwise, it will use the `trigger` * option passed to the `$tooltipProvider.options` method; else it will * default to the trigger supplied to this directive factory. * * The hide trigger is based on the show trigger. If the `trigger` option * was passed to the `$tooltipProvider.options` method, it will use the * mapped trigger from `triggerMap` or the passed trigger if the map is * undefined; otherwise, it uses the `triggerMap` value of the show * trigger; else it will just use the show trigger. */ function getTriggers ( trigger ) { var show = trigger || options.trigger || defaultTriggerShow; var hide = triggerMap[show] || show; return { show: show, hide: hide }; } var directiveName = snake_case( type ); var startSym = $interpolate.startSymbol(); var endSym = $interpolate.endSymbol(); var template = '<div '+ directiveName +'-popup '+ 'title="'+startSym+'title'+endSym+'" '+ 'content="'+startSym+'content'+endSym+'" '+ 'placement="'+startSym+'placement'+endSym+'" '+ 'class="'+startSym+'class'+endSym+'" '+ 'animation="animation" '+ 'is-open="isOpen"'+ '>'+ '</div>'; return { restrict: 'EA', compile: function (tElem, tAttrs) { var tooltipLinker = $compile( template ); return function link ( scope, element, attrs ) { var tooltip; var tooltipLinkedScope; var transitionTimeout; var popupTimeout; var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false; var triggers = getTriggers( undefined ); var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']); var ttScope = scope.$new(true); var positionTooltip = function () { var ttPosition = $position.positionElements(element, tooltip, ttScope.placement, appendToBody); ttPosition.top += 'px'; ttPosition.left += 'px'; // Now set the calculated positioning. tooltip.css( ttPosition ); }; // By default, the tooltip is not open. // TODO add ability to start tooltip opened ttScope.isOpen = false; function toggleTooltipBind () { if ( ! ttScope.isOpen ) { showTooltipBind(); } else { hideTooltipBind(); } } // Show the tooltip with delay if specified, otherwise show it immediately function showTooltipBind() { if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) { return; } prepareTooltip(); if ( ttScope.popupDelay ) { // Do nothing if the tooltip was already scheduled to pop-up. // This happens if show is triggered multiple times before any hide is triggered. if (!popupTimeout) { popupTimeout = $timeout( show, ttScope.popupDelay, false ); popupTimeout.then(function(reposition){reposition();}); } } else { show()(); } } function hideTooltipBind () { scope.$apply(function () { hide(); }); } // Show the tooltip popup element. function show() { popupTimeout = null; // If there is a pending remove transition, we must cancel it, lest the // tooltip be mysteriously removed. if ( transitionTimeout ) { $timeout.cancel( transitionTimeout ); transitionTimeout = null; } // Don't show empty tooltips. if ( ! ttScope.content ) { return angular.noop; } createTooltip(); // Set the initial positioning. tooltip.css({ top: 0, left: 0, display: 'block' }); ttScope.$digest(); positionTooltip(); // And show the tooltip. ttScope.isOpen = true; ttScope.$digest(); // digest required as $apply is not called // Return positioning function as promise callback for correct // positioning after draw. return positionTooltip; } // Hide the tooltip popup element. function hide() { // First things first: we don't show it anymore. ttScope.isOpen = false; //if tooltip is going to be shown after delay, we must cancel this $timeout.cancel( popupTimeout ); popupTimeout = null; // And now we remove it from the DOM. However, if we have animation, we // need to wait for it to expire beforehand. // FIXME: this is a placeholder for a port of the transitions library. if ( ttScope.animation ) { if (!transitionTimeout) { transitionTimeout = $timeout(removeTooltip, 500); } } else { removeTooltip(); } } function createTooltip() { // There can only be one tooltip element per directive shown at once. if (tooltip) { removeTooltip(); } tooltipLinkedScope = ttScope.$new(); tooltip = tooltipLinker(tooltipLinkedScope, function (tooltip) { if ( appendToBody ) { $document.find( 'body' ).append( tooltip ); } else { element.after( tooltip ); } }); } function removeTooltip() { transitionTimeout = null; if (tooltip) { tooltip.remove(); tooltip = null; } if (tooltipLinkedScope) { tooltipLinkedScope.$destroy(); tooltipLinkedScope = null; } } function prepareTooltip() { prepPlacement(); prepPopupDelay(); } /** * Observe the relevant attributes. */ attrs.$observe( type, function ( val ) { ttScope.content = val; if (!val && ttScope.isOpen ) { hide(); } }); attrs.$observe( 'disabled', function ( val ) { if (val && ttScope.isOpen ) { hide(); } }); attrs.$observe( prefix+'Title', function ( val ) { ttScope.title = val; }); attrs.$observe( prefix+'Class', function ( val ) { ttScope.class = val; }); function prepPlacement() { var val = attrs[ prefix + 'Placement' ]; ttScope.placement = angular.isDefined( val ) ? val : options.placement; } function prepPopupDelay() { var val = attrs[ prefix + 'PopupDelay' ]; var delay = parseInt( val, 10 ); ttScope.popupDelay = ! isNaN(delay) ? delay : options.popupDelay; } var unregisterTriggers = function () { element.unbind(triggers.show, showTooltipBind); element.unbind(triggers.hide, hideTooltipBind); }; function prepTriggers() { var val = attrs[ prefix + 'Trigger' ]; unregisterTriggers(); triggers = getTriggers( val ); if ( triggers.show === triggers.hide ) { element.bind( triggers.show, toggleTooltipBind ); } else { element.bind( triggers.show, showTooltipBind ); element.bind( triggers.hide, hideTooltipBind ); } } prepTriggers(); var animation = scope.$eval(attrs[prefix + 'Animation']); ttScope.animation = angular.isDefined(animation) ? !!animation : options.animation; var appendToBodyVal = scope.$eval(attrs[prefix + 'AppendToBody']); appendToBody = angular.isDefined(appendToBodyVal) ? appendToBodyVal : appendToBody; // if a tooltip is attached to <body> we need to remove it on // location change as its parent scope will probably not be destroyed // by the change. if ( appendToBody ) { scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () { if ( ttScope.isOpen ) { hide(); } }); } // Make sure tooltip is destroyed and removed. scope.$on('$destroy', function onDestroyTooltip() { $timeout.cancel( transitionTimeout ); $timeout.cancel( popupTimeout ); unregisterTriggers(); removeTooltip(); ttScope = null; }); }; } }; }; }]; }) .directive( 'tooltipPopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', class: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-popup.html' }; }) .directive( 'tooltip', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltip', 'tooltip', 'mouseenter' ); }]) .directive( 'tooltipHtmlUnsafePopup', function () { return { restrict: 'EA', replace: true, scope: { content: '@', placement: '@', class: '@', animation: '&', isOpen: '&' }, templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html' }; }) .directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) { return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' ); }]);
define(['jquery', 'underscore', 'backbone', 'backbone.marionette', 'util/logger', 'app' ], function ($, _, Backbone, Marionette, log, app) { return Marionette.Layout.extend({ regions: { main : '#main' }, events: { 'click a:not([rel*="click"])' : 'onNavItemClicked' }, // ----- EVENTS HANDLERS ----- onNavItemClicked: function(ev) { ev.preventDefault(); Backbone.history.navigate(ev.target.pathname, { trigger: true }); } }); });
var path = require("path"); module.exports = { context: __dirname, entry: "./frontend/src/index.jsx", devServer: { contentBase: './build', port: 9000, https: false, }, output: { path: path.join(__dirname, 'app', 'assets', 'javascripts', 'build'), filename: "bundle.js", }, module: { loaders: [ { test: /.jsx?$/, exclude: /node_modules/, loader: ['babel'], query: { presets: ['es2015', 'react'] } }, { test: /\.css$/, loader: "style-loader!css-loader" }, { test: /.svg$/, loaders: ['url-loader?mimetype=image/svg+xml'] }, { test: /.png$/, loaders: ['url-loader?mimetype=image/png'] }, { test: /.jpe?g$/, loaders: ['url-loader?mimetype=image/jpg'] }, ] }, devtool: 'source-maps', resolve: { extensions: ["", ".js", ".jsx" ] } };
var utils = require('./_utils') module.exports = function(esskOptions) { return function () { var folders = [ esskOptions.jsBasePath, 'test' ] // Run eslint return utils.exec('./node_modules/.bin/eslint', folders) } }
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M3 8c0 .55.45 1 1 1h4v2H5c-.55 0-1 .45-1 1s.45 1 1 1h3v2H4c-.55 0-1 .45-1 1s.45 1 1 1h4c1.1 0 2-.9 2-2v-1.5c0-.83-.67-1.5-1.5-1.5.83 0 1.5-.67 1.5-1.5V9c0-1.1-.9-2-2-2H4c-.55 0-1 .45-1 1zm18 4v3c0 1.1-.9 2-2 2h-5c-1.1 0-2-.9-2-2V9c0-1.1.9-2 2-2h6c.55 0 1 .45 1 1s-.45 1-1 1h-6v6h5v-2h-1.5c-.55 0-1-.45-1-1s.45-1 1-1H20c.55 0 1 .45 1 1z" /> , 'ThreeGMobiledataRounded');
import * as areaActions from './actions' export {areaActions} export * from './constants' export * from './reducer'
'use strict'; /** * Module dependencies. */ var users = require('../../app/controllers/users.server.controller'), incomes = require('../../app/controllers/incomes.server.controller'); module.exports = function(app) { // Article Routes app.route('/incomes') .get(incomes.list) .post(users.requiresLogin, incomes.create); app.route('/incomes/:incomeId') .get(incomes.read) .put(users.requiresLogin, incomes.hasAuthorization, incomes.update) .delete(users.requiresLogin, incomes.hasAuthorization, incomes.delete); // Finish by binding the article middleware app.param('incomeId', incomes.incomeByID); };
import { log, error } from './logger'; export function unhandledRequest(verb, path, request){ const msg = `[FakeServer] received unhandled request for ${verb} ${path}`; error(msg, request); throw new Error(msg); } export function handledRequest(verb, path) { log(`[FakeServer] handled: ${verb} ${path}`); }
/** * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com * * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/, http://www.vinterwebb.se/ * * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilzén and Mammon Media and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License: * http://www.opensource.org/licenses/mit-license.php * */ /* ******************* */ /* Constructor & Init */ /* ******************* */ var SWFUpload; if (SWFUpload == undefined) { SWFUpload = function (settings) { this.initSWFUpload(settings); }; } SWFUpload.prototype.initSWFUpload = function (settings) { try { this.customSettings = {}; // A container where developers can place their own settings associated with this instance. this.settings = settings; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; // Setup global control tracking SWFUpload.instances[this.movieName] = this; // Load the settings. Load the Flash movie. this.initSettings(); this.loadFlash(); this.displayDebugInfo(); } catch (ex) { delete SWFUpload.instances[this.movieName]; throw ex; } }; /* *************** */ /* Static Members */ /* *************** */ SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 2009-03-25"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED : -100, FILE_EXCEEDS_SIZE_LIMIT : -110, ZERO_BYTE_FILE : -120, INVALID_FILETYPE : -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR : -200, MISSING_UPLOAD_URL : -210, IO_ERROR : -220, SECURITY_ERROR : -230, UPLOAD_LIMIT_EXCEEDED : -240, UPLOAD_FAILED : -250, SPECIFIED_FILE_ID_NOT_FOUND : -260, FILE_VALIDATION_FAILED : -270, FILE_CANCELLED : -280, UPLOAD_STOPPED : -290 }; SWFUpload.FILE_STATUS = { QUEUED : -1, IN_PROGRESS : -2, ERROR : -3, COMPLETE : -4, CANCELLED : -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE : -100, SELECT_FILES : -110, START_UPLOAD : -120 }; SWFUpload.CURSOR = { ARROW : -1, HAND : -2 }; SWFUpload.WINDOW_MODE = { WINDOW : "window", TRANSPARENT : "transparent", OPAQUE : "opaque" }; // Private: takes a URL, determines if it is relative and converts to an absolute URL // using the current site. Only processes the URL if it can, otherwise returns the URL untouched SWFUpload.completeURL = function(url) { if (typeof(url) !== "string" || url.match(/^https?:\/\//i) || url.match(/^\//)) { return url; } var currentURL = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); var indexSlash = window.location.pathname.lastIndexOf("/"); if (indexSlash <= 0) { path = "/"; } else { path = window.location.pathname.substr(0, indexSlash) + "/"; } return /*currentURL +*/ path + url; }; /* ******************** */ /* Instance Members */ /* ******************** */ // Private: initSettings ensures that all the // settings are set, getting a default value if one was not assigned. SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (settingName, defaultValue) { this.settings[settingName] = (this.settings[settingName] == undefined) ? defaultValue : this.settings[settingName]; }; // Upload backend settings this.ensureDefault("upload_url", ""); this.ensureDefault("preserve_relative_urls", false); this.ensureDefault("file_post_name", "[file]"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); this.ensureDefault("assume_success_timeout", 0); // File Settings this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); // Default zero means "unlimited" this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); // Flash Settings this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); // Button Settings this.ensureDefault("button_image_url"); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", ""); this.ensureDefault("button_placeholder", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.HAND); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW); // Debug Settings this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; // Here to maintain v2 API // Event Handlers this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); // Other settings this.customSettings = this.settings.custom_settings; // Update the flash url if needed if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime(); } if (!this.settings.preserve_relative_urls) { //this.settings.flash_url = SWFUpload.completeURL(this.settings.flash_url); // Don't need to do this one since flash doesn't look at it this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url); this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url); } delete this.ensureDefault; }; // Private: loadFlash replaces the button_placeholder element with the flash movie. SWFUpload.prototype.loadFlash = function () { var targetElement, tempParent; // Make sure an element with the ID we are going to use doesn't already exist if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added"; } // Get the element where we will be placing the flash movie targetElement = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (targetElement == undefined) { throw "Could not find the placeholder element: " + this.settings.button_placeholder_id; } // Append the container and load the flash tempParent = document.createElement("div"); tempParent.innerHTML = this.getFlashHTML(); // Using innerHTML is non-standard but the only sensible way to dynamically add Flash in IE (and maybe other browsers) targetElement.parentNode.replaceChild(tempParent.firstChild, targetElement); // Fix IE Flash/Form bug if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement(); } }; // Private: getFlashHTML generates the object tag needed to embed the flash in to the document SWFUpload.prototype.getFlashHTML = function () { // Flash Satay object syntax: http://www.alistapart.com/articles/flashsatay return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="', this.settings.button_window_mode, '" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', '</object>'].join(""); }; // Private: getFlashVars builds the parameter string that will be passed // to flash in the flashvars param. SWFUpload.prototype.getFlashVars = function () { // Build a string from the post param object var paramString = this.buildParamString(); var httpSuccessString = this.settings.http_success.join(","); // Build the parameter string return ["movieName=", encodeURIComponent(this.movieName), "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url), "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string), "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&amp;httpSuccess=", encodeURIComponent(httpSuccessString), "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "&amp;params=", encodeURIComponent(paramString), "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name), "&amp;fileTypes=", encodeURIComponent(this.settings.file_types), "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width), "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height), "&amp;buttonText=", encodeURIComponent(this.settings.button_text), "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&amp;buttonAction=", encodeURIComponent(this.settings.button_action), "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor) ].join(""); }; // Public: getMovieElement retrieves the DOM reference to the Flash element added by SWFUpload // The element is cached after the first lookup SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName); } if (this.movieElement === null) { throw "Could not find Flash element"; } return this.movieElement; }; // Private: buildParamString takes the name/value pairs in the post_params setting object // and joins them up in to a string formatted "name=value&amp;name=value" SWFUpload.prototype.buildParamString = function () { var postParams = this.settings.post_params; var paramStringPairs = []; if (typeof(postParams) === "object") { for (var name in postParams) { if (postParams.hasOwnProperty(name)) { paramStringPairs.push(encodeURIComponent(name.toString()) + "=" + encodeURIComponent(postParams[name].toString())); } } } return paramStringPairs.join("&amp;"); }; // Public: Used to remove a SWFUpload instance from the page. This method strives to remove // all references to the SWF, and other objects so memory is properly freed. // Returns true if everything was destroyed. Returns a false if a failure occurs leaving SWFUpload in an inconsistant state. // Credits: Major improvements provided by steffen SWFUpload.prototype.destroy = function () { try { // Make sure Flash is done before we try to remove it this.cancelUpload(null, false); // Remove the SWFUpload DOM nodes var movieElement = null; movieElement = this.getMovieElement(); if (movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE // Loop through all the movie's properties and remove all function references (DOM/JS IE 6/7 memory leak workaround) for (var i in movieElement) { try { if (typeof(movieElement[i]) === "function") { movieElement[i] = null; } } catch (ex1) {} } // Remove the Movie Element from the page try { movieElement.parentNode.removeChild(movieElement); } catch (ex) {} } // Remove IE form fix reference window[this.movieName] = null; // Destroy other references SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true; } catch (ex2) { return false; } }; // Public: displayDebugInfo prints out settings and configuration // information about this SWFUpload instance. // This function (and any references to it) can be deleted when placing // SWFUpload in production. SWFUpload.prototype.displayDebugInfo = function () { this.debug( [ "---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url: ", this.settings.upload_url, "\n", "\t", "flash_url: ", this.settings.flash_url, "\n", "\t", "use_query_string: ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error: ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success: ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout: ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name: ", this.settings.file_post_name, "\n", "\t", "post_params: ", this.settings.post_params.toString(), "\n", "\t", "file_types: ", this.settings.file_types, "\n", "\t", "file_types_description: ", this.settings.file_types_description, "\n", "\t", "file_size_limit: ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit: ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit: ", this.settings.file_queue_limit, "\n", "\t", "debug: ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching: ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id: ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_placeholder: ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n", "\t", "button_image_url: ", this.settings.button_image_url.toString(), "\n", "\t", "button_width: ", this.settings.button_width.toString(), "\n", "\t", "button_height: ", this.settings.button_height.toString(), "\n", "\t", "button_text: ", this.settings.button_text.toString(), "\n", "\t", "button_text_style: ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding: ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action: ", this.settings.button_action.toString(), "\n", "\t", "button_disabled: ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings: ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned: ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned: ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned: ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned: ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned: ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned: ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned: ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned: ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned: ", (typeof this.settings.debug_handler === "function").toString(), "\n" ].join("") ); }; /* Note: addSetting and getSetting are no longer used by SWFUpload but are included the maintain v2 API compatibility */ // Public: (Deprecated) addSetting adds a setting value. If the value given is undefined or null then the default_value is used. SWFUpload.prototype.addSetting = function (name, value, default_value) { if (value == undefined) { return (this.settings[name] = default_value); } else { return (this.settings[name] = value); } }; // Public: (Deprecated) getSetting gets a setting. Returns an empty string if the setting was not found. SWFUpload.prototype.getSetting = function (name) { if (this.settings[name] != undefined) { return this.settings[name]; } return ""; }; // Private: callFlash handles function calls made to the Flash element. // Calls are made with a setTimeout for some functions to work around // bugs in the ExternalInterface library. SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; // Flash's method if calling ExternalInterface methods (code adapted from MooTools). try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + '</invoke>'); returnValue = eval(returnString); } catch (ex) { throw "Call to " + functionName + " failed"; } // Unescape file post param values if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue); } return returnValue; }; /* ***************************** -- Flash control methods -- Your UI should use these to operate SWFUpload ***************************** */ // WARNING: this function does not work in Flash Player 10 // Public: selectFile causes a File Selection Dialog window to appear. This // dialog only allows 1 file to be selected. SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile"); }; // WARNING: this function does not work in Flash Player 10 // Public: selectFiles causes a File Selection Dialog window to appear/ This // dialog allows the user to select any number of files // Flash Bug Warning: Flash limits the number of selectable files based on the combined length of the file names. // If the selection name length is too long the dialog will fail in an unpredictable manner. There is no work-around // for this bug. SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles"); }; // Public: startUpload starts uploading the first file in the queue unless // the optional parameter 'fileID' specifies the ID SWFUpload.prototype.startUpload = function (fileID) { this.callFlash("StartUpload", [fileID]); }; // Public: cancelUpload cancels any queued file. The fileID parameter may be the file ID or index. // If you do not specify a fileID the current uploading file or first file in the queue is cancelled. // If you do not want the uploadError event to trigger you can specify false for the triggerErrorEvent parameter. SWFUpload.prototype.cancelUpload = function (fileID, triggerErrorEvent) { if (triggerErrorEvent !== false) { triggerErrorEvent = true; } this.callFlash("CancelUpload", [fileID, triggerErrorEvent]); }; // Public: stopUpload stops the current upload and requeues the file at the beginning of the queue. // If nothing is currently uploading then nothing happens. SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload"); }; /* ************************ * Settings methods * These methods change the SWFUpload settings. * SWFUpload settings should not be changed directly on the settings object * since many of the settings need to be passed to Flash in order to take * effect. * *********************** */ // Public: getStats gets the file statistics object. SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats"); }; // Public: setStats changes the SWFUpload statistics. You shouldn't need to // change the statistics but you can. Changing the statistics does not // affect SWFUpload accept for the successful_uploads count which is used // by the upload_limit setting to determine how many files the user may upload. SWFUpload.prototype.setStats = function (statsObject) { this.callFlash("SetStats", [statsObject]); }; // Public: getFile retrieves a File object by ID or Index. If the file is // not found then 'null' is returned. SWFUpload.prototype.getFile = function (fileID) { if (typeof(fileID) === "number") { return this.callFlash("GetFileByIndex", [fileID]); } else { return this.callFlash("GetFile", [fileID]); } }; // Public: addFileParam sets a name/value pair that will be posted with the // file specified by the Files ID. If the name already exists then the // exiting value will be overwritten. SWFUpload.prototype.addFileParam = function (fileID, name, value) { return this.callFlash("AddFileParam", [fileID, name, value]); }; // Public: removeFileParam removes a previously set (by addFileParam) name/value // pair from the specified file. SWFUpload.prototype.removeFileParam = function (fileID, name) { this.callFlash("RemoveFileParam", [fileID, name]); }; // Public: setUploadUrl changes the upload_url setting. SWFUpload.prototype.setUploadURL = function (url) { this.settings.upload_url = url.toString(); this.callFlash("SetUploadURL", [url]); }; // Public: setPostParams changes the post_params setting SWFUpload.prototype.setPostParams = function (paramsObject) { this.settings.post_params = paramsObject; this.callFlash("SetPostParams", [paramsObject]); }; // Public: addPostParam adds post name/value pair. Each name can have only one value. SWFUpload.prototype.addPostParam = function (name, value) { this.settings.post_params[name] = value; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: removePostParam deletes post name/value pair. SWFUpload.prototype.removePostParam = function (name) { delete this.settings.post_params[name]; this.callFlash("SetPostParams", [this.settings.post_params]); }; // Public: setFileTypes changes the file_types setting and the file_types_description setting SWFUpload.prototype.setFileTypes = function (types, description) { this.settings.file_types = types; this.settings.file_types_description = description; this.callFlash("SetFileTypes", [types, description]); }; // Public: setFileSizeLimit changes the file_size_limit setting SWFUpload.prototype.setFileSizeLimit = function (fileSizeLimit) { this.settings.file_size_limit = fileSizeLimit; this.callFlash("SetFileSizeLimit", [fileSizeLimit]); }; // Public: setFileUploadLimit changes the file_upload_limit setting SWFUpload.prototype.setFileUploadLimit = function (fileUploadLimit) { this.settings.file_upload_limit = fileUploadLimit; this.callFlash("SetFileUploadLimit", [fileUploadLimit]); }; // Public: setFileQueueLimit changes the file_queue_limit setting SWFUpload.prototype.setFileQueueLimit = function (fileQueueLimit) { this.settings.file_queue_limit = fileQueueLimit; this.callFlash("SetFileQueueLimit", [fileQueueLimit]); }; // Public: setFilePostName changes the file_post_name setting SWFUpload.prototype.setFilePostName = function (filePostName) { this.settings.file_post_name = filePostName; this.callFlash("SetFilePostName", [filePostName]); }; // Public: setUseQueryString changes the use_query_string setting SWFUpload.prototype.setUseQueryString = function (useQueryString) { this.settings.use_query_string = useQueryString; this.callFlash("SetUseQueryString", [useQueryString]); }; // Public: setRequeueOnError changes the requeue_on_error setting SWFUpload.prototype.setRequeueOnError = function (requeueOnError) { this.settings.requeue_on_error = requeueOnError; this.callFlash("SetRequeueOnError", [requeueOnError]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setHTTPSuccess = function (http_status_codes) { if (typeof http_status_codes === "string") { http_status_codes = http_status_codes.replace(" ", "").split(","); } this.settings.http_success = http_status_codes; this.callFlash("SetHTTPSuccess", [http_status_codes]); }; // Public: setHTTPSuccess changes the http_success setting SWFUpload.prototype.setAssumeSuccessTimeout = function (timeout_seconds) { this.settings.assume_success_timeout = timeout_seconds; this.callFlash("SetAssumeSuccessTimeout", [timeout_seconds]); }; // Public: setDebugEnabled changes the debug_enabled setting SWFUpload.prototype.setDebugEnabled = function (debugEnabled) { this.settings.debug_enabled = debugEnabled; this.callFlash("SetDebugEnabled", [debugEnabled]); }; // Public: setButtonImageURL loads a button image sprite SWFUpload.prototype.setButtonImageURL = function (buttonImageURL) { if (buttonImageURL == undefined) { buttonImageURL = ""; } this.settings.button_image_url = buttonImageURL; this.callFlash("SetButtonImageURL", [buttonImageURL]); }; // Public: setButtonDimensions resizes the Flash Movie and button SWFUpload.prototype.setButtonDimensions = function (width, height) { this.settings.button_width = width; this.settings.button_height = height; var movie = this.getMovieElement(); if (movie != undefined) { movie.style.width = width + "px"; movie.style.height = height + "px"; } this.callFlash("SetButtonDimensions", [width, height]); }; // Public: setButtonText Changes the text overlaid on the button SWFUpload.prototype.setButtonText = function (html) { this.settings.button_text = html; this.callFlash("SetButtonText", [html]); }; // Public: setButtonTextPadding changes the top and left padding of the text overlay SWFUpload.prototype.setButtonTextPadding = function (left, top) { this.settings.button_text_top_padding = top; this.settings.button_text_left_padding = left; this.callFlash("SetButtonTextPadding", [left, top]); }; // Public: setButtonTextStyle changes the CSS used to style the HTML/Text overlaid on the button SWFUpload.prototype.setButtonTextStyle = function (css) { this.settings.button_text_style = css; this.callFlash("SetButtonTextStyle", [css]); }; // Public: setButtonDisabled disables/enables the button SWFUpload.prototype.setButtonDisabled = function (isDisabled) { this.settings.button_disabled = isDisabled; this.callFlash("SetButtonDisabled", [isDisabled]); }; // Public: setButtonAction sets the action that occurs when the button is clicked SWFUpload.prototype.setButtonAction = function (buttonAction) { this.settings.button_action = buttonAction; this.callFlash("SetButtonAction", [buttonAction]); }; // Public: setButtonCursor changes the mouse cursor displayed when hovering over the button SWFUpload.prototype.setButtonCursor = function (cursor) { this.settings.button_cursor = cursor; this.callFlash("SetButtonCursor", [cursor]); }; /* ******************************* Flash Event Interfaces These functions are used by Flash to trigger the various events. All these functions a Private. Because the ExternalInterface library is buggy the event calls are added to a queue and the queue then executed by a setTimeout. This ensures that events are executed in a determinate order and that the ExternalInterface bugs are avoided. ******************************* */ SWFUpload.prototype.queueEvent = function (handlerName, argumentArray) { // Warning: Don't call this.debug inside here or you'll create an infinite loop if (argumentArray == undefined) { argumentArray = []; } else if (!(argumentArray instanceof Array)) { argumentArray = [argumentArray]; } var self = this; if (typeof this.settings[handlerName] === "function") { // Queue the event this.eventQueue.push(function () { this.settings[handlerName].apply(this, argumentArray); }); // Execute the next queued event setTimeout(function () { self.executeNextEvent(); }, 0); } else if (this.settings[handlerName] !== null) { throw "Event handler " + handlerName + " is unknown or is not a function"; } }; // Private: Causes the next event in the queue to be executed. Since events are queued using a setTimeout // we must queue them in order to garentee that they are executed in order. SWFUpload.prototype.executeNextEvent = function () { // Warning: Don't call this.debug inside here or you'll create an infinite loop var f = this.eventQueue ? this.eventQueue.shift() : null; if (typeof(f) === "function") { f.apply(this); } }; // Private: unescapeFileParams is part of a workaround for a flash bug where objects passed through ExternalInterface cannot have // properties that contain characters that are not valid for JavaScript identifiers. To work around this // the Flash Component escapes the parameter names and we must unescape again before passing them along. SWFUpload.prototype.unescapeFilePostParams = function (file) { var reg = /[$]([0-9a-f]{4})/i; var unescapedPost = {}; var uk; if (file != undefined) { for (var k in file.post) { if (file.post.hasOwnProperty(k)) { uk = k; var match; while ((match = reg.exec(uk)) !== null) { uk = uk.replace(match[0], String.fromCharCode(parseInt("0x" + match[1], 16))); } unescapedPost[uk] = file.post[k]; } } file.post = unescapedPost; } return file; }; // Private: Called by Flash to see if JS can call in to Flash (test if External Interface is working) SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface"); } catch (ex) { return false; } }; // Private: This event is called by Flash when it has finished loading. Don't modify this. // Use the swfupload_loaded_handler event setting to execute custom code when SWFUpload has loaded. SWFUpload.prototype.flashReady = function () { // Check that the movie element is loaded correctly with its ExternalInterface methods defined var movieElement = this.getMovieElement(); if (!movieElement) { this.debug("Flash called back ready but the flash movie can't be found."); return; } this.cleanUp(movieElement); this.queueEvent("swfupload_loaded_handler"); }; // Private: removes Flash added fuctions to the DOM node to prevent memory leaks in IE. // This function is called by Flash each time the ExternalInterface functions are created. SWFUpload.prototype.cleanUp = function (movieElement) { // Pro-actively unhook all the Flash functions try { if (this.movieElement && typeof(movieElement.CallFunction) === "unknown") { // We only want to do this in IE this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var key in movieElement) { try { if (typeof(movieElement[key]) === "function") { movieElement[key] = null; } } catch (ex) { } } } } catch (ex1) { } // Fix Flashes own cleanup code so if the SWFMovie was removed from the page // it doesn't display errors. window["__flash__removeCallback"] = function (instance, name) { try { if (instance) { instance[name] = null; } } catch (flashEx) { } }; }; /* This is a chance to do something before the browse window opens */ SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler"); }; /* Called when a file is successfully added to the queue. */ SWFUpload.prototype.fileQueued = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queued_handler", file); }; /* Handle errors that occur when an attempt to queue a file fails. */ SWFUpload.prototype.fileQueueError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("file_queue_error_handler", [file, errorCode, message]); }; /* Called after the file dialog has closed and the selected files have been queued. You could call startUpload here if you want the queued files to begin uploading immediately. */ SWFUpload.prototype.fileDialogComplete = function (numFilesSelected, numFilesQueued, numFilesInQueue) { this.queueEvent("file_dialog_complete_handler", [numFilesSelected, numFilesQueued, numFilesInQueue]); }; SWFUpload.prototype.uploadStart = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("return_upload_start_handler", file); }; SWFUpload.prototype.returnUploadStart = function (file) { var returnValue; if (typeof this.settings.upload_start_handler === "function") { file = this.unescapeFilePostParams(file); returnValue = this.settings.upload_start_handler.call(this, file); } else if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function"; } // Convert undefined to true so if nothing is returned from the upload_start_handler it is // interpretted as 'true'. if (returnValue === undefined) { returnValue = true; } returnValue = !!returnValue; this.callFlash("ReturnUploadStart", [returnValue]); }; SWFUpload.prototype.uploadProgress = function (file, bytesComplete, bytesTotal) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_progress_handler", [file, bytesComplete, bytesTotal]); }; SWFUpload.prototype.uploadError = function (file, errorCode, message) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_error_handler", [file, errorCode, message]); }; SWFUpload.prototype.uploadSuccess = function (file, serverData, responseReceived) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_success_handler", [file, serverData, responseReceived]); }; SWFUpload.prototype.uploadComplete = function (file) { file = this.unescapeFilePostParams(file); this.queueEvent("upload_complete_handler", file); }; /* Called by SWFUpload JavaScript and Flash functions when debug is enabled. By default it writes messages to the internal debug console. You can override this event and have messages written where you want. */ SWFUpload.prototype.debug = function (message) { this.queueEvent("debug_handler", message); }; /* ********************************** Debug Console The debug console is a self contained, in page location for debug message to be sent. The Debug Console adds itself to the body if necessary. The console is automatically scrolled as messages appear. If you are using your own debug handler or when you deploy to production and have debug disabled you can remove these functions to reduce the file size and complexity. ********************************** */ // Private: debugMessage is the default debug_handler. If you want to print debug messages // call the debug() function. When overriding the function your own function should // check to see if the debug setting is true before outputting debug information. SWFUpload.prototype.debugMessage = function (message) { if (this.settings.debug) { var exceptionMessage, exceptionValues = []; // Check for an exception object and print it nicely if (typeof message === "object" && typeof message.name === "string" && typeof message.message === "string") { for (var key in message) { if (message.hasOwnProperty(key)) { exceptionValues.push(key + ": " + message[key]); } } exceptionMessage = exceptionValues.join("\n") || ""; exceptionValues = exceptionMessage.split("\n"); exceptionMessage = "EXCEPTION: " + exceptionValues.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(exceptionMessage); } else { SWFUpload.Console.writeLine(message); } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (message) { var console, documentForm; try { console = document.getElementById("SWFUpload_Console"); if (!console) { documentForm = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(documentForm); console = document.createElement("textarea"); console.id = "SWFUpload_Console"; console.style.fontFamily = "monospace"; console.setAttribute("wrap", "off"); console.wrap = "off"; console.style.overflow = "auto"; console.style.width = "700px"; console.style.height = "350px"; console.style.margin = "5px"; documentForm.appendChild(console); } console.value += message + "\n"; console.scrollTop = console.scrollHeight - console.clientHeight; } catch (ex) { alert("Exception: " + ex.name + " Message: " + ex.message); } };
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import ReactTags from 'react-tokenized-input'; import isLength from 'validator/lib/isLength'; import matches from 'validator/lib/matches'; import uniqBy from 'lodash.uniqby'; import some from 'lodash.some'; import ErrorMessage from './ErrorMessage/component'; import TagsList from './TagsList/component'; class Tags extends Component { constructor(props) { super(props); this.state = { isInValid: null, errorMessage: '', selectedTags: [], suggestedTags: this.props.suggestedTags, }; this.handleAddition = this.handleAddition.bind(this); this.handleDelete = this.handleDelete.bind(this); } componentWillReceiveProps() { // ToDo } componentDidUpdate() { const { selectedTags } = this.state; const { handleSelectedTags } = this.props; handleSelectedTags(selectedTags); } handleAddition(tag) { let { errorMessage } = this.state; const { selectedTags } = this.state; const { minChar, maxChar, maxTags, typeOfTags } = this.props; const currenTag = tag; const trimmedTag = currenTag.name.trim().toString(); const isSyntaxValid = matches(trimmedTag, /^[\d\w\s/+\-_]+$/); const isTagValid = isLength(trimmedTag, { min: minChar, max: maxChar }) && selectedTags.length !== maxTags && isSyntaxValid; currenTag.name = trimmedTag; if (isTagValid) { const tagslist = [...selectedTags, currenTag]; const uniqueTagsList = uniqBy(tagslist, 'name'); this.setState({ selectedTags: uniqueTagsList, }); } // Error messaging section if (trimmedTag.length < minChar) { errorMessage = `Please type at least ${minChar} characters.`; } else if (!isSyntaxValid) { errorMessage = 'Please check your syntax! Some of your characters are not valid.'; } else if (trimmedTag.length > maxChar) { errorMessage = `Sorry, a max of ${maxChar} characters is allowed.`; } else if (selectedTags.length === maxTags) { errorMessage = `Sorry, the maximum number of ${typeOfTags} is ${maxTags}.`; } else if (some(selectedTags, { name: trimmedTag })) { errorMessage = 'This tag has already been added.'; } else { errorMessage = null; } this.setState({ errorMessage, }); } handleDelete(i) { const { selectedTags } = this.state; const { maxTags } = this.props; const tagslist = selectedTags.slice(0); let { errorMessage } = this.state; tagslist.splice(i, 1); // Error messaging section if (selectedTags.length - 1 < maxTags) { errorMessage = null; } this.setState({ selectedTags: tagslist, errorMessage, }); } render() { const { suggestedTags, selectedTags, errorMessage } = this.state; const { customStyles, placeHolderText, minTags, maxTags, typeOfTags } = this.props; return ( <div> {minTags && <p>Select a minimum of {minTags} and a maximum of {maxTags} {typeOfTags}.</p>} <ReactTags suggestions={suggestedTags} tags={selectedTags} handleAddition={this.handleAddition} handleDelete={this.handleDelete} placeholder={placeHolderText} allowNew minQueryLength={1} classNames={customStyles} /> {errorMessage && <ErrorMessage errorMessage={errorMessage} />} {suggestedTags && <TagsList suggestedTags={suggestedTags} handleAddition={this.handleAddition} />} </div> ); } } Tags.propTypes = { suggestedTags: PropTypes.arrayOf(PropTypes.object), placeHolderText: PropTypes.string, handleSelectedTags: PropTypes.func.isRequired, minChar: PropTypes.number, maxChar: PropTypes.number, minTags: PropTypes.number, maxTags: PropTypes.number, typeOfTags: PropTypes.string.isRequired, }; Tags.defaultProps = { suggestedTags: [], placeHolderText: null, minChar: 3, maxChar: 30, minTags: null, maxTags: 10, }; export default Tags;
export default class FacetDocumentTypes { constructor($facet) { this.$facet = $facet; this.$facet.find(".dropdown-item").click(this.selectType.bind(this)); this.$removeFilterButton = this.$facet.find(".remove-filter"); this.toggleCancel(); this.$removeFilterButton.click(this.cancelSelection.bind(this)); this.key = "document-type"; } selectType(event) { if (event.target && event.target.nodeName === 'INPUT') { // Default behavior for the checkbox, however... } else { // ...for the surrounding label we need to explicitly code the behavior as otherwise // bootstrap would catch the event and use it to close the dropdown. event.stopPropagation(); event.preventDefault(); let $checkbox; if (event.target.nodeName === "LABEL") { $checkbox = $(event.target).find("input"); } else { $checkbox = $(event.target).parents("label").first().find("input"); } $checkbox.prop("checked", !$checkbox.prop("checked")); $checkbox.change(); } this.toggleCancel(); } toggleCancel() { if (this.$facet.find("input:checked").length > 0) { this.$removeFilterButton.show(); } else { this.$removeFilterButton.hide(); } } cancelSelection(event) { this.$facet.find("input").prop("checked", false); this.$removeFilterButton.hide(); this.$facet.find("input").change(); } getQueryString() { let documentTypes = []; this.$facet.find('input[type=checkbox]').each((_, input) => { if ($(input).prop('checked')) { documentTypes.push($(input).val()); } }); documentTypes.sort(); if (documentTypes.length > 0) { return 'document-type:' + documentTypes.join(',') + ' '; } else { return ''; } } /** * Adds the item count to the values and hides away those with a count of zero. Also disables the button * when there is no value with a count biger than zero, unless a value is selected */ update(data) { let $filter_list = $("#filter-" + this.key + "-list"); for (let bucket_entry of data['new_facets']['document_type']['list']) { let $obj = $filter_list.find("[data-id=" + bucket_entry["name"] + "]"); $obj.find(".facet-item-count").text(bucket_entry["count"]); } } setFromQueryString(params) { if (params['document-type']) { let types = params['document-type'].split(','); this.$facet.find("input").each((i, el) => { $(el).prop("checked", types.indexOf($(el).val()) !== -1); }); this.$removeFilterButton.show(); } else { this.$facet.find("input").prop("checked", false); this.$removeFilterButton.hide(); } } }
import { Sprites as SP, Animations as ANI, Sequence, Easing } from 'animationvideo'; import { textBox } from './effects/effects'; import cutsceneBase from './cutsceneBase'; export default function (Audiomanager) { return cutsceneBase({ music: 'assets/music/cut', //addBindings: false, images: { 'f4': 'assets/intro/f4.jpg', }, animation: (scene, layer, destroy) => { let l; l = [ SP.Rect({ color: '#fff', animation: Sequence(1, 0, [[ ANI.ChangeTo({ color: '#000' }, 100, Easing.quadInOut), ANI.Wait() ]]) }) ]; layer.unshift(l); l = [ SP.Image({ image: 'f4', x: 400, y: 300, scaleX: 1, scaleY: 1, a: 0, animation: Sequence(1, -0, [[ ANI.ChangeTo({ a: 1 }, 1000), ANI.Wait(8000), ANI.ChangeTo({ a: 0 }, 1000) ], [ ANI.ChangeTo({ y: 200, scaleX: 1.1, scaleY: 1.1 }, 10000) ]]) }) ]; layer.unshift(l); l = [ new SP.FastBlur({ alphaMode: 'lighter', scaleX: 20, scaleY: 20, a: 0.4, animation: Sequence(true, 0, [[ ANI.ChangeTo({ a: 0.1 }, 5000), ANI.ChangeTo({ a: 0.4 }, 5000), ]]) }) ]; layer.unshift(l); l = []; textBox(Audiomanager, l, 'In der Tat! Habe Steffi auf dem Konzert gesehen!', 25, 25, 430, 500); textBox(Audiomanager, l, '(Ich hasse!)', 50, 250, 150, 2000); textBox(Audiomanager, l, '(Ich liebe aber auch!)', 550, 270, 230, 4000); layer.unshift(l); layer.unshift([(ctx, t) => (t >= 10100) && destroy()]); return layer; } }); }
const os = require('os') const debug = process.argv.some(value => value.includes('--debug')) const dataPath = `${os.homedir()}/.ELaunch` const userConfigFile = `${dataPath}/config.json5` module.exports = { debug, dataPath, userConfigFile, languages: [{ value: 'zh', label: '简体中文', }, { value: 'en', label: 'English', }], fallbackLng: 'en', }
// This file is part of Indico. // Copyright (C) 2002 - 2022 CERN // // Indico is free software; you can redistribute it and/or // modify it under the terms of the MIT License; see the // LICENSE file for more details. /* global showFormErrors:false, initForms:false */ import {$T} from '../../utils/i18n'; (function($) { $.widget('indico.ajaxqbubble', { options: { qBubbleOptions: { position: { effect: false, }, content: { text: $('<span>', {text: $T.gettext('Loading...')}), }, }, url: null, method: 'GET', cache: false, success: null, onClose: null, // callback to invoke after closing the qtip by submitting the inner form. the argument // is null if closed manually, otherwise the JSON returned by the server. qtipConstructor: null, }, _create: function() { var self = this; var qBubbleOptions = _.pick(self.options, 'qBubbleOptions').qBubbleOptions; var ajaxOptions = _.omit(self.options, 'qBubbleOptions'); var returnData = null; var options = $.extend(true, {}, qBubbleOptions, { events: { show: function(evt, api) { $.ajax( $.extend(true, {}, ajaxOptions, { complete: IndicoUI.Dialogs.Util.progress(), error: handleAjaxError, success: function(data, _, xhr) { if ($.isFunction(ajaxOptions.success)) { ajaxOptions.success.call(self.element, data); } var loadedURL = xhr.getResponseHeader('X-Indico-URL'); if (loadedURL) { // in case of a redirect we need to update the url used to submit the ajaxified // form. otherwise url normalization might fail during the POST requests. // we also remove the _=\d+ cache buster since it's only relevant for the GET // request and added there automatically loadedURL = loadedURL .replace(/&_=\d+/, '') .replace(/\?_=\d+$/, '') .replace(/\?_=\d+&/, '?'); } function updateContent(data) { if (data) { api.set( 'content.text', ajaxifyForm( $(data.html) .find('form') .addBack('form') ) ); if (data.js) { $('body').append(data.js); } } } function ajaxifyForm($form) { initForms($form); var killProgress; return $form.ajaxForm({ url: $form.attr('action') || loadedURL, method: 'POST', error: handleAjaxError, beforeSubmit: function() { killProgress = IndicoUI.Dialogs.Util.progress(); }, complete: function() { killProgress(); }, success: function(data) { if (data.success) { self.element.next('.label').text(data.new_value); returnData = data; api.hide(true); } else { updateContent(data); showFormErrors($('#qtip-' + api.id + '-content')); } }, }); } updateContent(data); }, }) ); if (qBubbleOptions.events && qBubbleOptions.events.show) { qBubbleOptions.events.show(evt, api); } }, hide: function(evt, api) { var originalEvent = evt.originalEvent; if (self.options.onClose) { self.options.onClose(returnData); } returnData = null; // in order not to hide the qBubble when selecting a date if (originalEvent && $(originalEvent.target).closest('#ui-datepicker-div').length) { return false; } if (qBubbleOptions.events && qBubbleOptions.events.hide) { qBubbleOptions.events.hide(evt, api); } return true; }, hidden: function(evt, api) { api.get('content.text').remove(); if (qBubbleOptions.events && qBubbleOptions.events.hidden) { qBubbleOptions.events.hidden(evt, api); } }, }, }); if (self.options.qtipConstructor) { self.options.qtipConstructor(self.element, options); } else { self.element.qbubble(options); } }, }); })(jQuery);
/* eslint-disable camelcase */ 'use strict' let spawn = require('child_process').spawn let net = require('net') let SERVER = process.env.TRAVIS ? 'gnatsd/gnatsd' : 'gnatsd' let DEFAULT_PORT = 4222 function start_server(port, optFlags, done) { if (!port) { port = DEFAULT_PORT } if (typeof optFlags === 'function') { done = optFlags optFlags = null } let flags = ['-p', port, '-a', '127.0.0.1'] if (optFlags) { flags = flags.concat(optFlags) } if (process.env.PRINT_LAUNCH_CMD) { console.log(flags.join(' ')) } let server = spawn(SERVER, flags) let start = new Date() let wait = 0 let maxWait = 5 * 1000 // 5 secs let delta = 250 let socket let timer let resetSocket = () => { if (socket !== undefined) { socket.removeAllListeners() socket.destroy() socket = undefined } } let finish = err => { resetSocket() if (timer !== undefined) { clearInterval(timer) timer = undefined } if (done) { done(err) } } // Test for when socket is bound. timer = setInterval(() => { resetSocket() wait = new Date() - start if (wait > maxWait) { finish(new Error("Can't connect to server on port: " + port)) } // Try to connect to the correct port. socket = net.createConnection(port) // Success socket.on('connect', () => { if (server.pid === null) { // We connected but not to our server.. finish(new Error('Server already running on port: ' + port)) } else { finish() } }) // Wait for next try.. socket.on('error', error => { finish( new Error( 'Problem connecting to server on port: ' + port + ' (' + error + ')' ) ) }) }, delta) // Other way to catch another server running. server.on('exit', (code, signal) => { if (code === 1) { finish( new Error( 'Server exited with bad code, already running? (' + code + ' / ' + signal + ')' ) ) } }) // Server does not exist.. server.stderr.on('data', data => { if (/^execvp\(\)/.test(data)) { clearInterval(timer) finish(new Error("Can't find the " + SERVER)) } }) return server } function waitStop(server, done) { if (server.killed) { if (done) { done() } } else { setTimeout(function() { waitStop(server, done) }) } } function stop_server(server, done) { if (server) { server.kill() waitStop(server, done) } else if (done) { done() } } // starts a number of servers in a cluster at the specified ports. // must call with at least one port. function start_cluster(ports, routePort, optFlags, done) { if (typeof optFlags === 'function') { done = optFlags optFlags = null } let servers = [] let started = 0 let server = add_member(ports[0], routePort, routePort, optFlags, () => { started++ servers.push(server) if (started === ports.length) { done() } }) let others = ports.slice(1) others.forEach(function(p) { let s = add_member(p, routePort, p + 1000, optFlags, () => { started++ servers.push(s) if (started === ports.length) { done() } }) }) return servers } // adds more cluster members, if more than one server is added additional // servers are added after the specified delay. function add_member_with_delay(ports, routePort, delay, optFlags, done) { if (typeof optFlags === 'function') { done = optFlags optFlags = null } let servers = [] ports.forEach(function(p, i) { setTimeout(function() { let s = add_member(p, routePort, p + 1000, optFlags, () => { servers.push(s) if (servers.length === ports.length) { done() } }) }, i * delay) }) return servers } function add_member(port, routePort, clusterPort, optFlags, done) { if (typeof optFlags === 'function') { done = optFlags optFlags = null } optFlags = optFlags || [] let opts = JSON.parse(JSON.stringify(optFlags)) opts.push('--routes', 'nats://localhost:' + routePort) opts.push('--cluster', 'nats://localhost:' + clusterPort) return start_server(port, opts, done) } exports.stop_cluster = function(servers, done) { let count = servers.length function latch() { count-- if (count === 0) { done() } } servers.forEach(s => { stop_server(s, latch) }) } exports.find_server = (port, servers) => { return servers.find(s => { return s.spawnargs[2] === port }) } exports.start_server = start_server exports.stop_server = stop_server exports.add_member_with_delay = add_member_with_delay exports.start_cluster = start_cluster exports.add_member = add_member exports.startServer = start_server exports.stopServer = stop_server exports.addMemberWithDelay = add_member_with_delay exports.startCluster = start_cluster exports.addMember = add_member
/* * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ { const global = %GlobalProperties(); const PRINT = typeof print === "function" ? print : () => {}; global.console = { log(...args) { %CallFunction(PRINT, null, ...args); } }; }
import WebSocketRequestContext from './WebSocketRequestContext.js' export default class WebSocketEvent { #connectionId = null #payload = null #route = null constructor(connectionId, route, payload) { this.#connectionId = connectionId this.#payload = payload this.#route = route } create() { const requestContext = new WebSocketRequestContext( 'MESSAGE', this.#route, this.#connectionId, ).create() return { body: this.#payload, isBase64Encoded: false, requestContext, } } }
'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; module.exports = function mergeRecursive(items) { var merge = function merge(target, source) { var merged = {}; var mergedKeys = Object.keys(Object.assign({}, target, source)); mergedKeys.forEach(function (key) { if (target[key] === undefined && source[key] !== undefined) { merged[key] = source[key]; } else if (target[key] !== undefined && source[key] === undefined) { merged[key] = target[key]; } else if (target[key] !== undefined && source[key] !== undefined) { if (target[key] === source[key]) { merged[key] = target[key]; } else if (!Array.isArray(target[key]) && _typeof(target[key]) === 'object' && !Array.isArray(source[key]) && _typeof(source[key]) === 'object') { merged[key] = merge(target[key], source[key]); } else { merged[key] = [].concat(target[key], source[key]); } } }); return merged; }; if (!items) { return this; } if (items.constructor.name === 'Collection') { return new this.constructor(merge(this.items, items.all())); } return new this.constructor(merge(this.items, items)); };
$(function (){ $('#all-languages-added').mouseover(function(){ $('#add-text').html('<em>All Tracks Added!</em>'); }); $('#all-languages-added').mouseleave(function(){ $('#add-text').html('Add Language Track'); }); });
/** * Created by choizhang on 16/6/14. */ import { baseExport, baseInputSetting } from '../base'; import * as util from '../../util/util'; function defaultSetting(obj) { obj.other = { 'range': { label: '框高度', value: 50, max: 100, min: 50, setDom: (setting, value={}) => { let newValue = util.setDom(setting, value.value); obj.dom.find('textarea').css('height', newValue); }, setSetting: () => { this.value = obj.dom.find('textarea').css('height'); } } }; return baseInputSetting(obj); } export function textarea(data) { let setting = defaultSetting({data: data}) let $html, require, other; //对是否必填进行初始化操作1 if (!setting.checkbox.isChecked) { //不是必填 require = `style="visibility: hidden;"`; } $html = $(` <div class="text-textarea sui-form-viewType-0" data="rank"> <label> <span class="form-autoNum"></span> <span class="form-required" ${require}>*</span> <span class="title">${setting.input[0].text}</span> </label> <textarea disabled>${setting.input[1].text}</textarea> </div> `); setting = defaultSetting({data: data, dom: $html}); return baseExport($html, setting, other); }
version https://git-lfs.github.com/spec/v1 oid sha256:a1b5fe3d367a355e59b3d092e3d6d22e1c1a4f7d8526620d9b6df4041e423564 size 7081
// client side // toolbelt.js // - client side utitlity library (function() { // Establish the root object // Save the previous toolbelt variable // Create the toolbelt object var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || this; var previousToolbelt = root.toolbelt; const toolbelt = Object.create(null); // Node export v. Browser global // Inspired by underscore if (typeof exports != 'undefined' && !exports.nodeType) { if (typeof module != 'undefined' && !module.nodeType && module.exports) { exports = module.exports = toolbelt; } exports.toolbelt = toolbelt; } else { root.toolbelt = toolbelt; } /** * Restores the previous toolbelt variable * @return {Object} this reference */ toolbelt.noConflict = function() { root.toolbelt = previousToolbelt; return this; }; toolbelt.event = Object.create(null); toolbelt.base = Object.create(null); toolbelt.event.stop = function(event) { event.preventDefault(); event.stopPropagation(); return false; }; toolbelt.normalize = function(obj, normal) { obj = _.clone(obj); Object.keys(normal).forEach(function(key) { if (defines.DEBUG && !obj.hasOwnProperty(key)) { console.warn(`expected key: ${key} missing in object:`, obj) } if (obj[key] == null) { obj[key] = normal[key]; } }); return obj; }; toolbelt.assert = function(cond, str) { if (defines.DEBUG) { if (!cond) { throw new Error(str); } } }; // AMD registration: http://requirejs.org/docs/whyamd.html // Copied from underscore if (typeof define == 'function' && define.amd) { define('toolbelt', [], function() { return toolbelt; }); } })();
/* searchapi2 A module implementing the searchapi2 api calls. See: https://github.com/kbase/search_api2 This implementation is not complete, but functional enough for it's usages. Extend as need be. */ define(['./JSONRPC20'], (JSONRPC20) => { 'use strict'; class SearchAPI2 extends JSONRPC20 { search_objects({ params, timeout }) { return this.callMethod({ method: 'search_objects', params, timeout, }); } } return SearchAPI2; });
import TableView from '@/components/TableView/index.vue' import ContractUtils from '@/data/contract/utils' import {loadResources} from '@/data/resource/loader' import ContractDetail from '@/components/ContractDetail/index.vue' export default { name: 'fl-contract-manager', data() { return { // contracts: [], query: '', currentContract: {}, contractList: [], masterContract: {}, loading: false } }, components: { TableView, ContractDetail }, props: { contracts: Array }, watch: { contracts() { this.initView() } }, mounted() { if (this.contracts) { this.initView() } }, methods: { initView() { if (!this.contracts.length || this.shouldUpdate() === false) return this.masterContract = {} const query = this.$route.query Object.assign(query, this.$route.params) this.loading = true this.loadData(query) .then(this.formatContracts) .then((contractList) => { this.contractList = contractList if (this.masterContract.contractId) { this.showContractDetailHandler(this.masterContract) } else if (contractList.length) { this.showContractDetailHandler(contractList[0]) } this.fireContractsChange() }) .finally(() => { this.loading = false this.shouldUpdate() //更新key值 }) }, //避免重复请求合同数据 shouldUpdate() { var updateKey = this.contracts.map(contract => { return `${contract.contractId}` }).join('_') if (this.updateKey !== updateKey) { this.updateKey = updateKey return true } else { return false } }, formatContracts({contracts, resources}) { var resourcesMap = {} var contractList = [] resources.forEach(resource => { resourcesMap[resource.resourceId] = resource }) contracts.forEach((contract) => { contract.resourceDetail = resourcesMap[contract.resourceId] if (contract.contractId === this.masterContract.contractId) { Object.assign(this.masterContract, contract) ContractUtils.format(this.masterContract) } else { ContractUtils.format(contract) contractList.push(contract) } }) return contractList }, loadData() { var contractIds = [] var resourceIds = [] this.contracts.map(contract => { if (contract.contractId){ contractIds.push(contract.contractId) } resourceIds.push(contract.resourceId) if (contract.isMasterContract) { this.masterContract = contract } }) resourceIds = Array.from(new Set(resourceIds)) return Promise.all([this.loadContractInfos(contractIds), this.loadResourcesInfo(resourceIds)]) .then(res => { var [contracts, resources] = res return { contracts, resources } }) }, loadResourcesInfo(resourceIds) { return loadResources(resourceIds) }, loadContractInfos(contractIds) { return this.$services.contractRecords.get({ params: { contractIds: contractIds.filter(id=>id).join(',') } }).then(res => res.getData()) }, showContractDetailHandler(contract) { if (!contract || !contract.contractId) { // this.$message.warning('未创建合同') return } this.currentContract = contract }, fireContractsChange(){ var contracts = this.contractList if (this.masterContract.contractId) { contracts = contracts.concat(this.masterContract) } this.$emit('contracts-change', contracts) }, updateContractHandler(contract) { Object.assign(this.currentContract, contract) this.fireContractsChange() } } }
/* * svg-editor.js * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * Copyright(c) 2010 Pavol Rusnak * Copyright(c) 2010 Jeff Schiller * Copyright(c) 2010 Narendra Sisodiya * */ // Dependencies: // 1) units.js // 2) browser.js // 3) svgcanvas.js (function() { document.addEventListener("touchstart", touchHandler, true); document.addEventListener("touchmove", touchHandler, true); document.addEventListener("touchend", touchHandler, true); document.addEventListener("touchcancel", touchHandler, true); if(!window.svgEditor) window.svgEditor = function($) { var svgCanvas; var Editor = {}; var is_ready = false; var defaultPrefs = { lang:'en', iconsize:'m', bkgd_color:'#FFF', bkgd_url:'', img_save:'embed' }, curPrefs = {}, // Note: Difference between Prefs and Config is that Prefs can be // changed in the UI and are stored in the browser, config can not curConfig = { canvasName: 'default', canvas_expansion: 3, dimensions: [640,480], initFill: { color: 'FF0000', // solid red opacity: 1 }, initStroke: { width: 5, color: '000000', // solid black opacity: 1 }, initOpacity: 1, imgPath: '/assets/images/', langPath: '/assets/locale/', extPath: '/assets/extensions/', jGraduatePath: '/assets/jgraduate/images/', extensions: ['ext-markers.js','ext-connector.js', 'ext-eyedropper.js', 'ext-shapes.js', 'ext-imagelib.js', 'ext-grid.js'], initTool: 'select', wireframe: false, colorPickerCSS: null, gridSnapping: false, gridColor: "#000", baseUnit: 'px', snappingStep: 10, showRulers: true }, uiStrings = Editor.uiStrings = { common: { "ok":"OK", "cancel":"Cancel", "key_up":"Up", "key_down":"Down", "key_backspace":"Backspace", "key_del":"Del" }, // This is needed if the locale is English, since the locale strings are not read in that instance. layers: { "layer":"Layer" }, notification: { "invalidAttrValGiven":"Invalid value given", "noContentToFitTo":"No content to fit to", "dupeLayerName":"There is already a layer named that!", "enterUniqueLayerName":"Please enter a unique layer name", "enterNewLayerName":"Please enter the new layer name", "layerHasThatName":"Layer already has that name", "QmoveElemsToLayer":"Move selected elements to layer \"%s\"?", "QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!", "QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!", "QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?", "QignoreSourceChanges":"Ignore changes made to SVG source?", "featNotSupported":"Feature not supported", "enterNewImgURL":"Enter the new image URL", "defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.", "loadingImage":"Loading image, please wait...", "saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.", "noteTheseIssues": "Also note the following issues: ", "unsavedChanges": "There are unsaved changes.", "enterNewLinkURL": "Enter the new hyperlink URL", "errorLoadingSVG": "Error: Unable to load SVG data", "URLloadFail": "Unable to load from URL", "retrieving": 'Retrieving "%s" ...' } }; var curPrefs = {}; //$.extend({}, defaultPrefs); var customHandlers = {}; Editor.curConfig = curConfig; Editor.tool_scale = 1; // Store and retrieve preferences $.pref = function(key, val) { if(val) curPrefs[key] = val; key = 'svg-edit-'+key; var host = location.hostname, onweb = host && host.indexOf('.') >= 0, store = (val != undefined), storage = false; // Some FF versions throw security errors here try { if(window.localStorage) { // && onweb removed so Webkit works locally storage = localStorage; } } catch(e) {} try { if(window.globalStorage && onweb) { storage = globalStorage[host]; } } catch(e) {} if(storage) { if(store) storage.setItem(key, val); else if (storage.getItem(key)) return storage.getItem(key) + ''; // Convert to string for FF (.value fails in Webkit) } else if(window.widget) { if(store) widget.setPreferenceForKey(val, key); else return widget.preferenceForKey(key); } else { if(store) { var d = new Date(); d.setTime(d.getTime() + 31536000000); val = encodeURIComponent(val); document.cookie = key+'='+val+'; expires='+d.toUTCString(); } else { var result = document.cookie.match(new RegExp(key + "=([^;]+)")); return result?decodeURIComponent(result[1]):''; } } } Editor.setConfig = function(opts) { $.each(opts, function(key, val) { // Only allow prefs defined in defaultPrefs if(key in defaultPrefs) { $.pref(key, val); } }); $.extend(true, curConfig, opts); if(opts.extensions) { curConfig.extensions = opts.extensions; } } // Extension mechanisms must call setCustomHandlers with two functions: opts.open and opts.save // opts.open's responsibilities are: // - invoke a file chooser dialog in 'open' mode // - let user pick a SVG file // - calls setCanvas.setSvgString() with the string contents of that file // opts.save's responsibilities are: // - accept the string contents of the current document // - invoke a file chooser dialog in 'save' mode // - save the file to location chosen by the user Editor.setCustomHandlers = function(opts) { Editor.ready(function() { if(opts.open) { $('#tool_open > input[type="file"]').remove(); $('#tool_open').show(); svgCanvas.open = opts.open; } if(opts.save) { Editor.show_save_warning = false; svgCanvas.bind("saved", opts.save); } if(opts.pngsave) { svgCanvas.bind("exported", opts.pngsave); } customHandlers = opts; }); } Editor.randomizeIds = function() { svgCanvas.randomizeIds(arguments) } Editor.init = function() { // For external openers (function() { // let the opener know SVG Edit is ready var w = window.opener; if (w) { try { var svgEditorReadyEvent = w.document.createEvent("Event"); svgEditorReadyEvent.initEvent("svgEditorReady", true, true); w.document.documentElement.dispatchEvent(svgEditorReadyEvent); } catch(e) {} } })(); (function() { // Load config/data from URL if given var urldata = $.deparam.querystring(true); if(!$.isEmptyObject(urldata)) { if(urldata.dimensions) { urldata.dimensions = urldata.dimensions.split(','); } if(urldata.extensions) { urldata.extensions = urldata.extensions.split(','); } if(urldata.bkgd_color) { urldata.bkgd_color = '#' + urldata.bkgd_color; } svgEditor.setConfig(urldata); var src = urldata.source; var qstr = $.param.querystring(); if(!src) { // urldata.source may have been null if it ended with '=' if(qstr.indexOf('source=data:') >= 0) { src = qstr.match(/source=(data:[^&]*)/)[1]; } } if(src) { if(src.indexOf("data:") === 0) { // plusses get replaced by spaces, so re-insert src = src.replace(/ /g, "+"); Editor.loadFromDataURI(src); } else { Editor.loadFromString(src); } } else if(qstr.indexOf('paramurl=') !== -1) { // Get paramater URL (use full length of remaining location.href) svgEditor.loadFromURL(qstr.substr(9)); } else if(urldata.url) { svgEditor.loadFromURL(urldata.url); } } else { var name = 'svgedit-' + Editor.curConfig.canvasName; var cached = window.localStorage.getItem(name); if (cached) { Editor.loadFromString(cached); } } })(); var extFunc = function() { $.each(curConfig.extensions, function() { var extname = this; $.getScript(curConfig.extPath + extname, function(d) { // Fails locally in Chrome 5 if(!d) { var s = document.createElement('script'); s.src = curConfig.extPath + extname; document.querySelector('head').appendChild(s); } }); }); var good_langs = []; $('#lang_select option').each(function() { good_langs.push(this.value); }); // var lang = ('lang' in curPrefs) ? curPrefs.lang : null; Editor.putLocale(null, good_langs); } // Load extensions // Bit of a hack to run extensions in local Opera/IE9 if(document.location.protocol === 'file:') { setTimeout(extFunc, 100); } else { extFunc(); } $.svgIcons(curConfig.imgPath + 'svg_edit_icons.svg', { w:24, h:24, id_match: false, no_img: !svgedit.browser.isWebkit(), // Opera & Firefox 4 gives odd behavior w/images fallback_path: curConfig.imgPath, fallback:{ 'new_image':'clear.png', 'save':'save.png', 'open':'open.png', 'source':'source.png', 'docprops':'document-properties.png', 'wireframe':'wireframe.png', 'undo':'undo.png', 'redo':'redo.png', 'select':'select.png', 'select_node':'select_node.png', 'pencil':'fhpath.png', 'pen':'line.png', 'square':'square.png', 'rect':'rect.png', 'fh_rect':'freehand-square.png', 'circle':'circle.png', 'ellipse':'ellipse.png', 'fh_ellipse':'freehand-circle.png', 'path':'path.png', 'text':'text.png', 'image':'image.png', 'zoom':'zoom.png', 'clone':'clone.png', 'node_clone':'node_clone.png', 'delete':'delete.png', 'node_delete':'node_delete.png', 'group':'shape_group.png', 'ungroup':'shape_ungroup.png', 'move_top':'move_top.png', 'move_bottom':'move_bottom.png', 'to_path':'to_path.png', 'link_controls':'link_controls.png', 'reorient':'reorient.png', 'align_left':'align-left.png', 'align_center':'align-center', 'align_right':'align-right', 'align_top':'align-top', 'align_middle':'align-middle', 'align_bottom':'align-bottom', 'go_up':'go-up.png', 'go_down':'go-down.png', 'ok':'save.png', 'cancel':'cancel.png', 'arrow_right':'flyouth.png', 'arrow_down':'dropdown.gif' }, placement: { '#logo':'logo', '#tool_clear div,#layer_new':'new_image', '#tool_save div':'save', '#tool_export div':'export', '#tool_open div div':'open', '#tool_import div div':'import', '#tool_source':'source', '#tool_docprops > div':'docprops', '#tool_wireframe':'wireframe', '#tool_undo':'undo', '#tool_redo':'redo', '#tool_select':'select', '#tool_fhpath':'pencil', '#tool_line':'pen', '#tool_rect,#tools_rect_show':'rect', '#tool_square':'square', '#tool_fhrect':'fh_rect', '#tool_ellipse,#tools_ellipse_show':'ellipse', '#tool_circle':'circle', '#tool_fhellipse':'fh_ellipse', '#tool_path':'path', '#tool_text,#layer_rename':'text', '#tool_image':'image', '#tool_zoom':'zoom', '#tool_clone,#tool_clone_multi':'clone', '#tool_node_clone':'node_clone', '#layer_delete,#tool_delete,#tool_delete_multi':'delete', '#tool_node_delete':'node_delete', '#tool_add_subpath':'add_subpath', '#tool_openclose_path':'open_path', '#tool_move_top':'move_top', '#tool_move_bottom':'move_bottom', '#tool_topath':'to_path', '#tool_node_link':'link_controls', '#tool_reorient':'reorient', '#tool_group':'group', '#tool_ungroup':'ungroup', '#tool_unlink_use':'unlink_use', '#tool_alignleft, #tool_posleft':'align_left', '#tool_aligncenter, #tool_poscenter':'align_center', '#tool_alignright, #tool_posright':'align_right', '#tool_aligntop, #tool_postop':'align_top', '#tool_alignmiddle, #tool_posmiddle':'align_middle', '#tool_alignbottom, #tool_posbottom':'align_bottom', '#cur_position':'align', '#linecap_butt,#cur_linecap':'linecap_butt', '#linecap_round':'linecap_round', '#linecap_square':'linecap_square', '#linejoin_miter,#cur_linejoin':'linejoin_miter', '#linejoin_round':'linejoin_round', '#linejoin_bevel':'linejoin_bevel', '#url_notice':'warning', '#layer_up':'go_up', '#layer_down':'go_down', '#layer_moreopts':'context_menu', '#layerlist td.layervis':'eye', '#tool_source_save,#tool_docprops_save,#tool_prefs_save':'ok', '#tool_source_cancel,#tool_docprops_cancel,#tool_prefs_cancel':'cancel', '#rwidthLabel, #iwidthLabel':'width', '#rheightLabel, #iheightLabel':'height', '#cornerRadiusLabel span':'c_radius', '#angleLabel':'angle', '#linkLabel,#tool_make_link,#tool_make_link_multi':'globe_link', '#zoomLabel':'zoom', '#tool_fill label': 'fill', '#tool_stroke .icon_label': 'stroke', '#group_opacityLabel': 'opacity', '#blurLabel': 'blur', '#font_sizeLabel': 'fontsize', '.flyout_arrow_horiz':'arrow_right', '.dropdown button, #main_button .dropdown':'arrow_down', '#palette .palette_item:first, #fill_bg, #stroke_bg':'no_color' }, resize: { '#logo .svg_icon': 28, '.flyout_arrow_horiz .svg_icon': 5, '.layer_button .svg_icon, #layerlist td.layervis .svg_icon': 14, '.dropdown button .svg_icon': 7, '#main_button .dropdown .svg_icon': 9, '.palette_item:first .svg_icon' : 15, '#fill_bg .svg_icon, #stroke_bg .svg_icon': 16, '.toolbar_button button .svg_icon':16, '.stroke_tool div div .svg_icon': 20, '#tools_bottom label .svg_icon': 18 }, callback: function(icons) { $('.toolbar_button button > svg, .toolbar_button button > img').each(function() { $(this).parent().prepend(this); }); var tleft = $('#tools_left'); if (tleft.length != 0) { var min_height = tleft.offset().top + tleft.outerHeight(); } // var size = $.pref('iconsize'); // if(size && size != 'm') { // svgEditor.setIconSize(size); // } else if($(window).height() < min_height) { // // Make smaller // svgEditor.setIconSize('s'); // } // Look for any missing flyout icons from plugins $('.tools_flyout').each(function() { var shower = $('#' + this.id + '_show'); var sel = shower.attr('data-curopt'); // Check if there's an icon here if(!shower.children('svg, img').length) { var clone = $(sel).children().clone(); if(clone.length) { clone[0].removeAttribute('style'); //Needed for Opera shower.append(clone); } } }); svgEditor.runCallbacks(); setTimeout(function() { $('.flyout_arrow_horiz:empty').each(function() { $(this).append($.getSvgIcon('arrow_right').width(5).height(5)); }); }, 1); } }); Editor.canvas = svgCanvas = new $.SvgCanvas(document.getElementById("svgcanvas"), curConfig); Editor.show_save_warning = false; var palette = ["#000000", "#3f3f3f", "#7f7f7f", "#bfbfbf", "#ffffff", "#ff0000", "#ff7f00", "#ffff00", "#7fff00", "#00ff00", "#00ff7f", "#00ffff", "#007fff", "#0000ff", "#7f00ff", "#ff00ff", "#ff007f", "#7f0000", "#7f3f00", "#7f7f00", "#3f7f00", "#007f00", "#007f3f", "#007f7f", "#003f7f", "#00007f", "#3f007f", "#7f007f", "#7f003f", "#ffaaaa", "#ffd4aa", "#ffffaa", "#d4ffaa", "#aaffaa", "#aaffd4", "#aaffff", "#aad4ff", "#aaaaff", "#d4aaff", "#ffaaff", "#ffaad4" ], isMac = (navigator.platform.indexOf("Mac") >= 0), isWebkit = (navigator.userAgent.indexOf("AppleWebKit") >= 0), modKey = (isMac ? "meta+" : "ctrl+"), // ⌘ path = svgCanvas.pathActions, undoMgr = svgCanvas.undoMgr, Utils = svgedit.utilities, default_img_url = curConfig.imgPath + "logo.png", workarea = $("#workarea"), canv_menu = $("#cmenu_canvas"), layer_menu = $("#cmenu_layers"), exportWindow = null, tool_scale = 1, zoomInIcon = 'crosshair', zoomOutIcon = 'crosshair', ui_context = 'toolbars', orig_source = '', paintBox = {fill: null, stroke:null}; // This sets up alternative dialog boxes. They mostly work the same way as // their UI counterparts, expect instead of returning the result, a callback // needs to be included that returns the result as its first parameter. // In the future we may want to add additional types of dialog boxes, since // they should be easy to handle this way. (function() { $('#dialog_container').draggable({cancel:'#dialog_content, #dialog_buttons *', containment: 'window'}); var box = $('#dialog_box'), btn_holder = $('#dialog_buttons'); var dbox = function(type, msg, callback, defText) { $('#dialog_content').html('<p>'+msg.replace(/\n/g,'</p><p>')+'</p>') .toggleClass('prompt',(type=='prompt')); btn_holder.empty(); var ok = $('<input type="button" value="' + uiStrings.common.ok + '">').appendTo(btn_holder); if(type != 'alert') { $('<input type="button" value="' + uiStrings.common.cancel + '">') .appendTo(btn_holder) .click(function() { box.hide();callback(false)}); } if(type == 'prompt') { var input = $('<input type="text">').prependTo(btn_holder); input.val(defText || ''); input.bind('keydown', 'return', function() {ok.click();}); } if(type == 'process') { ok.hide(); } box.show(); ok.click(function() { box.hide(); var resp = (type == 'prompt')?input.val():true; if(callback) callback(resp); }).focus(); if(type == 'prompt') input.focus(); } $.alert = function(msg, cb) { dbox('alert', msg, cb);}; $.confirm = function(msg, cb) { dbox('confirm', msg, cb);}; $.process_cancel = function(msg, cb) { dbox('process', msg, cb);}; $.prompt = function(msg, txt, cb) { dbox('prompt', msg, cb, txt);}; }()); var setSelectMode = function() { var curr = $('.tool_button_current'); if(curr.length && curr[0].id !== 'tool_select') { curr.removeClass('tool_button_current').addClass('tool_button'); $('#tool_select').addClass('tool_button_current').removeClass('tool_button'); $('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all} #svgcanvas svg{cursor:default}'); } svgCanvas.setMode('select'); workarea.css('cursor','auto'); }; var togglePathEditMode = function(editmode, elems) { $('#path_node_panel').toggle(editmode); $('#tools_bottom_2,#tools_bottom_3').toggle(!editmode); if(editmode) { // Change select icon $('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); $('#tool_select').addClass('tool_button_current').removeClass('tool_button'); setIcon('#tool_select', 'select_node'); multiselected = false; if(elems.length) { selectedElement = elems[0]; } } else { setIcon('#tool_select', 'select'); } } // used to make the flyouts stay on the screen longer the very first time var flyoutspeed = 1250; var textBeingEntered = false; var selectedElement = null; var multiselected = false; var editingsource = false; var docprops = false; var preferences = false; var cur_context = ''; var orig_title = $('title:first').text(); var saveHandler = function(window,svg) { Editor.show_save_warning = false; // by default, we add the XML prolog back, systems integrating SVG-edit (wikis, CMSs) // can just provide their own custom save handler and might not want the XML prolog svg = '<?xml version="1.0"?>\n' + svg; // Opens the SVG in new window, with warning about Mozilla bug #308590 when applicable var ua = navigator.userAgent; // Chrome 5 (and 6?) don't allow saving, show source instead ( http://code.google.com/p/chromium/issues/detail?id=46735 ) // IE9 doesn't allow standalone Data URLs ( https://connect.microsoft.com/IE/feedback/details/542600/data-uri-images-fail-when-loaded-by-themselves ) if((~ua.indexOf('Chrome') && $.browser.version >= 533) || ~ua.indexOf('MSIE')) { showSourceEditor(0,true); return; } var win = window.open("data:image/svg+xml;base64," + Utils.encode64(svg)); // Alert will only appear the first time saved OR the first time the bug is encountered var done = $.pref('save_notice_done'); if(done !== "all") { var note = uiStrings.notification.saveFromBrowser.replace('%s', 'SVG'); // Check if FF and has <defs/> if(ua.indexOf('Gecko/') !== -1) { if(svg.indexOf('<defs') !== -1) { note += "\n\n" + uiStrings.notification.defsFailOnSave; $.pref('save_notice_done', 'all'); done = "all"; } else { $.pref('save_notice_done', 'part'); } } else { $.pref('save_notice_done', 'all'); } if(done !== 'part') { win.alert(note); } } }; var exportHandler = function(window, data) { var issues = data.issues; if(!$('#export_canvas').length) { $('<canvas>', {id: 'export_canvas'}).hide().appendTo('body'); } var c = $('#export_canvas')[0]; c.width = svgCanvas.contentW; c.height = svgCanvas.contentH; canvg(c, data.svg, {renderCallback: function() { var datauri = c.toDataURL('image/png'); exportWindow.location.href = datauri; var done = $.pref('export_notice_done'); if(done !== "all") { var note = uiStrings.notification.saveFromBrowser.replace('%s', 'PNG'); // Check if there's issues if(issues.length) { var pre = "\n \u2022 "; note += ("\n\n" + uiStrings.notification.noteTheseIssues + pre + issues.join(pre)); } // Note that this will also prevent the notice even though new issues may appear later. // May want to find a way to deal with that without annoying the user $.pref('export_notice_done', 'all'); exportWindow.alert(note); } }}); }; // called when we've selected a different element var selectedChanged = function(window,elems) { var mode = svgCanvas.getMode(); if(mode === "select") setSelectMode(); var is_node = (mode == "pathedit"); // if elems[1] is present, then we have more than one element selectedElement = (elems.length == 1 || elems[1] == null ? elems[0] : null); multiselected = (elems.length >= 2 && elems[1] != null); if (selectedElement != null) { // unless we're already in always set the mode of the editor to select because // upon creation of a text element the editor is switched into // select mode and this event fires - we need our UI to be in sync if (!is_node) { updateToolbar(); } } // if (elem != null) // Deal with pathedit mode togglePathEditMode(is_node, elems); updateContextPanel(); svgCanvas.runExtensions("selectedChanged", { elems: elems, selectedElement: selectedElement, multiselected: multiselected }); }; // Call when part of element is in process of changing, generally // on mousemove actions like rotate, move, etc. var elementTransition = function(window,elems) { var mode = svgCanvas.getMode(); var elem = elems[0]; if(!elem) return; multiselected = (elems.length >= 2 && elems[1] != null); // Only updating fields for single elements for now if(!multiselected) { switch ( mode ) { case "rotate": var ang = svgCanvas.getRotationAngle(elem); $('#angle').val(ang); $('#tool_reorient').toggleClass('disabled', ang == 0); break; // TODO: Update values that change on move/resize, etc // case "select": // case "resize": // break; } } svgCanvas.runExtensions("elementTransition", { elems: elems }); }; // called when any element has changed var elementChanged = function(window,elems) { var mode = svgCanvas.getMode(); if(mode === "select") { setSelectMode(); } for (var i = 0; i < elems.length; ++i) { var elem = elems[i]; // if the element changed was the svg, then it could be a resolution change if (elem && elem.tagName === "svg") { populateLayers(); updateCanvas(); } // Update selectedElement if element is no longer part of the image. // This occurs for the text elements in Firefox else if(elem && selectedElement && selectedElement.parentNode == null) { // || elem && elem.tagName == "path" && !multiselected) { // This was added in r1430, but not sure why selectedElement = elem; } } Editor.show_save_warning = true; // we update the contextual panel with potentially new // positional/sizing information (we DON'T want to update the // toolbar here as that creates an infinite loop) // also this updates the history buttons // we tell it to skip focusing the text control if the // text element was previously in focus updateContextPanel(); // In the event a gradient was flipped: if(selectedElement && mode === "select") { paintBox.fill.update(); paintBox.stroke.update(); } svgCanvas.runExtensions("elementChanged", { elems: elems }); }; var zoomChanged = svgCanvas.zoomChanged = function(window, bbox, autoCenter) { var scrbar = 15, res = svgCanvas.getResolution(), w_area = workarea, canvas_pos = $('#svgcanvas').position(); var z_info = svgCanvas.setBBoxZoom(bbox, w_area.width()-scrbar, w_area.height()-scrbar); if(!z_info) return; var zoomlevel = z_info.zoom, bb = z_info.bbox; if(zoomlevel < .001) { changeZoom({value: .1}); return; } // $('#zoom').val(Math.round(zoomlevel*100)); $('#zoom').val(zoomlevel*100); if(autoCenter) { updateCanvas(); } else { updateCanvas(false, {x: bb.x * zoomlevel + (bb.width * zoomlevel)/2, y: bb.y * zoomlevel + (bb.height * zoomlevel)/2}); } if(svgCanvas.getMode() == 'zoom' && bb.width) { // Go to select if a zoom box was drawn setSelectMode(); } zoomDone(); } $('#cur_context_panel').delegate('a', 'click', function() { var link = $(this); if(link.attr('data-root')) { svgCanvas.leaveContext(); } else { svgCanvas.setContext(link.text()); } svgCanvas.clearSelection(); return false; }); var contextChanged = function(win, context) { var link_str = ''; if(context) { var str = ''; link_str = '<a href="#" data-root="y">' + svgCanvas.getCurrentDrawing().getCurrentLayerName() + '</a>'; $(context).parentsUntil('#svgcontent > g').andSelf().each(function() { if(this.id) { str += ' > ' + this.id; if(this !== context) { link_str += ' > <a href="#">' + this.id + '</a>'; } else { link_str += ' > ' + this.id; } } }); cur_context = str; } else { cur_context = null; } $('#cur_context_panel').toggle(!!context).html(link_str); updateTitle(); } // Makes sure the current selected paint is available to work with var prepPaints = function() { paintBox.fill.prep(); paintBox.stroke.prep(); } var flyout_funcs = {}; var setupFlyouts = function(holders) { $.each(holders, function(hold_sel, btn_opts) { var buttons = $(hold_sel).children(); var show_sel = hold_sel + '_show'; var shower = $(show_sel); var def = false; buttons.addClass('tool_button') .unbind('click mousedown mouseup') // may not be necessary .each(function(i) { // Get this buttons options var opts = btn_opts[i]; // Remember the function that goes with this ID flyout_funcs[opts.sel] = opts.fn; if(opts.isDefault) def = i; // Clicking the icon in flyout should set this set's icon var func = function(event) { var options = opts; //find the currently selected tool if comes from keystroke if (event.type === "keydown") { var flyoutIsSelected = $(options.parent + "_show").hasClass('tool_button_current'); var currentOperation = $(options.parent + "_show").attr("data-curopt"); $.each(holders[opts.parent], function(i, tool){ if (tool.sel == currentOperation) { if(!event.shiftKey || !flyoutIsSelected) { options = tool; } else { options = holders[opts.parent][i+1] || holders[opts.parent][0]; } } }); } if($(this).hasClass('disabled')) return false; if (toolButtonClick(show_sel)) { options.fn(); } if(options.icon) { var icon = $.getSvgIcon(options.icon, true); } else { var icon = $(options.sel).children().eq(0).clone(); } icon[0].setAttribute('width',shower.width()); icon[0].setAttribute('height',shower.height()); shower.children(':not(.flyout_arrow_horiz)').remove(); shower.append(icon).attr('data-curopt', options.sel); // This sets the current mode } $(this).mouseup(func); if(opts.key) { $(document).bind('keydown', opts.key[0] + " shift+" + opts.key[0], func); } }); if(def) { shower.attr('data-curopt', btn_opts[def].sel); } else if(!shower.attr('data-curopt')) { // Set first as default shower.attr('data-curopt', btn_opts[0].sel); } var timer; var pos = $(show_sel).position(); $(hold_sel).css({'left': pos.left+34, 'top': pos.top+40}); // Clicking the "show" icon should set the current mode shower.mousedown(function(evt) { if(shower.hasClass('disabled')) return false; var holder = $(hold_sel); var l = pos.left+34; var w = holder.width()*-1; var time = holder.data('shown_popop')?200:0; timer = setTimeout(function() { // Show corresponding menu if(!shower.data('isLibrary')) { holder.css('left', w).show().animate({ left: l },150); } else { holder.css('left', l).show(); } holder.data('shown_popop',true); },time); evt.preventDefault(); }).mouseup(function(evt) { clearTimeout(timer); var opt = $(this).attr('data-curopt'); // Is library and popped up, so do nothing if(shower.data('isLibrary') && $(show_sel.replace('_show','')).is(':visible')) { toolButtonClick(show_sel, true); return; } if (toolButtonClick(show_sel) && (opt in flyout_funcs)) { flyout_funcs[opt](); } }); // $('#tools_rect').mouseleave(function(){$('#tools_rect').fadeOut();}); }); setFlyoutTitles(); } var makeFlyoutHolder = function(id, child) { var div = $('<div>',{ 'class': 'tools_flyout', id: id }).appendTo('#svg_editor').append(child); return div; } var setFlyoutPositions = function() { $('.tools_flyout').each(function() { var shower = $('#' + this.id + '_show'); var pos = shower.offset(); var w = shower.outerWidth(); $(this).css({left: (pos.left + w)*tool_scale, top: pos.top}); }); } var setFlyoutTitles = function() { $('.tools_flyout').each(function() { var shower = $('#' + this.id + '_show'); if(shower.data('isLibrary')) return; var tooltips = []; $(this).children().each(function() { tooltips.push(this.title); }); shower[0].title = tooltips.join(' / '); }); } var resize_timer; var extAdded = function(window, ext) { var cb_called = false; var resize_done = false; var cb_ready = true; // Set to false to delay callback (e.g. wait for $.svgIcons) function prepResize() { if(resize_timer) { clearTimeout(resize_timer); resize_timer = null; } if(!resize_done) { resize_timer = setTimeout(function() { resize_done = true; setIconSize(curPrefs.iconsize); }, 50); } } var runCallback = function() { if(ext.callback && !cb_called && cb_ready) { cb_called = true; ext.callback(); } } var btn_selects = []; if(ext.context_tools) { $.each(ext.context_tools, function(i, tool) { // Add select tool var cont_id = tool.container_id?(' id="' + tool.container_id + '"'):""; var panel = $('#' + tool.panel); // create the panel if it doesn't exist if(!panel.length) panel = $('<div>', {id: tool.panel}).appendTo("#tools_top"); // TODO: Allow support for other types, or adding to existing tool switch (tool.type) { case 'tool_button': var html = '<div class="tool_button">' + tool.id + '</div>'; var div = $(html).appendTo(panel); if (tool.events) { $.each(tool.events, function(evt, func) { $(div).bind(evt, func); }); } break; case 'select': var html = '<label' + cont_id + '>' + '<select id="' + tool.id + '">'; $.each(tool.options, function(val, text) { var sel = (val == tool.defval) ? " selected":""; html += '<option value="'+val+'"' + sel + '>' + text + '</option>'; }); html += "</select></label>"; // Creates the tool, hides & adds it, returns the select element var sel = $(html).appendTo(panel).find('select'); $.each(tool.events, function(evt, func) { $(sel).bind(evt, func); }); break; case 'button-select': var html = '<div id="' + tool.id + '" class="dropdown toolset" title="' + tool.title + '">' + '<div id="cur_' + tool.id + '" class="icon_label"></div><button></button></div>'; var list = $('<ul id="' + tool.id + '_opts"></ul>').appendTo('#option_lists'); if(tool.colnum) { list.addClass('optcols' + tool.colnum); } // Creates the tool, hides & adds it, returns the select element var dropdown = $(html).appendTo(panel).children(); btn_selects.push({ elem: ('#' + tool.id), list: ('#' + tool.id + '_opts'), title: tool.title, callback: tool.events.change, cur: ('#cur_' + tool.id) }); break; case 'input': var html = '<label' + cont_id + '>' + '<span id="' + tool.id + '_label">' + tool.label + ':</span>' + '<input id="' + tool.id + '" title="' + tool.title + '" size="' + (tool.size || "4") + '" value="' + (tool.defval || "") + '" type="text"/></label>' // Creates the tool, hides & adds it, returns the select element // Add to given tool.panel var inp = $(html).appendTo(panel).find('input'); if(tool.spindata) { inp.SpinButton(tool.spindata); } if(tool.events) { $.each(tool.events, function(evt, func) { inp.bind(evt, func); }); } break; default: break; } }); } if(ext.buttons) { var fallback_obj = {}, placement_obj = {}, svgicons = ext.svgicons; var holders = {}; // Add buttons given by extension $.each(ext.buttons, function(i, btn) { var icon; var id = btn.id; var num = i; // Give button a unique ID while($('#'+id).length) { id = btn.id + '_' + (++num); } if(!svgicons) { icon = $('<img src="' + btn.icon + '">'); } else { fallback_obj[id] = btn.icon; var svgicon = btn.svgicon?btn.svgicon:btn.id; if(btn.type == 'app_menu') { placement_obj['#' + id + ' > div'] = svgicon; } else { placement_obj['#' + id] = svgicon; } } var cls, parent; // Set button up according to its type switch ( btn.type ) { case 'mode_flyout': case 'mode': cls = 'tool_button'; parent = "#tools_left"; break; case 'context': cls = 'tool_button'; parent = "#" + btn.panel; // create the panel if it doesn't exist if(!$(parent).length) $('<div>', {id: btn.panel}).appendTo("#tools_top"); break; case 'app_menu': cls = ''; parent = '#main_menu ul'; break; } var button = $((btn.list || btn.type == 'app_menu')?'<li/>':'<div/>') .attr("id", id) .attr("title", btn.title) .addClass(cls); if(!btn.includeWith && !btn.list) { if("position" in btn) { $(parent).children().eq(btn.position).before(button); } else { button.appendTo(parent); } if(btn.type =='mode_flyout') { // Add to flyout menu / make flyout menu // var opts = btn.includeWith; // // opts.button, default, position var ref_btn = $(button); var flyout_holder = ref_btn.parent(); // Create a flyout menu if there isn't one already if(!ref_btn.parent().hasClass('tools_flyout')) { // Create flyout placeholder var tls_id = ref_btn[0].id.replace('tool_','tools_') var show_btn = ref_btn.clone() .attr('id',tls_id + '_show') .append($('<div>',{'class':'flyout_arrow_horiz'})); ref_btn.before(show_btn); // Create a flyout div flyout_holder = makeFlyoutHolder(tls_id, ref_btn); flyout_holder.data('isLibrary', true); show_btn.data('isLibrary', true); } // var ref_data = Actions.getButtonData(opts.button); placement_obj['#' + tls_id + '_show'] = btn.id; // TODO: Find way to set the current icon using the iconloader if this is not default // Include data for extension button as well as ref button var cur_h = holders['#'+flyout_holder[0].id] = [{ sel: '#'+id, fn: btn.events.click, icon: btn.id, // key: btn.key, isDefault: true }, ref_data]; // // // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} // // var pos = ("position" in opts)?opts.position:'last'; // var len = flyout_holder.children().length; // // // Add at given position or end // if(!isNaN(pos) && pos >= 0 && pos < len) { // flyout_holder.children().eq(pos).before(button); // } else { // flyout_holder.append(button); // cur_h.reverse(); // } } else if(btn.type == 'app_menu') { button.append('<div>').append(btn.title); } } else if(btn.list) { // Add button to list button.addClass('push_button'); $('#' + btn.list + '_opts').append(button); if(btn.isDefault) { $('#cur_' + btn.list).append(button.children().clone()); var svgicon = btn.svgicon?btn.svgicon:btn.id; placement_obj['#cur_' + btn.list] = svgicon; } } else if(btn.includeWith) { // Add to flyout menu / make flyout menu var opts = btn.includeWith; // opts.button, default, position var ref_btn = $(opts.button); var flyout_holder = ref_btn.parent(); // Create a flyout menu if there isn't one already if(!ref_btn.parent().hasClass('tools_flyout')) { // Create flyout placeholder var tls_id = ref_btn[0].id.replace('tool_','tools_') var show_btn = ref_btn.clone() .attr('id',tls_id + '_show') .append($('<div>',{'class':'flyout_arrow_horiz'})); ref_btn.before(show_btn); // Create a flyout div flyout_holder = makeFlyoutHolder(tls_id, ref_btn); } var ref_data = Actions.getButtonData(opts.button); if(opts.isDefault) { placement_obj['#' + tls_id + '_show'] = btn.id; } // TODO: Find way to set the current icon using the iconloader if this is not default // Include data for extension button as well as ref button var cur_h = holders['#'+flyout_holder[0].id] = [{ sel: '#'+id, fn: btn.events.click, icon: btn.id, key: btn.key, isDefault: btn.includeWith?btn.includeWith.isDefault:0 }, ref_data]; // {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: 4, parent: '#tools_rect', icon: 'rect'} var pos = ("position" in opts)?opts.position:'last'; var len = flyout_holder.children().length; // Add at given position or end if(!isNaN(pos) && pos >= 0 && pos < len) { flyout_holder.children().eq(pos).before(button); } else { flyout_holder.append(button); cur_h.reverse(); } } if(!svgicons) { button.append(icon); } if(!btn.list) { // Add given events to button $.each(btn.events, function(name, func) { if(name == "click") { if(btn.type == 'mode') { if(btn.includeWith) { button.bind(name, func); } else { button.bind(name, function() { if(toolButtonClick(button)) { func(); } }); } if(btn.key) { $(document).bind('keydown', btn.key, func); if(btn.title) button.attr("title", btn.title + ' ['+btn.key+']'); } } else { button.bind(name, func); } } else { button.bind(name, func); } }); } setupFlyouts(holders); }); $.each(btn_selects, function() { addAltDropDown(this.elem, this.list, this.callback, {seticon: true}); }); if (svgicons) cb_ready = false; // Delay callback $.svgIcons(svgicons, { w:24, h:24, id_match: false, no_img: (!isWebkit), fallback: fallback_obj, placement: placement_obj, callback: function(icons) { // Non-ideal hack to make the icon match the current size if(curPrefs.iconsize && curPrefs.iconsize != 'm') { prepResize(); } cb_ready = true; // Ready for callback runCallback(); } }); } runCallback(); }; var getPaint = function(color, opac, type) { // update the editor's fill paint var opts = null; if (color.indexOf("url(#") === 0) { var refElem = svgCanvas.getRefElem(color); if(refElem) { refElem = refElem.cloneNode(true); } else { refElem = $("#" + type + "_color defs *")[0]; } opts = { alpha: opac }; opts[refElem.tagName] = refElem; } else if (color.indexOf("#") === 0) { opts = { alpha: opac, solidColor: color.substr(1) }; } else { opts = { alpha: opac, solidColor: 'none' }; } return new $.jGraduate.Paint(opts); }; // updates the toolbar (colors, opacity, etc) based on the selected element // This function also updates the opacity and id elements that are in the context panel var updateToolbar = function() { if (selectedElement != null) { switch ( selectedElement.tagName ) { case 'use': case 'image': case 'foreignObject': break; case 'g': case 'a': // Look for common styles var gWidth = null; var childs = selectedElement.getElementsByTagName('*'); for(var i = 0, len = childs.length; i < len; i++) { var swidth = childs[i].getAttribute("stroke-width"); if(i === 0) { gWidth = swidth; } else if(gWidth !== swidth) { gWidth = null; } } $('#stroke_width').val(gWidth === null ? "" : gWidth); paintBox.fill.update(true); paintBox.stroke.update(true); break; default: paintBox.fill.update(true); paintBox.stroke.update(true); //console.log(paintBox.fill); $('#stroke_width').val(selectedElement.getAttribute("stroke-width") || 1); $('#stroke_style').val(selectedElement.getAttribute("stroke-dasharray")||"none"); var attr = selectedElement.getAttribute("stroke-linejoin") || 'miter'; if ($('#linejoin_' + attr).length != 0) setStrokeOpt($('#linejoin_' + attr)[0]); attr = selectedElement.getAttribute("stroke-linecap") || 'butt'; if ($('#linecap_' + attr).length != 0) setStrokeOpt($('#linecap_' + attr)[0]); } } // All elements including image and group have opacity if(selectedElement != null) { var opac_perc = ((selectedElement.getAttribute("opacity")||1.0)*100); $('#group_opacity').val(opac_perc); $('#opac_slider').slider('option', 'value', opac_perc); $('#elem_id').val(selectedElement.id); } updateToolButtonState(); }; var setImageURL = Editor.setImageURL = function(url) { if(!url) url = default_img_url; svgCanvas.setImageURL(url); $('#image_url').val(url); if(url.indexOf('data:') === 0) { // data URI found $('#image_url').hide(); $('#change_image_url').show(); } else { // regular URL svgCanvas.embedImage(url, function(datauri) { if(!datauri) { // Couldn't embed, so show warning $('#url_notice').show(); } else { $('#url_notice').hide(); } default_img_url = url; }); $('#image_url').show(); $('#change_image_url').hide(); } } var setInputWidth = function(elem) { var w = Math.min(Math.max(12 + elem.value.length * 6, 50), 300); $(elem).width(w); } // updates the context panel tools based on the selected element var updateContextPanel = function() { var elem = selectedElement; // If element has just been deleted, consider it null if(elem != null && !elem.parentNode) elem = null; var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName(); var currentMode = svgCanvas.getMode(); var unit = curConfig.baseUnit !== 'px' ? curConfig.baseUnit : null; var is_node = currentMode == 'pathedit'; //elem ? (elem.id && elem.id.indexOf('pathpointgrip') == 0) : false; var menu_items = $('#cmenu_canvas li'); $('#selected_panel, #multiselected_panel, #g_panel, #rect_panel, #circle_panel,\ #ellipse_panel, #line_panel, #text_panel, #image_panel, #container_panel, #use_panel, #a_panel').hide(); if (elem != null) { var elname = elem.nodeName; // If this is a link with no transform and one child, pretend // its child is selected // console.log('go', elem) // if(elname === 'a') { // && !$(elem).attr('transform')) { // elem = elem.firstChild; // } var angle = svgCanvas.getRotationAngle(elem); $('#angle').val(angle); var blurval = svgCanvas.getBlur(elem); $('#blur').val(blurval); $('#blur_slider').slider('option', 'value', blurval); if(svgCanvas.addedNew) { if(elname === 'image') { // Prompt for URL if not a data URL if(svgCanvas.getHref(elem).indexOf('data:') !== 0) { promptImgURL(); } } /*else if(elname == 'text') { // TODO: Do something here for new text }*/ } if(!is_node && currentMode != 'pathedit') { $('#selected_panel').show(); // Elements in this array already have coord fields if(['line', 'circle', 'ellipse'].indexOf(elname) >= 0) { $('#xy_panel').hide(); } else { var x,y; // Get BBox vals for g, polyline and path if(['g', 'polyline', 'path'].indexOf(elname) >= 0) { var bb = svgCanvas.getStrokedBBox([elem]); if(bb) { x = bb.x; y = bb.y; } } else { x = elem.getAttribute('x'); y = elem.getAttribute('y'); } if(unit) { x = svgedit.units.convertUnit(x); y = svgedit.units.convertUnit(y); } $('#selected_x').val(x || 0); $('#selected_y').val(y || 0); $('#xy_panel').show(); } // Elements in this array cannot be converted to a path var no_path = ['image', 'text', 'path', 'g', 'use'].indexOf(elname) == -1; $('#tool_topath').toggle(no_path); $('#tool_reorient').toggle(elname == 'path'); $('#tool_reorient').toggleClass('disabled', angle == 0); } else { var point = path.getNodePoint(); $('#tool_add_subpath').removeClass('push_button_pressed').addClass('tool_button'); $('#tool_node_delete').toggleClass('disabled', !path.canDeleteNodes); // Show open/close button based on selected point setIcon('#tool_openclose_path', path.closed_subpath ? 'open_path' : 'close_path'); if(point) { var seg_type = $('#seg_type'); if(unit) { point.x = svgedit.units.convertUnit(point.x); point.y = svgedit.units.convertUnit(point.y); } $('#path_node_x').val(point.x); $('#path_node_y').val(point.y); if(point.type) { seg_type.val(point.type).removeAttr('disabled'); } else { seg_type.val(4).attr('disabled','disabled'); } } return; } // update contextual tools here var panels = { g: [], a: [], rect: ['rx','width','height'], image: ['width','height'], circle: ['cx','cy','r'], ellipse: ['cx','cy','rx','ry'], line: ['x1','y1','x2','y2'], text: [], 'use': [] }; var el_name = elem.tagName; // if($(elem).data('gsvg')) { // $('#g_panel').show(); // } var link_href = null; if (el_name === 'a') { link_href = svgCanvas.getHref(elem); $('#g_panel').show(); } if(elem.parentNode.tagName === 'a') { if(!$(elem).siblings().length) { $('#a_panel').show(); link_href = svgCanvas.getHref(elem.parentNode); } } // Hide/show the make_link buttons $('#tool_make_link, #tool_make_link').toggle(!link_href); if(link_href) { $('#link_url').val(link_href); } if(panels[el_name]) { var cur_panel = panels[el_name]; $('#' + el_name + '_panel').show(); $.each(cur_panel, function(i, item) { var attrVal = elem.getAttribute(item); if(curConfig.baseUnit !== 'px' && elem[item]) { var bv = elem[item].baseVal.value; attrVal = svgedit.units.convertUnit(bv); } $('#' + el_name + '_' + item).val(attrVal || 0); }); if(el_name == 'text') { $('#text_panel').css("display", "inline"); if (svgCanvas.getItalic()) { $('#tool_italic').addClass('push_button_pressed').removeClass('tool_button'); } else { $('#tool_italic').removeClass('push_button_pressed').addClass('tool_button'); } if (svgCanvas.getBold()) { $('#tool_bold').addClass('push_button_pressed').removeClass('tool_button'); } else { $('#tool_bold').removeClass('push_button_pressed').addClass('tool_button'); } $('#font_family').val(elem.getAttribute("font-family")); $('#font_size').val(elem.getAttribute("font-size")); $('#text').val(elem.textContent); if (svgCanvas.addedNew) { // Timeout needed for IE9 setTimeout(function() { $('#text').focus().select(); },100); } } // text else if(el_name == 'image') { setImageURL(svgCanvas.getHref(elem)); } // image else if(el_name === 'g' || el_name === 'use') { $('#container_panel').show(); var title = svgCanvas.getTitle(); var label = $('#g_title')[0]; label.value = title; setInputWidth(label); var d = 'disabled'; if(el_name == 'use') { label.setAttribute(d, d); } else { label.removeAttribute(d); } } } menu_items[(el_name === 'g' ? 'en':'dis') + 'ableContextMenuItems']('#ungroup'); menu_items[((el_name === 'g' || !multiselected) ? 'dis':'en') + 'ableContextMenuItems']('#group'); } // if (elem != null) else if (multiselected) { $('#multiselected_panel').show(); menu_items .enableContextMenuItems('#group') .disableContextMenuItems('#ungroup'); } else { menu_items.disableContextMenuItems('#delete,#cut,#copy,#group,#ungroup,#move_front,#move_up,#move_down,#move_back'); } // update history buttons if (undoMgr.getUndoStackSize() > 0) { $('#tool_undo').removeClass( 'disabled'); } else { $('#tool_undo').addClass( 'disabled'); } if (undoMgr.getRedoStackSize() > 0) { $('#tool_redo').removeClass( 'disabled'); } else { $('#tool_redo').addClass( 'disabled'); } svgCanvas.addedNew = false; if ( (elem && !is_node) || multiselected) { // update the selected elements' layer $('#selLayerNames').removeAttr('disabled').val(currentLayerName); // Enable regular menu options canv_menu.enableContextMenuItems('#delete,#cut,#copy,#move_front,#move_up,#move_down,#move_back'); } else { $('#selLayerNames').attr('disabled', 'disabled'); } }; $('#text').focus( function(){ textBeingEntered = true; } ); $('#text').blur( function(){ textBeingEntered = false; } ); // bind the selected event to our function that handles updates to the UI svgCanvas.bind("selected", selectedChanged); svgCanvas.bind("transition", elementTransition); svgCanvas.bind("changed", elementChanged); svgCanvas.bind("saved", saveHandler); svgCanvas.bind("exported", exportHandler); svgCanvas.bind("zoomed", zoomChanged); svgCanvas.bind("contextset", contextChanged); svgCanvas.bind("extension_added", extAdded); svgCanvas.textActions.setInputElem($("#text")[0]); var str = '<div class="palette_item" data-rgb="none"></div>' $.each(palette, function(i,item){ str += '<div class="palette_item" style="background-color: ' + item + ';" data-rgb="' + item + '"></div>'; }); $('#palette').append(str); // Set up editor background functionality // TODO add checkerboard as "pattern" var color_blocks = ['#FFF','#888','#000']; // ,'url(data:image/gif;base64,R0lGODlhEAAQAIAAAP%2F%2F%2F9bW1iH5BAAAAAAALAAAAAAQABAAAAIfjG%2Bgq4jM3IFLJgpswNly%2FXkcBpIiVaInlLJr9FZWAQA7)']; var str = ''; $.each(color_blocks, function() { str += '<div class="color_block" style="background-color:' + this + ';"></div>'; }); $('#bg_blocks').append(str); var blocks = $('#bg_blocks div'); var cur_bg = 'cur_background'; blocks.each(function() { var blk = $(this); blk.click(function() { blocks.removeClass(cur_bg); $(this).addClass(cur_bg); }); }); if($.pref('bkgd_color')) { setBackground($.pref('bkgd_color'), $.pref('bkgd_url')); } else if($.pref('bkgd_url')) { // No color set, only URL setBackground(defaultPrefs.bkgd_color, $.pref('bkgd_url')); } if($.pref('img_save')) { curPrefs.img_save = $.pref('img_save'); $('#image_save_opts input').val([curPrefs.img_save]); } var changeRectRadius = function(ctl) { svgCanvas.setRectRadius(ctl.value); } var changeFontSize = function(ctl) { svgCanvas.setFontSize(ctl.value); } var changeStrokeWidth = function(ctl) { var val = ctl.value; if(val == 0 && selectedElement && ['line', 'polyline'].indexOf(selectedElement.nodeName) >= 0) { val = ctl.value = 1; } svgCanvas.setStrokeWidth(val); } var changeRotationAngle = function(ctl) { svgCanvas.setRotationAngle(ctl.value); $('#tool_reorient').toggleClass('disabled', ctl.value == 0); } var changeZoom = function(ctl) { var zoomlevel = ctl.value / 100; if(zoomlevel < .001) { ctl.value = .1; return; } var zoom = svgCanvas.getZoom(); var w_area = workarea; zoomChanged(window, { width: 0, height: 0, // center pt of scroll position x: (w_area[0].scrollLeft + w_area.width()/2)/zoom, y: (w_area[0].scrollTop + w_area.height()/2)/zoom, zoom: zoomlevel }, true); } var changeOpacity = function(ctl, val) { if(val == null) val = ctl.value; $('#group_opacity').val(val); if(!ctl || !ctl.handle) { $('#opac_slider').slider('option', 'value', val); } svgCanvas.setOpacity(val/100); } var changeBlur = function(ctl, val, noUndo) { if(val == null) val = ctl.value; $('#blur').val(val); var complete = false; if(!ctl || !ctl.handle) { $('#blur_slider').slider('option', 'value', val); complete = true; } if(noUndo) { svgCanvas.setBlurNoUndo(val); } else { svgCanvas.setBlur(val, complete); } } var operaRepaint = function() { // Repaints canvas in Opera. Needed for stroke-dasharray change as well as fill change if(!window.opera) return; $('<p/>').hide().appendTo('body').remove(); } $('#stroke_style').change(function(){ svgCanvas.setStrokeAttr('stroke-dasharray', $(this).val()); operaRepaint(); }); $('#stroke_linejoin').change(function(){ svgCanvas.setStrokeAttr('stroke-linejoin', $(this).val()); operaRepaint(); }); // Lose focus for select elements when changed (Allows keyboard shortcuts to work better) $('select').change(function(){$(this).blur();}); // fired when user wants to move elements to another layer var promptMoveLayerOnce = false; $('#selLayerNames').change(function(){ var destLayer = this.options[this.selectedIndex].value; var confirm_str = uiStrings.notification.QmoveElemsToLayer.replace('%s',destLayer); var moveToLayer = function(ok) { if(!ok) return; promptMoveLayerOnce = true; svgCanvas.moveSelectedToLayer(destLayer); svgCanvas.clearSelection(); populateLayers(); } if (destLayer) { if(promptMoveLayerOnce) { moveToLayer(true); } else { $.confirm(confirm_str, moveToLayer); } } }); $('#font_family').change(function() { svgCanvas.setFontFamily(this.value); }); $('#seg_type').change(function() { svgCanvas.setSegType($(this).val()); }); $('#text').keyup(function(){ svgCanvas.setTextContent(this.value); }); $('#image_url').change(function(){ setImageURL(this.value); }); $('#link_url').change(function() { if(this.value.length) { svgCanvas.setLinkURL(this.value); } else { svgCanvas.removeHyperlink(); } }); $('#g_title').change(function() { svgCanvas.setGroupTitle(this.value); }); $('.attr_changer').change(function() { var attr = this.getAttribute("data-attr"); var val = this.value; var valid = svgedit.units.isValidUnit(attr, val, selectedElement); if(!valid) { $.alert(uiStrings.notification.invalidAttrValGiven); this.value = selectedElement.getAttribute(attr); return false; } if (attr !== "id") { if (isNaN(val)) { val = svgCanvas.convertToNum(attr, val); } else if(curConfig.baseUnit !== 'px') { // Convert unitless value to one with given unit var unitData = svgedit.units.getTypeMap(); if(selectedElement[attr] || svgCanvas.getMode() === "pathedit" || attr === "x" || attr === "y") { val *= unitData[curConfig.baseUnit]; } } } // if the user is changing the id, then de-select the element first // change the ID, then re-select it with the new ID if (attr === "id") { var elem = selectedElement; svgCanvas.clearSelection(); elem.id = val; svgCanvas.addToSelection([elem],true); } else { svgCanvas.changeSelectedAttribute(attr, val); } this.blur(); }); // Prevent selection of elements when shift-clicking $('#palette').mouseover(function() { var inp = $('<input type="hidden">'); $(this).append(inp); inp.focus().remove(); }) $('.palette_item').mousedown(function(evt){ var right_click = evt.button === 2; var isStroke = evt.shiftKey || right_click; var picker = isStroke ? "stroke" : "fill"; var color = $(this).attr('data-rgb'); var paint = null; // Webkit-based browsers returned 'initial' here for no stroke if (color === 'none' || color === 'transparent' || color === 'initial') { color = 'none'; paint = new $.jGraduate.Paint(); } else { paint = new $.jGraduate.Paint({alpha: 100, solidColor: color.substr(1)}); } paintBox[picker].setPaint(paint); if (isStroke) { svgCanvas.setColor('stroke', color); if (color != 'none' && svgCanvas.getStrokeOpacity() != 1) { svgCanvas.setPaintOpacity('stroke', 1.0); } } else { svgCanvas.setColor('fill', color); if (color != 'none' && svgCanvas.getFillOpacity() != 1) { svgCanvas.setPaintOpacity('fill', 1.0); } } updateToolButtonState(); }).bind('contextmenu', function(e) {e.preventDefault()}); $("#toggle_stroke_tools").on("click", function() { $("#tools_bottom").toggleClass("expanded"); }); // This is a common function used when a tool has been clicked (chosen) // It does several common things: // - removes the tool_button_current class from whatever tool currently has it // - hides any flyouts // - adds the tool_button_current class to the button passed in var toolButtonClick = function(button, noHiding) { if ($(button).hasClass('disabled')) return false; if($(button).parent().hasClass('tools_flyout')) return true; var fadeFlyouts = fadeFlyouts || 'normal'; if(!noHiding) { $('.tools_flyout').fadeOut(fadeFlyouts); } $('#styleoverrides').text(''); workarea.css('cursor','auto'); $('.tool_button_current').removeClass('tool_button_current').addClass('tool_button'); $(button).addClass('tool_button_current').removeClass('tool_button'); return true; }; (function() { var last_x = null, last_y = null, w_area = workarea[0], panning = false, keypan = false; $('#svgcanvas').bind('mousemove mouseup', function(evt) { if(panning === false) return; w_area.scrollLeft -= (evt.clientX - last_x); w_area.scrollTop -= (evt.clientY - last_y); last_x = evt.clientX; last_y = evt.clientY; if(evt.type === 'mouseup') panning = false; return false; }).mousedown(function(evt) { if(evt.button === 1 || keypan === true) { panning = true; last_x = evt.clientX; last_y = evt.clientY; return false; } }); $(window).mouseup(function() { panning = false; }); $(document).bind('keydown', 'space', function(evt) { svgCanvas.spaceKey = keypan = true; evt.preventDefault(); }).bind('keyup', 'space', function(evt) { evt.preventDefault(); svgCanvas.spaceKey = keypan = false; }).bind('keydown', 'shift', function(evt) { if(svgCanvas.getMode() === 'zoom') { workarea.css('cursor', zoomOutIcon); } }).bind('keyup', 'shift', function(evt) { if(svgCanvas.getMode() === 'zoom') { workarea.css('cursor', zoomInIcon); } }) }()); function setStrokeOpt(opt, changeElem) { var id = opt.id; var bits = id.split('_'); var pre = bits[0]; var val = bits[1]; if(changeElem) { svgCanvas.setStrokeAttr('stroke-' + pre, val); } operaRepaint(); setIcon('#cur_' + pre , id, 20); $(opt).addClass('current').siblings().removeClass('current'); } (function() { var button = $('#main_icon'); var overlay = $('#main_icon span'); var list = $('#main_menu'); var on_button = false; var height = 0; var js_hover = true; var set_click = false; var hideMenu = function() { list.fadeOut(200); }; $(window).mouseup(function(evt) { if(!on_button) { button.removeClass('buttondown'); // do not hide if it was the file input as that input needs to be visible // for its change event to fire if (evt.target.tagName != "INPUT") { list.fadeOut(200); } else if(!set_click) { set_click = true; $(evt.target).click(function() { list.css('margin-left','-9999px').show(); }); } } on_button = false; }).mousedown(function(evt) { // $(".contextMenu").hide(); // console.log('cm', $(evt.target).closest('.contextMenu')); var islib = $(evt.target).closest('div.tools_flyout, .contextMenu').length; if(!islib) $('.tools_flyout:visible,.contextMenu').fadeOut(250); }); overlay.bind('mousedown',function() { if (!button.hasClass('buttondown')) { button.addClass('buttondown').removeClass('buttonup') // Margin must be reset in case it was changed before; list.css('margin-left',0).show(); if(!height) { height = list.height(); } // Using custom animation as slideDown has annoying "bounce effect" list.css('height',0).animate({ 'height': height },200); on_button = true; return false; } else { button.removeClass('buttondown').addClass('buttonup'); list.fadeOut(200); } }).hover(function() { on_button = true; }).mouseout(function() { on_button = false; }); var list_items = $('#main_menu li'); // Check if JS method of hovering needs to be used (Webkit bug) list_items.mouseover(function() { js_hover = ($(this).css('background-color') == 'rgba(0, 0, 0, 0)'); list_items.unbind('mouseover'); if(js_hover) { list_items.mouseover(function() { this.style.backgroundColor = '#FFC'; }).mouseout(function() { this.style.backgroundColor = 'transparent'; return true; }); } }); }()); // Made public for UI customization. // TODO: Group UI functions into a public svgEditor.ui interface. Editor.addDropDown = function(elem, callback, dropUp) { if ($(elem).length == 0) return; // Quit if called on non-existant element var button = $(elem).find('button'); var list = $(elem).find('ul').attr('id', $(elem)[0].id + '-list'); if(!dropUp) { // Move list to place where it can overflow container $('#option_lists').append(list); } var on_button = false; if(dropUp) { $(elem).addClass('dropup'); } list.find('li').bind('mouseup', callback); $(window).mouseup(function(evt) { if(!on_button) { button.removeClass('down'); list.hide(); } on_button = false; }); button.bind('mousedown',function() { if (!button.hasClass('down')) { button.addClass('down'); if(!dropUp) { var pos = $(elem).position(); list.css({ top: pos.top + 24, left: pos.left - 10 }); } list.show(); on_button = true; } else { button.removeClass('down'); list.hide(); } }).hover(function() { on_button = true; }).mouseout(function() { on_button = false; }); } // TODO: Combine this with addDropDown or find other way to optimize var addAltDropDown = function(elem, list, callback, opts) { var button = $(elem); var list = $(list); var on_button = false; var dropUp = opts.dropUp; if(dropUp) { $(elem).addClass('dropup'); } list.find('li').bind('mouseup', function() { if(opts.seticon) { setIcon('#cur_' + button[0].id , $(this).children()); $(this).addClass('current').siblings().removeClass('current'); } callback.apply(this, arguments); }); $(window).mouseup(function(evt) { if(!on_button) { button.removeClass('down'); list.hide(); list.css({top:0, left:0}); } on_button = false; }); var height = list.height(); $(elem).bind('mousedown',function() { var off = $(elem).offset(); if(dropUp) { off.top -= list.height(); off.left += 8; } else { off.top += $(elem).height(); } $(list).offset(off); if (!button.hasClass('down')) { button.addClass('down'); list.show(); on_button = true; return false; } else { button.removeClass('down'); // CSS position must be reset for Webkit list.hide(); list.css({top:0, left:0}); } }).hover(function() { on_button = true; }).mouseout(function() { on_button = false; }); if(opts.multiclick) { list.mousedown(function() { on_button = true; }); } } Editor.addDropDown('#font_family_dropdown', function() { var fam = $(this).text(); $('#font_family').val($(this).text()).change(); }); Editor.addDropDown('#opacity_dropdown', function() { if($(this).find('div').length) return; var perc = parseInt($(this).text().split('%')[0]); changeOpacity(false, perc); }, true); // For slider usage, see: http://jqueryui.com/demos/slider/ $("#opac_slider").slider({ start: function() { $('#opacity_dropdown li:not(.special)').hide(); }, stop: function() { $('#opacity_dropdown li').show(); $(window).mouseup(); }, slide: function(evt, ui){ changeOpacity(ui); } }); Editor.addDropDown('#blur_dropdown', $.noop); var slideStart = false; $("#blur_slider").slider({ max: 10, step: .1, stop: function(evt, ui) { slideStart = false; changeBlur(ui); $('#blur_dropdown li').show(); $(window).mouseup(); }, start: function() { slideStart = true; }, slide: function(evt, ui){ changeBlur(ui, null, slideStart); } }); Editor.addDropDown('#zoom_dropdown', function() { var item = $(this); var val = item.attr('data-val'); if(val) { zoomChanged(window, val); } else { changeZoom({value:parseInt(item.text())}); } }, true); addAltDropDown('#stroke_linecap', '#linecap_opts', function() { setStrokeOpt(this, true); }, {dropUp: true}); addAltDropDown('#stroke_linejoin', '#linejoin_opts', function() { setStrokeOpt(this, true); }, {dropUp: true}); addAltDropDown('#tool_position', '#position_opts', function() { var letter = this.id.replace('tool_pos','').charAt(0); svgCanvas.alignSelectedElements(letter, 'page'); }, {multiclick: true}); /* When a flyout icon is selected (if flyout) { - Change the icon - Make pressing the button run its stuff } - Run its stuff When its shortcut key is pressed - If not current in list, do as above , else: - Just run its stuff */ // Unfocus text input when workarea is mousedowned. (function() { var inp; var unfocus = function() { $(inp).blur(); } $('#svg_editor').find('button, select, input:not(#text)').focus(function() { inp = this; ui_context = 'toolbars'; workarea.mousedown(unfocus); }).blur(function() { ui_context = 'canvas'; workarea.unbind('mousedown', unfocus); // Go back to selecting text if in textedit mode if(svgCanvas.getMode() == 'textedit') { $('#text').focus(); } }); }()); var clickSelect = function() { if (toolButtonClick('#tool_select')) { svgCanvas.setMode('select'); $('#styleoverrides').text('#svgcanvas svg *{cursor:move;pointer-events:all}, #svgcanvas svg{cursor:default}'); } }; var clickFHPath = function() { if (toolButtonClick('#tool_fhpath')) { svgCanvas.setMode('fhpath'); } }; var clickLine = function() { if (toolButtonClick('#tool_line')) { svgCanvas.setMode('line'); } }; var clickSquare = function(){ if (toolButtonClick('#tool_square')) { svgCanvas.setMode('square'); } }; var clickRect = function(){ if (toolButtonClick('#tool_rect')) { svgCanvas.setMode('rect'); } }; var clickFHRect = function(){ if (toolButtonClick('#tool_fhrect')) { svgCanvas.setMode('fhrect'); } }; var clickCircle = function(){ if (toolButtonClick('#tool_circle')) { svgCanvas.setMode('circle'); } }; var clickEllipse = function(){ if (toolButtonClick('#tool_ellipse')) { svgCanvas.setMode('ellipse'); } }; var clickFHEllipse = function(){ if (toolButtonClick('#tool_fhellipse')) { svgCanvas.setMode('fhellipse'); } }; var clickImage = function(){ if (toolButtonClick('#tool_image')) { svgCanvas.setMode('image'); } }; var clickZoom = function(){ if (toolButtonClick('#tool_zoom')) { svgCanvas.setMode('zoom'); workarea.css('cursor', zoomInIcon); } }; var dblclickZoom = function(){ if (toolButtonClick('#tool_zoom')) { zoomImage(); setSelectMode(); } }; var clickText = function(){ if (toolButtonClick('#tool_text')) { svgCanvas.setMode('text'); } }; var clickPath = function(){ if (toolButtonClick('#tool_path')) { svgCanvas.setMode('path'); } }; // Delete is a contextual tool that only appears in the ribbon if // an element has been selected var deleteSelected = function() { if (selectedElement != null || multiselected) { svgCanvas.deleteSelectedElements(); } }; var cutSelected = function() { if (selectedElement != null || multiselected) { svgCanvas.cutSelectedElements(); } }; var copySelected = function() { if (selectedElement != null || multiselected) { svgCanvas.copySelectedElements(); } }; var pasteInCenter = function() { var zoom = svgCanvas.getZoom(); var x = (workarea[0].scrollLeft + workarea.width()/2)/zoom - svgCanvas.contentW; var y = (workarea[0].scrollTop + workarea.height()/2)/zoom - svgCanvas.contentH; svgCanvas.pasteElements('point', x, y); } var moveToTopSelected = function() { if (selectedElement != null) { svgCanvas.moveToTopSelectedElement(); } }; var moveToBottomSelected = function() { if (selectedElement != null) { svgCanvas.moveToBottomSelectedElement(); } }; var moveUpDownSelected = function(dir) { if (selectedElement != null) { svgCanvas.moveUpDownSelected(dir); } }; var convertToPath = function() { if (selectedElement != null) { svgCanvas.convertToPath(); } } var reorientPath = function() { if (selectedElement != null) { path.reorient(); } } var makeHyperlink = function() { if (selectedElement != null || multiselected) { $.prompt(uiStrings.notification.enterNewLinkURL, "http://", function(url) { if(url) svgCanvas.makeHyperlink(url); }); } } var moveSelected = function(dx,dy) { if (selectedElement != null || multiselected) { if(curConfig.gridSnapping) { // Use grid snap value regardless of zoom level var multi = svgCanvas.getZoom() * curConfig.snappingStep; dx *= multi; dy *= multi; } svgCanvas.moveSelectedElements(dx,dy); } }; var linkControlPoints = function() { var linked = !$('#tool_node_link').hasClass('push_button_pressed'); if (linked) $('#tool_node_link').addClass('push_button_pressed').removeClass('tool_button'); else $('#tool_node_link').removeClass('push_button_pressed').addClass('tool_button'); path.linkControlPoints(linked); } var clonePathNode = function() { if (path.getNodePoint()) { path.clonePathNode(); } }; var deletePathNode = function() { if (path.getNodePoint()) { path.deletePathNode(); } }; var addSubPath = function() { var button = $('#tool_add_subpath'); var sp = !button.hasClass('push_button_pressed'); if (sp) { button.addClass('push_button_pressed').removeClass('tool_button'); } else { button.removeClass('push_button_pressed').addClass('tool_button'); } path.addSubPath(sp); }; var opencloseSubPath = function() { path.opencloseSubPath(); } var selectNext = function() { svgCanvas.cycleElement(1); }; var selectPrev = function() { svgCanvas.cycleElement(0); }; var rotateSelected = function(cw,step) { if (selectedElement == null || multiselected) return; if(!cw) step *= -1; var new_angle = $('#angle').val()*1 + step; svgCanvas.setRotationAngle(new_angle); updateContextPanel(); }; var clickClear = function(){ var dims = curConfig.dimensions; $.confirm(uiStrings.notification.QwantToClear, function(ok) { if(!ok) return; setSelectMode(); svgCanvas.clear(); svgCanvas.setResolution(dims[0], dims[1]); updateCanvas(true); zoomImage(); populateLayers(); updateContextPanel(); prepPaints(); svgCanvas.runExtensions('onNewDocument'); }); }; var clickBold = function(){ svgCanvas.setBold( !svgCanvas.getBold() ); updateContextPanel(); return false; }; var clickItalic = function(){ svgCanvas.setItalic( !svgCanvas.getItalic() ); updateContextPanel(); return false; }; var clickSave = function(){ // In the future, more options can be provided here var saveOpts = { 'images': curPrefs.img_save, 'round_digits': 6 } svgCanvas.save(saveOpts); }; var clickExport = function() { // Open placeholder window (prevents popup) if(!customHandlers.pngsave) { var str = uiStrings.notification.loadingImage; exportWindow = window.open("data:text/html;charset=utf-8,<title>" + str + "<\/title><h1>" + str + "<\/h1>"); } if(window.canvg) { svgCanvas.rasterExport(); } else { $.getScript('/assets/canvg/rgbcolor.js', function() { $.getScript('/assets/canvg/canvg.js', function() { svgCanvas.rasterExport(); }); }); } } // by default, svgCanvas.open() is a no-op. // it is up to an extension mechanism (opera widget, etc) // to call setCustomHandlers() which will make it do something var clickOpen = function(){ svgCanvas.open(); }; var clickImport = function(){ }; var clickUndo = function(){ if (undoMgr.getUndoStackSize() > 0) { undoMgr.undo(); populateLayers(); } }; var clickRedo = function(){ if (undoMgr.getRedoStackSize() > 0) { undoMgr.redo(); populateLayers(); } }; var clickGroup = function(){ // group if (multiselected) { svgCanvas.groupSelectedElements(); } // ungroup else if(selectedElement){ svgCanvas.ungroupSelectedElement(); } }; var clickClone = function(){ svgCanvas.cloneSelectedElements(20,20); }; var clickAlign = function() { var letter = this.id.replace('tool_align','').charAt(0); svgCanvas.alignSelectedElements(letter, $('#align_relative_to').val()); }; var zoomImage = function(multiplier) { var res = svgCanvas.getResolution(); multiplier = multiplier?res.zoom * multiplier:1; // setResolution(res.w * multiplier, res.h * multiplier, true); $('#zoom').val(multiplier * 100); svgCanvas.setZoom(multiplier); zoomDone(); updateCanvas(true); }; var zoomDone = function() { // updateBgImage(); updateWireFrame(); //updateCanvas(); // necessary? } var clickWireframe = function() { var wf = !$('#tool_wireframe').hasClass('push_button_pressed'); if (wf) $('#tool_wireframe').addClass('push_button_pressed').removeClass('tool_button'); else $('#tool_wireframe').removeClass('push_button_pressed').addClass('tool_button'); workarea.toggleClass('wireframe'); if(supportsNonSS) return; var wf_rules = $('#wireframe_rules'); if(!wf_rules.length) { wf_rules = $('<style id="wireframe_rules"><\/style>').appendTo('head'); } else { wf_rules.empty(); } updateWireFrame(); } var updateWireFrame = function() { // Test support if(supportsNonSS) return; var rule = "#workarea.wireframe #svgcontent * { stroke-width: " + 1/svgCanvas.getZoom() + "px; }"; $('#wireframe_rules').text(workarea.hasClass('wireframe') ? rule : ""); } var showSourceEditor = function(e, forSaving){ if (editingsource) return; editingsource = true; $('#save_output_btns').toggle(!!forSaving); $('#tool_source_back').toggle(!forSaving); var str = orig_source = svgCanvas.getSvgString(); $('#svg_source_textarea').val(str); $('#svg_source_editor').fadeIn(); properlySourceSizeTextArea(); $('#svg_source_textarea').focus(); }; $('#svg_docprops_container, #svg_prefs_container').draggable({cancel:'button,fieldset', containment: 'window'}); var showDocProperties = function(){ if (docprops) return; docprops = true; // This selects the correct radio button by using the array notation $('#image_save_opts input').val([curPrefs.img_save]); // update resolution option with actual resolution var res = svgCanvas.getResolution(); if(curConfig.baseUnit !== "px") { res.w = svgedit.units.convertUnit(res.w) + curConfig.baseUnit; res.h = svgedit.units.convertUnit(res.h) + curConfig.baseUnit; } $('#canvas_width').val(res.w); $('#canvas_height').val(res.h); $('#canvas_title').val(svgCanvas.getDocumentTitle()); $('#svg_docprops').show(); }; var showPreferences = function(){ if (preferences) return; preferences = true; $('#main_menu').hide(); // Update background color with current one var blocks = $('#bg_blocks div'); var cur_bg = 'cur_background'; var canvas_bg = $.pref('bkgd_color'); var url = $.pref('bkgd_url'); // if(url) url = url[1]; blocks.each(function() { var blk = $(this); var is_bg = blk.css('background-color') == canvas_bg; blk.toggleClass(cur_bg, is_bg); if(is_bg) $('#canvas_bg_url').removeClass(cur_bg); }); if(!canvas_bg) blocks.eq(0).addClass(cur_bg); if(url) { $('#canvas_bg_url').val(url); } $('grid_snapping_step').attr('value', curConfig.snappingStep); if (curConfig.gridSnapping == true) { $('#grid_snapping_on').attr('checked', 'checked'); } else { $('#grid_snapping_on').removeAttr('checked'); } $('#svg_prefs').show(); }; var properlySourceSizeTextArea = function(){ // TODO: remove magic numbers here and get values from CSS var height = $('#svg_source_container').height() - 80; $('#svg_source_textarea').css('height', height); }; var saveSourceEditor = function(){ if (!editingsource) return; var saveChanges = function() { svgCanvas.clearSelection(); hideSourceEditor(); zoomImage(); populateLayers(); updateTitle(); prepPaints(); } if (!svgCanvas.setSvgString($('#svg_source_textarea').val())) { $.confirm(uiStrings.notification.QerrorsRevertToSource, function(ok) { if(!ok) return false; saveChanges(); }); } else { saveChanges(); } setSelectMode(); }; var updateTitle = function(title) { title = title || svgCanvas.getDocumentTitle(); var new_title = orig_title + (title?': ' + title:''); // Remove title update with current context info, isn't really necessary // if(cur_context) { // new_title = new_title + cur_context; // } $('title:first').text(new_title); } var saveDocProperties = function(){ // set title var new_title = $('#canvas_title').val(); updateTitle(new_title); svgCanvas.setDocumentTitle(new_title); // update resolution var width = $('#canvas_width'), w = width.val(); var height = $('#canvas_height'), h = height.val(); if(w != "fit" && !svgedit.units.isValidUnit('width', w)) { $.alert(uiStrings.notification.invalidAttrValGiven); width.parent().addClass('error'); return false; } width.parent().removeClass('error'); if(h != "fit" && !svgedit.units.isValidUnit('height', h)) { $.alert(uiStrings.notification.invalidAttrValGiven); height.parent().addClass('error'); return false; } height.parent().removeClass('error'); if(!svgCanvas.setResolution(w, h)) { $.alert(uiStrings.notification.noContentToFitTo); return false; } // set image save option curPrefs.img_save = $('#image_save_opts :checked').val(); $.pref('img_save',curPrefs.img_save); updateCanvas(); hideDocProperties(); }; var savePreferences = function() { // set background var color = $('#bg_blocks div.cur_background').css('background-color') || '#FFF'; setBackground(color, $('#canvas_bg_url').val()); // set language var lang = $('#lang_select').val(); if(lang != curPrefs.lang) { Editor.putLocale(lang); } // set icon size setIconSize($('#iconsize').val()); // set grid setting curConfig.gridSnapping = $('#grid_snapping_on')[0].checked; curConfig.snappingStep = $('#grid_snapping_step').val(); curConfig.showRulers = $('#show_rulers')[0].checked; $('#rulers').toggle(curConfig.showRulers); if(curConfig.showRulers) updateRulers(); curConfig.baseUnit = $('#base_unit').val(); svgCanvas.setConfig(curConfig); updateCanvas(); hidePreferences(); } function setBackground(color, url) { // if(color == curPrefs.bkgd_color && url == curPrefs.bkgd_url) return; $.pref('bkgd_color', color); $.pref('bkgd_url', url); // This should be done in svgcanvas.js for the borderRect fill svgCanvas.setBackground(color, url); } var setIcon = Editor.setIcon = function(elem, icon_id, forcedSize) { var icon = (typeof icon_id === 'string') ? $.getSvgIcon(icon_id, true) : icon_id.clone(); if(!icon) { console.log('NOTE: Icon image missing: ' + icon_id); return; } $(elem).empty().append(icon); } var ua_prefix; (ua_prefix = function() { var regex = /^(Moz|Webkit|Khtml|O|ms|Icab)(?=[A-Z])/; var someScript = document.getElementsByTagName('script')[0]; for(var prop in someScript.style) { if(regex.test(prop)) { // test is faster than match, so it's better to perform // that on the lot and match only when necessary return prop.match(regex)[0]; } } // Nothing found so far? if('WebkitOpacity' in someScript.style) return 'Webkit'; if('KhtmlOpacity' in someScript.style) return 'Khtml'; return ''; }()); var scaleElements = function(elems, scale) { var prefix = '-' + ua_prefix.toLowerCase() + '-'; var sides = ['top', 'left', 'bottom', 'right']; elems.each(function() { // console.log('go', scale); // Handled in CSS // this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')'; var el = $(this); var w = el.outerWidth() * (scale - 1); var h = el.outerHeight() * (scale - 1); var margins = {}; for(var i = 0; i < 4; i++) { var s = sides[i]; var cur = el.data('orig_margin-' + s); if(cur == null) { cur = parseInt(el.css('margin-' + s)); // Cache the original margin el.data('orig_margin-' + s, cur); } var val = cur * scale; if(s === 'right') { val += w; } else if(s === 'bottom') { val += h; } el.css('margin-' + s, val); // el.css('outline', '1px solid red'); } }); } var setIconSize = Editor.setIconSize = function(size, force) { if(size == curPrefs.size && !force) return; // return; // var elems = $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open'); console.log('size', size); var sel_toscale = '#tools_top .toolset, #editor_panel > *, #history_panel > *,\ #main_button, #tools_left > *, #path_node_panel > *, #multiselected_panel > *,\ #g_panel > *, #tool_font_size > *, .tools_flyout'; var elems = $(sel_toscale); var scale = 1; if(typeof size == 'number') { scale = size; } else { var icon_sizes = { s:.75, m:1, l:1.25, xl:1.5 }; scale = icon_sizes[size]; } Editor.tool_scale = tool_scale = scale; setFlyoutPositions(); // $('.tools_flyout').each(function() { // var pos = $(this).position(); // console.log($(this), pos.left+(34 * scale)); // $(this).css({'left': pos.left+(34 * scale), 'top': pos.top+(77 * scale)}); // console.log('l', $(this).css('left')); // }); // var scale = .75;//0.75; var hidden_ps = elems.parents(':hidden'); hidden_ps.css('visibility', 'hidden').show(); scaleElements(elems, scale); hidden_ps.css('visibility', 'visible').hide(); // console.timeEnd('elems'); // return; $.pref('iconsize', size); $('#iconsize').val(size); // Change icon size // $('.tool_button, .push_button, .tool_button_current, .disabled, .icon_label, #url_notice, #tool_open') // .find('> svg, > img').each(function() { // this.setAttribute('width',size_num); // this.setAttribute('height',size_num); // }); // // $.resizeSvgIcons({ // '.flyout_arrow_horiz > svg, .flyout_arrow_horiz > img': size_num / 5, // '#logo > svg, #logo > img': size_num * 1.3, // '#tools_bottom .icon_label > *': (size_num === 16 ? 18 : size_num * .75) // }); // if(size != 's') { // $.resizeSvgIcons({'#layerbuttons svg, #layerbuttons img': size_num * .6}); // } // Note that all rules will be prefixed with '#svg_editor' when parsed var cssResizeRules = { // ".tool_button,\ // .push_button,\ // .tool_button_current,\ // .push_button_pressed,\ // .disabled,\ // .icon_label,\ // .tools_flyout .tool_button": { // 'width': {s: '16px', l: '32px', xl: '48px'}, // 'height': {s: '16px', l: '32px', xl: '48px'}, // 'padding': {s: '1px', l: '2px', xl: '3px'} // }, // ".tool_sep": { // 'height': {s: '16px', l: '32px', xl: '48px'}, // 'margin': {s: '2px 2px', l: '2px 5px', xl: '2px 8px'} // }, // "#main_icon": { // 'width': {s: '31px', l: '53px', xl: '75px'}, // 'height': {s: '22px', l: '42px', xl: '64px'} // }, "#tools_top": { 'left': 50, 'height': 72 }, "#tools_left": { 'width': 31, 'top': 74 }, "div#workarea": { 'left': 38, 'top': 74 } // "#tools_bottom": { // 'left': {s: '27px', l: '46px', xl: '65px'}, // 'height': {s: '58px', l: '98px', xl: '145px'} // }, // "#color_tools": { // 'border-spacing': {s: '0 1px'}, // 'margin-top': {s: '-1px'} // }, // "#color_tools .icon_label": { // 'width': {l:'43px', xl: '60px'} // }, // ".color_tool": { // 'height': {s: '20px'} // }, // "#tool_opacity": { // 'top': {s: '1px'}, // 'height': {s: 'auto', l:'auto', xl:'auto'} // }, // "#tools_top input, #tools_bottom input": { // 'margin-top': {s: '2px', l: '4px', xl: '5px'}, // 'height': {s: 'auto', l: 'auto', xl: 'auto'}, // 'border': {s: '1px solid #555', l: 'auto', xl: 'auto'}, // 'font-size': {s: '.9em', l: '1.2em', xl: '1.4em'} // }, // "#zoom_panel": { // 'margin-top': {s: '3px', l: '4px', xl: '5px'} // }, // "#copyright, #tools_bottom .label": { // 'font-size': {l: '1.5em', xl: '2em'}, // 'line-height': {s: '15px'} // }, // "#tools_bottom_2": { // 'width': {l: '295px', xl: '355px'}, // 'top': {s: '4px'} // }, // "#tools_top > div, #tools_top": { // 'line-height': {s: '17px', l: '34px', xl: '50px'} // }, // ".dropdown button": { // 'height': {s: '18px', l: '34px', xl: '40px'}, // 'line-height': {s: '18px', l: '34px', xl: '40px'}, // 'margin-top': {s: '3px'} // }, // "#tools_top label, #tools_bottom label": { // 'font-size': {s: '1em', l: '1.5em', xl: '2em'}, // 'height': {s: '25px', l: '42px', xl: '64px'} // }, // "div.toolset": { // 'height': {s: '25px', l: '42px', xl: '64px'} // }, // "#tool_bold, #tool_italic": { // 'font-size': {s: '1.5em', l: '3em', xl: '4.5em'} // }, // "#sidepanels": { // 'top': {s: '50px', l: '88px', xl: '125px'}, // 'bottom': {s: '51px', l: '68px', xl: '65px'} // }, // '#layerbuttons': { // 'width': {l: '130px', xl: '175px'}, // 'height': {l: '24px', xl: '30px'} // }, // '#layerlist': { // 'width': {l: '128px', xl: '150px'} // }, // '.layer_button': { // 'width': {l: '19px', xl: '28px'}, // 'height': {l: '19px', xl: '28px'} // }, // "input.spin-button": { // 'background-image': {l: "url('/assets/images/spinbtn_updn_big.png')", xl: "url('/assets/images/spinbtn_updn_big.png')"}, // 'background-position': {l: '100% -5px', xl: '100% -2px'}, // 'padding-right': {l: '24px', xl: '24px' } // }, // "input.spin-button.up": { // 'background-position': {l: '100% -45px', xl: '100% -42px'} // }, // "input.spin-button.down": { // 'background-position': {l: '100% -85px', xl: '100% -82px'} // }, // "#position_opts": { // 'width': {all: (size_num*4) +'px'} // } }; var rule_elem = $('#tool_size_rules'); if(!rule_elem.length) { rule_elem = $('<style id="tool_size_rules"><\/style>').appendTo('head'); } else { rule_elem.empty(); } if(size != 'm') { var style_str = ''; $.each(cssResizeRules, function(selector, rules) { selector = '#svg_editor ' + selector.replace(/,/g,', #svg_editor'); style_str += selector + '{'; $.each(rules, function(prop, values) { if(typeof values === 'number') { var val = (values * scale) + 'px'; } else if(values[size] || values.all) { var val = (values[size] || values.all); } style_str += (prop + ':' + val + ';'); }); style_str += '}'; }); //this.style[ua_prefix + 'Transform'] = 'scale(' + scale + ')'; var prefix = '-' + ua_prefix.toLowerCase() + '-'; style_str += (sel_toscale + '{' + prefix + 'transform: scale(' + scale + ');}' + ' #svg_editor div.toolset .toolset {' + prefix + 'transform: scale(1); margin: 1px !important;}' // Hack for markers + ' #svg_editor .ui-slider {' + prefix + 'transform: scale(' + (1/scale) + ');}' // Hack for sliders ); rule_elem.text(style_str); } setFlyoutPositions(); } var cancelOverlays = function() { $('#dialog_box').hide(); if (!editingsource && !docprops && !preferences) { if(cur_context) { svgCanvas.leaveContext(); } return; }; if (editingsource) { if (orig_source !== $('#svg_source_textarea').val()) { $.confirm(uiStrings.notification.QignoreSourceChanges, function(ok) { if(ok) hideSourceEditor(); }); } else { hideSourceEditor(); } } else if (docprops) { hideDocProperties(); } else if (preferences) { hidePreferences(); } resetScrollPos(); }; var hideSourceEditor = function(){ $('#svg_source_editor').hide(); editingsource = false; $('#svg_source_textarea').blur(); }; var hideDocProperties = function(){ $('#svg_docprops').hide(); $('#canvas_width,#canvas_height').removeAttr('disabled'); $('#resolution')[0].selectedIndex = 0; $('#image_save_opts input').val([curPrefs.img_save]); docprops = false; }; var hidePreferences = function(){ $('#svg_prefs').hide(); preferences = false; }; var win_wh = {width:$(window).width(), height:$(window).height()}; var resetScrollPos = $.noop, curScrollPos; // Fix for Issue 781: Drawing area jumps to top-left corner on window resize (IE9) if(svgedit.browser.isIE()) { (function() { resetScrollPos = function() { if(workarea[0].scrollLeft === 0 && workarea[0].scrollTop === 0) { workarea[0].scrollLeft = curScrollPos.left; workarea[0].scrollTop = curScrollPos.top; } } curScrollPos = { left: workarea[0].scrollLeft, top: workarea[0].scrollTop }; $(window).resize(resetScrollPos); svgEditor.ready(function() { // TODO: Find better way to detect when to do this to minimize // flickering effect setTimeout(function() { resetScrollPos(); }, 500); }); workarea.scroll(function() { curScrollPos = { left: workarea[0].scrollLeft, top: workarea[0].scrollTop }; }); }()); } $(window).resize(function(evt) { if (editingsource) { properlySourceSizeTextArea(); } $.each(win_wh, function(type, val) { var curval = $(window)[type](); workarea[0]['scroll' + (type==='width'?'Left':'Top')] -= (curval - val)/2; win_wh[type] = curval; }); }); (function() { workarea.scroll(function() { // TODO: jQuery's scrollLeft/Top() wouldn't require a null check if ($('#ruler_x').length != 0) { $('#ruler_x')[0].scrollLeft = workarea[0].scrollLeft; } if ($('#ruler_y').length != 0) { $('#ruler_y')[0].scrollTop = workarea[0].scrollTop; } }); }()); $('#url_notice').click(function() { $.alert(this.title); }); $('#change_image_url').click(promptImgURL); function promptImgURL() { var curhref = svgCanvas.getHref(selectedElement); curhref = curhref.indexOf("data:") === 0?"":curhref; $.prompt(uiStrings.notification.enterNewImgURL, curhref, function(url) { if(url) setImageURL(url); }); } // added these event handlers for all the push buttons so they // behave more like buttons being pressed-in and not images (function() { var toolnames = ['clear','open','save','source','delete','delete_multi','paste','clone','clone_multi','move_top','move_bottom']; var all_tools = ''; var cur_class = 'tool_button_current'; $.each(toolnames, function(i,item) { all_tools += '#tool_' + item + (i==toolnames.length-1?',':''); }); $(all_tools).mousedown(function() { $(this).addClass(cur_class); }).bind('mousedown mouseout', function() { $(this).removeClass(cur_class); }); $('#tool_undo, #tool_redo').mousedown(function(){ if (!$(this).hasClass('disabled')) $(this).addClass(cur_class); }).bind('mousedown mouseout',function(){ $(this).removeClass(cur_class);} ); }()); // switch modifier key in tooltips if mac // NOTE: This code is not used yet until I can figure out how to successfully bind ctrl/meta // in Opera and Chrome if (isMac && !window.opera) { var shortcutButtons = ["tool_clear", "tool_save", "tool_source", "tool_undo", "tool_redo", "tool_clone"]; var i = shortcutButtons.length; while (i--) { var button = document.getElementById(shortcutButtons[i]); if (button != null) { var title = button.title; var index = title.indexOf("Ctrl+"); button.title = [title.substr(0, index), "Cmd+", title.substr(index + 5)].join(''); } } } // TODO: go back to the color boxes having white background-color and then setting // background-image to none.png (otherwise partially transparent gradients look weird) var colorPicker = function(elem) { var picker = elem.attr('id') == 'stroke_color' ? 'stroke' : 'fill'; // var opacity = (picker == 'stroke' ? $('#stroke_opacity') : $('#fill_opacity')); var paint = paintBox[picker].paint; var title = (picker == 'stroke' ? 'Pick a Stroke Paint and Opacity' : 'Pick a Fill Paint and Opacity'); var was_none = false; var pos = elem.offset(); $("#color_picker") .draggable({cancel:'.jGraduate_tabs, .jGraduate_colPick, .jGraduate_gradPick, .jPicker', containment: 'window'}) .css(curConfig.colorPickerCSS || {'left': pos.left-140, 'bottom': 40}) .jGraduate( { paint: paint, window: { pickerTitle: title }, images: { clientPath: curConfig.jGraduatePath }, newstop: 'inverse' }, function(p) { paint = new $.jGraduate.Paint(p); paintBox[picker].setPaint(paint); svgCanvas.setPaint(picker, paint); $('#color_picker').hide(); }, function(p) { $('#color_picker').hide(); }); }; var updateToolButtonState = function() { var bNoFill = (svgCanvas.getColor('fill') == 'none'); var bNoStroke = (svgCanvas.getColor('stroke') == 'none'); var buttonsNeedingStroke = [ '#tool_fhpath', '#tool_line' ]; var buttonsNeedingFillAndStroke = [ '#tools_rect .tool_button', '#tools_ellipse .tool_button', '#tool_text', '#tool_path']; if (bNoStroke) { for (var index in buttonsNeedingStroke) { var button = buttonsNeedingStroke[index]; if ($(button).hasClass('tool_button_current')) { clickSelect(); } $(button).addClass('disabled'); } } else { for (var index in buttonsNeedingStroke) { var button = buttonsNeedingStroke[index]; $(button).removeClass('disabled'); } } if (bNoStroke && bNoFill) { for (var index in buttonsNeedingFillAndStroke) { var button = buttonsNeedingFillAndStroke[index]; if ($(button).hasClass('tool_button_current')) { clickSelect(); } $(button).addClass('disabled'); } } else { for (var index in buttonsNeedingFillAndStroke) { var button = buttonsNeedingFillAndStroke[index]; $(button).removeClass('disabled'); } } svgCanvas.runExtensions("toolButtonStateUpdate", { nofill: bNoFill, nostroke: bNoStroke }); // Disable flyouts if all inside are disabled $('.tools_flyout').each(function() { var shower = $('#' + this.id + '_show'); var has_enabled = false; $(this).children().each(function() { if(!$(this).hasClass('disabled')) { has_enabled = true; } }); shower.toggleClass('disabled', !has_enabled); }); operaRepaint(); }; var PaintBox = function(container, type) { var cur = curConfig[type === 'fill' ? 'initFill' : 'initStroke']; // set up gradients to be used for the buttons var svgdocbox = new DOMParser().parseFromString( '<svg xmlns="http://www.w3.org/2000/svg"><rect width="16.5" height="16.5"\ fill="#' + cur.color + '" opacity="' + cur.opacity + '"/>\ <defs><linearGradient id="gradbox_"/></defs></svg>', 'text/xml'); var docElem = svgdocbox.documentElement; docElem = $(container)[0].appendChild(document.importNode(docElem, true)); docElem.setAttribute('width',16.5); this.rect = docElem.firstChild; this.defs = docElem.getElementsByTagName('defs')[0]; this.grad = this.defs.firstChild; this.paint = new $.jGraduate.Paint({solidColor: cur.color}); this.type = type; this.setPaint = function(paint, apply) { this.paint = paint; var fillAttr = "none"; var ptype = paint.type; var opac = paint.alpha / 100; switch ( ptype ) { case 'solidColor': fillAttr = (paint[ptype] != 'none') ? "#" + paint[ptype] : paint[ptype]; break; case 'linearGradient': case 'radialGradient': this.defs.removeChild(this.grad); this.grad = this.defs.appendChild(paint[ptype]); var id = this.grad.id = 'gradbox_' + this.type; fillAttr = "url(#" + id + ')'; } this.rect.setAttribute('fill', fillAttr); this.rect.setAttribute('opacity', opac); if(apply) { svgCanvas.setColor(this.type, paintColor, true); svgCanvas.setPaintOpacity(this.type, paintOpacity, true); } } this.update = function(apply) { if(!selectedElement) return; var type = this.type; switch ( selectedElement.tagName ) { case 'use': case 'image': case 'foreignObject': // These elements don't have fill or stroke, so don't change // the current value return; case 'g': case 'a': var gPaint = null; var childs = selectedElement.getElementsByTagName('*'); for(var i = 0, len = childs.length; i < len; i++) { var elem = childs[i]; var p = elem.getAttribute(type); if(i === 0) { gPaint = p; } else if(gPaint !== p) { gPaint = null; break; } } if(gPaint === null) { // No common color, don't update anything var paintColor = null; return; } var paintColor = gPaint; var paintOpacity = 1; break; default: var paintOpacity = parseFloat(selectedElement.getAttribute(type + "-opacity")); if (isNaN(paintOpacity)) { paintOpacity = 1.0; } var defColor = type === "fill" ? "black" : "none"; var paintColor = selectedElement.getAttribute(type) || defColor; } if(apply) { svgCanvas.setColor(type, paintColor, true); svgCanvas.setPaintOpacity(type, paintOpacity, true); } paintOpacity *= 100; var paint = getPaint(paintColor, paintOpacity, type); // update the rect inside #fill_color/#stroke_color this.setPaint(paint); } this.prep = function() { var ptype = this.paint.type; switch ( ptype ) { case 'linearGradient': case 'radialGradient': var paint = new $.jGraduate.Paint({copy: this.paint}); svgCanvas.setPaint(type, paint); } } }; paintBox.fill = new PaintBox('#fill_color', 'fill'); paintBox.stroke = new PaintBox('#stroke_color', 'stroke'); $('#stroke_width').val(curConfig.initStroke.width); $('#group_opacity').val(curConfig.initOpacity * 100); // Use this SVG elem to test vectorEffect support var test_el = paintBox.fill.rect.cloneNode(false); test_el.setAttribute('style','vector-effect:non-scaling-stroke'); var supportsNonSS = (test_el.style.vectorEffect === 'non-scaling-stroke'); test_el.removeAttribute('style'); var svgdocbox = paintBox.fill.rect.ownerDocument; // Use this to test support for blur element. Seems to work to test support in Webkit var blur_test = svgdocbox.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur'); if(typeof blur_test.stdDeviationX === "undefined") { $('#tool_blur').hide(); } $(blur_test).remove(); // Test for zoom icon support (function() { var pre = '-' + ua_prefix.toLowerCase() + '-zoom-'; var zoom = pre + 'in'; workarea.css('cursor', zoom); if(workarea.css('cursor') === zoom) { zoomInIcon = zoom; zoomOutIcon = pre + 'out'; } workarea.css('cursor', 'auto'); }()); // Test for embedImage support (use timeout to not interfere with page load) setTimeout(function() { svgCanvas.embedImage('/assets/images/logo.png', function(datauri) { if(!datauri) { // Disable option $('#image_save_opts [value=embed]').attr('disabled','disabled'); $('#image_save_opts input').val(['ref']); curPrefs.img_save = 'ref'; $('#image_opt_embed').css('color','#666').attr('title',uiStrings.notification.featNotSupported); } }); },1000); $('#fill_color, #tool_fill .icon_label').click(function(){ colorPicker($('#fill_color')); updateToolButtonState(); }); $('#stroke_color, #tool_stroke .icon_label').click(function(){ colorPicker($('#stroke_color')); updateToolButtonState(); }); $('#group_opacityLabel').click(function() { $('#opacity_dropdown button').mousedown(); $(window).mouseup(); }); $('#zoomLabel').click(function() { $('#zoom_dropdown button').mousedown(); $(window).mouseup(); }); $('#tool_move_top').mousedown(function(evt){ $('#tools_stacking').show(); evt.preventDefault(); }); $('.layer_button').mousedown(function() { $(this).addClass('layer_buttonpressed'); }).mouseout(function() { $(this).removeClass('layer_buttonpressed'); }).mouseup(function() { $(this).removeClass('layer_buttonpressed'); }); $('.push_button').mousedown(function() { if (!$(this).hasClass('disabled')) { $(this).addClass('push_button_pressed').removeClass('push_button'); } }).mouseout(function() { $(this).removeClass('push_button_pressed').addClass('push_button'); }).mouseup(function() { $(this).removeClass('push_button_pressed').addClass('push_button'); }); $('#layer_new').click(function() { var i = svgCanvas.getCurrentDrawing().getNumLayers(); do { var uniqName = uiStrings.layers.layer + " " + ++i; } while(svgCanvas.getCurrentDrawing().hasLayer(uniqName)); $.prompt(uiStrings.notification.enterUniqueLayerName,uniqName, function(newName) { if (!newName) return; if (svgCanvas.getCurrentDrawing().hasLayer(newName)) { $.alert(uiStrings.notification.dupeLayerName); return; } svgCanvas.createLayer(newName); updateContextPanel(); populateLayers(); }); }); function deleteLayer() { if (svgCanvas.deleteCurrentLayer()) { updateContextPanel(); populateLayers(); // This matches what SvgCanvas does // TODO: make this behavior less brittle (svg-editor should get which // layer is selected from the canvas and then select that one in the UI) $('#layerlist tr.layer').removeClass("layersel"); $('#layerlist tr.layer:first').addClass("layersel"); } } function cloneLayer() { var name = svgCanvas.getCurrentDrawing().getCurrentLayerName() + ' copy'; $.prompt(uiStrings.notification.enterUniqueLayerName, name, function(newName) { if (!newName) return; if (svgCanvas.getCurrentDrawing().hasLayer(newName)) { $.alert(uiStrings.notification.dupeLayerName); return; } svgCanvas.cloneLayer(newName); updateContextPanel(); populateLayers(); }); } function mergeLayer() { if($('#layerlist tr.layersel').index() == svgCanvas.getCurrentDrawing().getNumLayers()-1) return; svgCanvas.mergeLayer(); updateContextPanel(); populateLayers(); } function moveLayer(pos) { var curIndex = $('#layerlist tr.layersel').index(); var total = svgCanvas.getCurrentDrawing().getNumLayers(); if(curIndex > 0 || curIndex < total-1) { curIndex += pos; svgCanvas.setCurrentLayerPosition(total-curIndex-1); populateLayers(); } } $('#layer_delete').click(deleteLayer); $('#layer_up').click(function() { moveLayer(-1); }); $('#layer_down').click(function() { moveLayer(1); }); $('#layer_rename').click(function() { var curIndex = $('#layerlist tr.layersel').prevAll().length; var oldName = $('#layerlist tr.layersel td.layername').text(); $.prompt(uiStrings.notification.enterNewLayerName,"", function(newName) { if (!newName) return; if (oldName == newName || svgCanvas.getCurrentDrawing().hasLayer(newName)) { $.alert(uiStrings.notification.layerHasThatName); return; } svgCanvas.renameCurrentLayer(newName); populateLayers(); }); }); var SIDEPANEL_MAXWIDTH = 300; var SIDEPANEL_OPENWIDTH = 150; var sidedrag = -1, sidedragging = false, allowmove = false; var resizePanel = function(evt) { if (!allowmove) return; if (sidedrag == -1) return; sidedragging = true; var deltax = sidedrag - evt.pageX; var sidepanels = $('#sidepanels'); var sidewidth = parseInt(sidepanels.css('width')); if (sidewidth+deltax > SIDEPANEL_MAXWIDTH) { deltax = SIDEPANEL_MAXWIDTH - sidewidth; sidewidth = SIDEPANEL_MAXWIDTH; } else if (sidewidth+deltax < 2) { deltax = 2 - sidewidth; sidewidth = 2; } if (deltax == 0) return; sidedrag -= deltax; var layerpanel = $('#layerpanel'); workarea.css('right', parseInt(workarea.css('right'))+deltax); sidepanels.css('width', parseInt(sidepanels.css('width'))+deltax); layerpanel.css('width', parseInt(layerpanel.css('width'))+deltax); var ruler_x = $('#ruler_x'); ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax); } $('#sidepanel_handle') .mousedown(function(evt) { sidedrag = evt.pageX; $(window).mousemove(resizePanel); allowmove = false; // Silly hack for Chrome, which always runs mousemove right after mousedown setTimeout(function() { allowmove = true; }, 20); }) .mouseup(function(evt) { if (!sidedragging) toggleSidePanel(); sidedrag = -1; sidedragging = false; }); $(window).mouseup(function() { sidedrag = -1; sidedragging = false; $('#svg_editor').unbind('mousemove', resizePanel); }); // if width is non-zero, then fully close it, otherwise fully open it // the optional close argument forces the side panel closed var toggleSidePanel = function(close){ var w = parseInt($('#sidepanels').css('width')); var deltax = (w > 2 || close ? 2 : SIDEPANEL_OPENWIDTH) - w; var sidepanels = $('#sidepanels'); var layerpanel = $('#layerpanel'); var ruler_x = $('#ruler_x'); workarea.css('right', parseInt(workarea.css('right')) + deltax); sidepanels.css('width', parseInt(sidepanels.css('width')) + deltax); layerpanel.css('width', parseInt(layerpanel.css('width')) + deltax); ruler_x.css('right', parseInt(ruler_x.css('right')) + deltax); }; // this function highlights the layer passed in (by fading out the other layers) // if no layer is passed in, this function restores the other layers var toggleHighlightLayer = function(layerNameToHighlight) { var curNames = new Array(svgCanvas.getCurrentDrawing().getNumLayers()); for (var i = 0; i < curNames.length; ++i) { curNames[i] = svgCanvas.getCurrentDrawing().getLayerName(i); } if (layerNameToHighlight) { for (var i = 0; i < curNames.length; ++i) { if (curNames[i] != layerNameToHighlight) { svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 0.5); } } } else { for (var i = 0; i < curNames.length; ++i) { svgCanvas.getCurrentDrawing().setLayerOpacity(curNames[i], 1.0); } } }; var populateLayers = function(){ var layerlist = $('#layerlist tbody'); var selLayerNames = $('#selLayerNames'); layerlist.empty(); selLayerNames.empty(); var currentLayerName = svgCanvas.getCurrentDrawing().getCurrentLayerName(); var layer = svgCanvas.getCurrentDrawing().getNumLayers(); var icon = $.getSvgIcon('eye'); // we get the layers in the reverse z-order (the layer rendered on top is listed first) while (layer--) { var name = svgCanvas.getCurrentDrawing().getLayerName(layer); // contenteditable=\"true\" var appendstr = "<tr class=\"layer"; if (name == currentLayerName) { appendstr += " layersel" } appendstr += "\">"; if (svgCanvas.getCurrentDrawing().getLayerVisibility(name)) { appendstr += "<td class=\"layervis\"/><td class=\"layername\" >" + name + "</td></tr>"; } else { appendstr += "<td class=\"layervis layerinvis\"/><td class=\"layername\" >" + name + "</td></tr>"; } layerlist.append(appendstr); selLayerNames.append("<option value=\"" + name + "\">" + name + "</option>"); } if(icon !== undefined) { var copy = icon.clone(); $('td.layervis',layerlist).append(icon.clone()); $.resizeSvgIcons({'td.layervis .svg_icon':14}); } // handle selection of layer $('#layerlist td.layername') .mouseup(function(evt){ $('#layerlist tr.layer').removeClass("layersel"); var row = $(this.parentNode); row.addClass("layersel"); svgCanvas.setCurrentLayer(this.textContent); evt.preventDefault(); }) .mouseover(function(evt){ $(this).css({"font-style": "italic", "color":"blue"}); toggleHighlightLayer(this.textContent); }) .mouseout(function(evt){ $(this).css({"font-style": "normal", "color":"black"}); toggleHighlightLayer(); }); $('#layerlist td.layervis').click(function(evt){ var row = $(this.parentNode).prevAll().length; var name = $('#layerlist tr.layer:eq(' + row + ') td.layername').text(); var vis = $(this).hasClass('layerinvis'); svgCanvas.setLayerVisibility(name, vis); if (vis) { $(this).removeClass('layerinvis'); } else { $(this).addClass('layerinvis'); } }); // if there were too few rows, let's add a few to make it not so lonely var num = 5 - $('#layerlist tr.layer').size(); while (num-- > 0) { // FIXME: there must a better way to do this layerlist.append("<tr><td style=\"color:white\">_</td><td/></tr>"); } }; populateLayers(); // function changeResolution(x,y) { // var zoom = svgCanvas.getResolution().zoom; // setResolution(x * zoom, y * zoom); // } var centerCanvas = function() { // this centers the canvas vertically in the workarea (horizontal handled in CSS) workarea.css('line-height', workarea.height() + 'px'); }; $(window).bind('load resize', centerCanvas); function stepFontSize(elem, step) { var orig_val = elem.value-0; var sug_val = orig_val + step; var increasing = sug_val >= orig_val; if(step === 0) return orig_val; if(orig_val >= 24) { if(increasing) { return Math.round(orig_val * 1.1); } else { return Math.round(orig_val / 1.1); } } else if(orig_val <= 1) { if(increasing) { return orig_val * 2; } else { return orig_val / 2; } } else { return sug_val; } } function stepZoom(elem, step) { var orig_val = elem.value-0; if(orig_val === 0) return 100; var sug_val = orig_val + step; if(step === 0) return orig_val; if(orig_val >= 100) { return sug_val; } else { if(sug_val >= orig_val) { return orig_val * 2; } else { return orig_val / 2; } } } // function setResolution(w, h, center) { // updateCanvas(); // // w-=0; h-=0; // // $('#svgcanvas').css( { 'width': w, 'height': h } ); // // $('#canvas_width').val(w); // // $('#canvas_height').val(h); // // // // if(center) { // // var w_area = workarea; // // var scroll_y = h/2 - w_area.height()/2; // // var scroll_x = w/2 - w_area.width()/2; // // w_area[0].scrollTop = scroll_y; // // w_area[0].scrollLeft = scroll_x; // // } // } $('#resolution').change(function(){ var wh = $('#canvas_width,#canvas_height'); if(!this.selectedIndex) { if($('#canvas_width').val() == 'fit') { wh.removeAttr("disabled").val(100); } } else if(this.value == 'content') { wh.val('fit').attr("disabled","disabled"); } else { var dims = this.value.split('x'); $('#canvas_width').val(dims[0]); $('#canvas_height').val(dims[1]); wh.removeAttr("disabled"); } }); //Prevent browser from erroneously repopulating fields $('input,select').attr("autocomplete","off"); // Associate all button actions as well as non-button keyboard shortcuts var Actions = function() { // sel:'selector', fn:function, evt:'event', key:[key, preventDefault, NoDisableInInput] var tool_buttons = [ {sel:'#tool_select', fn: clickSelect, evt: 'click', key: ['V', true]}, {sel:'#tool_fhpath', fn: clickFHPath, evt: 'click', key: ['Q', true]}, {sel:'#tool_line', fn: clickLine, evt: 'click', key: ['L', true]}, {sel:'#tool_rect', fn: clickRect, evt: 'mouseup', key: ['R', true], parent: '#tools_rect', icon: 'rect'}, {sel:'#tool_square', fn: clickSquare, evt: 'mouseup', parent: '#tools_rect', icon: 'square'}, {sel:'#tool_fhrect', fn: clickFHRect, evt: 'mouseup', parent: '#tools_rect', icon: 'fh_rect'}, {sel:'#tool_ellipse', fn: clickEllipse, evt: 'mouseup', key: ['E', true], parent: '#tools_ellipse', icon: 'ellipse'}, {sel:'#tool_circle', fn: clickCircle, evt: 'mouseup', parent: '#tools_ellipse', icon: 'circle'}, {sel:'#tool_fhellipse', fn: clickFHEllipse, evt: 'mouseup', parent: '#tools_ellipse', icon: 'fh_ellipse'}, {sel:'#tool_path', fn: clickPath, evt: 'click', key: ['P', true]}, {sel:'#tool_text', fn: clickText, evt: 'click', key: ['T', true]}, {sel:'#tool_image', fn: clickImage, evt: 'mouseup'}, {sel:'#tool_zoom', fn: clickZoom, evt: 'mouseup', key: ['Z', true]}, {sel:'#tool_clear', fn: clickClear, evt: 'mouseup', key: ['N', true]}, {sel:'#tool_save', fn: function() { editingsource?saveSourceEditor():clickSave()}, evt: 'mouseup', key: ['S', true]}, {sel:'#tool_export', fn: clickExport, evt: 'mouseup'}, {sel:'#tool_open', fn: clickOpen, evt: 'mouseup', key: ['O', true]}, {sel:'#tool_import', fn: clickImport, evt: 'mouseup'}, {sel:'#tool_source', fn: showSourceEditor, evt: 'click', key: ['U', true]}, {sel:'#tool_wireframe', fn: clickWireframe, evt: 'click', key: ['F', true]}, {sel:'#tool_source_cancel,#svg_source_overlay,#tool_docprops_cancel,#tool_prefs_cancel', fn: cancelOverlays, evt: 'click', key: ['esc', false, false], hidekey: true}, {sel:'#tool_source_save', fn: saveSourceEditor, evt: 'click'}, {sel:'#tool_docprops_save', fn: saveDocProperties, evt: 'click'}, {sel:'#tool_docprops', fn: showDocProperties, evt: 'mouseup'}, {sel:'#tool_prefs_save', fn: savePreferences, evt: 'click'}, {sel:'#tool_prefs_option', fn: function() {showPreferences();return false}, evt: 'mouseup'}, {sel:'#tool_delete,#tool_delete_multi', fn: deleteSelected, evt: 'click', key: ['del/backspace', true]}, {sel:'#tool_reorient', fn: reorientPath, evt: 'click'}, {sel:'#tool_node_link', fn: linkControlPoints, evt: 'click'}, {sel:'#tool_node_clone', fn: clonePathNode, evt: 'click'}, {sel:'#tool_node_delete', fn: deletePathNode, evt: 'click'}, {sel:'#tool_openclose_path', fn: opencloseSubPath, evt: 'click'}, {sel:'#tool_add_subpath', fn: addSubPath, evt: 'click'}, {sel:'#tool_move_top', fn: moveToTopSelected, evt: 'click', key: 'ctrl+shift+]'}, {sel:'#tool_move_bottom', fn: moveToBottomSelected, evt: 'click', key: 'ctrl+shift+['}, {sel:'#tool_topath', fn: convertToPath, evt: 'click'}, {sel:'#tool_make_link,#tool_make_link_multi', fn: makeHyperlink, evt: 'click'}, {sel:'#tool_undo', fn: clickUndo, evt: 'click', key: ['Z', true]}, {sel:'#tool_redo', fn: clickRedo, evt: 'click', key: ['Y', true]}, {sel:'#tool_clone,#tool_clone_multi', fn: clickClone, evt: 'click', key: ['D', true]}, {sel:'#tool_group', fn: clickGroup, evt: 'click', key: ['G', true]}, {sel:'#tool_ungroup', fn: clickGroup, evt: 'click'}, {sel:'#tool_unlink_use', fn: clickGroup, evt: 'click'}, {sel:'[id^=tool_align]', fn: clickAlign, evt: 'click'}, // these two lines are required to make Opera work properly with the flyout mechanism // {sel:'#tools_rect_show', fn: clickRect, evt: 'click'}, // {sel:'#tools_ellipse_show', fn: clickEllipse, evt: 'click'}, {sel:'#tool_bold', fn: clickBold, evt: 'mousedown'}, {sel:'#tool_italic', fn: clickItalic, evt: 'mousedown'}, {sel:'#sidepanel_handle', fn: toggleSidePanel, key: ['X']}, {sel:'#copy_save_done', fn: cancelOverlays, evt: 'click'}, // Shortcuts not associated with buttons {key: 'ctrl+left', fn: function(){rotateSelected(0,1)}}, {key: 'ctrl+right', fn: function(){rotateSelected(1,1)}}, {key: 'ctrl+shift+left', fn: function(){rotateSelected(0,5)}}, {key: 'ctrl+shift+right', fn: function(){rotateSelected(1,5)}}, {key: 'shift+O', fn: selectPrev}, {key: 'shift+P', fn: selectNext}, {key: [modKey+'up', true], fn: function(){zoomImage(2);}}, {key: [modKey+'down', true], fn: function(){zoomImage(.5);}}, {key: [modKey+']', true], fn: function(){moveUpDownSelected('Up');}}, {key: [modKey+'[', true], fn: function(){moveUpDownSelected('Down');}}, {key: ['up', true], fn: function(){moveSelected(0,-1);}}, {key: ['down', true], fn: function(){moveSelected(0,1);}}, {key: ['left', true], fn: function(){moveSelected(-1,0);}}, {key: ['right', true], fn: function(){moveSelected(1,0);}}, {key: 'shift+up', fn: function(){moveSelected(0,-10)}}, {key: 'shift+down', fn: function(){moveSelected(0,10)}}, {key: 'shift+left', fn: function(){moveSelected(-10,0)}}, {key: 'shift+right', fn: function(){moveSelected(10,0)}}, {key: ['alt+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-1)}}, {key: ['alt+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,1)}}, {key: ['alt+left', true], fn: function(){svgCanvas.cloneSelectedElements(-1,0)}}, {key: ['alt+right', true], fn: function(){svgCanvas.cloneSelectedElements(1,0)}}, {key: ['alt+shift+up', true], fn: function(){svgCanvas.cloneSelectedElements(0,-10)}}, {key: ['alt+shift+down', true], fn: function(){svgCanvas.cloneSelectedElements(0,10)}}, {key: ['alt+shift+left', true], fn: function(){svgCanvas.cloneSelectedElements(-10,0)}}, {key: ['alt+shift+right', true], fn: function(){svgCanvas.cloneSelectedElements(10,0)}}, {key: 'A', fn: function(){svgCanvas.selectAllInCurrentLayer();}}, // Standard shortcuts {key: modKey+'z', fn: clickUndo}, {key: modKey + 'shift+z', fn: clickRedo}, {key: modKey + 'y', fn: clickRedo}, {key: modKey+'x', fn: cutSelected}, {key: modKey+'c', fn: copySelected}, {key: modKey+'v', fn: pasteInCenter} ]; // Tooltips not directly associated with a single function var key_assocs = { '4/Shift+4': '#tools_rect_show', '5/Shift+5': '#tools_ellipse_show' }; return { setAll: function() { var flyouts = {}; $.each(tool_buttons, function(i, opts) { // Bind function to button if(opts.sel) { var btn = $(opts.sel); if (btn.length == 0) return true; // Skip if markup does not exist if(opts.evt) { if (svgedit.browser.isTouch() && opts.evt === "click") opts.evt = "mousedown" btn[opts.evt](opts.fn); } // Add to parent flyout menu, if able to be displayed if(opts.parent && $(opts.parent + '_show').length != 0) { var f_h = $(opts.parent); if(!f_h.length) { f_h = makeFlyoutHolder(opts.parent.substr(1)); } f_h.append(btn); if(!$.isArray(flyouts[opts.parent])) { flyouts[opts.parent] = []; } flyouts[opts.parent].push(opts); } } // Bind function to shortcut key if(opts.key) { // Set shortcut based on options var keyval, shortcut = '', disInInp = true, fn = opts.fn, pd = false; if($.isArray(opts.key)) { keyval = opts.key[0]; if(opts.key.length > 1) pd = opts.key[1]; if(opts.key.length > 2) disInInp = opts.key[2]; } else { keyval = opts.key; } keyval += ''; $.each(keyval.split('/'), function(i, key) { $(document).bind('keydown', key, function(e) { fn(); if(pd) { e.preventDefault(); } // Prevent default on ALL keys? return false; }); }); // Put shortcut in title if(opts.sel && !opts.hidekey && btn.attr('title')) { var new_title = btn.attr('title').split('[')[0] + ' (' + keyval + ')'; key_assocs[keyval] = opts.sel; // Disregard for menu items if(!btn.parents('#main_menu').length) { btn.attr('title', new_title); } } } }); // Setup flyouts setupFlyouts(flyouts); // Misc additional actions // Make "return" keypress trigger the change event $('.attr_changer, #image_url').bind('keydown', 'return', function(evt) {$(this).change();evt.preventDefault();} ); $(window).bind('keydown', 'tab', function(e) { if(ui_context === 'canvas') { e.preventDefault(); selectNext(); } }).bind('keydown', 'shift+tab', function(e) { if(ui_context === 'canvas') { e.preventDefault(); selectPrev(); } }); $('#tool_zoom').dblclick(dblclickZoom); }, setTitles: function() { $.each(key_assocs, function(keyval, sel) { var menu = ($(sel).parents('#main_menu').length); $(sel).each(function() { if(menu) { var t = $(this).text().split(' [')[0]; } else { var t = this.title.split(' [')[0]; } var key_str = ''; // Shift+Up $.each(keyval.split('/'), function(i, key) { var mod_bits = key.split('+'), mod = ''; if(mod_bits.length > 1) { mod = mod_bits[0] + '+'; key = mod_bits[1]; } key_str += (i?'/':'') + mod + (uiStrings['key_'+key] || key); }); if(menu) { this.lastChild.textContent = t +' ['+key_str+']'; } else { this.title = t +' ['+key_str+']'; } }); }); }, getButtonData: function(sel) { var b; $.each(tool_buttons, function(i, btn) { if(btn.sel === sel) b = btn; }); return b; } }; }(); Actions.setAll(); // Select given tool Editor.ready(function() { var tool, itool = curConfig.initTool, container = $("#tools_left, #svg_editor .tools_flyout"), pre_tool = container.find("#tool_" + itool), reg_tool = container.find("#" + itool); if(pre_tool.length) { tool = pre_tool; } else if(reg_tool.length){ tool = reg_tool; } else { tool = $("#tool_select"); } tool.click().mouseup(); if(curConfig.wireframe) { $('#tool_wireframe').click(); } if(curConfig.showlayers) { toggleSidePanel(); } $('#rulers').toggle(!!curConfig.showRulers); if (curConfig.showRulers) { $('#show_rulers')[0].checked = true; } if(curConfig.gridSnapping) { $('#grid_snapping_on')[0].checked = true; } if(curConfig.baseUnit) { $('#base_unit').val(curConfig.baseUnit); } if(curConfig.snappingStep) { $('#grid_snapping_step').val(curConfig.snappingStep); } }); $('#rect_rx').SpinButton({ min: 0, max: 1000, step: 1, callback: changeRectRadius }); $('#stroke_width').SpinButton({ min: 0, max: 99, step: 1, smallStep: 0.1, callback: changeStrokeWidth }); $('#angle').SpinButton({ min: -180, max: 180, step: 5, callback: changeRotationAngle }); $('#font_size').SpinButton({ step: 1, min: 0.001, stepfunc: stepFontSize, callback: changeFontSize }); $('#group_opacity').SpinButton({ step: 5, min: 0, max: 100, callback: changeOpacity }); $('#blur').SpinButton({ step: .1, min: 0, max: 10, callback: changeBlur }); $('#zoom').SpinButton({ min: 0.001, max: 10000, step: 50, stepfunc: stepZoom, callback: changeZoom }) // Set default zoom .val(svgCanvas.getZoom() * 100); $("#workarea").contextMenu({ menu: 'cmenu_canvas', inSpeed: 0 }, function(action, el, pos) { switch ( action ) { case 'delete': deleteSelected(); break; case 'cut': cutSelected(); break; case 'copy': copySelected(); break; case 'paste': svgCanvas.pasteElements(); break; case 'paste_in_place': svgCanvas.pasteElements('in_place'); break; case 'group': svgCanvas.groupSelectedElements(); break; case 'ungroup': svgCanvas.ungroupSelectedElement(); break; case 'move_front': moveToTopSelected(); break; case 'move_up': moveUpDownSelected('Up'); break; case 'move_down': moveUpDownSelected('Down'); break; case 'move_back': moveToBottomSelected(); break; default: if(svgedit.contextmenu && svgedit.contextmenu.hasCustomHandler(action)){ svgedit.contextmenu.getCustomHandler(action).call(); } break; } if(svgCanvas.clipBoard.length) { canv_menu.enableContextMenuItems('#paste,#paste_in_place'); } }); var lmenu_func = function(action, el, pos) { switch ( action ) { case 'dupe': cloneLayer(); break; case 'delete': deleteLayer(); break; case 'merge_down': mergeLayer(); break; case 'merge_all': svgCanvas.mergeAllLayers(); updateContextPanel(); populateLayers(); break; } } $("#layerlist").contextMenu({ menu: 'cmenu_layers', inSpeed: 0 }, lmenu_func ); $("#layer_moreopts").contextMenu({ menu: 'cmenu_layers', inSpeed: 0, allowLeft: true }, lmenu_func ); $('.contextMenu li').mousedown(function(ev) { ev.preventDefault(); }) $('#cmenu_canvas li').disableContextMenu(); canv_menu.enableContextMenuItems('#delete,#cut,#copy'); window.onbeforeunload = function() { if ('localStorage' in window) { var name = 'svgedit-' + Editor.curConfig.canvasName; window.localStorage.setItem(name, svgCanvas.getSvgString()); Editor.show_save_warning = false; } // Suppress warning if page is empty if(undoMgr.getUndoStackSize() === 0) { Editor.show_save_warning = false; } // show_save_warning is set to "false" when the page is saved. if(!curConfig.no_save_warning && Editor.show_save_warning) { // Browser already asks question about closing the page return uiStrings.notification.unsavedChanges; } }; Editor.openPrep = function(func) { $('#main_menu').hide(); if(undoMgr.getUndoStackSize() === 0) { func(true); } else { $.confirm(uiStrings.notification.QwantToOpen, func); } } // use HTML5 File API: http://www.w3.org/TR/FileAPI/ // if browser has HTML5 File API support, then we will show the open menu item // and provide a file input to click. When that change event fires, it will // get the text contents of the file and send it to the canvas if (window.FileReader) { var import_image = function(e) { e.stopPropagation(); e.preventDefault(); $("#workarea").removeAttr("style"); $('#main_menu').hide(); var file = null; if (e.type == "drop") file = e.dataTransfer.files[0] else file = this.files[0]; if (file) { if(file.type.indexOf("image") != -1) { //detected an image //svg handling if(file.type.indexOf("svg") != -1) { var reader = new FileReader(); reader.onloadend = function(e) { svgCanvas.importSvgString(e.target.result, true); svgCanvas.ungroupSelectedElement() svgCanvas.ungroupSelectedElement() svgCanvas.groupSelectedElements() svgCanvas.alignSelectedElements("m", "page") svgCanvas.alignSelectedElements("c", "page") }; reader.readAsText(file); } //bitmap handling else { var reader = new FileReader(); reader.onloadend = function(e) { // let's insert the new image until we know its dimensions insertNewImage = function(img_width, img_height){ var newImage = svgCanvas.addSvgElementFromJson({ "element": "image", "attr": { "x": 0, "y": 0, "width": img_width, "height": img_height, "id": svgCanvas.getNextId(), "style": "pointer-events:inherit" } }); svgCanvas.setHref(newImage, e.target.result); svgCanvas.selectOnly([newImage]) svgCanvas.alignSelectedElements("m", "page") svgCanvas.alignSelectedElements("c", "page") updateContextPanel(); } // create dummy img so we know the default dimensions var img_width = 100; var img_height = 100; var img = new Image(); img.src = e.target.result; img.style.opacity = 0; img.onload = function() { img_width = img.offsetWidth img_height = img.offsetHeight insertNewImage(img_width, img_height); } }; reader.readAsDataURL(file) } } } } function onDragEnter(e) { e.stopPropagation(); e.preventDefault(); // and indicator should be displayed here, such as "drop files here" } function onDragOver(e) { e.stopPropagation(); e.preventDefault(); } function onDragLeave(e) { e.stopPropagation(); e.preventDefault(); // hypothetical indicator should be removed here } workarea[0].addEventListener('dragenter', onDragEnter, false); workarea[0].addEventListener('dragover', onDragOver, false); workarea[0].addEventListener('dragleave', onDragLeave, false); workarea[0].addEventListener('drop', import_image, false); var open = $('<input type="file">').change(function() { var f = this; Editor.openPrep(function(ok) { if(!ok) return; svgCanvas.clear(); if(f.files.length==1) { var reader = new FileReader(); reader.onloadend = function(e) { loadSvgString(e.target.result); updateCanvas(); }; reader.readAsText(f.files[0]); } }); }); $("#tool_open").show().prepend(open); var img_import = $('<input type="file">').change(import_image); $("#tool_import").show().prepend(img_import); } var updateCanvas = Editor.updateCanvas = function(center, new_ctr) { var w = workarea.width(), h = workarea.height(); var w_orig = w, h_orig = h; var zoom = svgCanvas.getZoom(); var w_area = workarea; var cnvs = $("#svgcanvas"); var old_ctr = { x: w_area[0].scrollLeft + w_orig/2, y: w_area[0].scrollTop + h_orig/2 }; var multi = curConfig.canvas_expansion; w = Math.max(w_orig, svgCanvas.contentW * zoom * multi); h = Math.max(h_orig, svgCanvas.contentH * zoom * multi); if(w == w_orig && h == h_orig) { workarea.css('overflow','hidden'); } else { workarea.css('overflow','scroll'); } var old_can_y = cnvs.height()/2; var old_can_x = cnvs.width()/2; cnvs.width(w).height(h); var new_can_y = h/2; var new_can_x = w/2; var offset = svgCanvas.updateCanvas(w, h); var ratio = new_can_x / old_can_x; var scroll_x = w/2 - w_orig/2; var scroll_y = h/2 - h_orig/2; if(!new_ctr) { var old_dist_x = old_ctr.x - old_can_x; var new_x = new_can_x + old_dist_x * ratio; var old_dist_y = old_ctr.y - old_can_y; var new_y = new_can_y + old_dist_y * ratio; new_ctr = { x: new_x, y: new_y }; } else { new_ctr.x += offset.x, new_ctr.y += offset.y; } if(center) { // Go to top-left for larger documents if(svgCanvas.contentW > w_area.width()) { // Top-left workarea[0].scrollLeft = offset.x - 10; workarea[0].scrollTop = offset.y - 10; } else { // Center w_area[0].scrollLeft = scroll_x; w_area[0].scrollTop = scroll_y; } } else { w_area[0].scrollLeft = new_ctr.x - w_orig/2; w_area[0].scrollTop = new_ctr.y - h_orig/2; } if(curConfig.showRulers) { updateRulers(cnvs, zoom); workarea.scroll(); } } // Make [1,2,5] array var r_intervals = []; for(var i = .1; i < 1E5; i *= 10) { r_intervals.push(1 * i); r_intervals.push(2 * i); r_intervals.push(5 * i); } function updateRulers(scanvas, zoom) { if(!zoom) zoom = svgCanvas.getZoom(); if(!scanvas) scanvas = $("#svgcanvas"); var limit = 30000; var c_elem = svgCanvas.getContentElem(); var units = svgedit.units.getTypeMap(); var unit = units[curConfig.baseUnit]; // 1 = 1px for(var d = 0; d < 2; d++) { var is_x = (d === 0); var dim = is_x ? 'x' : 'y'; var lentype = is_x?'width':'height'; var content_d = c_elem.getAttribute(dim)-0; var $hcanv_orig = $('#ruler_' + dim + ' canvas:first'); // Bit of a hack to fully clear the canvas in Safari & IE9 $hcanv = $hcanv_orig.clone(); $hcanv_orig.replaceWith($hcanv); var hcanv = $hcanv[0]; // Set the canvas size to the width of the container var ruler_len = scanvas[lentype](); var total_len = ruler_len; hcanv.parentNode.style[lentype] = total_len + 'px'; var canv_count = 1; var ctx_num = 0; var ctx_arr; var ctx = hcanv.getContext("2d"); ctx.fillStyle = "rgb(200,0,0)"; ctx.fillRect(0,0,hcanv.width,hcanv.height); // Remove any existing canvasses $hcanv.siblings().remove(); // Create multiple canvases when necessary (due to browser limits) if(ruler_len >= limit) { var num = parseInt(ruler_len / limit) + 1; ctx_arr = Array(num); ctx_arr[0] = ctx; for(var i = 1; i < num; i++) { hcanv[lentype] = limit; var copy = hcanv.cloneNode(true); hcanv.parentNode.appendChild(copy); ctx_arr[i] = copy.getContext('2d'); } copy[lentype] = ruler_len % limit; // set copy width to last ruler_len = limit; } hcanv[lentype] = ruler_len; var u_multi = unit * zoom; // Calculate the main number interval var raw_m = 50 / u_multi; var multi = 1; for(var i = 0; i < r_intervals.length; i++) { var num = r_intervals[i]; multi = num; if(raw_m <= num) { break; } } var big_int = multi * u_multi; ctx.font = "9px sans-serif"; var ruler_d = ((content_d / u_multi) % multi) * u_multi; var label_pos = ruler_d - big_int; for (; ruler_d < total_len; ruler_d += big_int) { label_pos += big_int; var real_d = ruler_d - content_d; var cur_d = Math.round(ruler_d) + .5; if(is_x) { ctx.moveTo(cur_d, 15); ctx.lineTo(cur_d, 0); } else { ctx.moveTo(15, cur_d); ctx.lineTo(0, cur_d); } var num = (label_pos - content_d) / u_multi; var label; if(multi >= 1) { label = Math.round(num); } else { var decs = (multi+'').split('.')[1].length; label = num.toFixed(decs)-0; } // Do anything special for negative numbers? // var is_neg = label < 0; // real_d2 = Math.abs(real_d2); // Change 1000s to Ks if(label !== 0 && label !== 1000 && label % 1000 === 0) { label = (label / 1000) + 'K'; } if(is_x) { ctx.fillText(label, ruler_d+2, 8); } else { var str = (label+'').split(''); for(var i = 0; i < str.length; i++) { ctx.fillText(str[i], 1, (ruler_d+9) + i*9); } } var part = big_int / 10; for(var i = 1; i < 10; i++) { var sub_d = Math.round(ruler_d + part * i) + .5; if(ctx_arr && sub_d > ruler_len) { ctx_num++; ctx.stroke(); if(ctx_num >= ctx_arr.length) { i = 10; ruler_d = total_len; continue; } ctx = ctx_arr[ctx_num]; ruler_d -= limit; sub_d = Math.round(ruler_d + part * i) + .5; } var line_num = (i % 2)?12:10; if(is_x) { ctx.moveTo(sub_d, 15); ctx.lineTo(sub_d, line_num); } else { ctx.moveTo(15, sub_d); ctx.lineTo(line_num ,sub_d); } } } // console.log('ctx', ctx); ctx.strokeStyle = "#000"; ctx.stroke(); } } // $(function() { updateCanvas(true); // }); // var revnums = "svg-editor.js ($Rev: 2277 $) "; // revnums += svgCanvas.getVersion(); // $('#copyright')[0].setAttribute("title", revnums); // Callback handler for embedapi.js try{ var json_encode = function(obj){ //simple partial JSON encoder implementation if(window.JSON && JSON.stringify) return JSON.stringify(obj); var enc = arguments.callee; //for purposes of recursion if(typeof obj == "boolean" || typeof obj == "number"){ return obj+'' //should work... }else if(typeof obj == "string"){ //a large portion of this is stolen from Douglas Crockford's json2.js return '"'+ obj.replace( /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g , function (a) { return '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) +'"'; //note that this isn't quite as purtyful as the usualness }else if(obj.length){ //simple hackish test for arrayish-ness for(var i = 0; i < obj.length; i++){ obj[i] = enc(obj[i]); //encode every sub-thingy on top } return "["+obj.join(",")+"]"; }else{ var pairs = []; //pairs will be stored here for(var k in obj){ //loop through thingys pairs.push(enc(k)+":"+enc(obj[k])); //key: value } return "{"+pairs.join(",")+"}" //wrap in the braces } } window.addEventListener("message", function(e){ var cbid = parseInt(e.data.substr(0, e.data.indexOf(";"))); try{ e.source.postMessage("SVGe"+cbid+";"+json_encode(eval(e.data)), "*"); }catch(err){ e.source.postMessage("SVGe"+cbid+";error:"+err.message, "*"); } }, false) }catch(err){ window.embed_error = err; } // For Compatibility with older extensions $(function() { window.svgCanvas = svgCanvas; svgCanvas.ready = svgEditor.ready; }); Editor.setLang = function(lang, allStrings) { $.pref('lang', lang); $('#lang_select').val(lang); if(allStrings) { var notif = allStrings.notification; // $.extend will only replace the given strings var oldLayerName = $('#layerlist tr.layersel td.layername').text(); var rename_layer = (oldLayerName == uiStrings.common.layer + ' 1'); $.extend(uiStrings, allStrings); svgCanvas.setUiStrings(allStrings); Actions.setTitles(); if(rename_layer) { svgCanvas.renameCurrentLayer(uiStrings.common.layer + ' 1'); populateLayers(); } svgCanvas.runExtensions("langChanged", lang); // Update flyout tooltips setFlyoutTitles(); // Copy title for certain tool elements var elems = { '#stroke_color': '#tool_stroke .icon_label, #tool_stroke .color_block', '#fill_color': '#tool_fill label, #tool_fill .color_block', '#linejoin_miter': '#cur_linejoin', '#linecap_butt': '#cur_linecap' } $.each(elems, function(source, dest) { $(dest).attr('title', $(source)[0].title); }); // Copy alignment titles $('#multiselected_panel div[id^=tool_align]').each(function() { $('#tool_pos' + this.id.substr(10))[0].title = this.title; }); } }; }; var callbacks = []; function loadSvgString(str, callback) { var success = svgCanvas.setSvgString(str) !== false; callback = callback || $.noop; if(success) { callback(true); } else { $.alert(uiStrings.notification.errorLoadingSVG, function() { callback(false); }); } } Editor.ready = function(cb) { if(!is_ready) { callbacks.push(cb); } else { cb(); } }; Editor.runCallbacks = function() { $.each(callbacks, function() { this(); }); is_ready = true; }; Editor.loadFromString = function(str) { Editor.ready(function() { loadSvgString(str); }); }; Editor.disableUI = function(featList) { // $(function() { // $('#tool_wireframe, #tool_image, #main_button, #tool_source, #sidepanels').remove(); // $('#tools_top').css('left', 5); // }); }; Editor.loadFromURL = function(url, opts) { if(!opts) opts = {}; var cache = opts.cache; var cb = opts.callback; Editor.ready(function() { $.ajax({ 'url': url, 'dataType': 'text', cache: !!cache, success: function(str) { loadSvgString(str, cb); }, error: function(xhr, stat, err) { if(xhr.status != 404 && xhr.responseText) { loadSvgString(xhr.responseText, cb); } else { $.alert(uiStrings.notification.URLloadFail + ": \n"+err+'', cb); } } }); }); }; Editor.loadFromDataURI = function(str) { Editor.ready(function() { var pre = 'data:image/svg+xml;base64,'; var src = str.substring(pre.length); loadSvgString(svgedit.utilities.decode64(src)); }); }; Editor.addExtension = function() { var args = arguments; // Note that we don't want this on Editor.ready since some extensions // may want to run before then (like server_opensave). $(function() { if(svgCanvas) svgCanvas.addExtension.apply(this, args); }); }; return Editor; }(jQuery); // Run init once DOM is loaded $(svgEditor.init); })(); // ?iconsize=s&bkgd_color=555 // svgEditor.setConfig({ // // imgPath: 'foo', // dimensions: [800, 600], // canvas_expansion: 5, // initStroke: { // color: '0000FF', // width: 3.5, // opacity: .5 // }, // initFill: { // color: '550000', // opacity: .75 // }, // extensions: ['ext-helloworld.js'] // })
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * Post Schema */ var PostSchema = new Schema({ name: { type: String, default: '', required: 'Please fill Post name', trim: true }, content: { type: String, default: '', required: 'Please add content to your post', trim: true }, skill: [{ type: String, ref: 'Skillset' }], created: { type: Date, default: Date.now }, user: { type: Schema.ObjectId, ref: 'User' } }); mongoose.model('Post', PostSchema);
var browserSync = require('browser-sync').create(), _path = require('../gulp.config').path; /* ------------------------------- * BROSWER SYNC + WATCH TASK * ------------------------------- */ module.exports = { dep: ['build'], fn: function(gulp, callback) { browserSync.init({ server: _path.build }); //WATCH FOR CHANGES TO SCSS, PUG, HTML AND JS FILES AND RUN BACKUP gulp.watch(_path.lib + _path.scss + '**/*.scss', ['compile:sass']).on('change', browserSync.reload); gulp.watch(_path.lib + _path.pug + '**/*.pug', ['compile:pug']).on('change', browserSync.reload); gulp.watch(_path.lib + _path.js + '*.js', ['copyjs']).on('change', browserSync.reload); } }
import React from 'react' import Text from 'wix-style-react/dist/src/Text' import {Row, Col} from 'wix-style-react/dist/src/Grid' import Avatar from 'react-avatar' import Button from 'wix-style-react/dist/src/Button' function addZero (d) { if (d < 10) { return '0' + d } return d } function dateToString (v) { const date = new Date (v) const day = date.getDate () const month = date.getMonth () const hours = date.getHours () const minutes = date.getMinutes () const dateStr = day + '.' + addZero(month) + ' ' + hours + ':' + addZero(minutes) return dateStr } const Message = (props) => { const onClick = () => ( props.onClick (props.data.key) ) return ( <Row> <Col span='1'> <Avatar src={props.data.imageUrl} round={true}/> </Col> <Col span='10'> <Row> <Text appearance='T2.3'> {props.data.author} </Text>&nbsp; <Text appearance='T3.4'> {dateToString (props.data.time)} </Text> </Row> <Row> <Col> <Text appearance='T2'> {props.data.text} </Text> </Col> </Row> </Col> <Col span='1'> <Button onClick={onClick}>X</Button> </Col> </Row> ) } export default Message
var Readly = require("./readly.js"); var fs = require('fs'); var stream = require('stream'); var reader = new Readly.Emitter("test.txt"); var strm; console.log("read all:") reader.on('line', function(line) { console.log(line); }); var c3 = function() { console.log("_________________ now with stream instead of filename"); strm = fs.createReadStream('test.txt', { encoding: 'utf8' }); reader = new Readly.Emitter(strm); reader.on('line', function(line) { console.log(line); }); reader.on('end', function() { console.log('____________________________ now as transform string'); fs.createReadStream('test.txt').pipe(new Readly.Transform()).on('end', function() { console.log("\r\nEND") }).pipe(process.stdout); }); reader.readAll(); } var c2 = function() { reader.removeListener('end', c2); reader.on('end', c3); console.log("-----------------"); console.log("skip 3 read 3:") reader.read(3, 3); } var c1 = function() { reader.removeListener('end', c1); reader.on('end', c2); console.log("-----------------"); console.log("read first 3:") reader.readFirst(3); } reader.on('end', c1); reader.read();
/** * @fileOverview I contain utility functions. * @module Utils */ 'use strict'; /* *************************** Required Classes **************************** */ /* *************************** Constructor Code **************************** */ /* *************************** Public Methods ****************************** */ /** * I dedup an array of objects by key. * @param theArray - I am the array to dedupe. * @param key - I am the key to dedupe the array by. * @returns {Array} */ function linkSafeString( str ){ var str2=str.toLowerCase(); str2=str2.split(" ").join("-"); str2=str2.split("&").join("-"); return str2; } exports.linkSafeString = linkSafeString;
var test = require('tap').test var Log = require('../../log') var MemoryStorage = require('../memory-storage') var MemoryStateMachine = require('../memory-state-machine') var log = new Log(new MemoryStorage(), new MemoryStateMachine()) test( 'load: loads state and entries from storage', function (t) { var storage = new MemoryStorage() storage.data = { currentTerm: 5, votedFor: 3 } storage.entries = [{ term: 4}, { term: 5}] var l = new Log(storage) l.load() .then( function () { t.equal(l.currentTerm, 5, 'loaded currentTerm') t.equal(l.votedFor, 3, 'loaded votedFor') t.equal(l.entries.length, 2, 'loaded entries') t.end() } ) } ) test( 'appendEntries: Reply false if term < currentTerm (§5.1)', function (t) { log.currentTerm = 2 log.appendEntries({ term: 1 }) .then( function (success) { log.currentTerm = 0 t.equal(success, false, 'denied') t.end() } ) } ) test( 'appendEntries: Reply false if log doesn’t contain an entry at prevLogIndex ' + 'whose term matches prevLogTerm (§5.3)', function (t) { log.entries = [{ term: 1 }, { term: 2 }] log.appendEntries( { term: 3, prevLogIndex: 1, prevLogTerm: 3 } ) .then( function (success) { t.equals(success, false, 'denied') t.end() } ) } ) test( 'appendEntries: If an existing entry conflicts with a new one (same index ' + 'but different terms), delete the existing entry and all that follow it (§5.3)', function (t) { log.entries = [{ term: 1 }, { term: 2 }, { term: 3 }, { term: 4 }, { term: 5 }] log.appendEntries( { term: 2, prevLogIndex: 1, prevLogTerm: 2, entries: { startIndex: 2, values: [{ term: 2 }] } } ) .then( function (success) { t.equal(success, true, 'succeeded') t.equal(log.entries.length, 3, 'correct length') t.equal(log.entries[2].term, 2, 'correct term') t.end() } ) } ) test( 'appendEntries: Append any new entries not already in the log', function (t) { log.entries = [{ term: 1 }, { term: 2 }] log.appendEntries( { term: 2, prevLogIndex: 1, prevLogTerm: 2, entries: { startIndex: 2, values: [{ term: 2 }, { term: 2 }, { term: 2 }] } } ) .then( function (success) { t.equal(success, true, 'succeeded') t.equal(log.entries.length, 5, 'correct length') t.equal(log.entries[4].term, 2, 'correct term') t.end() } ) } ) test( 'appendEntries: If leaderCommit > commitIndex, '+ 'set commitIndex = min(leaderCommit, lastIndex)', function (t) { log.commitIndex = -1 log.entries = [{ term: 1 }, { term: 2 }] log.appendEntries( { term: 2, prevLogIndex: 1, prevLogTerm: 2, leaderCommit: 1 } ) .then( function (success) { t.equal(success, true) t.equal(log.commitIndex, 1, 'updated commitIndex') t.end() } ) } ) test( 'appendEntries: If log is empty the first entry gets added', function (t) { log.entries = [] log.appendEntries( { term: 1, prevLogIndex: -1, prevLogTerm: 0, entries: { startIndex: 0, values: [{ term: 2 }, { term: 2 }, { term: 2 }] } } ) .then( function (success) { t.equal(success, true) t.equal(log.entries.length, 3, 'correct length') t.end() } ) } ) test( 'requestVote: Reply false if term < currentTerm (§5.1)', function (t) { log.currentTerm = 2 log.requestVote( { term: 1, candidateId: 1, lastLogIndex: 1, lastLogTerm: 1} ) .then( function (voteGranted) { t.equal(voteGranted, false) t.end() } ) } ) test( 'requestVote: Reply false if lastLogTerm = currentTerm and lastLogIndex < mine', function (t) { log.currentTerm = 1 log.entries = [{ term: 1 }, { term: 1 }] log.requestVote( { term: 1, candidateId: 1, lastLogIndex: 0, lastLogTerm: 1} ) .then( function (voteGranted) { t.equal(voteGranted, false) t.end() } ) } ) test( 'requestVote: Reply false if votedFor != candidateId', function (t) { log.currentTerm = 0 log.votedFor = 2 log.requestVote( { term: 1, candidateId: 1, lastLogIndex: 0, lastLogTerm: 1} ) .then( function (voteGranted) { t.equal(voteGranted, false) t.end() } ) } ) test( 'requestVote: Reply true if votedFor is null and term > currentTerm', function (t) { log.currentTerm = 0 log.votedFor = 0 log.requestVote( { term: 1, candidateId: 1, lastLogIndex: 1, lastLogTerm: 1} ) .then( function (voteGranted) { t.equal(voteGranted, true) t.end() } ) } ) test( 'execute: executes the correct entries', function (t) { var log = new Log(new MemoryStorage(), new MemoryStateMachine()) log.lastApplied = 0 log.entries = [{ term: 1 }, { term: 5 }, { term: 5 }, { term: 9 }] // only term 5 entries should get executed here log.execute(2) .then( function (lastApplied) { t.equal(lastApplied, 2) t.equal(log.lastApplied, 2) // MemoryStateMachine increments it's state for each execution. // It starts at 1 plus the 2 exepected calls should make it 3. t.equal(log.stateMachine.state, 3) t.end() } ) } ) test( 'updateCommitIndex: commitIndex is never set higher than lastIndex', function (t) { log.commitIndex = 1 log.entries = [{ term: 1 }, { term: 5 }, { term: 5 }, { term: 9 }] log.updateCommitIndex(80) t.equal(log.commitIndex, 3) t.end() } ) test( 'updateCommitIndex: commitIndex is never set lower', function (t) { log.commitIndex = 1 log.entries = [{ term: 1 }, { term: 5 }, { term: 5 }, { term: 9 }] log.updateCommitIndex(0) t.equal(log.commitIndex, 1) t.end() } )
const command = "create table author (id number, name string, age number, city string, state string, country string)"; let tableName = ""; let columnsString = []; const regex = /^create\s+table\s+(\w+)\s+\((.+)\)$/; const match = command.trim().match(regex); if (match) { tableName = match[1]; columnsString = match[2].split(", "); } console.log(`tableName = "${tableName}"`); console.log(`columnsString = [ ${columnsString.map((e) => "'" + e + "'")} ]`); const columns = columnsString.reduce((acc, column) => { const [key, value] = column.trim().replace(/\s+/, " ").split(" "); return { ...acc, [key]: value }; }, {}); // equivalente: // let columns = {}; // for (let column of columnsString) { // const [key, value] = column.trim().replace(/\s+/, " ").split(" "); // columns[key] = value; // } const database = { tables: { [tableName]: { columns, data: [] } } }; console.log(JSON.stringify(database, null, " "));
'use strict'; ( function() { var template = '<img alt="" src="" />', templateBlock = new CKEDITOR.template( '<figure class="{captionedClass}">' + template + '<figcaption>{captionPlaceholder}</figcaption>' + '</figure>' ), alignmentsObj = { left: 0, center: 1, right: 2 }, regexPercent = /^\s*(\d+\%)\s*$/i; CKEDITOR.plugins.add( 'leadingimage', { lang: 'en,zh-cn', requires: 'widget,dialog', icons: 'image', hidpi: true, onLoad: function() { CKEDITOR.addCss( '.cke_image_nocaption{' + // This is to remove unwanted space so resize // wrapper is displayed property. 'line-height:0' + '}' + '.cke_editable.cke_image_sw, .cke_editable.cke_image_sw *{cursor:sw-resize !important}' + '.cke_editable.cke_image_se, .cke_editable.cke_image_se *{cursor:se-resize !important}' + '.cke_image_resizer{' + 'display:none;' + 'position:absolute;' + 'width:10px;' + 'height:10px;' + 'bottom:-5px;' + 'right:-5px;' + 'background:#000;' + 'outline:1px solid #fff;' + // Prevent drag handler from being misplaced (http://dev.ckeditor.com/ticket/11207). 'line-height:0;' + 'cursor:se-resize;' + '}' + '.cke_image_resizer_wrapper{' + 'position:relative;' + 'display:inline-block;' + 'line-height:0;' + '}' + // Bottom-left corner style of the resizer. '.cke_image_resizer.cke_image_resizer_left{' + 'right:auto;' + 'left:-5px;' + 'cursor:sw-resize;' + '}' + '.cke_widget_wrapper:hover .cke_image_resizer,' + '.cke_image_resizer.cke_image_resizing{' + 'display:block' + '}' + // Expand widget wrapper when linked inline image. '.cke_widget_wrapper>a{' + 'display:inline-block' + '}' ); }, init: function( editor ) { var config = editor.config, lang = editor.lang.leadingimage, image = widgetDef( editor ); // Add custom elementspath names to widget definition. image.pathName = lang.pathName; image.editables.caption.pathName = lang.pathNameCaption; // Register the widget. editor.widgets.add( 'leadingimage', image ); // Add toolbar button for this plugin. editor.ui.addButton && editor.ui.addButton( 'LeadingImage', { icon: 'image', label: editor.lang.common.image, command: 'leadingimage', toolbar: 'insert,10' } ); // Register context menu option for editing widget. if ( editor.contextMenu ) { editor.addMenuGroup( 'image', 10 ); editor.addMenuItem( 'image', { label: lang.menu, command: 'leadingimage', group: 'image' } ); } CKEDITOR.dialog.add( 'leadingimage', this.path + 'dialogs/leadingimage.js' ); }, afterInit: function( editor ) { // Integrate with align commands (justify plugin). var align = { left: 1, right: 1, center: 1, block: 1 }, integrate = alignCommandIntegrator( editor ); for ( var value in align ) integrate( value ); // Integrate with link commands (link plugin). linkCommandIntegrator( editor ); } } ); // @param {CKEDITOR.editor} // @returns {Object} function widgetDef( editor ) { var alignClasses = editor.config.leadingImage_alignClasses, captionedClass = editor.config.leadingImage_captionedClass; function deflate() { if ( this.deflated ) return; // Remember whether widget was focused before destroyed. if ( editor.widgets.focused === this.widget ) this.focused = true; editor.widgets.destroy( this.widget ); // Mark widget was destroyed. this.deflated = true; } function inflate() { var editable = editor.editable(), doc = editor.document; // Create a new widget. This widget will be either captioned // non-captioned, block or inline according to what is the // new state of the widget. if ( this.deflated ) { this.widget = editor.widgets.initOn( this.element, 'leadingimage', this.widget.data ); // Once widget was re-created, it may become an inline element without // block wrapper (i.e. when unaligned, end not captioned). Let's do some // sort of autoparagraphing here (http://dev.ckeditor.com/ticket/10853). if ( this.widget.inline && !( new CKEDITOR.dom.elementPath( this.widget.wrapper, editable ).block ) ) { var block = doc.createElement( editor.activeEnterMode === CKEDITOR.ENTER_P ? 'p' : 'div' ); block.replace( this.widget.wrapper ); this.widget.wrapper.move( block ); } // The focus must be transferred from the old one (destroyed) // to the new one (just created). if ( this.focused ) { this.widget.focus(); delete this.focused; } delete this.deflated; } // If now widget was destroyed just update wrapper's alignment. // According to the new state. else { setWrapperAlign( this.widget, alignClasses ); } } return { allowedContent: getWidgetAllowedContent( editor ), requiredContent: 'img[src,alt]', features: getWidgetFeatures( editor ), styleableElements: 'img figure', // This widget converts style-driven dimensions to attributes. contentTransformations: [ [ 'img[width]: sizeToAttribute' ] ], // This widget has an editable caption. editables: { caption: { selector: 'figcaption', allowedContent: 'br em strong sub sup u s; a[!href,target]' } }, parts: { image: 'img', caption: 'figcaption' // parts#link defined in widget#init }, // The name of this widget's dialog. dialog: 'leadingimage', // Template of the widget: plain image. template: template, data: function() { var features = this.features; // Image can't be captioned when figcaption is disallowed (http://dev.ckeditor.com/ticket/11004). if ( this.data.hasCaption && !editor.filter.checkFeature( features.caption ) ) this.data.hasCaption = false; // Image can't be aligned when floating is disallowed (http://dev.ckeditor.com/ticket/11004). if ( this.data.align !== 'none' && !editor.filter.checkFeature( features.align ) ) this.data.align = 'none'; // Convert the internal form of the widget from the old state to the new one. this.shiftState( { widget: this, element: this.element, oldData: this.oldData, newData: this.data, deflate: deflate, inflate: inflate } ); // Update widget.parts.link since it will not auto-update unless widget // is destroyed and re-inited. if ( !this.data.link ) { if ( this.parts.link ) delete this.parts.link; } else { if ( !this.parts.link ) this.parts.link = this.parts.image.getParent(); } this.parts.image.setAttributes( { src: this.data.src, // This internal is required by the editor. 'data-cke-saved-src': this.data.src, alt: this.data.alt } ); // If shifting non-captioned -> captioned, remove classes // related to styles from <img/>. if ( this.oldData && !this.oldData.hasCaption && this.data.hasCaption ) { for ( var c in this.data.classes ) this.parts.image.removeClass( c ); } // Set dimensions of the image according to gathered data. // Do it only when the attributes are allowed (http://dev.ckeditor.com/ticket/11004). if ( editor.filter.checkFeature( features.dimension ) ) setDimensions( this ); // Cache current data. this.oldData = CKEDITOR.tools.extend( {}, this.data ); }, init: function() { var helpers = CKEDITOR.plugins.leadingimage, image = this.parts.image, data = { hasCaption: !!this.parts.caption, src: image.getAttribute( 'src' ), alt: image.getAttribute( 'alt' ) || '', width: image.getAttribute( 'width' ) || '', height: image.getAttribute( 'height' ) || '', // Lock ratio is on by default (http://dev.ckeditor.com/ticket/10833). lock: this.ready ? helpers.checkHasNaturalRatio( image ) : true }; // If we used 'a' in widget#parts definition, it could happen that // selected element is a child of widget.parts#caption. Since there's no clever // way to solve it with CSS selectors, it's done like that. (http://dev.ckeditor.com/ticket/11783). var link = image.getAscendant( 'a' ); if ( link && this.wrapper.contains( link ) ) this.parts.link = link; // Depending on configuration, read style/class from element and // then remove it. Removed style/class will be set on wrapper in #data listener. // Note: Center alignment is detected during upcast, so only left/right cases // are checked below. if ( !data.align ) { var alignElement = data.hasCaption ? this.element : image; // Read the initial left/right alignment from the class set on element. if ( alignClasses ) { if ( alignElement.hasClass( alignClasses[ 0 ] ) ) { data.align = 'left'; } else if ( alignElement.hasClass( alignClasses[ 2 ] ) ) { data.align = 'right'; } if ( data.align ) { alignElement.removeClass( alignClasses[ alignmentsObj[ data.align ] ] ); } else { data.align = 'none'; } } // Read initial float style from figure/image and then remove it. else { data.align = alignElement.getStyle( 'float' ) || 'none'; alignElement.removeStyle( 'float' ); } } // Update data.link object with attributes if the link has been discovered. if ( editor.plugins.link && this.parts.link ) { data.link = helpers.getLinkAttributesParser()( editor, this.parts.link ); // Get rid of cke_widget_* classes in data. Otherwise // they might appear in link dialog. var advanced = data.link.advanced; if ( advanced && advanced.advCSSClasses ) { advanced.advCSSClasses = CKEDITOR.tools.trim( advanced.advCSSClasses.replace( /cke_\S+/, '' ) ); } } // Get rid of extra vertical space when there's no caption. // It will improve the look of the resizer. this.wrapper[ ( data.hasCaption ? 'remove' : 'add' ) + 'Class' ]( 'cke_image_nocaption' ); this.setData( data ); // Setup dynamic image resizing with mouse. // Don't initialize resizer when dimensions are disallowed (http://dev.ckeditor.com/ticket/11004). if ( editor.filter.checkFeature( this.features.dimension ) && editor.config.leadingImage_disableResizer !== true ) setupResizer( this ); this.shiftState = helpers.stateShifter( this.editor ); // Add widget editing option to its context menu. this.on( 'contextMenu', function( evt ) { evt.data.image = CKEDITOR.TRISTATE_OFF; // Integrate context menu items for link. // Note that widget may be wrapped in a link, which // does not belong to that widget (http://dev.ckeditor.com/ticket/11814). if ( this.parts.link || this.wrapper.getAscendant( 'a' ) ) evt.data.link = evt.data.unlink = CKEDITOR.TRISTATE_OFF; } ); // Pass the reference to this widget to the dialog. this.on( 'dialog', function( evt ) { evt.data.widget = this; }, this ); }, // Overrides default method to handle internal mutability of leadingimage. // @see CKEDITOR.plugins.widget#addClass addClass: function( className ) { getStyleableElement( this ).addClass( className ); }, // Overrides default method to handle internal mutability of leadingimage. // @see CKEDITOR.plugins.widget#hasClass hasClass: function( className ) { return getStyleableElement( this ).hasClass( className ); }, // Overrides default method to handle internal mutability of leadingimage. // @see CKEDITOR.plugins.widget#removeClass removeClass: function( className ) { getStyleableElement( this ).removeClass( className ); }, // Overrides default method to handle internal mutability of leadingimage. // @see CKEDITOR.plugins.widget#getClasses getClasses: ( function() { var classRegex = new RegExp( '^(' + [].concat( captionedClass, alignClasses ).join( '|' ) + ')$' ); return function() { var classes = this.repository.parseElementClasses( getStyleableElement( this ).getAttribute( 'class' ) ); for ( var c in classes ) { if ( classRegex.test( c ) ) delete classes[ c ]; } return classes; }; } )(), upcast: upcastWidgetElement( editor ), downcast: downcastWidgetElement( editor ), getLabel: function() { var label = ( this.data.alt || '' ) + ' ' + this.pathName; return this.editor.lang.widget.label.replace( /%1/, label ); } }; } /** * A set of Enhanced Image (image2) plugin helpers. * * @class * @singleton */ CKEDITOR.plugins.leadingimage = { stateShifter: function( editor ) { // Tag name used for centering non-captioned widgets. var doc = editor.document, alignClasses = editor.config.leadingImage_alignClasses, captionedClass = editor.config.leadingImage_captionedClass, editable = editor.editable(), // The order that stateActions get executed. It matters! shiftables = [ 'hasCaption', 'align', 'link' ]; // Atomic procedures, one per state variable. var stateActions = { align: function( shift, oldValue, newValue ) { var el = shift.element; // Alignment changed. if ( shift.changed.align ) { // No caption in the new state. if ( !shift.newData.hasCaption ) { // Changed to "center" (non-captioned). if ( newValue == 'center' ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Changed to "non-center" from "center" while caption removed. if ( !shift.changed.hasCaption && oldValue == 'center' && newValue != 'center' ) { shift.deflate(); shift.element = unwrapFromCentering( el ); } } } // Alignment remains and "center" removed caption. else if ( newValue == 'center' && shift.changed.hasCaption && !shift.newData.hasCaption ) { shift.deflate(); shift.element = wrapInCentering( editor, el ); } // Finally set display for figure. if ( !alignClasses && el.is( 'figure' ) ) { if ( newValue == 'center' ) el.setStyle( 'display', 'inline-block' ); else el.removeStyle( 'display' ); } }, hasCaption: function( shift, oldValue, newValue ) { // This action is for real state change only. if ( !shift.changed.hasCaption ) return; // Get <img/> or <a><img/></a> from widget. Note that widget element might itself // be what we're looking for. Also element can be <p style="text-align:center"><a>...</a></p>. var imageOrLink; if ( shift.element.is( { img: 1, a: 1 } ) ) imageOrLink = shift.element; else imageOrLink = shift.element.findOne( 'a,img' ); // Switching hasCaption always destroys the widget. shift.deflate(); // There was no caption, but the caption is to be added. if ( newValue ) { // Create new <figure> from widget template. var figure = CKEDITOR.dom.element.createFromHtml( templateBlock.output( { captionedClass: captionedClass, captionPlaceholder: editor.lang.leadingimage.captionPlaceholder } ), doc ); // Replace element with <figure>. replaceSafely( figure, shift.element ); // Use old <img/> or <a><img/></a> instead of the one from the template, // so we won't lose additional attributes. imageOrLink.replace( figure.findOne( 'img' ) ); // Update widget's element. shift.element = figure; } // The caption was present, but now it's to be removed. else { // Unwrap <img/> or <a><img/></a> from figure. imageOrLink.replace( shift.element ); // Update widget's element. shift.element = imageOrLink; } }, link: function( shift, oldValue, newValue ) { if ( shift.changed.link ) { var img = shift.element.is( 'img' ) ? shift.element : shift.element.findOne( 'img' ), link = shift.element.is( 'a' ) ? shift.element : shift.element.findOne( 'a' ), // Why deflate: // If element is <img/>, it will be wrapped into <a>, // which becomes a new widget.element. // If element is <a><img/></a>, it will be unlinked // so <img/> becomes a new widget.element. needsDeflate = ( shift.element.is( 'a' ) && !newValue ) || ( shift.element.is( 'img' ) && newValue ), newEl; if ( needsDeflate ) shift.deflate(); // If unlinked the image, returned element is <img>. if ( !newValue ) newEl = unwrapFromLink( link ); else { // If linked the image, returned element is <a>. if ( !oldValue ) newEl = wrapInLink( img, shift.newData.link ); // Set and remove all attributes associated with this state. var attributes = CKEDITOR.plugins.leadingimage.getLinkAttributesGetter()( editor, newValue ); if ( !CKEDITOR.tools.isEmpty( attributes.set ) ) ( newEl || link ).setAttributes( attributes.set ); if ( attributes.removed.length ) ( newEl || link ).removeAttributes( attributes.removed ); } if ( needsDeflate ) shift.element = newEl; } } }; function wrapInCentering( editor, element ) { var attribsAndStyles = {}; if ( alignClasses ) attribsAndStyles.attributes = { 'class': alignClasses[ 1 ] }; else attribsAndStyles.styles = { 'text-align': 'center' }; // There's no gentle way to center inline element with CSS, so create p/div // that wraps widget contents and does the trick either with style or class. var center = doc.createElement( editor.activeEnterMode == CKEDITOR.ENTER_P ? 'p' : 'div', attribsAndStyles ); // Replace element with centering wrapper. replaceSafely( center, element ); element.move( center ); return center; } function unwrapFromCentering( element ) { var imageOrLink = element.findOne( 'a,img' ); imageOrLink.replace( element ); return imageOrLink; } // Wraps <img/> -> <a><img/></a>. // Returns reference to <a>. // // @param {CKEDITOR.dom.element} img // @param {Object} linkData // @returns {CKEDITOR.dom.element} function wrapInLink( img, linkData ) { var link = doc.createElement( 'a', { attributes: { href: linkData.url } } ); link.replace( img ); img.move( link ); return link; } // De-wraps <a><img/></a> -> <img/>. // Returns the reference to <img/> // // @param {CKEDITOR.dom.element} link // @returns {CKEDITOR.dom.element} function unwrapFromLink( link ) { var img = link.findOne( 'img' ); img.replace( link ); return img; } function replaceSafely( replacing, replaced ) { if ( replaced.getParent() ) { var range = editor.createRange(); range.moveToPosition( replaced, CKEDITOR.POSITION_BEFORE_START ); // Remove old element. Do it before insertion to avoid a case when // element is moved from 'replaced' element before it, what creates // a tricky case which insertElementIntorRange does not handle. replaced.remove(); editable.insertElementIntoRange( replacing, range ); } else { replacing.replace( replaced ); } } return function( shift ) { var name, i; shift.changed = {}; for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; shift.changed[ name ] = shift.oldData ? shift.oldData[ name ] !== shift.newData[ name ] : false; } // Iterate over possible state variables. for ( i = 0; i < shiftables.length; i++ ) { name = shiftables[ i ]; stateActions[ name ]( shift, shift.oldData ? shift.oldData[ name ] : null, shift.newData[ name ] ); } shift.inflate(); }; }, /** * Checks whether the current image ratio matches the natural one * by comparing dimensions. * * @param {CKEDITOR.dom.element} image * @returns {Boolean} */ checkHasNaturalRatio: function( image ) { var $ = image.$, natural = this.getNatural( image ); // The reason for two alternative comparisons is that the rounding can come from // both dimensions, e.g. there are two cases: // 1. height is computed as a rounded relation of the real height and the value of width, // 2. width is computed as a rounded relation of the real width and the value of heigh. return Math.round( $.clientWidth / natural.width * natural.height ) == $.clientHeight || Math.round( $.clientHeight / natural.height * natural.width ) == $.clientWidth; }, /** * Returns natural dimensions of the image. For modern browsers * it uses natural(Width|Height). For old ones (IE8) it creates * a new image and reads the dimensions. * * @param {CKEDITOR.dom.element} image * @returns {Object} */ getNatural: function( image ) { var dimensions; if ( image.$.naturalWidth ) { dimensions = { width: image.$.naturalWidth, height: image.$.naturalHeight }; } else { var img = new Image(); img.src = image.getAttribute( 'src' ); dimensions = { width: img.width, height: img.height }; } return dimensions; }, /** * Returns an attribute getter function. Default getter comes from the Link plugin * and is documented by {@link CKEDITOR.plugins.link#getLinkAttributes}. * * **Note:** It is possible to override this method and use a custom getter e.g. * in the absence of the Link plugin. * * **Note:** If a custom getter is used, a data model format it produces * must be compatible with {@link CKEDITOR.plugins.link#getLinkAttributes}. * * **Note:** A custom getter must understand the data model format produced by * {@link #getLinkAttributesParser} to work correctly. * * @returns {Function} A function that gets (composes) link attributes. * @since 4.5.5 */ getLinkAttributesGetter: function() { // http://dev.ckeditor.com/ticket/13885 return CKEDITOR.plugins.link.getLinkAttributes; }, /** * Returns an attribute parser function. Default parser comes from the Link plugin * and is documented by {@link CKEDITOR.plugins.link#parseLinkAttributes}. * * **Note:** It is possible to override this method and use a custom parser e.g. * in the absence of the Link plugin. * * **Note:** If a custom parser is used, a data model format produced by the parser * must be compatible with {@link #getLinkAttributesGetter}. * * **Note:** If a custom parser is used, it should be compatible with the * {@link CKEDITOR.plugins.link#parseLinkAttributes} data model format. Otherwise the * Link plugin dialog may not be populated correctly with parsed data. However * as long as Enhanced Image is **not** used with the Link plugin dialog, any custom data model * will work, being stored as an internal property of Enhanced Image widget's data only. * * @returns {Function} A function that parses attributes. * @since 4.5.5 */ getLinkAttributesParser: function() { // http://dev.ckeditor.com/ticket/13885 return CKEDITOR.plugins.link.parseLinkAttributes; } }; function setWrapperAlign( widget, alignClasses ) { var wrapper = widget.wrapper, align = widget.data.align, hasCaption = widget.data.hasCaption; if ( alignClasses ) { // Remove all align classes first. for ( var i = 3; i--; ) wrapper.removeClass( alignClasses[ i ] ); if ( align == 'center' ) { // Avoid touching non-captioned, centered widgets because // they have the class set on the element instead of wrapper: // // <div class="cke_widget_wrapper"> // <p class="center-class"> // <img /> // </p> // </div> if ( hasCaption ) { wrapper.addClass( alignClasses[ 1 ] ); } } else if ( align != 'none' ) { wrapper.addClass( alignClasses[ alignmentsObj[ align ] ] ); } } else { if ( align == 'center' ) { if ( hasCaption ) wrapper.setStyle( 'text-align', 'center' ); else wrapper.removeStyle( 'text-align' ); wrapper.removeStyle( 'float' ); } else { if ( align == 'none' ) wrapper.removeStyle( 'float' ); else wrapper.setStyle( 'float', align ); wrapper.removeStyle( 'text-align' ); } } } // Returns a function that creates widgets from all <img> and // <figure class="{config.image2_captionedClass}"> elements. // // @param {CKEDITOR.editor} editor // @returns {Function} function upcastWidgetElement( editor ) { var isCenterWrapper = centerWrapperChecker( editor ), captionedClass = editor.config.leadingImage_captionedClass; // @param {CKEDITOR.htmlParser.element} el // @param {Object} data return function( el, data ) { var dimensions = { width: 1, height: 1 }, name = el.name, image; // http://dev.ckeditor.com/ticket/11110 Don't initialize on pasted fake objects. if ( el.attributes[ 'data-cke-realelement' ] ) return; // If a center wrapper is found, there are 3 possible cases: // // 1. <div style="text-align:center"><figure>...</figure></div>. // In this case centering is done with a class set on widget.wrapper. // Simply replace centering wrapper with figure (it's no longer necessary). // // 2. <p style="text-align:center"><img/></p>. // Nothing to do here: <p> remains for styling purposes. // // 3. <div style="text-align:center"><img/></div>. // Nothing to do here (2.) but that case is only possible in enterMode different // than ENTER_P. if ( isCenterWrapper( el ) ) { if ( name == 'div' ) { var figure = el.getFirst( 'figure' ); // Case #1. if ( figure ) { el.replaceWith( figure ); el = figure; } } // Cases #2 and #3 (handled transparently) // If there's a centering wrapper, save it in data. data.align = 'center'; // Image can be wrapped in link <a><img/></a>. image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); } // No center wrapper has been found. else if ( name == 'figure' && el.hasClass( captionedClass ) ) { image = el.getFirst( 'img' ) || el.getFirst( 'a' ).getFirst( 'img' ); // Upcast linked image like <a><img/></a>. } else if ( isLinkedOrStandaloneImage( el ) ) { image = el.name == 'a' ? el.children[ 0 ] : el; } if ( !image ) return; // If there's an image, then cool, we got a widget. // Now just remove dimension attributes expressed with %. for ( var d in dimensions ) { var dimension = image.attributes[ d ]; if ( dimension && dimension.match( regexPercent ) ) delete image.attributes[ d ]; } return el; }; } // Returns a function which transforms the widget to the external format // according to the current configuration. // // @param {CKEDITOR.editor} function downcastWidgetElement( editor ) { var alignClasses = editor.config.leadingImage_alignClasses; // @param {CKEDITOR.htmlParser.element} el return function( el ) { // In case of <a><img/></a>, <img/> is the element to hold // inline styles or classes (image2_alignClasses). var attrsHolder = el.name == 'a' ? el.getFirst() : el, attrs = attrsHolder.attributes, align = this.data.align; // De-wrap the image from resize handle wrapper. // Only block widgets have one. if ( !this.inline ) { var resizeWrapper = el.getFirst( 'span' ); if ( resizeWrapper ) resizeWrapper.replaceWith( resizeWrapper.getFirst( { img: 1, a: 1 } ) ); } if ( align && align != 'none' ) { var styles = CKEDITOR.tools.parseCssText( attrs.style || '' ); // When the widget is captioned (<figure>) and internally centering is done // with widget's wrapper style/class, in the external data representation, // <figure> must be wrapped with an element holding an style/class: // // <div style="text-align:center"> // <figure class="image" style="display:inline-block">...</figure> // </div> // or // <div class="some-center-class"> // <figure class="image">...</figure> // </div> // if ( align == 'center' && el.name == 'figure' ) { el = el.wrapWith( new CKEDITOR.htmlParser.element( 'div', alignClasses ? { 'class': alignClasses[ 1 ] } : { style: 'text-align:center' } ) ); } // If left/right, add float style to the downcasted element. else if ( align in { left: 1, right: 1 } ) { if ( alignClasses ) attrsHolder.addClass( alignClasses[ alignmentsObj[ align ] ] ); else styles[ 'float' ] = align; } // Update element styles. if ( !alignClasses && !CKEDITOR.tools.isEmpty( styles ) ) attrs.style = CKEDITOR.tools.writeCssText( styles ); } return el; }; } // Returns a function that checks if an element is a centering wrapper. // // @param {CKEDITOR.editor} editor // @returns {Function} function centerWrapperChecker( editor ) { var captionedClass = editor.config.leadingImage_captionedClass, alignClasses = editor.config.leadingImage_alignClasses, validChildren = { figure: 1, a: 1, img: 1 }; return function( el ) { // Wrapper must be either <div> or <p>. if ( !( el.name in { div: 1, p: 1 } ) ) return false; var children = el.children; // Centering wrapper can have only one child. if ( children.length !== 1 ) return false; var child = children[ 0 ]; // Only <figure> or <img /> can be first (only) child of centering wrapper, // regardless of its type. if ( !( child.name in validChildren ) ) return false; // If centering wrapper is <p>, only <img /> can be the child. // <p style="text-align:center"><img /></p> if ( el.name == 'p' ) { if ( !isLinkedOrStandaloneImage( child ) ) return false; } // Centering <div> can hold <img/> or <figure>, depending on enterMode. else { // If a <figure> is the first (only) child, it must have a class. // <div style="text-align:center"><figure>...</figure><div> if ( child.name == 'figure' ) { if ( !child.hasClass( captionedClass ) ) return false; } else { // Centering <div> can hold <img/> or <a><img/></a> only when enterMode // is ENTER_(BR|DIV). // <div style="text-align:center"><img /></div> // <div style="text-align:center"><a><img /></a></div> if ( editor.enterMode == CKEDITOR.ENTER_P ) return false; // Regardless of enterMode, a child which is not <figure> must be // either <img/> or <a><img/></a>. if ( !isLinkedOrStandaloneImage( child ) ) return false; } } // Centering wrapper got to be... centering. If image2_alignClasses are defined, // check for centering class. Otherwise, check the style. if ( alignClasses ? el.hasClass( alignClasses[ 1 ] ) : CKEDITOR.tools.parseCssText( el.attributes.style || '', true )[ 'text-align' ] == 'center' ) return true; return false; }; } // Checks whether element is <img/> or <a><img/></a>. // // @param {CKEDITOR.htmlParser.element} function isLinkedOrStandaloneImage( el ) { if ( el.name == 'img' ) return true; else if ( el.name == 'a' ) return el.children.length == 1 && el.getFirst( 'img' ); return false; } // Sets width and height of the widget image according to current widget data. // // @param {CKEDITOR.plugins.widget} widget function setDimensions( widget ) { var data = widget.data, dimensions = { width: data.width, height: data.height }, image = widget.parts.image; for ( var d in dimensions ) { if ( dimensions[ d ] ) image.setAttribute( d, dimensions[ d ] ); else image.removeAttribute( d ); } } // Defines all features related to drag-driven image resizing. // // @param {CKEDITOR.plugins.widget} widget function setupResizer( widget ) { var editor = widget.editor, editable = editor.editable(), doc = editor.document, // Store the resizer in a widget for testing (http://dev.ckeditor.com/ticket/11004). resizer = widget.resizer = doc.createElement( 'span' ); resizer.addClass( 'cke_image_resizer' ); resizer.setAttribute( 'title', editor.lang.leadingimage.resizer ); resizer.append( new CKEDITOR.dom.text( '\u200b', doc ) ); // Inline widgets don't need a resizer wrapper as an image spans the entire widget. if ( !widget.inline ) { var imageOrLink = widget.parts.link || widget.parts.image, oldResizeWrapper = imageOrLink.getParent(), resizeWrapper = doc.createElement( 'span' ); resizeWrapper.addClass( 'cke_image_resizer_wrapper' ); resizeWrapper.append( imageOrLink ); resizeWrapper.append( resizer ); widget.element.append( resizeWrapper, true ); // Remove the old wrapper which could came from e.g. pasted HTML // and which could be corrupted (e.g. resizer span has been lost). if ( oldResizeWrapper.is( 'span' ) ) oldResizeWrapper.remove(); } else { widget.wrapper.append( resizer ); } // Calculate values of size variables and mouse offsets. resizer.on( 'mousedown', function( evt ) { var image = widget.parts.image, // "factor" can be either 1 or -1. I.e.: For right-aligned images, we need to // subtract the difference to get proper width, etc. Without "factor", // resizer starts working the opposite way. factor = widget.data.align == 'right' ? -1 : 1, // The x-coordinate of the mouse relative to the screen // when button gets pressed. startX = evt.data.$.screenX, startY = evt.data.$.screenY, // The initial dimensions and aspect ratio of the image. startWidth = image.$.clientWidth, startHeight = image.$.clientHeight, ratio = startWidth / startHeight, listeners = [], // A class applied to editable during resizing. cursorClass = 'cke_image_s' + ( !~factor ? 'w' : 'e' ), nativeEvt, newWidth, newHeight, updateData, moveDiffX, moveDiffY, moveRatio; // Save the undo snapshot first: before resizing. editor.fire( 'saveSnapshot' ); // Mousemove listeners are removed on mouseup. attachToDocuments( 'mousemove', onMouseMove, listeners ); // Clean up the mousemove listener. Update widget data if valid. attachToDocuments( 'mouseup', onMouseUp, listeners ); // The entire editable will have the special cursor while resizing goes on. editable.addClass( cursorClass ); // This is to always keep the resizer element visible while resizing. resizer.addClass( 'cke_image_resizing' ); // Attaches an event to a global document if inline editor. // Additionally, if classic (`iframe`-based) editor, also attaches the same event to `iframe`'s document. function attachToDocuments( name, callback, collection ) { var globalDoc = CKEDITOR.document, listeners = []; if ( !doc.equals( globalDoc ) ) listeners.push( globalDoc.on( name, callback ) ); listeners.push( doc.on( name, callback ) ); if ( collection ) { for ( var i = listeners.length; i--; ) collection.push( listeners.pop() ); } } // Calculate with first, and then adjust height, preserving ratio. function adjustToX() { newWidth = startWidth + factor * moveDiffX; newHeight = Math.round( newWidth / ratio ); } // Calculate height first, and then adjust width, preserving ratio. function adjustToY() { newHeight = startHeight - moveDiffY; newWidth = Math.round( newHeight * ratio ); } // This is how variables refer to the geometry. // Note: x corresponds to moveOffset, this is the position of mouse // Note: o corresponds to [startX, startY]. // // +--------------+--------------+ // | | | // | I | II | // | | | // +------------- o -------------+ _ _ _ // | | | ^ // | VI | III | | moveDiffY // | | x _ _ _ _ _ v // +--------------+---------|----+ // | | // <-------> // moveDiffX function onMouseMove( evt ) { nativeEvt = evt.data.$; // This is how far the mouse is from the point the button was pressed. moveDiffX = nativeEvt.screenX - startX; moveDiffY = startY - nativeEvt.screenY; // This is the aspect ratio of the move difference. moveRatio = Math.abs( moveDiffX / moveDiffY ); // Left, center or none-aligned widget. if ( factor == 1 ) { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) adjustToX(); // Case: I. else { if ( moveRatio >= ratio ) adjustToX(); else adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: II. else { adjustToY(); } } } // Right-aligned widget. It mirrors behaviours, so I becomes II, // IV becomes III and vice-versa. else { if ( moveDiffX <= 0 ) { // Case: IV. if ( moveDiffY <= 0 ) { if ( moveRatio >= ratio ) adjustToY(); else adjustToX(); } // Case: I. else { adjustToY(); } } else { // Case: III. if ( moveDiffY <= 0 ) adjustToX(); // Case: II. else { if ( moveRatio >= ratio ) { adjustToX(); } else { adjustToY(); } } } } // Don't update attributes if less than 10. // This is to prevent images to visually disappear. if ( newWidth >= 15 && newHeight >= 15 ) { image.setAttributes( { width: newWidth, height: newHeight } ); updateData = true; } else { updateData = false; } } function onMouseUp() { var l; while ( ( l = listeners.pop() ) ) l.removeListener(); // Restore default cursor by removing special class. editable.removeClass( cursorClass ); // This is to bring back the regular behaviour of the resizer. resizer.removeClass( 'cke_image_resizing' ); if ( updateData ) { widget.setData( { width: newWidth, height: newHeight } ); // Save another undo snapshot: after resizing. editor.fire( 'saveSnapshot' ); } // Don't update data twice or more. updateData = false; } } ); // Change the position of the widget resizer when data changes. widget.on( 'data', function() { resizer[ widget.data.align == 'right' ? 'addClass' : 'removeClass' ]( 'cke_image_resizer_left' ); } ); } // Integrates widget alignment setting with justify // plugin's commands (execution and refreshment). // @param {CKEDITOR.editor} editor // @param {String} value 'left', 'right', 'center' or 'block' function alignCommandIntegrator( editor ) { var execCallbacks = [], enabled; return function( value ) { var command = editor.getCommand( 'justify' + value ); // Most likely, the justify plugin isn't loaded. if ( !command ) return; // This command will be manually refreshed along with // other commands after exec. execCallbacks.push( function() { command.refresh( editor, editor.elementPath() ); } ); if ( value in { right: 1, left: 1, center: 1 } ) { command.on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); if ( widget ) { widget.setData( 'align', value ); // Once the widget changed its align, all the align commands // must be refreshed: the event is to be cancelled. for ( var i = execCallbacks.length; i--; ) execCallbacks[ i ](); evt.cancel(); } } ); } command.on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ), allowed = { right: 1, left: 1, center: 1 }; if ( !widget ) return; // Cache "enabled" on first use. This is because filter#checkFeature may // not be available during plugin's afterInit in the future — a moment when // alignCommandIntegrator is called. if ( enabled === undefined ) enabled = editor.filter.checkFeature( editor.widgets.registered.leadingimage.features.align ); // Don't allow justify commands when widget alignment is disabled (http://dev.ckeditor.com/ticket/11004). if ( !enabled ) this.setState( CKEDITOR.TRISTATE_DISABLED ); else { this.setState( ( widget.data.align == value ) ? ( CKEDITOR.TRISTATE_ON ) : ( ( value in allowed ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ) ); } evt.cancel(); } ); }; } function linkCommandIntegrator( editor ) { // Nothing to integrate with if link is not loaded. if ( !editor.plugins.link ) return; CKEDITOR.on( 'dialogDefinition', function( evt ) { var dialog = evt.data; if ( dialog.name == 'link' ) { var def = dialog.definition; var onShow = def.onShow, onOk = def.onOk; def.onShow = function() { var widget = getFocusedWidget( editor ), displayTextField = this.getContentElement( 'info', 'linkDisplayText' ).getElement().getParent().getParent(); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) { this.setupContent( widget.data.link || {} ); // Hide the display text in case of linking leadingImage widget. displayTextField.hide(); } else { // Make sure that display text is visible, as it might be hidden by leadingImage integration // before. displayTextField.show(); onShow.apply( this, arguments ); } }; // Set widget data if linking the widget using // link dialog (instead of default action). // State shifter handles data change and takes // care of internal DOM structure of linked widget. def.onOk = function() { var widget = getFocusedWidget( editor ); // Widget cannot be enclosed in a link, i.e. // <a>foo<inline widget/>bar</a> if ( widget && ( widget.inline ? !widget.wrapper.getAscendant( 'a' ) : 1 ) ) { var data = {}; // Collect data from fields. this.commitContent( data ); // Set collected data to widget. widget.setData( 'link', data ); } else { onOk.apply( this, arguments ); } }; } } ); // Overwrite default behaviour of unlink command. editor.getCommand( 'unlink' ).on( 'exec', function( evt ) { var widget = getFocusedWidget( editor ); // Override unlink only when link truly belongs to the widget. // If wrapped inline widget in a link, let default unlink work (http://dev.ckeditor.com/ticket/11814). if ( !widget || !widget.parts.link ) return; widget.setData( 'link', null ); // Selection (which is fake) may not change if unlinked image in focused widget, // i.e. if captioned image. Let's refresh command state manually here. this.refresh( editor, editor.elementPath() ); evt.cancel(); } ); // Overwrite default refresh of unlink command. editor.getCommand( 'unlink' ).on( 'refresh', function( evt ) { var widget = getFocusedWidget( editor ); if ( !widget ) return; // Note that widget may be wrapped in a link, which // does not belong to that widget (http://dev.ckeditor.com/ticket/11814). this.setState( widget.data.link || widget.wrapper.getAscendant( 'a' ) ? CKEDITOR.TRISTATE_OFF : CKEDITOR.TRISTATE_DISABLED ); evt.cancel(); } ); } // Returns the focused widget, if of the type specific for this plugin. // If no widget is focused, `null` is returned. // // @param {CKEDITOR.editor} // @returns {CKEDITOR.plugins.widget} function getFocusedWidget( editor ) { var widget = editor.widgets.focused; if ( widget && widget.name === 'leadingimage' ) return widget; return null; } // Returns a set of widget allowedContent rules, depending // on configurations like config#leadingImage_alignClasses or // config#leadingImage_captionedClass. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetAllowedContent( editor ) { var alignClasses = editor.config.leadingImage_alignClasses, rules = { // Widget may need <div> or <p> centering wrapper. div: { match: centerWrapperChecker( editor ) }, p: { match: centerWrapperChecker( editor ) }, img: { attributes: '!src,alt,width,height' }, figure: { classes: '!' + editor.config.leadingImage_captionedClass }, figcaption: true }; if ( alignClasses ) { // Centering class from the config. rules.div.classes = alignClasses[ 1 ]; rules.p.classes = rules.div.classes; // Left/right classes from the config. rules.img.classes = alignClasses[ 0 ] + ',' + alignClasses[ 2 ]; rules.figure.classes += ',' + rules.img.classes; } else { // Centering with text-align. rules.div.styles = 'text-align'; rules.p.styles = 'text-align'; rules.img.styles = 'float'; rules.figure.styles = 'float,display'; } return rules; } // Returns a set of widget feature rules, depending // on editor configuration. Note that the following may not cover // all the possible cases since requiredContent supports a single // tag only. // // @param {CKEDITOR.editor} // @returns {Object} function getWidgetFeatures( editor ) { var alignClasses = editor.config.leadingImage_alignClasses, features = { dimension: { requiredContent: 'img[width,height]' }, align: { requiredContent: 'img' + ( alignClasses ? '(' + alignClasses[ 0 ] + ')' : '{float}' ) }, caption: { requiredContent: 'figcaption' } }; return features; } // Returns element which is styled, considering current // state of the widget. // // @see CKEDITOR.plugins.widget#applyStyle // @param {CKEDITOR.plugins.widget} widget // @returns {CKEDITOR.dom.element} function getStyleableElement( widget ) { return widget.data.hasCaption ? widget.element : widget.parts.image; } } )(); /** * A CSS class applied to the `<figure>` element of a captioned image. * * Read more in the [documentation](#!/guide/dev_captionedimage) and see the * [SDK sample](http://sdk.ckeditor.com/samples/captionedimage.html). * * // Changes the class to "captionedImage". * config.leadingImage_captionedClass = 'captionedImage'; * * @cfg {String} [leadingImage_captionedClass='image'] * @member CKEDITOR.config */ CKEDITOR.config.leadingImage_captionedClass = 'image'; /** * Determines whether dimension inputs should be automatically filled when the image URL changes in the Enhanced Image * plugin dialog window. * * Read more in the [documentation](#!/guide/dev_captionedimage) and see the * [SDK sample](http://sdk.ckeditor.com/samples/captionedimage.html). * * config.leadingImage_prefillDimensions = false; * * @since 4.5 * @cfg {Boolean} [leadingImage_prefillDimensions=true] * @member CKEDITOR.config */ /** * Disables the image resizer. By default the resizer is enabled. * * Read more in the [documentation](#!/guide/dev_captionedimage) and see the * [SDK sample](http://sdk.ckeditor.com/samples/captionedimage.html). * * config.leadingImage_disableResizer = true; * * @since 4.5 * @cfg {Boolean} [leadingImage_disableResizer=false] * @member CKEDITOR.config */ /** * CSS classes applied to aligned images. Useful to take control over the way * the images are aligned, i.e. to customize output HTML and integrate external stylesheets. * * Classes should be defined in an array of three elements, containing left, center, and right * alignment classes, respectively. For example: * * config.leadingImage_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * **Note**: Once this configuration option is set, the plugin will no longer produce inline * styles for alignment. It means that e.g. the following HTML will be produced: * * <img alt="My image" class="custom-center-class" src="foo.png" /> * * instead of: * * <img alt="My image" style="float:left" src="foo.png" /> * * **Note**: Once this configuration option is set, corresponding style definitions * must be supplied to the editor: * * * For [classic editor](#!/guide/dev_framed) it can be done by defining additional * styles in the {@link CKEDITOR.config#contentsCss stylesheets loaded by the editor}. The same * styles must be provided on the target page where the content will be loaded. * * For [inline editor](#!/guide/dev_inline) the styles can be defined directly * with `<style> ... <style>` or `<link href="..." rel="stylesheet">`, i.e. within the `<head>` * of the page. * * For example, considering the following configuration: * * config.leadingImage_alignClasses = [ 'align-left', 'align-center', 'align-right' ]; * * CSS rules can be defined as follows: * * .align-left { * float: left; * } * * .align-right { * float: right; * } * * .align-center { * text-align: center; * } * * .align-center > figure { * display: inline-block; * } * * Read more in the [documentation](#!/guide/dev_captionedimage) and see the * [SDK sample](http://sdk.ckeditor.com/samples/captionedimage.html). * * @since 4.4 * @cfg {String[]} [leadingImage_alignClasses=null] * @member CKEDITOR.config */ /** * Determines whether alternative text is required for the captioned image. * * config.leadingImage_altRequired = true; * * Read more in the [documentation](#!/guide/dev_captionedimage) and see the * [SDK sample](http://sdk.ckeditor.com/samples/captionedimage.html). * * @since 4.6.0 * @cfg {Boolean} [leadingImage_altRequired=false] * @member CKEDITOR.config */
/* Copyright (c) 2013 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function () { "use strict"; angular.module('pot.directives', []) .directive('foodBtnPanel', function() { return { restrict: 'E', scope: { items: '=', showFilter: '=', clickHandler: '&' }, templateUrl: 'app/partials/food_btn_panel.html' }; }) .directive('foodbtn', function(food, $compile) { var tplBtn = '<a class="btn btn-default" ng-click="clickHandler({item:item.id})" title="Add {{ item.name }} to the pot"><img ng-src="{{ item.img }}"><span>{{ item.name }}</span></a> '; var tplBtnCooked = '<a class="btn btn-default" ng-click="clickHandler({item:cookedItem.id})" title="Add {{ cookedItem.name }} to the pot"><img ng-src="{{ cookedItem.img }}"></a>'; var tplBtnDried = '<a class="btn btn-default" ng-click="clickHandler({item:driedItem.id})" title="Add {{ driedItem.name }} to the pot"><img ng-src="{{ driedItem.img }}"></a>'; var tplGroupOpen = '<div class="food-btn-group btn-group">'; var tplGroupClose = '</div>'; return { restrict: 'E', replace: true, link: function(scope, element, attrs) { var template = '<div class="food-btn-group btn-group">' + tplBtn; var f = scope.item; scope.clickHandler = scope.$parent.clickHandler; // deprecated if (f.hasOwnProperty('cookable')) { scope.cookedItem = food[f.cookable.product]; template += tplBtnCooked; } if (f.hasOwnProperty('cooked')) { scope.cookedItem = food[f.cooked]; template += tplBtnCooked; } // deprecated if (f.hasOwnProperty('dryable')) { scope.driedItem = food[f.dryable.product]; template += tplBtnDried; } if (f.hasOwnProperty('dried')) { scope.driedItem = food[f.dried]; template += tplBtnDried; } template += '</div>'; element.html(template); $compile(element.contents())(scope); } } }); }());
import PropTypes from 'prop-types' import Lookup from './lookup' import Select from './select' import Toggle from './toggle' import Daterange from './daterange' import React from 'react' class Overview extends React.Component { static propTypes = { filters: PropTypes.array, results: PropTypes.object, onAddPanel: PropTypes.func, onChange: PropTypes.func, onDone: PropTypes.func, onRemovePanel: PropTypes.func, onReset: PropTypes.func, onUpdate: PropTypes.func } render() { const { filters, onDone } = this.props return ( <div className="reframe-filters-panel"> <div className="reframe-filters-header"> { onDone ? <div className="reframe-filters-header-icon" onClick={ this._handleDone.bind(this) }> <i className="fa fa-chevron-left" /> </div> : <div className="reframe-filters-header-icon" /> } <div className="reframe-filters-header-title"> Filter Results </div> <div className="reframe-filters-header-icon" /> </div> <div className="reframe-filters-body"> <div className="reframe-filters-overview"> { filters.map((filter, index) => { if(filter.type === 'toggle') return <Toggle {...this._getToggle(filter) } key={`filter_${index}`} /> if(filter.type === 'lookup') return <Lookup {...this._getLookup(filter) } key={`filter_${index}`} /> if(filter.type === 'select') return <Select {...this._getSelect(filter) } key={`filter_${index}`} /> if(filter.type === 'daterange') return <Daterange {...this._getDaterange(filter) } key={`filter_${index}`} /> })} </div> </div> <div className="reframe-filters-footer"> <button className="ui red fluid button" onClick={ this._handleReset.bind(this) }> Reset Filters </button> </div> </div> ) } _getToggle(filter) { const { results, onChange } = this.props const { format, label, name } = filter return { format, label, name, results, onChange } } _getLookup(filter) { const { results, onAddPanel, onChange, onRemovePanel } = this.props const { format, label, multiple, options } = filter return { format, label, multiple, name, options, results, onAddPanel, onChange, onRemovePanel } } _getSelect(filter) { const { results, onAddPanel, onChange, onRemovePanel } = this.props return { ...filter, results, onAddPanel, onChange, onRemovePanel } } _getDaterange(filter) { const { results, onAddPanel, onChange, onRemovePanel } = this.props return { ...filter, results, onAddPanel, onChange, onRemovePanel } } _handleDone() { this.props.onDone() } _handleReset() { this.props.onReset() } } export default Overview
import {Meteor} from 'meteor/meteor'; import {computed, observable, extendObservable, action, useStrict, toJS, map} from 'mobx'; import Mongo2Mobx from './Mongo2Mobx' //window.toJS = toJS; class MoviesStore { constructor() { // useStrict(true); this.mongo2mobx = new Mongo2Mobx(this); } @observable movies: []; @observable moviesLoading: false; @computed get total() { return this.movies && this.movies.length || 0; } @action updateMovies(newMovies) { this.movies = newMovies; } @action setMoviesLoading(boolean) { this.moviesLoading = boolean; } } // class MoviesStore { // constructor() { // //useStrict(true); // extendObservable(this, { // moviesLoading: false, // movies: [], // updateMovies: action((newMovies) => { // this.movies = newMovies; // }), // setMoviesLoading: action((boolean) => { // this.moviesLoading = boolean; // }), // }); // this.mongo2mobx = new Mongo2Mobx(this); // } // } var store = window.store = new MoviesStore(); export default store;
#!node const search = require('./search.json') const DELIM = ';' // Create a map of { 'project, issuetype', count } const issueMap = new Map() for (let issue of search.issues) { const { fields: { issuetype: { name: issuetype }, project: { key: project } } } = issue const mapKey = JSON.stringify({project, issuetype}) const count = issueMap.get(mapKey) || 0 issueMap.set(mapKey, count + 1) } // sort and print const issueMapAsc = new Map([...issueMap].sort()) console.log(`project${DELIM}issuetype${DELIM}count`) for (let [key, value] of issueMapAsc) { const {project, issuetype} = JSON.parse(key) console.log(`${project}${DELIM}${issuetype}${DELIM}${value}`) }
importScripts ("lib/glMatrix.js", //"lib/requestAnimationFrame.js", "src/J3D.js", "src/util/Color.js", "src/math/Vector2.js", "src/math/Vector3.js", "src/math/Matrix44.js", "src/engine/Engine.js", "src/engine/Camera.js", "src/engine/Light.js", "src/engine/Geometry.js", "src/engine/Mesh.js", "src/engine/Scene.js", "src/engine/Loader.js", "src/engine/ShaderAtlas.js", "src/engine/Texture.js", "src/engine/Cubemap.js", "src/engine/Transform.js", "src/engine/Postprocess.js", "src/engine/Primitives.js", "src/engine/FrameBuffer.js", "src/engine/ShaderSource.js", "src/engine/Shader.js", "src/util/Time.js", "src/util/ShaderUtil.js", "src/util/Logger.js", "src/engine/BuiltinShaders.js"); var engine, scene; var theta = 0; var redLightMax = 0.33; exports.run = function (canvas) { // Create engine engine = new J3D.Engine(canvas); // Setup camera camera = new J3D.Transform(); camera.camera = new J3D.Camera(); camera.position.z = -4; camera.rotation.y = Math.PI; engine.camera = camera; // Setup lights light1 = new J3D.Transform(); light1.light = new J3D.Light(J3D.DIRECT); light1.light.color = new J3D.Color(0.33, 0.33, 0, 1); light1.light.direction = new v3(0, -1, 0).norm(); light2 = new J3D.Transform(); light2.light = new J3D.Light(J3D.POINT); light2.light.color = new J3D.Color(redLightMax, 0, 0, 1); light2.position = new v3(10, 0, 0); light3 = new J3D.Transform(); light3.light = new J3D.Light(J3D.POINT); light3.light.color = new J3D.Color(0, 0, 0.66, 1); // Get scene and setup ambient light color scene = engine.scene; scene.ambient = J3D.Color.black; // Add lights and camera scene.add(camera); scene.add(light1); scene.add(light2); scene.add(light3); buildScene(); }; function buildScene(){ // Setup materials moMat = J3D.BuiltinShaders.fetch("Gouraud"); moMat.su.specularIntensity = 1; moMat.su.shininess = 32; moMat.su.color = new J3D.Color(0.9, 0.9, 0.9, 1); moMat.hasColorTexture = false; ctMat = J3D.BuiltinShaders.fetch("Phong"); ctMat.su.color = J3D.Color.white; ctMat.su.specularIntensity = 10; ctMat.su.shininess = 32; ctMat.colorTexture = new J3D.Texture("demo/models/textures/containerbake512.jpg"); ctMat.hasColorTexture = true; crMat = J3D.BuiltinShaders.fetch("Phong"); crMat.su.color = new J3D.Color(1,1,1,1);//J3D.Color.white; crMat.su.specularIntensity = 0.1; crMat.su.shininess = 0.1; crMat.colorTexture = new J3D.Texture("demo/models/textures/crate256.jpg"); crMat.hasColorTexture = true; haMat = J3D.BuiltinShaders.fetch("Gouraud"); haMat.su.specularIntensity = 1; haMat.su.shininess = 32; haMat.su.color = new J3D.Color(1,1,1,1); haMat.colorTexture = new J3D.Texture("demo/models/textures/metalbase.jpg"); haMat.hasColorTexture = true; // Setup transforms and meshes ct = new J3D.Transform(); ct.position.x = -1.5; J3D.Loader.loadJSON("demo/models/container.js", function(j) { ct.geometry = new J3D.Mesh(j); } ); ct.renderer = ctMat; mo = new J3D.Transform(); J3D.Loader.loadJSON("demo/models/monkeyhi.js", function(j) { mo.geometry = new J3D.Mesh(j); } ); mo.scale = v3.ONE().mul(0.66); mo.renderer = moMat; cr = new J3D.Transform(); cr.position.x = 1.5; cr.position.z = 0.5; J3D.Loader.loadJSON("demo/models/crate.js", function(j) { cr.geometry = new J3D.Mesh(j); } ); cr.renderer = crMat; ha = new J3D.Transform(); ha.position = new v3(0.2499574, 0.4273163, -0.2176546); ha.rotation.y = 0;//Math.PI; J3D.Loader.loadJSON("demo/models/handles.js", function(j) { ha.geometry = new J3D.Mesh(j); } ); ha.renderer = haMat; // Add all to the scene scene.add(ct); scene.add(mo); scene.add(cr).add(ha); } exports.draw = function () { /*requestAnimationFrame(draw);*/ light1.enabled = true; /*document.getElementById("yellow").checked;*/ light2.enabled = true; /*document.getElementById("red").checked;*/ light3.enabled = true; /*document.getElementById("blue").checked;*/ if (true/*document.getElementById("ambient").checked*/) { scene.ambient = new J3D.Color(0.1, 0.1, 0.1, 1); } else { scene.ambient = J3D.Color.black; } if (true/*document.getElementById("anim").checked*/) { ct.rotation.x += J3D.Time.deltaTime / 7000; ct.rotation.y -= J3D.Time.deltaTime / 3000; cr.rotation.x -= J3D.Time.deltaTime / 7000; cr.rotation.z += J3D.Time.deltaTime / 3000; mo.rotation.y -= J3D.Time.deltaTime / 7000; } light2.light.color.r = redLightMax * (Math.sin(theta) + 1) / 2; light3.position.x = Math.cos(theta/6) * 3; light3.position.z = Math.sin(theta/6) * 3; theta += 0.1; engine.render(); };
import React from 'react'; const Footer = () => { return ( <footer className="page-footer blue darken-2"> <div className="container"> <div className="row"> <div className="col l6 s12"> <h5 className="white-text">Footer Content</h5> <p className="grey-text text-lighten-4">You can use rows and columns here to organize your footer content.</p> </div> <div className="col l4 offset-l2 s12"> <h5 className="white-text">Links</h5> <ul> <li><a className="grey-text text-lighten-3" href="#!">Link 1</a></li> <li><a className="grey-text text-lighten-3" href="#!">Link 2</a></li> <li><a className="grey-text text-lighten-3" href="#!">Link 3</a></li> <li><a className="grey-text text-lighten-3" href="#!">Link 4</a></li> </ul> </div> </div> </div> <div className="footer-copyright"> <div className="container"> © {new Date().getFullYear()} Copyright Text <a className="grey-text text-lighten-4 right" href="#!">More Links</a> </div> </div> </footer> ); }; export default Footer;
/** * DocumentFormatter - format and display a Document * @author Daniel Ringwalt (ringw) */ /** * Accepts document as argument and draws document in discrete blocks * * @param {Vex.Flow.Document} Document object to retrieve information from * @constructor */ Vex.Flow.DocumentFormatter = function(document) { if (arguments.length > 0) this.init(document); } Vex.Flow.DocumentFormatter.prototype.init = function(document) { if (typeof document != "object") throw new Vex.RERR("ArgumentError", "new Vex.Flow.DocumentFormatter() requires Document object argument"); this.document = document; // Groups of measures are contained in blocks (which could correspond to a // line or a page of music.) // Each block is intended to be drawn on a different canvas. // Blocks must be managed by the subclass. this.measuresInBlock = []; // block # -> array of measure # in block this.blockDimensions = []; // block # -> [width, height] // Stave layout managed by subclass this.vfStaves = []; // measure # -> stave # -> VexFlow stave // Minimum measure widths can be used for formatting by subclasses this.minMeasureWidths = []; // minMeasureHeights: // this.minMeasureHeights[m][0] is space above measure // this.minMeasureHeights[m][s+1] is minimum height of stave s this.minMeasureHeights = []; } /** * Vex.Flow.DocumentFormatter.prototype.getStaveX: to be defined by subclass * Params: m (measure #), s (stave #) * Returns: x (number) */ /** * Calculate vertical position of stave within block * @param {Number} Measure number * @param {Number} Stave number */ Vex.Flow.DocumentFormatter.prototype.getStaveY = function(m, s) { // Default behavour: calculate from stave above this one (or 0 for top stave) // (Have to make sure not to call getStave on this stave) // If s == 0 and we are in a block, use the max extra space above the // top stave on any measure in the block if (s == 0) { var extraSpace = 0; // Find block for this measure this.measuresInBlock.forEach(function(measures) { if (measures.indexOf(m) > -1) { var maxExtraSpace = 50 - (new Vex.Flow.Stave(0,0,500).getYForLine(0)); measures.forEach(function(measure) { var extra = this.getMinMeasureHeight(measure)[0]; if (extra > maxExtraSpace) maxExtraSpace = extra; }, this); extraSpace = maxExtraSpace; return; } }, this); return extraSpace; } var higherStave = this.getStave(m, s - 1); return higherStave.y + higherStave.getHeight(); } /** * Vex.Flow.DocumentFormatter.prototype.getStaveWidth: defined in subclass * Params: m (measure #), s (stave #) * Returns: width (number) which should be less than the minimum width */ /** * Create a Vex.Flow.Stave from a Vex.Flow.Measure.Stave. * @param {Vex.Flow.Measure.Stave} Original stave object * @param {Number} x position * @param {Number} y position * @param {Number} width of stave * @return {Vex.Flow.Stave} Generated stave object */ Vex.Flow.DocumentFormatter.prototype.createVexflowStave = function(s, x,y,w) { var vfStave = new Vex.Flow.Stave(x, y, w); s.modifiers.forEach(function(mod) { switch (mod.type) { case "clef": vfStave.addClef(mod.clef); break; case "key": vfStave.addKeySignature(mod.key); break; case "time": var time_sig; if (typeof mod.time == "string") time_sig = mod.time; else time_sig = mod.num_beats.toString() + "/" + mod.beat_value.toString(); vfStave.addTimeSignature(time_sig); break; } }); if (typeof s.clef == "string") vfStave.clef = s.clef; return vfStave; } /** * Use getStaveX, getStaveY, getStaveWidth to create a Vex.Flow.Stave from * the document and store it in vfStaves. * @param {Number} Measure number * @param {Number} Stave number * @return {Vex.Flow.Stave} Stave for the measure and stave # */ Vex.Flow.DocumentFormatter.prototype.getStave = function(m, s) { if (m in this.vfStaves && s in this.vfStaves[m]) return this.vfStaves[m][s]; if (typeof this.getStaveX != "function" || typeof this.getStaveWidth != "function") throw new Vex.RERR("MethodNotImplemented", "Document formatter must implement getStaveX, getStaveWidth"); //console.log(m, this.document.getMeasure(m)); var stave = this.document.getMeasure(m).getStave(s); if (! stave) return undefined; var vfStave = this.createVexflowStave(stave, this.getStaveX(m, s), this.getStaveY(m, s), this.getStaveWidth(m, s)); if (! (m in this.vfStaves)) this.vfStaves[m] = []; this.vfStaves[m][s] = vfStave; return vfStave; } /** * Create a Vex.Flow.Voice from a Vex.Flow.Measure.Voice. * Each note is added to the proper Vex.Flow.Stave in staves * (spanning multiple staves in a single voice not currently supported.) * @param {Vex.Flow.Measure.Voice} Voice object * @param {Array} Vex.Flow.Staves to add the notes to * @return {Array} Vex.Flow.Voice, objects to be drawn, optional voice w/lyrics */ Vex.Flow.DocumentFormatter.prototype.getVexflowVoice =function(voice, staves){ var vfVoice = new Vex.Flow.Voice({num_beats: voice.time.num_beats, beat_value: voice.time.beat_value, resolution: Vex.Flow.RESOLUTION}); if (voice.time.soft) vfVoice.setMode(Vex.Flow.Voice.Mode.SOFT); // TODO: support spanning multiple staves if (typeof voice.stave != "number") throw new Vex.RERR("InvalidIRError", "Voice should have stave property"); vfVoice.setStave(staves[voice.stave]); var vexflowObjects = new Array(); var beamedNotes = null; // array of all vfNotes in beam var tiedNote = null; // only last vFNote in tie var tupletNotes = null, tupletOpts = null; var clef = staves[voice.stave].clef; var lyricVoice = null; for (var i = 0; i < voice.notes.length; i++) { var note = voice.notes[i]; var vfNote = this.getVexflowNote(voice.notes[i], {clef: clef}); if (note.beam == "begin") beamedNotes = [vfNote]; else if (note.beam && beamedNotes) { beamedNotes.push(vfNote); if (note.beam == "end") { vexflowObjects.push(new Vex.Flow.Beam(beamedNotes, true)); beamedNotes = null; } } if (note.tie == "end" || note.tie == "continue") // TODO: Tie only the correct indices vexflowObjects.push(new Vex.Flow.StaveTie({ first_note: tiedNote, last_note: vfNote })); if (note.tie == "begin" || note.tie == "continue") tiedNote = vfNote; if (note.tuplet) { if (tupletNotes) tupletNotes.push(vfNote); else { tupletNotes = [vfNote]; tupletOpts = note.tuplet; } if (tupletNotes.length == tupletOpts.num_notes) { vexflowObjects.push(new Vex.Flow.Tuplet(tupletNotes, tupletOpts)); tupletNotes.forEach(function(n) { vfVoice.addTickable(n) }); tupletNotes = null; tupletOpts = null; } } else vfVoice.addTickable(vfNote); if (note.lyric) { if (! lyricVoice) { lyricVoice = new Vex.Flow.Voice(vfVoice.time); if (voice.time.soft) lyricVoice.setMode(Vex.Flow.Voice.Mode.SOFT); lyricVoice.setStave(vfVoice.stave); // TODO: add padding at start of voice if necessary } lyricVoice.addTickable(new Vex.Flow.TextNote({ text: note.lyric.text, duration: note.duration })); } else if (lyricVoice) { // Add GhostNote for padding lyric voice lyricVoice.addTickable(new Vex.Flow.GhostNote({ duration: note.duration })); } } if (typeof console != "undefined" && console.assert) console.assert(vfVoice.stave instanceof Vex.Flow.Stave, "VexFlow voice should have a stave"); return [vfVoice, vexflowObjects, lyricVoice]; } /** * Create a Vex.Flow.StaveNote from a Vex.Flow.Measure.Note. * @param {Vex.Flow.Measure.Note} Note object * @param {Object} Options (currently only clef) * @return {Vex.Flow.StaveNote} StaveNote object */ Vex.Flow.DocumentFormatter.prototype.getVexflowNote = function(note, options) { var note_struct = Vex.Merge({}, options); note_struct.keys = note.keys; note_struct.duration = note.duration; if (note.stem_direction) note_struct.stem_direction = note.stem_direction; var vfNote = new Vex.Flow.StaveNote(note_struct); var i = 0; if (note.accidentals instanceof Array) note.accidentals.forEach(function(acc) { if (acc != null) vfNote.addAccidental(i, new Vex.Flow.Accidental(acc)); i++; }); var numDots = Vex.Flow.parseNoteDurationString(note.duration).dots; for (var i = 0; i < numDots; i++) vfNote.addDotToAll(); return vfNote; } Vex.Flow.DocumentFormatter.prototype.getMinMeasureWidth = function(m) { if (! (m in this.minMeasureWidths)) { // Calculate the maximum extra width on any stave (due to modifiers) var maxExtraWidth = 0; var measure = this.document.getMeasure(m); var vfStaves = measure.getStaves().map(function(stave) { var vfStave = this.createVexflowStave(stave, 0, 0, 500); var extraWidth = 500 - (vfStave.getNoteEndX()-vfStave.getNoteStartX()); if (extraWidth > maxExtraWidth) maxExtraWidth = extraWidth; return vfStave; }, this); // Create dummy canvas to use for formatting (required by TextNote) var canvas = document.createElement("canvas"); var context = Vex.Flow.Renderer.bolsterCanvasContext( canvas.getContext("2d")); var allVfVoices = []; var startStave = 0; // stave for part to start on measure.getParts().forEach(function(part) { var numStaves = part.getNumberOfStaves(); var partStaves = vfStaves.slice(startStave, startStave + numStaves); part.getVoices().forEach(function(voice) { var vfVoice = this.getVexflowVoice(voice, partStaves)[0]; allVfVoices.push(vfVoice); vfVoice.tickables.forEach(function(t) { t.setContext(context) }); }, this); startStave += numStaves; }, this); var formatter = new Vex.Flow.Formatter(); var noteWidth = formatter.preCalculateMinTotalWidth(allVfVoices); // Find max tickables in any voice, add a minimum space between them // to get a sane min width var maxTickables = 0; allVfVoices.forEach(function(v) { var numTickables = v.tickables.length; if (numTickables > maxTickables) maxTickables = numTickables; }); this.minMeasureWidths[m] = Vex.Max(50, maxExtraWidth + noteWidth + maxTickables*10 + 10); // Calculate minMeasureHeight by merging bounding boxes from each voice // and the bounding box from the stave var minHeights = []; // Initialize to zero for (var i = 0; i < vfStaves.length + 1; i++) minHeights.push(0); var i=-1; // allVfVoices consecutive by stave, increment for each new stave var lastStave = null; var staveY = vfStaves[0].getYForLine(0); var staveH = vfStaves[0].getYForLine(4) - staveY; var lastBoundingBox = null; allVfVoices.forEach(function(v) { if (v.stave !== lastStave) { if (i >= 0) { minHeights[i] += -lastBoundingBox.getY(); minHeights[i+1] = lastBoundingBox.getH() +lastBoundingBox.getY(); } lastBoundingBox = new Vex.Flow.BoundingBox(0, staveY, 500, staveH); lastStave = v.stave; i++; } lastBoundingBox.mergeWith(v.getBoundingBox()); }); minHeights[i] += -lastBoundingBox.getY(); minHeights[i+1] = lastBoundingBox.getH() +lastBoundingBox.getY(); this.minMeasureHeights[m] = minHeights; } return this.minMeasureWidths[m]; }; Vex.Flow.DocumentFormatter.prototype.getMinMeasureHeight = function(m) { if (! (m in this.minMeasureHeights)) this.getMinMeasureWidth(m); return this.minMeasureHeights[m]; } // Internal drawing functions Vex.Flow.DocumentFormatter.prototype.drawPart = function(part, vfStaves, context) { var staves = part.getStaves(); var voices = part.getVoices(); vfStaves.forEach(function(stave) { stave.setContext(context).draw(); }); var allVfObjects = new Array(); var vfVoices = new Array(); voices.forEach(function(voice) { var result = this.getVexflowVoice(voice, vfStaves); Array.prototype.push.apply(allVfObjects, result[1]); var vfVoice = result[0]; var lyricVoice = result[2]; vfVoice.tickables.forEach(function(tickable) { tickable.setStave(vfVoice.stave); }); vfVoices.push(vfVoice); if (lyricVoice) { lyricVoice.tickables.forEach(function(tickable) { tickable.setStave(lyricVoice.stave); }); vfVoices.push(lyricVoice); } }, this); var formatter = new Vex.Flow.Formatter().joinVoices(vfVoices); formatter.format(vfVoices, vfStaves[0].getNoteEndX() - vfStaves[0].getNoteStartX() - 10); var i = 0; vfVoices.forEach(function(vfVoice) { vfVoice.draw(context, vfVoice.stave); }); allVfObjects.forEach(function(obj) { obj.setContext(context).draw(); }); } // Options contains system_start, system_end for measure Vex.Flow.DocumentFormatter.prototype.drawMeasure = function(measure, vfStaves, context, options) { var startStave = 0; var parts = measure.getParts(); parts.forEach(function(part) { var numStaves = part.getNumberOfStaves(); var partStaves = vfStaves.slice(startStave, startStave + numStaves); this.drawPart(part, partStaves, context); startStave += numStaves; }, this); this.document.getStaveConnectors().forEach(function(connector) { if (! ((options.system_start && connector.system_start) || (options.system_end && connector.system_end) || connector.measure_start)) return; var firstPart = connector.parts[0], lastPart = connector.parts[connector.parts.length - 1]; var firstStave, lastStave; // Go through each part in measure to find the stave index var staveNum = 0, partNum = 0; parts.forEach(function(part) { if (partNum == firstPart) firstStave = staveNum; if (partNum == lastPart) lastStave = staveNum + part.getNumberOfStaves() - 1; staveNum += part.getNumberOfStaves(); partNum++; }); if (isNaN(firstStave) || isNaN(lastStave)) return; var type = connector.type == "single" ? Vex.Flow.StaveConnector.type.SINGLE : connector.type == "double" ? Vex.Flow.StaveConnector.type.DOUBLE : connector.type == "brace" ? Vex.Flow.StaveConnector.type.BRACE : connector.type =="bracket"? Vex.Flow.StaveConnector.type.BRACKET : null; if ((options.system_start && connector.system_start) || connector.measure_start) { (new Vex.Flow.StaveConnector(vfStaves[firstStave], vfStaves[lastStave]) ).setType(type).setContext(context).draw(); } if (options.system_end && connector.system_end) { var stave1 = vfStaves[firstStave], stave2 = vfStaves[lastStave]; var dummy1 = new Vex.Flow.Stave(stave1.x + stave1.width, stave1.y, 100); var dummy2 = new Vex.Flow.Stave(stave2.x + stave2.width, stave2.y, 100); (new Vex.Flow.StaveConnector(dummy1, dummy2) ).setType(type).setContext(context).draw(); } }); } Vex.Flow.DocumentFormatter.prototype.drawBlock = function(b, context) { this.getBlock(b); var measures = this.measuresInBlock[b]; measures.forEach(function(m) { var stave = 0; while (this.getStave(m, stave)) stave++; this.drawMeasure(this.document.getMeasure(m), this.vfStaves[m], context, {system_start: m == measures[0], system_end: m == measures[measures.length - 1]}); }, this); } /** * Vex.Flow.DocumentFormatter.prototype.draw - defined in subclass * Render document inside HTML element, creating canvases, etc. * Called a second time to update as necessary if the width of the element * changes, etc. * @param {Node} HTML node to draw inside * @param {Object} Subclass-specific options */ /** * Vex.Flow.DocumentFormatter.Liquid - default liquid formatter * Fit measures onto lines with a given width, in blocks of 1 line of music * * @constructor */ Vex.Flow.DocumentFormatter.Liquid = function(document) { if (arguments.length > 0) Vex.Flow.DocumentFormatter.call(this, document); this.width = 500; // default value this.zoom = 0.8; this.scale = 1.0; if (typeof window.devicePixelRatio == "number" && window.devicePixelRatio > 1) this.scale = Math.floor(window.devicePixelRatio); } Vex.Flow.DocumentFormatter.Liquid.prototype = new Vex.Flow.DocumentFormatter(); Vex.Flow.DocumentFormatter.Liquid.constructor = Vex.Flow.DocumentFormatter.Liquid; Vex.Flow.DocumentFormatter.Liquid.prototype.setWidth = function(width) { this.width = width; return this; } Vex.Flow.DocumentFormatter.Liquid.prototype.getBlock = function(b) { if (b in this.blockDimensions) return this.blockDimensions[b]; var startMeasure = 0; if (b > 0) { this.getBlock(b - 1); var prevMeasures = this.measuresInBlock[b - 1]; startMeasure = prevMeasures[prevMeasures.length - 1] + 1; } var numMeasures = this.document.getNumberOfMeasures(); if (startMeasure >= numMeasures) return null; // Update modifiers for first measure this.document.getMeasure(startMeasure).getStaves().forEach(function(s) { console.log(s); if (typeof s.clef == "string" && ! s.getModifier("clef")) { s.addModifier({type: "clef", clef: s.clef, automatic: true}); } if (typeof s.key == "string" && ! s.getModifier("key")) { s.addModifier({type: "key", key: s.key, automatic: true}); } // Time signature on first measure of piece only if (startMeasure == 0 && ! s.getModifier("time")) { if (typeof s.time_signature == "string") { //console.log(s); s.addModifier({type: "time", time: s.time_signature,automatic:true}); } //else if (typeof s.time == "object" && ! s.time.soft) else if (typeof s.time == "object") s.addModifier(Vex.Merge({type: "time", automatic: true}, s.time)); } }); // Store x, width of staves (y calculated automatically) if (! this.measureX) this.measureX = new Array(); if (! this.measureWidth) this.measureWidth = new Array(); // Calculate start x (15 if there are braces, 10 otherwise) var start_x = 10; this.document.getMeasure(startMeasure).getParts().forEach(function(part) { if (part.showsBrace()) start_x = 15; }); if (this.getMinMeasureWidth(startMeasure) + start_x + 10 >= this.width) { // Use only this measure and the minimum possible width var block = [this.getMinMeasureWidth(startMeasure) + start_x + 10, 0]; this.blockDimensions[b] = block; this.measuresInBlock[b] = [startMeasure]; this.measureX[startMeasure] = start_x; this.measureWidth[startMeasure] = block[0] - start_x - 10; } else { var curMeasure = startMeasure; var width = start_x + 10; while (width < this.width && curMeasure < numMeasures) { // Except for first measure, remove automatic modifiers // If there were any, invalidate the measure width if (curMeasure != startMeasure) this.document.getMeasure(curMeasure).getStaves().forEach(function(s) { if (s.deleteAutomaticModifiers() && this.minMeasureWidths && curMeasure in this.minMeasureWidths) delete this.minMeasureWidths[curMeasure]; }); width += this.getMinMeasureWidth(curMeasure); curMeasure++; } var endMeasure = curMeasure - 1; var measureRange = []; for (var m = startMeasure; m <= endMeasure; m++) measureRange.push(m); this.measuresInBlock[b] = measureRange; // Allocate width to measures var remainingWidth = this.width - start_x - 10; for (var m = startMeasure; m <= endMeasure; m++) { // Set each width to the minimum this.measureWidth[m] = Math.ceil(this.getMinMeasureWidth(m)); remainingWidth -= this.measureWidth[m]; } // Split rest of width evenly var extraWidth = Math.floor(remainingWidth / (endMeasure-startMeasure+1)); for (var m = startMeasure; m <= endMeasure; m++) this.measureWidth[m] += extraWidth; remainingWidth -= extraWidth * (endMeasure - startMeasure + 1); this.measureWidth[startMeasure] += remainingWidth; // Add remainder // Calculate x value for each measure this.measureX[startMeasure] = start_x; for (var m = startMeasure + 1; m <= endMeasure; m++) this.measureX[m] = this.measureX[m-1] + this.measureWidth[m-1]; this.blockDimensions[b] = [this.width, 0]; } // Calculate height of first measure var i = 0; var lastStave = undefined; var stave = this.getStave(startMeasure, 0); while (stave) { lastStave = stave; i++; stave = this.getStave(startMeasure, i); } var height = this.getStaveY(startMeasure, i-1); // Add max extra space for last stave on any measure in this block var maxExtraHeight = 90; // default: height of stave for (var i = startMeasure; i <= endMeasure; i++) { var minHeights = this.getMinMeasureHeight(i); var extraHeight = minHeights[minHeights.length - 1]; if (extraHeight > maxExtraHeight) maxExtraHeight = extraHeight; } height += maxExtraHeight; this.blockDimensions[b][1] = height; return this.blockDimensions[b]; } Vex.Flow.DocumentFormatter.Liquid.prototype.getStaveX = function(m, s) { if (! (m in this.measureX)) throw new Vex.RERR("FormattingError", "Creating stave for measure which does not belong to a block"); return this.measureX[m]; } Vex.Flow.DocumentFormatter.Liquid.prototype.getStaveWidth = function(m, s) { if (! (m in this.measureWidth)) throw new Vex.RERR("FormattingError", "Creating stave for measure which does not belong to a block"); return this.measureWidth[m]; } Vex.Flow.DocumentFormatter.Liquid.prototype.draw = function(elem, options) { if (this._htmlElem != elem) { this._htmlElem = elem; elem.innerHTML = ""; this.canvases = []; } //var canvasWidth = $(elem).width() - 10; // TODO: remove jQuery dependency var canvasWidth = elem.offsetWidth - 10; var renderWidth = Math.floor(canvasWidth / this.zoom); // Invalidate all blocks/staves/voices this.minMeasureWidths = []; // heights don't change with stave modifiers this.measuresInBlock = []; this.blockDimensions = []; this.vfStaves = []; this.measureX = []; this.measureWidth = []; this.setWidth(renderWidth); // Remove all non-canvas child nodes of elem using jQuery $(elem).children(":not(canvas)").remove(); var b = 0; while (this.getBlock(b)) { var canvas, context; var dims = this.blockDimensions[b]; var width = Math.ceil(dims[0] * this.zoom); var height = Math.ceil(dims[1] * this.zoom); if (! this.canvases[b]) { canvas = document.createElement('canvas'); canvas.width = width * this.scale; canvas.height = height * this.scale; if (this.scale > 1) { canvas.style.width = width.toString() + "px"; canvas.style.height = height.toString() + "px"; } canvas.id = elem.id + "_canvas" + b.toString(); // If a canvas exists after this one, insert before that canvas for (var a = b + 1; this.getBlock(a); a++) if (typeof this.canvases[a] == "object") { elem.insertBefore(canvas, this.canvases[a]); break; } if (! canvas.parentNode) elem.appendChild(canvas); // Insert at the end of elem this.canvases[b] = canvas; context = Vex.Flow.Renderer.bolsterCanvasContext(canvas.getContext("2d")); } else { canvas = this.canvases[b]; canvas.style.display = "inherit"; canvas.width = width * this.scale; canvas.height = height * this.scale; if (this.scale > 1) { canvas.style.width = width.toString() + "px"; canvas.style.height = height.toString() + "px"; } context = Vex.Flow.Renderer.bolsterCanvasContext(canvas.getContext("2d")); context.clearRect(0, 0, canvas.width, canvas.height); } // TODO: Figure out why setFont method is called if (typeof context.setFont != "function") { context.setFont = function(font) { this.font = font; return this; }; } context.scale(this.zoom * this.scale, this.zoom * this.scale); this.drawBlock(b, context); // Add anchor elements before canvas var lineAnchor = document.createElement("a"); lineAnchor.id = elem.id + "_line" + (b+1).toString(); elem.insertBefore(lineAnchor, canvas); this.measuresInBlock[b].forEach(function(m) { var anchor = elem.id + "_m" + this.document.getMeasureNumber(m).toString(); var anchorElem = document.createElement("a"); anchorElem.id = anchor; elem.insertBefore(anchorElem, canvas); }, this); b++; } while (typeof this.canvases[b] == "object") { // Remove canvases beyond the last one we are using elem.removeChild(this.canvases[b]); delete this.canvases[b]; b++; } }
function extractLinks(sentences) { let regex = /www\.[a-zA-Z0-9-]+(\.[a-zA-Z]+)+/gi; let output = []; for (let sentence of sentences) { let match = regex.exec(sentence); while (match){ output.push(match[0]); match = regex.exec(sentence); } } console.log(output.join('\n')); } extractLinks(['Join WebStars now for free, at www.web-stars.com', 'You can also support our partners:', 'Internet - www.internet.com', 'WebSpiders - www.webspiders101.com', 'Sentinel - www.sentinel.-ko']) extractLinks(['Need information about cheap hotels in London?', 'You can check us at www.london-hotels.co.uk!', 'We provide the best services in London.', 'Here are some reviews in some blogs:','"London Hotels are awesome!" - www.indigo.bloggers.com','"I am very satisfied with their services" - ww.ivan.bg', '"Best Hotel Services!" - www.rebel21.sedecrem.moc '])
$(document).ready(function () { if (self==window) { $('#usernameModal').modal('show'); } }); var config = { apiKey: "AIzaSyAknGSE55mNN1Pi6nVaZ1Llfw5_-eorP6c" , authDomain: "lewhacksserver01.firebaseapp.com" , databaseURL: "https://lewhacksserver01.firebaseio.com" , storageBucket: "" , messageingSenderId: "557003254902" }; firebase.initializeApp(config); var chatData = firebase.database().ref(); //Function that when you press enter after typing a message // to the Firebase reference to be stored within the database chatData.on("child_added", showMessage); function showMessage(msg) { var message = msg.val(); var messageSender = message.name; var messageContent = message.text; $printer.append("<div>" + messageSender + ": " + messageContent + "</div>"); scrollBottom(); // DO ON NEW MESSAGE (AJAX) } var $chat = $('.chat') , $printer = $('.messages', $chat) , $textArea = $("#message", $chat) , $postBtn = $('button', $chat) , printerH = $printer.innerHeight() , preventNewScroll = false; //// SCROLL BOTTOM function scrollBottom() { if (!preventNewScroll) { // if mouse is not over printer $printer.stop().animate({ scrollTop: $printer[0].scrollHeight - printerH }, 600); // SET SCROLLER TO BOTTOM } } scrollBottom(); // DO IMMEDIATELY function postMessage2(e) { // on Post click or 'enter' but allow new lines using shift+enter if (e.type == 'click' || (e.which == 13 && !e.shiftKey)) { e.preventDefault(); var msg = $("#message").val(); // not empty / space if ($.trim(msg)) { $("#message").val(''); // CLEAR TEXTAREA scrollBottom(); // DO ON POST chatData.push({ name: document.getElementById("username").value , text: msg }); } } } //// PREVENT SCROLL TO BOTTOM WHILE READING OLD MESSAGES $printer.hover(function (e) { preventNewScroll = e.type == 'mouseenter' ? true : false; if (!preventNewScroll) { scrollBottom(); } // On mouseleave go to bottom }); $textArea.keyup(postMessage2);
/* @flow */ /* eslint class-methods-use-this: "off" */ import Relay from 'react-relay'; export default class AddArticleMutation extends Relay.Mutation { static fragments = { user: () => Relay.QL` fragment on User { id } `, }; getMutation() { return Relay.QL`mutation{ addArticle }`; } getVariables() { return { title: this.props.title, author: this.props.author, }; } getFatQuery() { return Relay.QL` fragment on AddArticlePayload @relay(plural: true) { user { articles(last: 1000) { edges { node { id author title } } } } newArticleEdge } `; } getConfigs() { return [{ type: 'RANGE_ADD', parentName: 'user', parentID: this.props.user.id, connectionName: 'articles', edgeName: 'newArticleEdge', rangeBehaviors: { '': 'append', 'orederby(oldes)': 'prepend', }, }]; } getOptimisticResponse() { return { newArticleEdge: { node: { title: this.props.title, author: this.props.author, }, }, }; } }
//JUGGLING ASYNC var results = []; var counter = 0; function httpGet(index){ http.get(args[index], function(response) { response.pipe(bl(function (err, data) { results[index] = data.toString(); counter++; if(counter === 3) printResults(); })); }); } for (i = 0; i < 3; i++){ httpGet(i); } var printResults = function(){ console.log(results[0]); console.log(results[1]); console.log(results[2]); }
Meteor.subscribe("pollListings");
module.exports = { extends: 'eslint:recommended', env: { browser: true, node: true, }, rules: { indent: [ 'error', 2 ], 'linebreak-style': [ 'error', 'unix' ], quotes: [ 'error', 'single' ], semi: [ 'error', 'never' ], 'array-bracket-spacing': [2, 'never'], 'block-scoped-var': 2, 'brace-style': [2, '1tbs'], camelcase: 1, 'computed-property-spacing': [2, 'never'], curly: 2, 'eol-last': 2, eqeqeq: [2, 'smart'], 'max-depth': [1, 3], 'max-len': [1, 120], 'max-statements': [1, 30], 'new-cap': 1, 'no-extend-native': 2, 'no-mixed-spaces-and-tabs': 2, 'no-trailing-spaces': 2, 'no-unused-vars': 1, 'no-use-before-define': [2, 'nofunc'], 'object-curly-spacing': [2, 'always'], quotes: [2, 'single', 'avoid-escape'], 'keyword-spacing': 2, 'space-unary-ops': 2, }, }
(function() { 'use strict'; angular .module('app') .controller('NodespanelController', NodespanelController); NodespanelController.$inject = [ '$scope', '$window', 'dialogService', 'notificationService', 'localStorageService' ]; function NodespanelController($scope, $window, dialogService, notificationService, localStorageService) { // HEAD // var vm = this; vm.nodes = null; vm.newTree = newTree; vm.select = select; vm.remove = remove; vm.collapseGroup = collapseGroup; _create(); _activate(); $scope.$on('$destroy', _destroy); // BODY // function _getGroupState(fullName) { var state = localStorageService.load('b3groups.'+fullName); if (!state) { state = { collapsed: false }; } return state; } function _saveGroupState(fullName, state) { localStorageService.save('b3groups.'+fullName, state); } function _createGroup(groupName, fullName) { fullName = groupName; return { groups : {}, nodes : [], collapsed : _getGroupState(fullName).collapsed, name : groupName, fullName : fullName }; } function _insertToGroup(node, groupName, groups, fullName) { if (!groupName) return; var i = groupName.indexOf('.'); var nextGroup = ''; if (i >= 0) { nextGroup = groupName.substring(i+1); groupName = groupName.substring(0, i); } // We use this to get the collapsed status from localStorage if (!fullName) { fullName = groupName; } else { fullName = fullName+'.'+groupName; } if (!groups[groupName]) { groups[groupName] = _createGroup(groupName, fullName); } var group = groups[groupName]; if (nextGroup) { _insertToGroup(node, nextGroup, group.groups, fullName); } else { group.nodes.push(node.prototype.name); } } function _activate() { vm.trees = []; vm.nodes = { 'composites' : _createGroup('composites'), 'inputs' : _createGroup('inputs'), 'modulators' : _createGroup('modulators'), 'outputs' : _createGroup('outputs'), }; for (var key in b3e.nodes) { var node = b3e.nodes[key]; if (node.category === b3e.ROOT) continue; _insertToGroup(node, node.category+'s.'+node.group, vm.nodes); } var project = $window.editor.project.get(); var selected = project.trees.getSelected(); project.trees.each(function(tree) { var root = tree.nodes.getRoot(); vm.trees.push({ 'id' : tree._id, 'name' : root.title || 'A behavior tree', 'active' : tree===selected, }); }); } function _event(e) { if (e.type === 'nodechanged' && e._target.category !== b3e.ROOT) { return; } setTimeout(function() {$scope.$apply(function() { _activate(); });}, 0); } function _create() { $window.editor.on('nodechanged', _event); $window.editor.on('treeadded', _event); $window.editor.on('treeselected', _event); $window.editor.on('treeremoved', _event); $window.editor.on('treeimported', _event); } function _destroy() { $window.editor.off('treeadded', _event); $window.editor.off('nodechanged', _event); $window.editor.off('treeselected', _event); $window.editor.off('treeremoved', _event); $window.editor.off('treeimported', _event); } function newTree() { var p = $window.editor.project.get(); p.trees.add(); } function collapseGroup(group) { var state = _getGroupState(group.fullName); state.collapsed = !state.collapsed; _saveGroupState(group.fullName, state); group.collapsed = state.collapsed; } function select(id) { var p = $window.editor.project.get(); p.trees.select(id); } function remove(id) { dialogService. confirm( 'Remove tree?', 'Are you sure you want to remove this tree?\n\nNote: all blocks using this tree will be removed.' ).then(function() { var p = $window.editor.project.get(); p.trees.remove(id); notificationService.success( 'Tree removed', 'The tree has been removed from this project.' ); }); } } })();
'use strict'; // Load the global `expect` shim require('expectations'); expect.addAssertion('toBeArray', function() { if (!Array.isArray(this.value)) { return this.assertions.fail('to be an array.'); } this.assertions.pass(); }); expect.addAssertion('toBeBoolean', function() { if (this.value !== true && this.value !== false) { return this.assertions.fail('to be a boolean.'); } this.assertions.pass(); }); expect.addAssertion('toBeFalse', function() { if (this.value !== false) { return this.assertions.fail('to be false.'); } this.assertions.pass(); }); expect.addAssertion('toBeFunction', function() { if (typeof this.value !== 'function') { return this.assertions.fail('to be a function.'); } this.assertions.pass(); }); expect.addAssertion('toBeInstanceOf', function(klass) { var actualClassName = this.value.constructor ? this.value.constructor.name : undefined; var expectedClassName; if (typeof klass === 'string') { expectedClassName = klass; } else { expectedClassName = klass.name; } if (actualClassName !== expectedClassName) { return this.assertions.fail('to be an instance of ' + expectedClassName + '.'); } this.assertions.pass(); }); expect.addAssertion('toBeNumber', function() { if (typeof this.value !== 'number') { return this.assertions.fail('to be a number.'); } this.assertions.pass(); }); expect.addAssertion('toBeObject', function() { // don't treat arrays or `null` as objects if (typeof this.value !== 'object' || Array.isArray(this.value) || this.value === null) { return this.assertions.fail('to be an object.'); } this.assertions.pass(); }); expect.addAssertion('toBeString', function() { if (typeof this.value !== 'string') { return this.assertions.fail('to be a string.'); } this.assertions.pass(); }); expect.addAssertion('toBeTrue', function() { if (this.value !== true) { return this.assertions.fail('to be true.'); } this.assertions.pass(); });
/** * @author zhixin wen <wenzhixin2010@gmail.com> * extensions: https://github.com/vitalets/x-editable */ !function ($) { 'use strict'; $.extend($.fn.bootstrapTable.defaults, { editable: true, onEditableInit: function () { return false; }, onEditableSave: function (field, row, oldValue, $el) { return false; }, onEditableShown: function (field, row, $el, editable) { return false; }, onEditableHidden: function (field, row, $el) { return false; } }); $.extend($.fn.bootstrapTable.Constructor.EVENTS, { 'editable-init.bs.table': 'onEditableInit', 'editable-save.bs.table': 'onEditableSave', 'editable-shown.bs.table': 'onEditableShown', 'editable-hidden.bs.table': 'onEditableHidden' }); var BootstrapTable = $.fn.bootstrapTable.Constructor, _initTable = BootstrapTable.prototype.initTable, _initBody = BootstrapTable.prototype.initBody; BootstrapTable.prototype.initTable = function () { var that = this; _initTable.apply(this, Array.prototype.slice.apply(arguments)); if (!this.options.editable) { return; } $.each(this.columns, function (i, column) { if (!column.editable) { return; } var _formatter = column.formatter; column.formatter = function (value, row, index) { var result, formatterResult = ''; if(column.separateFormatter) { result = value; formatterResult = _formatter ? _formatter(value, row, index) : formatterResult; } else { result = _formatter ? _formatter(value, row, index) : value; } return ['<a href="javascript:void(0)"', ' data-name="' + column.field + '"', ' data-pk="' + row[that.options.idField] + '"', ' data-value="' + result + '"', '>' + '</a>' + formatterResult ].join(''); }; }); }; BootstrapTable.prototype.initBody = function () { var that = this; _initBody.apply(this, Array.prototype.slice.apply(arguments)); if (!this.options.editable) { return; } $.each(this.columns, function (i, column) { if (!column.editable) { return; } that.$body.find('a[data-name="' + column.field + '"]').editable(column.editable) .off('save').on('save', function (e, params) { var data = that.getData(), index = $(this).parents('tr[data-index]').data('index'), row = data[index], oldValue = row[column.field]; row[column.field] = params.submitValue; that.trigger('editable-save', column.field, row, oldValue, $(this)); }); that.$body.find('a[data-name="' + column.field + '"]').editable(column.editable) .off('shown').on('shown', function (e) { var data = that.getData(), index = $(this).parents('tr[data-index]').data('index'), row = data[index]; that.trigger('editable-shown', column.field, row, $(this)); }); that.$body.find('a[data-name="' + column.field + '"]').editable(column.editable) .off('hidden').on('hidden', function (e, editable) { var data = that.getData(), index = $(this).parents('tr[data-index]').data('index'), row = data[index]; that.trigger('editable-hidden', column.field, row, $(this), editable); }); }); this.trigger('editable-init'); }; }(jQuery);
/** * @jsx React.DOM */ /* not used but thats how you can use touch events * */ //React.initializeTouchEvents(true); /* not used but thats how you can use animation and other transition goodies * */ //var ReactCSSTransitionGroup = React.addons.CSSTransitionGroup; /** * we will use yes for true * we will use no for false * * React has some built ins that rely on state being true/false like classSet() * and these will not work with yes/no but can easily be modified / reproduced * * this single app uses the yes/no var so if you want you can switch back to true/false * * */ var yes = 'yes', no = 'no'; //var yes = true, no = false; /* bootstrap components * */ var Flash = ReactBootstrap.Alert; var Btn = ReactBootstrap.Button; var Modal = ReactBootstrap.Modal; /* create the container object * */ var snowUI = {}; /* create flash message * */ snowUI.SnowpiFlash = React.createClass({displayName: 'SnowpiFlash', getInitialState: function() { return { isVisible: true }; }, getDefaultProps: function() { return ({showclass:'info'}); }, render: function() { console.log(this.props); if(!this.state.isVisible) return null; var message = this.props.message ? this.props.message : this.props.children; return ( Flash({bsStyle: this.props.showclass, onDismiss: this.dismissFlash}, React.DOM.p(null, message) ) ); }, dismissFlash: function() { this.setState({isVisible: false}); } }); /* my little man component * simple example * */ snowUI.SnowpiMan = React.createClass({displayName: 'SnowpiMan', getDefaultProps: function() { return ({divstyle:{float:'right',}}); }, render: function() { return this.transferPropsTo( React.DOM.div({style: this.props.divstyle, dangerouslySetInnerHTML: {__html: snowtext.logoman}}) ); } }); //wallet select snowUI.walletSelect = React.createClass({displayName: 'walletSelect', componentDidMount: function() { var _this = this $("#walletselect").selectbox({ onChange: function (val, inst) { _this.props.route(val) }, effect: "fade" }); }, render: function() { var wallets; if(this.props.section === snowPath.wallet.substring(1)) { var _df = (this.props.wallet) ? snowPath.wallet + '/' + this.props.wallet : snowPath.wallet; } else { var _df = this.props.section; } return this.transferPropsTo( React.DOM.div({className: "list"}, React.DOM.div({className: "walletmsg", style: {display:'none'}}), React.DOM.select({onChange: this.route, id: "walletselect", defaultValue: _df}, wallets, React.DOM.optgroup(null), React.DOM.option({value: snowPath.wallet}, "list wallets"), React.DOM.option({value: snowPath.receive}, "receive coins"), React.DOM.option({value: snowPath.settings}, "settings"), React.DOM.option({value: snowPath.inq}, "inquisive queue") ) ) ); } }); var UI = React.createClass({displayName: 'UI', getInitialState: function() { /** * initialize the app * the plan is to keep only active references in root state. * we should use props for the fill outs * */ return { section:snowPath.wallet, moon:false, wallet:false, }; }, componentWillReceiveProps: function(nextProps) { /** * should be a mimic of initial * * */ console.log('UI nextProps',nextProps) if(nextProps.section)this.setState({section:nextProps.section}); if(nextProps.moon)this.setState({moon:nextProps.moon}); if(nextProps.wallet)this.setState({wallet:nextProps.wallet}); return false; }, changeTheme: function() { var mbody = $('body'); if(mbody.hasClass('themeable-snowcoinslight')==true) { mbody.removeClass('themeable-snowcoinslight'); } else { mbody.addClass('themeable-snowcoinslight'); } }, route: function(route) { route.preventDefault(); console.log($(route).attr('href')) //bone.router.navigate(snowPath.root + route, {trigger:true}); }, render: function() { return this.transferPropsTo( React.DOM.div(null, React.DOM.div({id: "snowpi-body"}, React.DOM.div({id: "walletbarspyhelper", style: {display:'block'}}), React.DOM.div({id: "walletbar", className: "affix"}, React.DOM.div({className: "wallet"}, React.DOM.div({className: "button-group"}, Btn({bsStyle: "link", 'data-toggle': "dropdown", className: "dropdown-toggle"}, snowtext.menu.menu.name), React.DOM.ul({className: "dropdown-menu", role: "menu"}, React.DOM.li({className: "nav-item-add"}, " ", React.DOM.a({onClick: this.route, href: snowPath.wallet + '/new'}, snowtext.menu.plus.name)), React.DOM.li({className: "nav-item-home"}, " ", React.DOM.a({onClick: this.route, href: snowPath.wallet}, snowtext.menu.list.name)), React.DOM.li({className: "nav-item-receive"}, React.DOM.a({onClick: this.route, href: snowPath.receive}, snowtext.menu.receive.name)), React.DOM.li({className: "nav-item-settings"}, React.DOM.a({onClick: this.route, href: snowPath.settings}, snowtext.menu.settings.name)), React.DOM.li({className: "divider"}), React.DOM.li({className: "nav-item-snowcat"}), React.DOM.li({className: "divider"}), React.DOM.li(null, React.DOM.div(null, React.DOM.div({onClick: this.changeTheme, className: "walletmenuspan changetheme bstooltip", title: "Switch between the light and dark theme", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, React.DOM.span({className: "glyphicon glyphicon-adjust"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "inquisive queue", 'data-toggle': "tooltip", 'data-placement': "bottom", 'data-container': "body"}, " ", React.DOM.a({className: "nav-item-inq"})), React.DOM.div({className: "walletmenuspan bstooltip", title: "Logout", 'data-toggle': "tooltip", 'data-placement': "right", 'data-container': "body"}, " ", React.DOM.a({href: "/signout"}, " ", React.DOM.span({className: "glyphicon glyphicon-log-out"}))), React.DOM.div({className: "clearfix"}) ) ) ) ) ), snowUI.walletSelect({route: this.route, section: this.state.section, wallet: this.state.wallet}), React.DOM.div({className: "logo"}, React.DOM.a({title: "inquisive.io snowcoins build info", 'data-container': "body", 'data-placement': "bottom", 'data-toggle': "tooltip", className: "walletbar-logo"})) ), React.DOM.div({className: "container-fluid"}, React.DOM.div({id: "menuspy", className: "dogemenu col-xs-1 col-md-2", 'data-spy': "affix", 'data-offset-top': "0"} ), React.DOM.div({id: "menuspyhelper", className: "dogemenu col-xs-1 col-md-2"}), React.DOM.div({className: "dogeboard col-xs-11 col-md-10"}, snowUI.AppInfo(null) ) ) /* end snowpi-body */ ) ) ); } }); //app info snowUI.AppInfo = React.createClass({displayName: 'AppInfo', render: function() { return ( React.DOM.div({id: "easter-egg", style: {display:'none'}}, React.DOM.div(null, React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Get Snowcoins"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, React.DOM.a({href: "https://github.com/inquisive/snowcoins", target: "_blank"}, "GitHub / Installation")), React.DOM.div({className: "col-sm-offset-1 col-sm-11"}, " ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.zip", target: "_blank"}, "Download zip"), " | ", React.DOM.a({href: "https://github.com/inquisive/snowcoins/latest.tar.gz", target: "_blank"}, "Download gz")) ), React.DOM.h4(null, "Built With"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://nodejs.org", target: "_blank"}, "nodejs")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://keystonejs.com", target: "_blank"}, "KeystoneJS")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://getbootstrap.com/", target: "_blank"}, "Bootstrap")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://github.com/countable/node-dogecoin", target: "_blank"}, "node-dogecoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://mongoosejs.com/", target: "_blank"}, "mongoose")) ), React.DOM.h4(null, "Donate"), React.DOM.div({className: "row"}, React.DOM.div({title: "iq", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, "iq: ", React.DOM.a({href: "https://inquisive.com/iq/snowkeeper", target: "_blank"}, "snowkeeper")), React.DOM.div({title: "Dogecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/dogecoin", target: "_blank"}, "Ðogecoin")), React.DOM.div({title: "Bitcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/bitcoin", target: "_blank"}, "Bitcoin")), React.DOM.div({title: "Litecoin", className: "col-sm-6 col-md-4"}, React.DOM.a({href: "https://snow.snowpi.org/share/litecoin", target: "_blank"}, "Litecoin")), React.DOM.div({title: "Darkcoin", className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "https://snow.snowpi.org/share/darkcoin", target: "_blank"}, "Darkcoin")) ) ), React.DOM.div({className: "blocks col-xs-offset-1 col-xs-10 col-md-offset-1 col-md-5 col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.h4(null, "Digital Coin Wallets"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://dogecoin.com", target: "_blank"}, "dogecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://bitcoin.org", target: "_blank"}, "bitcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://litecoin.org", target: "_blank"}, "litecoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://vertcoin.org", target: "_blank"}, "vertcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://octocoin.org", target: "_blank"}, "888")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://auroracoin.org", target: "_blank"}, "auroracoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://blackcoin.co", target: "_blank"}, "blackcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://digibyte.co", target: "_blank"}, "digibyte")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://digitalcoin.co", target: "_blank"}, "digitalcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://darkcoin.io", target: "_blank"}, "darkcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://maxcoin.co.uk", target: "_blank"}, "maxcoin")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://mintcoin.co", target: "_blank"}, "mintcoin")), React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-5"}, React.DOM.a({href: "http://einsteinium.org", target: "_blank"}, "einsteinium")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://peercoin.net", target: "_blank"}, "peercoin ")) ), React.DOM.h4(null, "Links"), React.DOM.div({className: "row"}, React.DOM.div({className: "col-sm-offset-1 col-sm-5 col-md-offset-1 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/snowcoins", target: "_blank"}, "/r/snowcoins")), React.DOM.div({className: "col-sm-6 col-md-4"}, React.DOM.a({href: "http://reddit.com/r/dogecoin", target: "_blank"}, "/r/dogecoin")) ) ), React.DOM.div({className: "clearfix"}) ) ) ); } });
(function() { 'use strict'; angular .module('user') .controller('UserController', UserController); UserController.$inject = ['UserService']; function UserController(UserService) { var vm = this; vm.empty = {}; vm.roles = [ { name: 'Admin', value: 'admin' }, { name: 'User', value: 'user' } ]; vm.toggleRoles = function(role) { var index = vm.user.roles.indexOf(role); if (index > -1) { vm.user.roles.splice(index, 1); } else { vm.user.roles.push(role); } } vm.findAll = function() { UserService.findAll().then(function(response) { vm.users = response.data; },function(error) { console.error(error); }); } vm.findAll(); vm.reset = function() { vm.user = angular.copy(vm.empty); } vm.populate = function(user) { vm.user = angular.copy(user); } vm.save = function(user) { if (user._id) { UserService.update(user).then(function(response) { vm.success = response.data; vm.findAll(); vm.reset(); },function(error) { console.log(error); vm.error = error.data; }); } else { UserService.create(user).then(function(response) { vm.success = response.data; vm.findAll(); vm.reset(); }, function(error) { console.error(error); vm.error = error.data; }); } } vm.remove = function(user) { if (confirm('Tem certeza que gostaria de remover o usuário ' + user.name + '?')) { UserService.remove(user._id).then(function(response) { vm.success = response.data; vm.findAll(); }, function(error) { console.error(error); vm.error = error.data; }); } } } })();
'use strict'; var winston = require('winston'); var fs = require('fs'); if (!fs.existsSync('logs')) { fs.mkdirSync('logs'); } var logger = new (winston.Logger)({ transports: [ new (winston.transports.File)({ name: 'info-file', filename: 'logs/filelog-info.log', datePattern: '.yyyy-MM-ddTHH', level: 'info' }), new (winston.transports.File)({ name: 'error-file', filename: 'logs/filelog-error.log', datePattern: '.yyyy-MM-ddTHH', level: 'error' }) ] }); module.exports = logger;
// JavaScript Document window.onload = function() { // Video var video = document.getElementById("video"); // Buttons var playButton = document.getElementById("play-pause"); var muteButton = document.getElementById("mute"); var fullScreenButton = document.getElementById("full-screen"); // Sliders var seekBar = document.getElementById("seek-bar"); var volumeBar = document.getElementById("volume-bar"); // Event listener for the play/pause button playButton.addEventListener("click", function() { if (video.paused == true) { // Play the video video.play(); // Update the button text to 'Pause' playButton.innerHTML = "<img src='img/ico-pause.png' alt='pause'>"; } else { // Pause the video video.pause(); // Update the button text to 'Play' playButton.innerHTML = "<img src='img/ico-play.png' alt='play'>"; } }); // Event listener for the mute button muteButton.addEventListener("click", function() { if (video.muted == false) { // Mute the video video.muted = true; // Update the button text muteButton.innerHTML = "<img src='img/ico-volumen-yes.png' alt='unMuted'>"; } else { // Unmute the video video.muted = false; // Update the button text muteButton.innerHTML = "<img src='img/ico-volumen-no.png' alt='Muted'>"; } }); // Event listener for the full-screen button fullScreenButton.addEventListener("click", function() { if (video.requestFullscreen) { video.requestFullscreen(); } else if (video.mozRequestFullScreen) { video.mozRequestFullScreen(); // Firefox } else if (video.webkitRequestFullscreen) { video.webkitRequestFullscreen(); // Chrome and Safari } }); // Event listener for the seek bar seekBar.addEventListener("change", function() { // Calculate the new time var time = video.duration * (seekBar.value / 100); // Update the video time video.currentTime = time; }); // Update the seek bar as the video plays video.addEventListener("timeupdate", function() { // Calculate the slider value var value = (100 / video.duration) * video.currentTime; // Update the slider value //seekBar.value = value; seekBar.style.width = value + '%'; }); // Pause the video when the slider handle is being dragged seekBar.addEventListener("mousedown", function() { video.pause(); }); // Play the video when the slider handle is dropped seekBar.addEventListener("mouseup", function() { video.play(); }); // Event listener for the volume bar volumeBar.addEventListener("change", function() { // Update the video volume video.volume = volumeBar.value; }); }
(function () { "use strict"; angular .module("Bookly.friends", [ "ui.router" ]) .config(["$stateProvider", function($stateProvider) { $stateProvider .state("friends", { url: "/friends", views: { "header": { templateUrl: "header/tmpl/header.html", controller: "HeaderCtrl", controllerAs: "vm" }, "content": { templateUrl: "friends/tmpl/friends.html", controller: "FriendsCtrl", controllerAs: "vm", resolve: { "currentAuth": ["AuthService", function (AuthService) { return AuthService.requireAuth(); }] } } } }) .state("friends.detail", { url: "/detail/:id", templateUrl: "friends/tmpl/friends-detail.html" }); }]); }());
import * as blc from "../lib"; import * as events from "../lib/internal/events"; import {describe, it} from "mocha"; import {expect} from "chai"; const blcCJS = require("../lib"); describe("API", () => { it("has necessary exports", () => { const classes = [ "HtmlChecker", "HtmlUrlChecker", "SiteChecker", "UrlChecker" ]; const objects = [ "DEFAULT_OPTIONS", "reasons" ]; const strings = [ ...Object.keys(events) ]; const modules = [ blc, // ES module blcCJS // CommonJS module ]; modules.forEach(module => { expect(module).to.be.an("object").that.has.keys(...classes, ...objects, ...strings); classes.forEach(key => expect(module).property(key).to.be.a("function")); objects.forEach(key => expect(module).property(key).to.be.an("object")); strings.forEach(key => expect(module).property(key).to.be.a("string")); }); }); });
require('../../src/js/app.js'); require('angular-mocks'); require('./controllersSpec.js'); require('./directivesSpec.js'); require('./servicesSpec.js'); require('./subscriberStatsSpec.js'); require('./audioAcquisitionProblemSpec.js'); require('./notificationsSpec.js'); require('./otErrorsSpec.js'); require('./subscriberReportSpec.js'); require('./microphonePickerSpec.js'); require('./isValidTokenRoleSpec.js');
import test from 'ava' import path from 'path' import includes from 'lodash/includes' import babelConfig from '../../lib/utils/babel-config' function programStub (fixture) { const directory = path.resolve('..', 'fixtures', fixture) return { directory } } test('it returns a default babel config for babel-loader query', (t) => { const program = programStub('site-without-babelrc') const config = babelConfig(program) t.true(typeof config === 'object') t.truthy(config.presets.length) t.truthy(config.plugins.length) }) test('all plugins are absolute paths to avoid babel lookups', (t) => { const program = programStub('site-without-babelrc') const config = babelConfig(program) config.presets.forEach(preset => t.true(path.resolve(preset) === preset)) config.plugins.forEach(plugin => t.true(path.resolve(plugin) === plugin)) }) test('fixture can resolve plugins in gatsby directory (crawling up)', (t) => { const program = programStub('site-with-valid-babelrc') const config = babelConfig(program) t.truthy(config.presets.length) }) test('throws error when babelrc is not parseable', (t) => { const program = programStub('site-with-invalid-babelrc') t.throws(() => babelConfig(program)) }) test('can read babel from packagejson', (t) => { const program = programStub('site-with-valid-babelpackage') const config = babelConfig(program) t.truthy(config.presets.length) }) test('when in development has hmre', (t) => { const program = programStub('site-without-babelrc') const config = babelConfig(program, 'develop') // regex matches: babel followed by any amount of hyphen or word characters const presetNames = config.presets.map(p => p.match(/babel[-|\w]+/)[0]) t.true(includes(presetNames, 'babel-preset-react-hmre')) }) test('throws when a plugin is not available', (t) => { const program = programStub('site-with-unresolvable-babelrc') t.throws(() => babelConfig(program)) }) test('throws when a configured preset is not availiable', (t) => { const program = programStub('site-with-unresovleable-configured-preset-babelrc') try { babelConfig(program) } catch (error) { t.regex(error.message, /"npm install --save babel-preset-env"/) } })
var events = require('./events'); var PROTOCOLS = ['host', 'rule', 'weinre', 'log', 'proxy', 'socks', 'pac', 'filter', 'ignore', 'enable', 'disable', 'delete', 'plugin', 'dispatch', 'urlParams', 'urlReplace', 'method', 'statusCode', 'replaceStatus', 'hostname', 'referer', 'accept', 'auth', 'etag', 'ua', 'cache', 'redirect', 'location', 'attachment', 'forwardedFor', 'responseFor', 'params', 'reqScript', 'resScript', 'reqDelay', 'resDelay', 'reqSpeed', 'resSpeed', 'reqHeaders', 'resHeaders', 'reqType', 'resType', 'reqCharset', 'resCharset', 'reqCookies', 'resCookies', 'reqCors', 'resCors', 'reqPrepend', 'resPrepend', 'reqBody', 'resBody', 'reqAppend', 'resAppend', 'reqReplace', 'resReplace', 'htmlPrepend', 'cssPrepend', 'jsPrepend', 'htmlBody', 'cssBody', 'jsBody', 'htmlAppend', 'cssAppend', 'jsAppend', 'req', 'res', 'reqWrite', 'resWrite', 'reqWriteRaw', 'resWriteRaw', 'exportsUrl', 'exports']; var innerRules = ['file', 'xfile', 'tpl', 'xtpl', 'rawfile', 'xrawfile']; var pluginRules = []; var forwardRules = innerRules.slice(); var webProtocols = ['http', 'https', 'ws', 'wss', 'tunnel']; var allInnerRules = PROTOCOLS.slice(0, 1).concat(webProtocols).concat(innerRules).concat(PROTOCOLS.slice(2)); allInnerRules.splice(allInnerRules.indexOf('plugin'), 1); var allRules = allInnerRules = allInnerRules.map(function(name) { return name + '://'; }); var plugins = {}; exports.setPlugins = function(pluginsState) { var pluginsOptions = pluginsState.pluginsOptions; var disabledPlugins = pluginsState.disabledPlugins; plugins = {}; pluginRules = []; forwardRules = innerRules.slice(); allRules = allInnerRules.slice(); if (!pluginsState.disabledAllPlugins) { pluginsOptions.forEach(function(plugin, i) { if (!i) { return; } var name = plugin.name; plugins[name] = plugin; if (!disabledPlugins[name]) { forwardRules.push(name); pluginRules.push('whistle.' + name, 'plugin.' + name); name += '://'; allRules.push(name, 'whistle.' + name); } }); } events.trigger('updatePlugins'); }; exports.PROTOCOLS = PROTOCOLS; exports.getForwardRules = function() { return forwardRules; }; exports.getPluginRules = function() { return pluginRules; }; exports.getAllRules = function() { return allRules; }; var ROOT_HELP_URL = 'https://avwo.github.io/whistle/rules/'; exports.getHelpUrl = function(rule) { if (!rule || rule === 'rule') { return ROOT_HELP_URL; } if (innerRules.indexOf(rule) !== -1) { return ROOT_HELP_URL + 'rule/' + rule + '.html'; } if (webProtocols.indexOf(rule) !== -1) { return ROOT_HELP_URL + 'rule/replace.html'; } if (PROTOCOLS.indexOf(rule) !== -1) { return ROOT_HELP_URL + rule + '.html'; } if (pluginRules.indexOf(rule) !== -1) { rule = rule.substring(rule.indexOf('.') + 1); } rule = plugins[rule]; if (rule && rule.homepage) { return rule.homepage; } return ROOT_HELP_URL; };
var searchData= [ ['certificate_20manipulation_20methods_20_28atcacert_5f_29',['Certificate manipulation methods (atcacert_)',['../a00840.html',1,'']]], ['configuration_20_28cfg_5f_29',['Configuration (cfg_)',['../a00836.html',1,'']]] ];
'use strict'; var tockenGenerator = require('shortid'); var User = require('../models/userModel'); var Vote = require('../models/voteModel'); var serverConfig = require('../config/server'); var emailSenderConfig = require('../config/emailSender'); module.exports = { getVoteForm: function (req, res) { res.render('index', { csrfToken: req.csrfToken() }); }, createVote: function (req, res) { var user = new User({ email: req.body.email }); // Check user param user.validate(function (err) { if (err) { res.status(400).json({ error: err, code: 'Sctr-CVact-l32' }); return; } // Generation link var token = tockenGenerator.generate(); var vote = new Vote({ "token": token, "Q1" : req.body.q1, "Q2" : req.body.q2, "Q3" : req.body.q3, "Q4" : req.body.q4, "Q5" : req.body.q5, "Q6" : req.body.q6, "Q7" : req.body.q7, "Q8" : req.body.q8 }); // Check vote param vote.validate(function (err) { if (err) { res.status(400).json({ error: err, code: 'Sctr-CVact-l32' }); return; } // Save user user.save(function (err, user) { if (err) { if (err.name === 'ValidationError') { res.status(400).json({ error: err.message, code: 'Sctr-CVact-l32' }); } else if (err.code === 11000) { res.render('index', { flashMsg: 'Vous avez déjà voté !', flashCode: 'error', csrfToken: req.csrfToken()}); //res.status(401).json({ error: 'Deja voté', code: 'Sctr-CVact-l34' }); } else { res.status(500).json({ error: err.message, code: 'Sctr-CVact-l36' }); } return; } var confirmationLink = serverConfig.domaine + '/confirm?token=' + token + '&email=' + user.email; // Save vote vote.save(function (err, result) { if (err) { if (err.name === 'ValidationError') { res.status(400).json({ error: err.message, code: 'Sctr-CVact-l58' }); } else { res.status(500).json({ error: err.message, code: 'Sctr-CVact-l60' }); } user.remove(); return; } var msg = 'Merci d\'avoir voté, pour confirmer votre vote, veuillez cliquer sur le lien suivant => ' + confirmationLink; // Send confirmation email req.app.get('emailSender').send({ text: msg, from: "damien@vicinitybordeaux.com", // TODO change email to: emailSenderConfig.email, subject: "Sondage" }, function (err, info) { if (err) { res.status(500).json({ error: 'server error', code: 'Sctr-CVact-l54' }); return; } res.render('index', { flashMsg: 'Un e-mail de confirmation vous a été envoyé, merci de bien vouloir confirmer votre vote !', flashCode: 'success', csrfToken: req.csrfToken() }); } ); }); }); }); }); }, confirmVote: function (req, res) { var token = req.query.token; var email = req.query.email; if (!token || !email) { res.status(400).json({ error: 'Bad request', code: 'Sctr-CoVact-1' }); return; } User.findOne({ email: email }, function (err, user) { if (err) { res.status(500).json({ error: 'SERVER ERROR', code: 'Sctr-CoVact-2' }); return; } Vote.findOne({ token: token }, function (err, vote) { if (err) { res.status(500).json({ error: 'SERVER ERROR', code: 'Sctr-CoVact-2' }); return; } vote.token = ''; vote.enable = true; vote.save(function (err) { if (err) { res.status(500).json({ error: 'SERVER ERROR', code: 'Sctr-CoVact-2' }); return; } res.redirect('/result'); }); }) }); }, statVote: function (req, res) { Vote.find({ enable: true }, function (err, votes) { if (err) { res.status(500).json({ error: 'server error', code: 'Sctr-SVact-1' }); return; } var count = votes.length; var stats = { 'Q1': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0}, 'Q2': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0}, 'Q3': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0}, 'Q4': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0}, 'Q5': {'R1': 0, 'R2': 0, 'R3': 0}, 'Q6': {'R1': 0, 'R2': 0, 'R3': 0}, 'Q7': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0}, 'Q8': {'R1': 0, 'R2': 0, 'R3': 0, 'R4': 0} }; votes.forEach(function (vote, index) { for (var i = 1; i <= 8; i++) { var questNumber = 'Q' + i; var respNumber = vote[questNumber]; stats[questNumber]['R' + respNumber]++; } }); res.render('result', { count: count, stats: stats}); }); } };
'use strict'; var x = 42; exports.x = x;
var rsvp = require('rsvp'), Valida = require('./valida'); var validator = module.exports = {}; validator.required = function(ctx, options, value) { if (typeof value == 'undefined' || value === null) { var err = { validator: 'required' }; addMessage(err, options); return err; } }; validator.empty = function(ctx, options, value) { if (typeof value !== 'undefined' && value !== null && !value.length) { var err = { validator: 'empty' }; addMessage(err, options); return err; } }; /* * options = { pattern, modified } */ validator.regex = function(ctx, options, value) { if (typeof value == 'undefined' || value === null) return; value = value + ''; if (Object.prototype.toString.call(options.pattern).slice(8, -1) !== 'RegExp') { options.pattern = new RegExp(options.pattern, options.modifiers); } if (!options.pattern.test(value)) { var mod = ''; if (options.pattern.global) mod += 'g'; if (options.pattern.ignoreCase) mod += 'i'; if (options.pattern.multiline) mod += 'm'; var err = { validator: 'regex', pattern: options.pattern.source, modifiers: mod }; addMessage(err, options); return err; } }; /* * options = { min, max } * value = array and non-array */ validator.len = function(ctx, options, value) { if (typeof value == 'undefined' || value === null) return; if (!Array.isArray(value)) value = value + ''; var valid = true; if (options.min !== undefined && options.min > value.length) valid = false; if (options.max !== undefined && options.max < value.length) valid = false; var err = { validator: 'len' }; if (options.min) { err.min = options.min; } if (options.max) { err.max = options.max; } addMessage(err, options); if (!valid) return err; }; validator.array = function(ctx, options, value) { if (typeof value == 'undefined' || value === null) return; if (!Array.isArray(value)) { var err = { validator: 'array' }; addMessage(err, options); return err; } }; validator.schema = function(ctx, options, value, cb) { if (typeof value == 'undefined' || value === null) return cb(); if (typeof options.schema === 'undefined') return cb(new Error('validator requires schema option')); value = Array.isArray(value) ? value : [ value ]; var errors = {}; var verify = function () { if (Object.keys(errors).length) return cb(null, { validator: 'schema', errors: errors }); cb(); }; var isValid = function (i, ctx) { if (ctx.isValid()) return; errors[i] = ctx.errors(); }; var parallel = value.map(function (permission, i) { return Valida.process(permission, options.schema) .then(isValid.bind(null, i)); }); return rsvp.all(parallel) .then(verify); }; validator.plainObject = function(ctx, options, value) { if (typeof value == 'undefined' || value === null) return; if (typeof value !== 'object' || Array.isArray(value)) { var err = { validator: 'plainObject' }; addMessage(err, options); return err; } }; validator.date = function(ctx, options, value) { if (typeof value === 'undefined' || value === null) return; var date = Date.parse(value); if (isNaN(date)) { var err = {validator: 'date'}; addMessage(err, options); return err; } } validator.integer = function(ctx, options, value) { if (typeof value === 'undefined' || value === null) return; if (!isInteger(value)) { var err = {validator: 'integer'}; addMessage(err, options); return err; } } validator.enum = function(ctx, options, value) { if (typeof value === 'undefined' || value === null) return; if (options.items.indexOf(value) == -1) { var err = {validator: 'enum'}; addMessage(err, options); return err; } } function addMessage (err, opt) { if (opt.msg) err.msg = opt.msg; } function isInteger(number) { return typeof number === "number" && isFinite(number) && Math.floor(number) === number; }
/* * IDBWrapper - A cross-browser wrapper for IndexedDB * Copyright (c) 2011 - 2012 Jens Arps * http://jensarps.de/ * * Licensed under the MIT (X11) license */ "use strict"; (function (name, definition, global) { if (typeof define === 'function') { define(definition); } else if (typeof module !== 'undefined' && module.exports) { module.exports = definition(); } else { global[name] = definition(); } })('IDBStore', function () { var IDBStore; var defaults = { storeName: 'Store', dbVersion: 1, keyPath: 'id', autoIncrement: true, onStoreReady: function () { }, indexes: [] }; IDBStore = function (kwArgs, onStoreReady) { function fixupConstants (object, constants) { for (var prop in constants) { object[prop] = constants[prop]; } } for(var key in defaults){ this[key] = typeof kwArgs[key] != 'undefined' ? kwArgs[key] : defaults[key]; } this.dbName = 'IDBWrapper-' + this.storeName; this.dbVersion = parseInt(this.dbVersion, 10); onStoreReady && (this.onStoreReady = onStoreReady); this.idb = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB; this.keyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.mozIDBKeyRange; this.consts = { 'READ_ONLY': 'readonly', 'READ_WRITE': 'readwrite', 'VERSION_CHANGE': 'versionchange' } this.cursor = window.IDBCursor || window.webkitIDBCursor; fixupConstants(this.cursor, { 'NEXT': 'next', 'NEXT_NO_DUPLICATE': 'nextunique', 'PREV': 'prev', 'PREV_NO_DUPLICATE': 'prevunique' }); this.openDB(); }; IDBStore.prototype = { db: null, dbName: null, dbVersion: null, store: null, storeName: null, keyPath: null, autoIncrement: null, indexes: null, features: null, onStoreReady: null, openDB: function () { this.newVersionAPI = typeof this.idb.setVersion == 'undefined'; if(!this.newVersionAPI){ throw new Error('The IndexedDB implementation in this browser is outdated. Please upgrade your browser.'); } var features = this.features = {}; features.hasAutoIncrement = !window.mozIndexedDB; // TODO: Still, really? var openRequest = this.idb.open(this.dbName, this.dbVersion); openRequest.onerror = function (error) { var gotVersionErr = false; if ('error' in error.target) { gotVersionErr = error.target.error.name == "VersionError"; } else if ('errorCode' in error.target) { gotVersionErr = error.target.errorCode == 12; // TODO: Use const } if (gotVersionErr) { console.error('Could not open database, version error:', error); } else { console.error('Could not open database, error:', error); } }.bind(this); openRequest.onsuccess = function (event) { if(this.db){ this.onStoreReady(); return; } this.db = event.target.result; if(this.db.objectStoreNames.contains(this.storeName)){ if(!this.store){ var emptyTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); this.store = emptyTransaction.objectStore(this.storeName); } // check indexes this.indexes.forEach(function(indexData){ var indexName = indexData.name; // normalize and provide existing keys indexData.keyPath = indexData.keyPath || indexName; indexData.unique = !!indexData.unique; indexData.multiEntry = !!indexData.multiEntry; if(!indexName){ throw new Error('Cannot create index: No index name given.'); } if(this.hasIndex(indexName)){ // check if it complies var actualIndex = this.store.index(indexName); var complies = ['keyPath', 'unique', 'multiEntry'].every(function(key){ // IE10 returns undefined for no multiEntry if (key == 'multiEntry' && actualIndex[key] === undefined && indexData[key] === false) { return true; } return indexData[key] == actualIndex[key]; }); if(!complies){ throw new Error('Cannot modify index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'); } } else { throw new Error('Cannot create new index "' + indexName + '" for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'); } }, this); this.onStoreReady(); } else { // We should never get here. throw new Error('Cannot create a new store for current version. Please bump version number to ' + ( this.dbVersion + 1 ) + '.'); } }.bind(this); openRequest.onupgradeneeded = function(/* IDBVersionChangeEvent */ event){ this.db = event.target.result; if(this.db.objectStoreNames.contains(this.storeName)){ this.store = event.target.transaction.objectStore(this.storeName); } else { this.store = this.db.createObjectStore(this.storeName, { keyPath: this.keyPath, autoIncrement: this.autoIncrement}); } this.indexes.forEach(function(indexData){ var indexName = indexData.name; // normalize and provide existing keys indexData.keyPath = indexData.keyPath || indexName; indexData.unique = !!indexData.unique; indexData.multiEntry = !!indexData.multiEntry; if(!indexName){ throw new Error('Cannot create index: No index name given.'); } if(this.hasIndex(indexName)){ // check if it complies var actualIndex = this.store.index(indexName); var complies = ['keyPath', 'unique', 'multiEntry'].every(function(key){ // IE10 returns undefined for no multiEntry if (key == 'multiEntry' && actualIndex[key] === undefined && indexData[key] === false) { return true; } return indexData[key] == actualIndex[key]; }); if(!complies){ // index differs, need to delete and re-create this.store.deleteIndex(indexName); this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry }); } } else { this.store.createIndex(indexName, indexData.keyPath, { unique: indexData.unique, multiEntry: indexData.multiEntry }); } }, this); }.bind(this); }, deleteDatabase: function () { if (this.idb.deleteDatabase) { this.idb.deleteDatabase(this.dbName); } }, /********************* * data manipulation * *********************/ put: function (dataObj, onSuccess, onError) { onError || (onError = function (error) { console.error('Could not write data.', error); }); onSuccess || (onSuccess = noop); if (typeof dataObj[this.keyPath] == 'undefined' && !this.features.hasAutoIncrement) { dataObj[this.keyPath] = this._getUID(); } var putTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); var putRequest = putTransaction.objectStore(this.storeName).put(dataObj); putRequest.onsuccess = function (event) { onSuccess(event.target.result); }; putRequest.onerror = onError; }, get: function (key, onSuccess, onError) { onError || (onError = function (error) { console.error('Could not read data.', error); }); onSuccess || (onSuccess = noop); var getTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); var getRequest = getTransaction.objectStore(this.storeName).get(key); getRequest.onsuccess = function (event) { onSuccess(event.target.result); }; getRequest.onerror = onError; }, remove: function (key, onSuccess, onError) { onError || (onError = function (error) { console.error('Could not remove data.', error); }); onSuccess || (onSuccess = noop); var removeTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); var deleteRequest = removeTransaction.objectStore(this.storeName).delete(key); deleteRequest.onsuccess = function (event) { onSuccess(event.target.result); }; deleteRequest.onerror = onError; }, getAll: function (onSuccess, onError) { onError || (onError = function (error) { console.error('Could not read data.', error); }); onSuccess || (onSuccess = noop); var getAllTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); var store = getAllTransaction.objectStore(this.storeName); if (store.getAll) { var getAllRequest = store.getAll(); getAllRequest.onsuccess = function (event) { onSuccess(event.target.result); }; getAllRequest.onerror = onError; } else { this._getAllCursor(getAllTransaction, onSuccess, onError); } }, _getAllCursor: function (tr, onSuccess, onError) { var all = []; var store = tr.objectStore(this.storeName); var cursorRequest = store.openCursor(); cursorRequest.onsuccess = function (event) { var cursor = event.target.result; if (cursor) { all.push(cursor.value); cursor['continue'](); } else { onSuccess(all); } }; cursorRequest.onError = onError; }, clear: function (onSuccess, onError) { onError || (onError = function (error) { console.error('Could not clear store.', error); }); onSuccess || (onSuccess = noop); var clearTransaction = this.db.transaction([this.storeName], this.consts.READ_WRITE); var clearRequest = clearTransaction.objectStore(this.storeName).clear(); clearRequest.onsuccess = function (event) { onSuccess(event.target.result); }; clearRequest.onerror = onError; }, _getUID: function () { // FF bails at times on non-numeric ids. So we take an even // worse approach now, using current time as id. Sigh. return +new Date(); }, /************ * indexing * ************/ getIndexList: function () { return this.store.indexNames; }, hasIndex: function (indexName) { return this.store.indexNames.contains(indexName); }, /********** * cursor * **********/ iterate: function (onItem, options) { options = mixin({ index: null, order: 'ASC', filterDuplicates: false, keyRange: null, writeAccess: false, onEnd: null, onError: function (error) { console.error('Could not open cursor.', error); } }, options || {}); var directionType = options.order.toLowerCase() == 'desc' ? 'PREV' : 'NEXT'; if (options.filterDuplicates) { directionType += '_NO_DUPLICATE'; } var cursorTransaction = this.db.transaction([this.storeName], this.consts[options.writeAccess ? 'READ_WRITE' : 'READ_ONLY']); var cursorTarget = cursorTransaction.objectStore(this.storeName); if (options.index) { cursorTarget = cursorTarget.index(options.index); } var cursorRequest = cursorTarget.openCursor(options.keyRange, this.cursor[directionType]); cursorRequest.onerror = options.onError; cursorRequest.onsuccess = function (event) { var cursor = event.target.result; if (cursor) { onItem(cursor.value, cursor, cursorTransaction); cursor['continue'](); } else { if(options.onEnd){ options.onEnd() } else { onItem(null); } } }; }, count: function (onSuccess, options) { options = mixin({ index: null, keyRange: null }, options || {}); var onError = options.onError || function (error) { console.error('Could not open cursor.', error); }; var cursorTransaction = this.db.transaction([this.storeName], this.consts.READ_ONLY); var cursorTarget = cursorTransaction.objectStore(this.storeName); if (options.index) { cursorTarget = cursorTarget.index(options.index); } var countRequest = cursorTarget.count(options.keyRange); countRequest.onsuccess = function (evt) { onSuccess(evt.target.result); }; countRequest.onError = function (error) { onError(error); }; }, /**************/ /* key ranges */ /**************/ makeKeyRange: function(options){ var keyRange, hasLower = typeof options.lower != 'undefined', hasUpper = typeof options.upper != 'undefined'; switch(true){ case hasLower && hasUpper: keyRange = this.keyRange.bound(options.lower, options.upper, options.excludeLower, options.excludeUpper); break; case hasLower: keyRange = this.keyRange.lowerBound(options.lower, options.excludeLower); break; case hasUpper: keyRange = this.keyRange.upperBound(options.upper, options.excludeUpper); break; default: throw new Error('Cannot create KeyRange. Provide one or both of "lower" or "upper" value.'); break; } return keyRange; } }; /** helpers **/ var noop = function () { }; var empty = {}; var mixin = function (target, source) { var name, s; for (name in source) { s = source[name]; if (s !== empty[name] && s !== target[name]) { target[name] = s; } } return target; }; return IDBStore; }, this);
import React from 'react'; import MainNav from './MainNav'; // Static Main Page export const MainPage = () => ( <div> <div className="row uc-landing__header-wrapper"> <img className="twelve column uc-landing__header" type="image/png" src="/img/delightful_food_for_a_healthy_life.png"/> </div> <div className="uc-workspace-grid--blocky"> <div className="uc-workspace-grid-box-nonclick"> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>Serving Chinese Customers, Penetrating US Markets</h5> <p> <strong>Union (Lian How) Food</strong> is a family-owned business with a continuous operation for more than half a century. In 1965, Mr. Y. B. Huang, founder of the company, started producing and marketing the proprietarily fermented bean and chili pastes/sauces in Taiwan. By the 1970s, the company had expanded with processing and sales facilities in China, Thailand, South and Central America, and the US Union International Food (UIF) was established in California in 1985. Under the <strong>Uncle Chen®</strong> brand, the subsidiary extended its business to include edible oils, sauces, seasonings/spices, teas and dried Asian foods. UIF has always aimed to produce and maintain the uncompromising high quality on its tasty, healthful, and convenient food products with continuous innovations. By implementing HACCP operational protocol and obtaining USFDA certification, UIF can proudly affirm the product safety for our worldwide customers. </p> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick--red"></div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>A Committment to Good Health</h5> <p> It has been Mr. Y. B. Huang’s firm commitment ever since the founding of Union Food, to conduct the business with social responsibility. Taking advantage of traditional Chinese fermentation processing while adopting the advanced technologies, the company endeavors to produce the delightfully tasty, proven healthful, and welcomingly convenient products for the market, both in China and abroad. Throughout his life he emphasizes personal integrity, product quality, and charity. Therefore, he never sacrifices these standards for personal gains, always sells high quality products at modest prices, and continually makes contributions to the communities. Mr. Daniel Chen, general manager of the company, was named one of the “One Hundred Outstanding Youths” in 2005 by the Chinese Ministry of State. With his education and training in traditional Chinese medicine, he applies the “food for health” principle in formulating and manufacturing products marketed by UIF. Safety of products, innovation in R&D, and excellence in customer services are his priority and goals in conducting the business. Consequently, UIF’s corporate mission statement is: Producing and maintaining the uncompromising high quality of tasty, healthful, and convenient food products with continuous innovations, and the ever-improving customer services. </p> </div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick--red"></div> <div className="uc-workspace-grid-box-nonclick uc-workspace-grid-box-nonclick"> <h5>American Standards for a Chinese Market</h5> <p> Horrendous incidents of food poisoning and contamination, such as, recycled waste oil used for human consumption, adulterated baby formula causing infant malnutrition and developmental damages, and health hazardous rice and bogus drugs on the market, were reported in recent years in China. People begin to be deeply concerned about food safety. Mr. Y.B. Huang and Daniel Chen felt the pain for the consumers there, and pondered, “Can’t we market our products sold in the United States for the past 30 years also on the shelves in China to lead the reform of its food industry?” “American standards for Chinese market!” has, thus, quickly become an idea enthusiastically received by our clients and supported by UIF associates. Consequently, entering Chinese market is now not only the hope, but determination and an aim for immediate actions of the corporation! </p> </div> <div></div> </div> <div className="uc-landing__contact-us"> <div> <h5>Store Hours & Location</h5> </div> <div> <p>Open daily 9am - 5pm</p> <p> 33035 Transit Avenue Union City, CA 94587 </p> </div> <div> <h5>Contact Us</h5> </div> <div> <p> <span className="socicon-instagram"></span> @HelloUncleChen </p> <p>For institutional clients: +15104718299</p> <p>For supermarkets: +15104716799</p> <p>For restaurants: +15104713799</p> <p>By fax: +15104719999</p> <p>By email: <a href="mailto:unclechen1688@gmail.com">unclechen1688@gmail.com</a></p> </div> </div> </div> ) export default MainPage;
import React from 'react' import Group from './Group' import InputCheckbox from './InputCheckbox' export default React.createClass({ displayName: 'Demo.Controls.ControlBool', propTypes: { name: React.PropTypes.string.isRequired, value: React.PropTypes.bool.isRequired, onChange: React.PropTypes.func.isRequired }, render() { return ( <Group name={this.props.name}> <InputCheckbox value={this.props.value} onChange={this.props.onChange} /> </Group> ) } })
const runner = require('./runner'); const main = generator => new Promise((resolve, reject) => { const it = generator(); const { value, done } = it.next(); if (done) return resolve(value); return runner({ thenable: value, resolve, reject }, it); }); module.exports = main;
import { call, put } from 'redux-saga/effects'; import UserRepositoriesActions from './redux'; import userRepositoriesRequest from './sagas'; import FixtureService from '../../services/FixtureService'; const stepper = fn => mock => fn.next(mock).value; const username = 'matheusmariano'; describe('User Repositories Sagas', () => { test('userRepositoriesRequest', () => { const step = stepper( userRepositoriesRequest(FixtureService, { username }), ); expect( step(), ).toEqual( call(FixtureService.userRepositoriesRequest, username), ); }); test('userRepositoriesRequestSuccess', () => { const response = FixtureService.userRepositoriesRequest(username); const step = stepper( userRepositoriesRequest(FixtureService, { username }), ); step(); // Request expect( step(response), ).toEqual( put(UserRepositoriesActions.userRepositoriesRequestSuccess(response.data)), ); }); test('userRepositoriesRequestFailure', () => { const response = { ok: false }; const step = stepper( userRepositoriesRequest(FixtureService, { username }), ); step(); // Request expect( step(response), ).toEqual( put(UserRepositoriesActions.userRepositoriesRequestFailure()), ); }); });
export const defaultState = { type: "default", visible: true }; export default function reducer(state = defaultState, action) { switch (action.type) { // set a specific filter type case "PAYMENT_FILTER_SET_TYPE": return { ...state, type: action.payload.type }; case "PAYMENT_FILTER_TOGGLE_VISIBILITY": return { ...state, visible: !state.visible }; case "PAYMENT_FILTER_CLEAR": case "GENERAL_FILTER_RESET": return { ...defaultState }; } return state; }
import express from 'express' import historyApiFallback from 'connect-history-api-fallback' import config from '../config' const app = express() const debug = require('debug')('kit:server') const paths = config.utils_paths app.use(historyApiFallback({ verbose: false })) // Serve app with Webpack if HMR is enabled if (config.compiler_enable_hmr) { const webpack = require('webpack') const webpackConfig = require('../build/webpack') const compiler = webpack(webpackConfig) app.use(require('./middleware/webpack-dev')({ compiler, publicPath: webpackConfig.output.publicPath })) app.use(require('./middleware/webpack-hmr')({ compiler })) } else { debug( 'Application is being run outside of development mode. This starter kit ' + 'does not provide any production-specific server functionality. To learn ' + 'more about deployment strategies, check out the "deployment" section ' + 'in the README.' ) // Serving ~/dist by default. Ideally these files should be served by // the web server and not the app server, but this helps to demo the // server in production. app.use(express.static(paths.base(config.dir_dist))) } export default app
Package.describe({ summary: "Moved to the 'ddp' package", version: '1.0.14' }); Package.onUse(function (api) { api.use("ddp"); api.imply("ddp"); // XXX COMPAT WITH PACKAGES BUILT FOR 0.9.0. // // (in particular, packages that have a weak dependency on this // package, since then exported symbols live on the // `Package.livedata` object) api.export('DDP'); api.export('DDPServer', 'server'); api.export('LivedataTest', {testOnly: true}); });
var searchData= [ ['nvic_20functions',['NVIC Functions',['../group___c_m_s_i_s___core___n_v_i_c_functions.html',1,'']]], ['nested_20vectored_20interrupt_20controller_20_28nvic_29',['Nested Vectored Interrupt Controller (NVIC)',['../group___c_m_s_i_s___n_v_i_c.html',1,'']]], ['n',['N',['../union_a_p_s_r___type.html#abae0610bc2a97bbf7f689e953e0b451f',1,'APSR_Type::N()'],['../unionx_p_s_r___type.html#abae0610bc2a97bbf7f689e953e0b451f',1,'xPSR_Type::N()']]], ['nelements',['NELEMENTS',['../group___l_p_c___types___public___macros.html#gafdd9296176e56fcfd83c07d345a045a7',1,'lpc_types.h']]], ['none_5fblocking',['NONE_BLOCKING',['../group___l_p_c___types___public___types.html#ggaddb88bff95842be0c54e0e979f45cf95ae00130e64382c35d172d226b79aa9acb',1,'lpc_types.h']]], ['nonmaskableint_5firqn',['NonMaskableInt_IRQn',['../group___l_p_c17xx___system.html#gga666eb0caeb12ec0e281415592ae89083ade177d9c70c89e084093024b932a4e30',1,'LPC17xx.h']]], ['npriv',['nPRIV',['../union_c_o_n_t_r_o_l___type.html#a2a6e513e8a6bf4e58db169e312172332',1,'CONTROL_Type']]], ['null',['NULL',['../group___l_p_c___types___public___macros.html#ga070d2ce7b6bb7e5c05602aa8c308d0c4',1,'lpc_types.h']]], ['nvic',['NVIC',['../group___c_m_s_i_s__core__base.html#gac8e97e8ce56ae9f57da1363a937f8a17',1,'core_cm3.h']]], ['nvic_5fbase',['NVIC_BASE',['../group___c_m_s_i_s__core__base.html#gaa0288691785a5f868238e0468b39523d',1,'core_cm3.h']]], ['nvic_5fclearpendingirq',['NVIC_ClearPendingIRQ',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga332e10ef9605dc6eb10b9e14511930f8',1,'core_cm3.h']]], ['nvic_5fdecodepriority',['NVIC_DecodePriority',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga4f23ef94633f75d3c97670a53949003c',1,'core_cm3.h']]], ['nvic_5fdisableirq',['NVIC_DisableIRQ',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga260fba04ac8346855c57f091d4ee1e71',1,'core_cm3.h']]], ['nvic_5fenableirq',['NVIC_EnableIRQ',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga3349f2e3580d7ce22d6530b7294e5921',1,'core_cm3.h']]], ['nvic_5fencodepriority',['NVIC_EncodePriority',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#gadb94ac5d892b376e4f3555ae0418ebac',1,'core_cm3.h']]], ['nvic_5fgetactive',['NVIC_GetActive',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga47a0f52794068d076c9147aa3cb8d8a6',1,'core_cm3.h']]], ['nvic_5fgetpendingirq',['NVIC_GetPendingIRQ',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#gafec8042db64c0f8ed432b6c8386a05d8',1,'core_cm3.h']]], ['nvic_5fgetpriority',['NVIC_GetPriority',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga1cbaf8e6abd4aa4885828e7f24fcfeb4',1,'core_cm3.h']]], ['nvic_5fgetprioritygrouping',['NVIC_GetPriorityGrouping',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga394f7ce2ca826c0da26284d17ac6524d',1,'core_cm3.h']]], ['nvic_5fsetpendingirq',['NVIC_SetPendingIRQ',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga3ecf446519da33e1690deffbf5be505f',1,'core_cm3.h']]], ['nvic_5fsetpriority',['NVIC_SetPriority',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga2305cbd44aaad792e3a4e538bdaf14f9',1,'core_cm3.h']]], ['nvic_5fsetprioritygrouping',['NVIC_SetPriorityGrouping',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga77cfbb35a9d8027e392034321bed6904',1,'core_cm3.h']]], ['nvic_5fstir_5fintid_5fmsk',['NVIC_STIR_INTID_Msk',['../group___c_m_s_i_s___n_v_i_c.html#gae4060c4dfcebb08871ca4244176ce752',1,'core_cm3.h']]], ['nvic_5fstir_5fintid_5fpos',['NVIC_STIR_INTID_Pos',['../group___c_m_s_i_s___n_v_i_c.html#ga9eebe495e2e48d302211108837a2b3e8',1,'core_cm3.h']]], ['nvic_5fsystemreset',['NVIC_SystemReset',['../group___c_m_s_i_s___core___n_v_i_c_functions.html#ga1143dec48d60a3d6f238c4798a87759c',1,'core_cm3.h']]], ['nvic_5ftype',['NVIC_Type',['../struct_n_v_i_c___type.html',1,'']]] ];
define(["jade"],function(jade){return function anonymous(locals,attrs,escape,rethrow,merge){attrs=attrs||jade.attrs,escape=escape||jade.escape,rethrow=rethrow||jade.rethrow,merge=merge||jade.merge;var buf=[];with(locals||{}){var interp;buf.push("<center>"),function(){if("number"==typeof boards.length)for(var e=0,t=boards.length;e<t;e++){var n=boards[e];buf.push("<a"),buf.push(attrs({href:"#/board/"+n.id+""},{href:!0})),buf.push(">"+escape((interp=n.id)==null?"":interp)+"</a> / ")}else for(var e in boards){var n=boards[e];buf.push("<a"),buf.push(attrs({href:"#/board/"+n.id+""},{href:!0})),buf.push(">"+escape((interp=n.id)==null?"":interp)+"</a> / ")}}.call(this),buf.push("</center>")}return buf.join("")}})
Sequoia.settings.addGroup('FileUpload', function() { this.add('FileUpload_Enabled', true, { type: 'boolean', public: true }); this.add('FileUpload_MaxFileSize', 2097152, { type: 'int', public: true }); this.add('FileUpload_MediaTypeWhiteList', 'image/*,audio/*,video/*,application/zip,application/x-rar-compressed,application/pdf,text/plain,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document', { type: 'string', public: true, i18nDescription: 'FileUpload_MediaTypeWhiteListDescription' }); this.add('FileUpload_ProtectFiles', true, { type: 'boolean', public: true, i18nDescription: 'FileUpload_ProtectFilesDescription' }); this.add('FileUpload_Storage_Type', 'GridFS', { type: 'select', values: [{ key: 'GridFS', i18nLabel: 'GridFS' }, { key: 'AmazonS3', i18nLabel: 'AmazonS3' }, { key: 'FileSystem', i18nLabel: 'FileSystem' }], public: true }); this.section('Amazon S3', function() { this.add('FileUpload_S3_Bucket', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_Acl', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_AWSAccessKeyId', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_AWSSecretAccessKey', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_CDN', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_Region', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' } }); this.add('FileUpload_S3_BucketURL', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' }, i18nDescription: 'Override_URL_to_which_files_are_uploaded_This_url_also_used_for_downloads_unless_a_CDN_is_given.' }); this.add('FileUpload_S3_URLExpiryTimeSpan', 120, { type: 'int', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'AmazonS3' }, i18nDescription: 'FileUpload_S3_URLExpiryTimeSpan_Description' }); }); this.section('File System', function() { this.add('FileUpload_FileSystemPath', '', { type: 'string', enableQuery: { _id: 'FileUpload_Storage_Type', value: 'FileSystem' } }); }); });
import {createValidator, required, isEmail} from '../../utils/validation'; export const nameValidator = createValidator({ name: [required] }); export const emailValidator = createValidator({ email: [required, isEmail] });
module.exports = function (app, models) { require("./user.service")(app, models); require("./task.service")(app, models); require("./image.service")(app, models); };
(function() { "use strict"; function capitalize(str) { return str.substr(0,1).toUpperCase()+str.substr(1); } $.extend(Playground, { bindReportPopover: function(card) { $('.report.popover .metadata').empty(); card.promise.then(function() { return card.metadataFor('*'); }).then(function(metadata) { var table = $('<table>'), row; if (Object.keys(metadata).length === 0) { table.append('<tr><td class="empty">no metadata</td></tr>'); } else { for (var key in metadata) { var loc = key.indexOf(':'); var group = capitalize(key.substr(0, loc)); var name = capitalize(key.substr(loc+1)); var label = group + " " + name; row = $('<tr><th>'+label+':</th><td>'+metadata[key]+'</td></tr>'); table.append(row); } } $('.report.popover .metadata').empty().append(table); Playground.repositionPopover(); }, Conductor.error); }, unbindReportPopover: function(card) { } }); })();
var Sequelize = require('sequelize'), sequelize = require('../modules/sequelize_db'), config = require('config'); var ArticleTag = sequelize.define('study_article_tag',{ id:{ type:Sequelize.INTEGER, autoIncrement: true, primaryKey:true }, name:Sequelize.STRING, }); ArticleTag.sync({force:config.get('reinitDB')}).then(function(){ console.log('ArticleTag sync success'); }).catch(function(error){ console.log('ArticleTag sync failed:' + error); }); module.exports = ArticleTag;
var searchData= [ ['malloc',['Malloc',['../helper_8h.html#a718daa2ee90d164bb8224833535f0b3b',1,'helper.h']]], ['maxpq_5fdeletemax',['MaxPQ_deleteMax',['../collection_8h.html#aa94df3c278f33ebe60810062465ec492',1,'collection.h']]], ['maxpq_5fdestroy',['MaxPQ_destroy',['../collection_8h.html#a4f60d1dd403832a9d4e29e7bd29fc277',1,'collection.h']]], ['maxpq_5finit',['MaxPQ_init',['../collection_8h.html#a7de84f7676113bdde1cf2f08f5b0afc2',1,'collection.h']]], ['maxpq_5finsert',['MaxPQ_insert',['../collection_8h.html#a565a9f18f31575230419c2af9be7edca',1,'collection.h']]], ['maxpq_5fisempty',['MaxPQ_isEmpty',['../collection_8h.html#a7e736099f70b3a71344fb8f43217c1f0',1,'collection.h']]], ['maxpq_5fmax',['MaxPQ_max',['../collection_8h.html#aa2cf783d0c425617aa23e08acaf2cfae',1,'collection.h']]], ['maxpq_5fshow',['MaxPQ_show',['../collection_8h.html#aaabee3ad7005232dbbe040be8ea5a0d2',1,'collection.h']]], ['maxpq_5fsize',['MaxPQ_size',['../collection_8h.html#a3f9c024d740f8e848e824cad1d44ee1a',1,'collection.h']]], ['merge_5fsort',['merge_sort',['../sort_8h.html#a35cd73973a6293882a77594190d91763',1,'sort.h']]], ['min',['min',['../helper_8h.html#aebfa23dbf6ec30f35f2986a654bd47c1',1,'helper.h']]] ];
/* * A program to resize an image in an AWS S3 bucket. * Written in Node.js, this program accepts an array of image sizes in the payload. * The image is then resized to the specified width(s) and stored in a new directory. */ var async = require('async'); var path = require('path'); var AWS = require('aws-sdk'); var gm = require('gm').subClass({ imageMagick: true }); var util = require('util'); // get reference to S3 client var s3 = new AWS.S3(); exports.handler = function(event, context) { // payload data var mediaId = event.media_id; var filename = event.file_name; var bucket = event.bucket; var sizesArray = event.sizesArray; if(!sizesArray) { /* * If sizesArray is not specified in the payload, then use * this as the default: */ sizesArray = [{ width: 50, // sets the width of the resized image to 50px dirName: 'thumbnail' // this is the folder name where the resized image will be stored }]; } var len = sizesArray.length; // Get the image type var typeMatch = filename.match(/\.([^.]*)$/); if (!typeMatch) { console.error('unable to infer image type for file ' + filename); return; } // make sure the image is a jpg or png var type = typeMatch[1].toLowerCase(); if (type != "jpg" && type != "png") { console.log('Image is not the right format: ' + srcKey); return; } // Upload resized image to same location in the S3 bucket but within a new directory async.forEachOf(sizesArray, function(value, key, callback) { async.waterfall([ function download(next) { console.log("downloading image"); // download the image from the S3 bucket s3.getObject({ Bucket: bucket, Key: mediaId + '/' + filename }, next); }, function process(response, next) { console.log("processing image"); // Transform the image gm(response.Body).size(function(err, size) { console.log(err); // Calculate the scaling factor so that the resized image has the same width/height ratio var scalingFactor = Math.min( sizesArray[key].width / size.width, sizesArray[key].width / size.height ); var width = scalingFactor * size.width; var height = scalingFactor * size.height; var index = key; this.resize(width, height).toBuffer( type.toUpperCase(), function(err, buffer) { if (err) { next(err); } else { next(null, buffer, key); } }); }); }, function upload(data, index, next) { console.log("uploading resized image " + index); // Place the resized image in the same bucket location, but in a different folder console.log('uploading to this location: ' + mediaId + '/' + sizesArray[index].dirName + "/" + filename); s3.putObject({ Bucket: bucket, Key: mediaId + '/' + sizesArray[index].dirName + "/" + filename, Body: data, ContentType: type.toUpperCase() }, next); } ], function(err, result) { if (err) { console.error(err); } callback(); }); }, function(err) { if (err) { console.log('Error uploading image'); console.error(err); } else { console.log('Successfully resized image'); } context.done(); }); };
/*! * robust-admin-theme (http://demo.pixinvent.com/robust-admin) * Copyright 2017 PIXINVENT * Licensed under the Themeforest Standard Licenses */ $(window).on("load",function(){require.config({paths:{echarts:"../../../app-assets/vendors/js/charts/echarts"}}),require(["echarts","echarts/chart/bar","echarts/chart/line"],function(ec){var myChart=ec.init(document.getElementById("basic-bar"));chartOptions={grid:{x:60,x2:40,y:45,y2:25},tooltip:{trigger:"axis"},legend:{data:["2011","2012"]},color:["#99B898","#FF847C"],xAxis:[{type:"value",boundaryGap:[0,.01]}],yAxis:[{type:"category",data:["Apple","Samsung","HTC","Nokia","Sony","LG"]}],series:[{name:"2011",type:"bar",data:[600,450,350,268,474,315]},{name:"2012",type:"bar",data:[780,689,468,174,436,482]}]},myChart.setOption(chartOptions),$(function(){function resize(){setTimeout(function(){myChart.resize()},200)}$(window).on("resize",resize),$(".menu-toggle").on("click",resize)})})});
// All code points in the Control Pictures block as per Unicode v5.0.0: [ 0x2400, 0x2401, 0x2402, 0x2403, 0x2404, 0x2405, 0x2406, 0x2407, 0x2408, 0x2409, 0x240A, 0x240B, 0x240C, 0x240D, 0x240E, 0x240F, 0x2410, 0x2411, 0x2412, 0x2413, 0x2414, 0x2415, 0x2416, 0x2417, 0x2418, 0x2419, 0x241A, 0x241B, 0x241C, 0x241D, 0x241E, 0x241F, 0x2420, 0x2421, 0x2422, 0x2423, 0x2424, 0x2425, 0x2426, 0x2427, 0x2428, 0x2429, 0x242A, 0x242B, 0x242C, 0x242D, 0x242E, 0x242F, 0x2430, 0x2431, 0x2432, 0x2433, 0x2434, 0x2435, 0x2436, 0x2437, 0x2438, 0x2439, 0x243A, 0x243B, 0x243C, 0x243D, 0x243E, 0x243F ];
(function($) { var d = document; var COMMENT = 'GEN_comment', STRING = 'GEN_string'; var regex = { } var EOL = "\n", sgl_quote = "'", dbl_quote = "\""; Symphony.Extensions.CodeEditor.highlighters['php'] = function(source_text) { if(source_text.length == 0) return null; var output = d.createElement('span'); var block_length; do { var first_char = source_text.charAt(0); if(first_char == sgl_quote) { block_length = source_text.indexOf(sgl_quote, 1) + 1; if(block_length == 0) block_length = source_text.length; $(output).appendSpan(STRING, source_text.slice(0, block_length)); } else if(first_char == dbl_quote) { var offset = 1; var stop = false do { block_length = source_text.indexOf(dbl_quote, offset) + 1; if(block_length > 1) { if(source_text.charAt(block_length - 2) == "\\") { offset = block_length; } else break; } else { block_length = source_text.length; break; } } while(true); $(output).appendSpan(STRING, source_text.slice(0, block_length)); } else if(first_char == "/") { if(source_text.charAt(1) == "/") { block_length = source_text.indexOf(EOL, 2) + 1; if(block_length == 0) block_length = source_text.length; $(output).appendSpan(COMMENT, source_text.slice(0, block_length)); } else if(source_text.charAt(1) == "*") { block_length = source_text.indexOf("*/", 2) + 2; if(block_length == 1) block_length = source_text.length; $(output).appendSpan(COMMENT, source_text.slice(0, block_length)); } } else { block_length = source_text.search(/(\'|\"|\/\/|\/\*|$)/); $(output).appendText(source_text.slice(0, block_length)); } source_text = source_text.slice(block_length); } while(source_text.length > 0); return output; } })(window.jQuery);
export default { key: 'Ab', suffix: 'm7', positions: [ { frets: '4x444x', fingers: '203330' }, { frets: '464444', fingers: '131111', barres: 4, capo: true }, { frets: 'x66877', fingers: '011423', barres: 6, capo: true }, { frets: 'xb9b9x', fingers: '021310', barres: 9, capo: true }, { frets: 'bbdbcb', fingers: '113121', barres: 11, capo: true } ] };
/** * jQuery UI InlineComponent Widget * * @copyright 2015 (c) Sahana Software Foundation * @license MIT * * requires jQuery 1.9.1+ * requires jQuery UI 1.10 widget factory * requires jQuery jstree 3.0.3 */ (function($, undefined) { "use strict"; var inlinecomponentID = 0; /** * InlineComponent widget * * Terminology: * - form - refers to the outer form * - input - refers to the hidden INPUT in the outer form that * holds the JSON data for all rows inside this widget, * and will be processed server-side when the outer * form get submitted * - widget - refers to this widget * - row, subform - refers to one row inside the widget * - field - refers to a field inside a subform */ $.widget('s3.inlinecomponent', { /** * Default options * * @todo implement/document options */ options: { }, /** * Create the widget */ _create: function() { var el = $(this.element); this.id = inlinecomponentID; inlinecomponentID += 1; // Namespace for events this.namespace = '.inlinecomponent'; }, /** * Update the widget options */ _init: function() { var el = $(this.element); this.formname = el.attr('id').split('-').pop(); this.input = $('#' + el.attr('field')); // Configure layout-dependend functions var layout = this._layout; if ($.inlineComponentLayout) { // Use custom script layout = $.inlineComponentLayout; } this._renderReadRow = layout.renderReadRow; this._appendReadRow = layout.appendReadRow; this._appendError = layout.appendError; this._updateColumn = layout.updateColumn; this.refresh(); }, /** * Remove generated elements & reset other changes */ _destroy: function() { $.Widget.prototype.destroy.call(this); }, /** * Redraw contents */ refresh: function() { var el = $(this.element); this._unbindEvents(); this._openSingleRowSubforms(); this._enforceRequired(); // Find non-static header rows this.labelRow = $('#sub-' + this.formname + ' .label-row:not(.static)'); this._showHeaders(); this._bindEvents(); }, // Initialization ----------------------------------------------------- /** * Automatically open single-row subform for editing, * and enforce add-row validation if it has defaults */ _openSingleRowSubforms: function() { var el = $(this.element), self = this; el.find('.inline-form.read-row.single').each(function() { // Open edit-row by default var names = $(this).attr('id').split('-'); var rowindex = names.pop(); // Will always be 0 self._editRow(rowindex); }); el.find('.inline-form.add-row.single').each(function() { // Check add-row for defaults var $row = $(this), defaults = false; $row.find('input[type!="hidden"], select, textarea').each(function() { var $this = $(this); if ($this.is(':visible') && $this.val() && $this.attr('type') != 'checkbox') { defaults = true; } }); if (defaults) { // Enforce validation self._markChanged($row); self._catchSubmit($row); } }); }, /** * Enforce validation of required subforms */ _enforceRequired: function() { var el = $(this.element), self = this; // Check for required subforms el.find('.inline-form.add-row.required').each(function() { // Ensure these get validated whether or not they are changed self._markChanged(this); self._catchSubmit(this); }); }, // Layout ------------------------------------------------------------- /** * The default layout-dependend functions */ _layout: { /** * Render a read-row (default row layout) * * @param {string} formname - the form name * @param {string|number} rowindex - the row index * @param {array} items - the data items * * @return {jQuery} the row */ renderReadRow: function(formname, rowindex, items) { var columns = ''; // Render the items for (var i=0, len=items.length; i<len; i++) { columns += '<td>' + items[i] + '</td>'; } // Append edit-button if ($('#edt-' + formname + '-none').length !== 0) { columns += '<td><div><div id="edt-' + formname + '-' + rowindex + '" class="inline-edt"></div></div></td>'; } else { columns += '<td></td>'; } // Append remove-button if ($('#rmv-' + formname + '-none').length !== 0) { columns += '<td><div><div id="rmv-' + formname + '-' + rowindex + '" class="inline-rmv"></div></div></td>'; } else { columns += '<td></td>'; } // Get the row var rowID = 'read-row-' + formname + '-' + rowindex; var row = $('#' + rowID); if (!row.length) { // New row row = $('<tr id="' + rowID + '" class="read-row">'); } // Add the columns to the row row.empty().html(columns); return row; }, /** * Append a new read-row to the inline component * * @param {string} formname - the formname * @param {jQuery} row - the row to append */ appendReadRow: function(formname, row) { $('#sub-' + formname + ' > table.embeddedComponent > tbody').append(row); }, /** * Append an error to a form field or row * * @param {string} formname - the form name * @param {string|number} rowindex - the input row index ('none' for add, '0' for edit) * @param {string} fieldname - the field name * @param {string} message - the error message */ appendError: function(formname, rowindex, fieldname, message) { var errorClass = formname + '_error', target, msg = '<div class="error">' + message + '</div>', colspan = function(t) { var columns = $(t + '> td'), total = 0; for (var i, len = columns.len, width; i<len; i++) { width = columns[i].attr('colspan'); if (width) { total += parseInt(width); } else { total += 1; } } return total; }, rowname = function() { if ('none' == rowindex) { return '#add-row-' + formname; } else { return '#edit-row-' + formname; } }; if (null === fieldname) { // Append error message to the whole subform target = rowname(); msg = $('<tr><td colspan="' + colspan(target) + '">' + msg + '</td></tr>'); } else { // Append error message to subform field target = '#sub_' + formname + '_' + formname + '_i_' + fieldname + '_edit_' + rowindex; if ($(target).is('[type="hidden"]')) { target = rowname(); msg = '<tr><td colspan="' + colspan(target) + '">' + msg + '</td></tr>'; } msg = $(msg); } msg.addClass(errorClass).hide().insertAfter(target); }, /** * Update (replace) the content of a column, needed to write * read-only field data into an edit row * * @param {jQuery} row - the row * @param {number} colIndex - the column index * @param {string|HTML} contents - the column contents */ updateColumn: function(row, colIndex, contents) { $(row).find('td').eq(colIndex).html(contents); } }, // Utilities ---------------------------------------------------------- /** * Mark a row as changed * * @param {jQuery} element - the trigger element */ _markChanged: function(element) { $(element).closest('.inline-form').addClass('changed'); }, /** * Parse the JSON from the real input, and bind the result * as 'data' object to the real input * * @return {object} the data object */ _deserialize: function() { var input = this.input; var data = JSON.parse(input.val()); input.data('data', data); return data; }, /** * Serialize the 'data' object of the real input as JSON and * set the JSON as value for the real input * * @return {string} the JSON */ _serialize: function() { var input = this.input; var json = JSON.stringify(input.data('data')); input.val(json); return json; }, /** * Display all errors */ _displayErrors: function() { $('.' + this.formname + '_error').show(); }, /** * Remove all error messages from all rows */ _removeErrors: function() { $('.' + this.formname + '_error').remove(); }, /** * Disable the add-row */ _disableAddRow: function() { var addRow = $('#add-row-' + this.formname); addRow.find('input, select, textarea').prop('disabled', true); addRow.find('.inline-add, .action-lnk').addClass('hide'); }, /** * Enable the add-row */ _enableAddRow: function() { var addRow = $('#add-row-' + this.formname); addRow.find('input, select, textarea').prop('disabled', false); addRow.find('.inline-add, .action-lnk').removeClass('hide'); }, /** * Show or hide non-static header row */ _showHeaders: function() { var labelRow = this.labelRow; if (labelRow && labelRow.length) { var formname = this.formname; var visibleReadRows = $('#sub-' + formname + ' .read-row:visible'); if (visibleReadRows.length) { labelRow.show(); } else { labelRow.hide(); } } }, /** * Ensure that all inline forms are checked upon submission of * main form * * @param {jQuery} element - the trigger element */ _catchSubmit: function(element) { var ns = this.namespace + this.id; $(this.element).closest('form') .unbind(ns) .bind('submit' + ns, {widget: this}, this._submitAll); }, // Data Processing and Validation ------------------------------------- /** * Collect the data from the form * * @param {object} data - the de-serialized JSON data * @param {string|number} rowindex - the row index */ _collectData: function(data, rowindex) { var formname = this.formname, rows = data['data'], row = {}, original = null; var formRow; if (rowindex == 'none') { formRow = $('#add-row-' + formname); } else { formRow = $('#edit-row-' + formname); var originalIndex = formRow.data('rowindex'); if (typeof originalIndex != 'undefined') { original = rows[originalIndex]; } } if (formRow.length) { // Trigger client-side validation: // Widgets in this formRow can bind handlers to the validate-event // which can stop the data collection (and thus prevent both server-side // validation and subform submission) by calling event.preventDefault(). var event = new $.Event('validate'); formRow.triggerHandler(event); if (event.isDefaultPrevented()) { return null; } } // Retain the original record ID if (original !== null) { var record_id = original['_id']; if (typeof record_id != 'undefined') { row['_id'] = record_id; } } // Collect the input data var fieldname, selector, input, value, cssclass, intvalue, fields = data['fields'], upload_index; for (var i=0; i < fields.length; i++) { fieldname = fields[i]['name']; selector = '#sub_' + formname + '_' + formname + '_i_' + fieldname + '_edit_' + rowindex; input = $(selector); if (input.length) { // Field is Writable value = input.val(); if (input.attr('type') == 'file') { // Clone the Input ready to accept new files var cloned = input.clone(); cloned.insertAfter(input); // Store the original input at the end of the form // - we move the original input as it doesn't contain the file otherwise on IE, etc // http://stackoverflow.com/questions/415483/clone-a-file-input-element-in-javascript var add_button = $('#add-' + formname + '-' + rowindex), multiple; if (add_button.length) { multiple = true; } else { // Only one row can exist & this must be added during form submission multiple = false; } if (!multiple && rowindex == 'none') { upload_index = '0'; } else { upload_index = rowindex; } var upload_id = 'upload_' + formname + '_' + fieldname + '_' + upload_index; // Remove any old upload for this index $('#' + upload_id).remove(); var form = input.closest('form'); input.css({display: 'none'}) .attr('id', upload_id) .attr('name', upload_id) .appendTo(form); if (value.match(/fakepath/)) { // IE, etc: Remove 'fakepath' from filename value = value.replace(/(c:\\)*fakepath\\/i, ''); } } else if (input.attr('type') == 'checkbox') { value = input.prop('checked'); } else { cssclass = input.attr('class'); if (cssclass == 'generic-widget') { // Reference values need to be ints for S3Represent to find a match in theset // - ensure we don't do this to dates though! intvalue = parseInt(value, 10); if (!isNaN(intvalue)) { value = intvalue; } } } } else { // Field is Read-only if (typeof original != 'undefined') { // Keep current value value = original[fieldname]['value']; } else { value = ''; } } row[fieldname] = value; } var single = $('#read-row-' + formname + '-' + rowindex).hasClass('single'); if (single) { // A multiple=False subform being edited // => setting all fields to '' indicates delete var deleteRow = true; for (fieldname in row) { if ((fieldname != '_id') && (row[fieldname] !== '')) { deleteRow = false; break; } } if (deleteRow) { // Check whether subform is required var required = $('#edit-row-' + formname).hasClass('required'); if (required) { // Subform is required => cannot delete this._appendError(formname, '0', fieldname, i18n.enter_value); row['_error'] = true; } else { // Delete it row['_delete'] = true; } } else { delete row['_error']; } } else { // Check whether subform is required var subformRequired = false; if ($('#add-row-' + formname).hasClass('required') || $('#edit-row-' + formname).hasClass('required')) { subformRequired = true; } // Make sure there is at least one row if (subformRequired) { // Check if empty delete row['_error']; var empty = true; for (fieldname in row) { if ((fieldname != '_id') && (row[fieldname] !== '')) { empty = false; } } if (empty) { var errorIndex = 'none'; if (rowindex != 'none') { // This is the edit-row, so the index is always '0' errorIndex = '0'; } // Check whether rows can be added (=whether there is an add-button) if ($('#add-' + formname + '-' + rowindex).length) { // Multiple=true, rows can be added if (!$('#read-row-' + formname + '-0').length) { // No rows present => error this._appendError(formname, errorIndex, fieldname, i18n.enter_value); row['_error'] = true; } } else { // Multiple=false, no other rows can exist => error this._appendError(formname, errorIndex, fieldname, i18n.enter_value); row['_error'] = true; } } } } // Add the defaults var defaults = data['defaults']; for (fieldname in defaults) { if (!row.hasOwnProperty(fieldname)) { value = defaults[fieldname]['value']; row[fieldname] = value; } } // Return the row object return row; }, /** * Validate a new/updated row * * @param {string|number} rowindex - the input row index ('none' for add, '0' for edit) * @param {object} data - the de-serialized JSON data * @param {object} row - the new row data */ _validate: function(data, rowindex, row) { var formname = this.formname; if (row._error) { // Required row which has already been validated as bad this._displayErrors(); return null; } // Construct the URL var c = data['controller'], f = data['function'], resource = data['resource'], component = data['component']; var url = S3.Ap.concat('/' + c + '/' + f + '/validate.json'), concat; if (null !== resource && typeof resource != 'undefined') { url += '?resource=' + resource; concat = '&'; } else { concat = '?'; } if (null !== component && typeof component != 'undefined') { url += concat + 'component=' + component; } // Request validation of the row // @ToDo: Skip read-only fields (especially Virtual) var row_json = JSON.stringify(row), response = null; $.ajaxS3({ async: false, type: 'POST', url: url, data: row_json, dataType: 'json', contentType: 'application/json; charset=utf-8', // gets moved to .done() inside .ajaxS3 success: function(data) { response = data; } }); // Check and report errors var has_errors = false; if (!response) { has_errors = true; } else if (response.hasOwnProperty('_error')) { has_errors = true; this._appendError(formname, rowindex, null, response._error); } var item, error, field; for (field in response) { item = response[field]; if (item.hasOwnProperty('_error')) { error = item._error; if (error == "invalid field") { // Virtual Field - not a real error item.text = item.value; } else { this._appendError(formname, rowindex, field, error); has_errors = true; } } } // Return the validated + represented row // (or null if there was an error) if (has_errors) { this._displayErrors(); return null; } else { return response; } }, // Form Actions ------------------------------------------------------- /** * Edit a row * * @param {string|number} rowindex - the row index * * @todo: separate out the update of the read-row */ _editRow: function(rowindex) { var formname = this.formname; var rowname = formname + '-' + rowindex; this._removeErrors(); var data = this._deserialize(); var fields = data['fields']; var row = data['data'][rowindex]; if (row._readonly) { // Can't edit the row if it is read-only return; } // Show all read rows for this field $('#sub-' + formname + ' .read-row').removeClass('hide'); // Hide the current read row, unless it's an Image if (formname != 'imageimage') { $('#read-row-' + rowname).addClass('hide'); } // Populate the edit row with the data for this rowindex var fieldname, element, input, text, value, i; for (i=0; i < fields.length; i++) { fieldname = fields[i]['name']; value = row[fieldname]['value']; element = '#sub_' + formname + '_' + formname + '_i_' + fieldname + '_edit_0'; // If the element is a select then we may need to add the option we're choosing var select = $('select' + element); if (select.length !== 0) { var option = $('select' + element + ' option[value="' + value + '"]'); if (option.length === 0) { // This option does not exist in the select, so add it // because otherwise val() won't work. Maybe the option // gets added later by a script (e.g. S3OptionsFilter) select.append('<option value="' + value + '">-</option>'); } } input = $(element); if (!input.length) { // Read-only field this._updateColumn($('#edit-row-' + formname), i, row[fieldname]['text']); } else { if (input.attr('type') == 'file') { // Update the existing upload item, if there is one var upload = $('#upload_' + formname + '_' + fieldname + '_' + rowindex); if (upload.length) { var id = input.attr('id'); var name = input.attr('name'); input.replaceWith(upload); upload.attr('id', id) .attr('name', name) .css({display: ''}); } } else if (input.attr('type') == 'checkbox') { input.prop('checked', value); } else { input.val(value); if (input.hasClass('multiselect-widget') && input.multiselect('instance')) { input.multiselect('refresh'); } else if (input.hasClass('groupedopts-widget') && input.groupedopts('instance')) { input.groupedopts('refresh'); } else if (input.hasClass('location-selector') && input.locationselector('instance')) { input.locationselector('refresh'); } else { // Populate text in autocompletes element = '#dummy_sub_' + formname + '_' + formname + '_i_' + fieldname + '_edit_0'; text = row[fieldname]['text']; $(element).val(text); } } } } // Insert the edit row after this read row var edit_row = $('#edit-row-' + formname); edit_row.insertAfter('#read-row-' + rowname); // Remember the current row index in the edit row & show it edit_row.data('rowindex', rowindex) .removeClass('hide'); // Trigger the dropdown change event $('#edit-row-' + formname + ' select:not(".lx-select")').change(); // Disable the add-row while editing this._disableAddRow(); this._showHeaders(); }, /** * Cancel editing a row * * @param {string|number} rowindex - the row index */ _cancelEdit: function(rowindex) { var formname = this.formname; var rowname = formname + '-' + rowindex; this._removeErrors(); var edit_row = $('#edit-row-' + formname); // Hide and reset the edit-row edit_row.addClass('hide') .data('rowindex', null) .removeClass('changed'); // Show the read-row $('#read-row-' + rowname).removeClass('hide'); // Enable the add-row this._enableAddRow(); this._showHeaders(); }, /** * Add a new row * * @todo: separate out the creation of a new read-row */ _addRow: function() { var formname = this.formname; var rowindex = 'none'; var add_button = $('#add-' + formname + '-' + rowindex), multiple; if (add_button.length) { multiple = true; } else { // Only one row can exist & this must be added during form submission multiple = false; } if (multiple) { // Hide add-button, show throbber add_button.addClass('hide'); var throbber = $('#throbber-' + formname + '-' + rowindex); throbber.removeClass('hide'); // Remove any previous error messages this._removeErrors(); } // Collect the values from the add-row var data = this._deserialize(); var row_data = this._collectData(data, 'none'); if (null === row_data) { // Data collection failed (e.g. client-side validation error) if (multiple) { throbber.addClass('hide'); add_button.removeClass('hide'); } return false; } // If this is an empty required=true row in a multiple=true with existing rows, then don't validate var add_required = $('#add-row-' + formname).hasClass('required'), empty, fieldname; if (add_required) { empty = true; for (fieldname in row_data) { if ((fieldname != '_id') && (row_data[fieldname] !== '')) { empty = false; } } if (empty) { // Check if we have other rows if ($('#add-' + formname + '-' + rowindex).length) { // multiple=true, can have other rows if ($('#read-row-' + formname + '-0').length) { // Rows present, so skip validation // Hide throbber, show add-button throbber.addClass('hide'); add_button.removeClass('hide'); return true; } } } } // Validate the data var new_row = this._validate(data, rowindex, row_data); var success = false; if (null !== new_row) { success = true; // Add a new row to the real_input JSON new_row['_changed'] = true; // mark as changed var newindex = data['data'].push(new_row) - 1; new_row['_index'] = newindex; this._serialize(); if (multiple) { // Create a new read-row, clear add-row var items = [], fields = data['fields'], i, field, upload, d, f, default_value; for (i=0; i < fields.length; i++) { field = fields[i]['name']; // Update all uploads to the new index upload = $('#upload_' + formname + '_' + field + '_none'); if (upload.length) { var upload_id = 'upload_' + formname + '_' + field + '_' + newindex; $('#' + upload_id).remove(); upload.attr('id', upload_id) .attr('name', upload_id); } items.push(new_row[field]['text']); // Reset add-field to default value d = $('#sub_' + formname + '_' + formname + '_i_' + field + '_edit_default'); f = $('#sub_' + formname + '_' + formname + '_i_' + field + '_edit_none'); if (f.attr('type') == 'file') { var self = this, emptyWidget = d.clone(); emptyWidget.attr('id', f.attr('id')) .attr('name', f.attr('name')) // Set event onto new input to Mark row changed when new files uploaded .change(function() { self._markChanged(this); self._catchSubmit(this); }); f.replaceWith(emptyWidget); } else { default_value = d.val(); f.val(default_value); // Update widgets if (f.attr('type') == 'checkbox') { f.prop('checked', d.prop('checked')); } else if (f.hasClass('multiselect-widget') && f.multiselect('instance')) { f.multiselect('refresh'); } else if (f.hasClass('groupedopts-widget') && f.groupedopts('instance')) { f.groupedopts('refresh'); } else if (f.hasClass('location-selector') && f.locationselector('instance')) { f.locationselector('refresh'); } } default_value = $('#dummy_sub_' + formname + '_' + formname + '_i_' + field + '_edit_default').val(); $('#dummy_sub_' + formname + '_' + formname + '_i_' + field + '_edit_none').val(default_value); } // Unmark changed $('#add-row-' + formname).removeClass('changed'); // Hide the add-row if explicit open-action available $(this.element).find('.inline-open-add').each(function() { $('#add-row-' + formname).hide(); $(this).show(); }); // Render new read row and append to container var read_row = this._renderReadRow(formname, newindex, items); // Append read-row this._appendReadRow(formname, read_row); this._showHeaders(); } } if (multiple) { // Hide throbber, show add-button throbber.addClass('hide'); add_button.removeClass('hide'); } if (success) { $(this.element).closest('form').unbind(this.namespace + this.id); } return success; }, /** * Update row * * @param {string|number} rowindex - the row index */ _updateRow: function(rowindex) { var formname = this.formname; var rowname = formname + '-' + rowindex; var rdy_button = $('#rdy-' + formname + '-0'), multiple; if (rdy_button.length) { multiple = true; } else { // Only one row can exist & this must be updated during form submission multiple = false; } if (multiple) { // Hide rdy_button, show throbber rdy_button.addClass('hide'); var throbber = $('#throbber-' + formname + '-0'); throbber.removeClass('hide'); // Remove any previous error messages this._removeErrors(); } // Collect the values from the edit-row var data = this._deserialize(); var row_data = this._collectData(data, '0'); if (null === row_data) { // Data collection failed (e.g. client-side validation error) if (multiple) { throbber.addClass('hide'); rdy_button.removeClass('hide'); } return false; } if (row_data['_delete']) { // multiple=False form which has set all fields to '' to delete the row data['data'][rowindex]['_delete'] = true; this._serialize(); return true; } else { // Validate the form data var new_row = this._validate(data, '0', row_data); var success = false; if (null !== new_row) { success = true; // Update the row in the real_input JSON new_row['_id'] = data['data'][rowindex]['_id']; new_row['_changed'] = true; // mark as changed new_row['_index'] = rowindex; data['data'][rowindex] = new_row; this._serialize(); if (multiple) { // Update read-row in the table, clear edit-row var items = [], fields = data['fields'], default_value, i; for (i=0; i < fields.length; i++) { var field = fields[i]['name']; items.push(new_row[field]['text']); // Reset edit-field to default value var d = $('#sub_' + formname + '_' + formname + '_i_' + field + '_edit_default'); var f = $('#sub_' + formname + '_' + formname + '_i_' + field + '_edit_0'); if (f.attr('type') == 'file') { var empty = d.clone(), self = this; empty.attr('id', f.attr('id')) .attr('name', f.attr('name')) // Set event onto new input to Mark row changed when new files uploaded .change(function() { self._markChanged(this); self._catchSubmit(this); }); f.replaceWith(empty); } else { default_value = d.val(); f.val(default_value); } default_value = $('#dummy_sub_' + formname + '_' + formname + '_i_' + field + '_edit_default').val(); $('#dummy_sub_' + formname + '_' + formname + '_i_' + field + '_edit_0').val(default_value); } // Unmark changed var edit_row = $('#edit-row-' + formname); edit_row.removeClass('changed'); // Update the read row var read_row = this._renderReadRow(formname, rowindex, items); // Hide and reset the edit row edit_row.addClass('hide') // Reset rowindex .data('rowindex', null); // Show the read row read_row.removeClass('hide'); // Re-enable add-row this._enableAddRow(); this._showHeaders(); } } if (multiple) { // Hide throbber, enable rdy_button throbber.addClass('hide'); rdy_button.removeClass('hide'); } return (success); } }, /** * Remove a row * * @param {string|number} rowindex - the row index */ _removeRow: function(rowindex) { var formname = this.formname; var rowname = formname + '-' + rowindex; // Confirmation dialog if (!confirm(i18n.delete_confirmation)) { return false; } // Update the real_input JSON with deletion of this row var data = this._deserialize(); data['data'][rowindex]['_delete'] = true; this._serialize(); // Remove the read-row for this item $('#read-row-' + rowname).remove(); this._showHeaders(); // Remove all uploads for this item $('input[name^="' + 'upload_' + formname + '_"][name$="_' + rowindex + '"]').remove(); var edit_row = $('#edit-row-' + formname); if (edit_row.hasClass('required')) { if (!$('#read-row-' + formname + '-0').length) { // No more rows present - set the add row as required $('#add-row-' + formname).addClass('required'); edit_row.removeClass('required'); // Ensure we validate this if not changed this._catchSubmit(edit_row); } } return true; }, // Event Handlers ----------------------------------------------------- /** * Submit all changed inline-rows, and then the outer form * * @param {event} event - the submit-event (scope = outer form) */ _submitAll: function(event) { var self = event.data.widget; event.preventDefault(); var el = $(self.element), empty, success, errors = false, row; // Find and validate all pending rows var rows = el.find('.inline-form.changed, .inline-form.required'); for (var i=0, len=rows.length; i < len; i++) { row = $(rows[i]); empty = true; if (!row.hasClass('required')) { // Check that the row contains data var inputs = row.find('input, select, textarea'), input; for (var j=0, numfields=inputs.length; j < numfields; j++) { input = $(inputs[j]); // Ignore hidden inputs unless they have an 'input' flag if (input.is('[type="hidden"]') && !input.data('input') || !input.is(':visible')) { continue; } if ((input.attr('type') != 'checkbox' && input.val()) || input.prop('checked')) { empty = false; break; } } } else { // Treat required rows as non-empty empty = false; } // Validate all non-empty rows if (!empty) { if (row.hasClass('add-row')) { success = self._addRow(); } else { success = self._updateRow(row.data('rowindex')); } if (!success) { errors = true; } } } if (!errors) { // Remove the submit-event handler for this widget and // continue submitting the main form (=this) $(this).unbind(self.namespace + self.id).submit(); } }, /** * S3SQLInlineComponentCheckbox: status update after form error */ _updateCheckboxStatus: function() { var el = $(this.element), self = this, checkbox, fieldname, value, data, row; el.find(':checkbox').each(function() { checkbox = $(this); fieldname = checkbox.attr('id').split('-')[2]; value = checkbox.val(); // Read current data from real input data = self._deserialize()['data']; // Find the corresponding data item for (var i=0, len=data.length; i < len; i++) { row = data[i]; if (row.hasOwnProperty(fieldname) && row[fieldname].value == value) { // Modify checkbox state, as-required if (row._changed) { checkbox.prop('checked', true); } else if (row._delete) { checkbox.prop('checked', false); } break; } } }); }, /** * S3SQLInlineComponentCheckbox: click-event handler * * @param {event} event - the click event */ _checkboxOnClick: function(event) { var self = event.data.widget, checkbox = $(this); var fieldname = checkbox.attr('id').split('-')[2], value = checkbox.val(), item = null, row; // Read current data from real input var data = self._deserialize().data; // Find the corresponding data item for (var i=0, len=data.length; i < len; i++) { row = data[i]; if (row.hasOwnProperty(fieldname) && row[fieldname].value == value) { item = row; break; } } // Modify data if (checkbox.prop('checked')) { if (!item) { // Not yet found, so initialise var label = checkbox.next().html(); // May be fragile to different formstyles :/ item = {}; item[fieldname] = {'text': label, 'value': value}; data.push(item); } item._changed = true; // Remove delete-marker if re-selected if (item.hasOwnProperty('_delete')) { delete item._delete; } } else if (item) { item._delete = true; } // Write data back to real input self._serialize(); }, /** * S3SQLInlineComponentMultiSelectWidget: change-event handler * * @param {event} event - the change event */ _multiselectOnChange: function(event) { var self = event.data.widget, multiselect = $(this); var fieldname = multiselect.attr('id').split('-')[1], values = multiselect.val(), row, item, label, value; // Read current data from real input var data = self._deserialize().data; // Update current items var current_items = [], i, len; for (i=0, len=data.length; i < len; i++) { row = data[i]; if (row.hasOwnProperty(fieldname)) { value = row[fieldname].value.toString(); if ($.inArray(value, values) == -1) { // No longer selected => mark for delete row._delete = true; } else { // Remove delete-marker if re-selected if (row.hasOwnProperty('_delete')) { delete row._delete; } } current_items.push(value); } } // Add new items var new_items = $(values).not(current_items).get(); for (i=0, len=new_items.length; i < len; i++) { value = new_items[i]; label = multiselect.find('option[value=' + value + ']').html(); item = {}; item[fieldname] = {'text': label, 'value': value}; item._changed = true; if (item.hasOwnProperty('_delete')) { delete item._delete; } data.push(item); } // Write data back to real input self._serialize(); }, // Event Management --------------------------------------------------- /** * Bind event handlers (after refresh) */ _bindEvents: function() { var el = $(this.element), ns = this.namespace, self = this; // Button events el.delegate('.read-row', 'click' + ns, function() { var names = $(this).attr('id').split('-'); var rowindex = names.pop(); self._editRow(rowindex); return false; }).delegate('.inline-add', 'click' + ns, function() { self._addRow(); return false; }).delegate('.inline-cnc', 'click' + ns, function() { var names = $(this).attr('id').split('-'); var zero = names.pop(); var formname = names.pop(); var rowindex = $('#edit-row-' + formname).data('rowindex'); self._cancelEdit(rowindex); return false; }).delegate('.inline-rdy', 'click' + ns, function() { var names = $(this).attr('id').split('-'); var zero = names.pop(); var formname = names.pop(); var rowindex = $('#edit-row-' + formname).data('rowindex'); self._updateRow(rowindex); return false; }).delegate('.inline-edt', 'click' + ns, function() { var names = $(this).attr('id').split('-'); var rowindex = names.pop(); self._editRow(rowindex); return false; }).delegate('.inline-rmv', 'click' + ns, function() { var names = $(this).attr('id').split('-'); var rowindex = names.pop(); self._removeRow(rowindex); return false; }).delegate('.error', 'click' + ns, function() { $(this).fadeOut('medium', function() { $(this).remove(); }); return false; }); // Form events var inputs = 'input', textInputs = 'input[type="text"],input[type="file"],textarea', fileInputs = 'input[type="file"]', otherInputs = 'input[type!="text"][type!="file"],select', multiSelects = 'select.multiselect-widget'; el.find('.add-row,.edit-row').each(function() { var $this = $(this); $this.find(textInputs).bind('input' + ns, function() { self._markChanged(this); self._catchSubmit(this); }); $this.find(fileInputs).bind('change' + ns, function() { self._markChanged(this); self._catchSubmit(this); }); $this.find(otherInputs).bind('focusin' + ns, function() { $(this).one('change' + ns, function() { self._markChanged(this); self._catchSubmit(this); }).one('focusout', function() { $(this).unbind('change' + ns); }); }); $this.find(multiSelects).bind('multiselectopen' + ns, function() { $(this).unbind('change' + ns) .one('change' + ns, function() { self._markChanged(this); self._catchSubmit(this); }); }); $this.find(inputs).bind('keypress' + ns, function(e) { if (e.which == 13) { e.preventDefault(); return false; } return true; }); }); el.find('.add-row').each(function() { $(this).find(inputs).bind('keyup' + ns, function(e) { switch (e.which) { case 13: // Enter self._addRow(); break; default: break; } }); }); el.find('.edit-row').each(function() { $(this).find(inputs).bind('keyup' + ns, function(e) { var rowIndex = $(this).closest('.edit-row').data('rowindex'); switch (e.which) { case 13: // Enter self._updateRow(rowIndex); break; case 27: // Escape self._cancelEdit(rowIndex); break; default: break; } }); }); // Event Management for S3SQLInlineComponentCheckbox if (el.hasClass('inline-checkbox')) { var error_wrapper = $(this.element).closest('form') .find('.error_wrapper'); if (error_wrapper.length) { this._updateCheckboxStatus(); } // Delegate click-event, so that it also applies for // dynamically inserted checkboxes el.delegate(':checkbox', 'click' + ns, {widget: this}, this._checkboxOnClick); } // Event Management for S3SQLInlineComponentMultiSelectWidget if (el.hasClass('inline-multiselect')) { el.find('.inline-multiselect-widget') .bind('change' + ns, {widget: this}, this._multiselectOnChange); } // Explicit open-action to reveal the add-row el.find('.inline-open-add').bind('click' + ns, function(e) { e.preventDefault(); $('#add-row-' + self.formname).removeClass('hide').show(); $(this).hide(); }); return true; }, /** * Unbind events (before refresh) */ _unbindEvents: function() { var el = $(this.element), ns = this.namespace; // Remove inline-multiselect-widget event handlers if (el.hasClass('inline-multiselect')) { el.find('.inline-multiselect-widget') .unbind(ns); } // Remove inline-locationselector-widget event handlers el.find('.inline-locationselector-widget') .unbind(ns); // Remove all form event handlers el.find('.add-row,.edit-row').each(function() { $(this).find('input,textarea,select').unbind(ns); }); // Remove open-action event handler el.find('.inline-open-add').unbind(ns); // Remove all delegations el.undelegate(ns); return true; } }); })(jQuery); $(document).ready(function() { // Activate on all inline-components in the current page $('.inline-component').inlinecomponent({}); });
const path = require('path'); exports.onCreateBabelConfig = ({ actions }) => { actions.setBabelOptions({ options: { babelrcRoots: true, }, }); }; exports.onCreateWebpackConfig = function onCreateWebpackConfig({ actions }) { actions.setWebpackConfig({ resolve: { symlinks: false, alias: { 'react': path.resolve('./node_modules/react'), 'react-dom': path.resolve('./node_modules/react-dom'), 'react-formal': path.resolve('../src'), '@docs': path.resolve('./src'), }, }, }); };
'use strict' const assert = require('chai').assert const index = require('../../src/reducers/index') describe('index()', function() { it('should be a function', function() { assert.isFunction(index) }) })
/** * Created by maurobuselli@gmail.com */ (function(){ 'use strict'; angular.module('AngularPanelsApp.pages.form') .controller('datepickerpopupCtrl', datepickerpopupCtrl); /** @ngInject */ function datepickerpopupCtrl($scope) { $scope.open = open; $scope.opened = false; $scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate']; $scope.format = $scope.formats[0]; $scope.options = { showWeeks: false }; function open() { $scope.opened = true; } } })();
(function() { 'use strict'; angular.module('characters') .directive('characterBack', characterBack); function characterBack(){ return function(scope, element, attrs){ var url = attrs.characterBack; element.css({ 'background-image': 'url(' + url +')', 'background-size' : 'cover', 'background-repeat': 'no-repeat', 'background-position': 'center' }); }; } })();
// @flow import { createElement } from 'react' import PropTypes from 'prop-types' import type { Theme } from './ThemeProvider' import createWarnTooManyClasses from '../utils/createWarnTooManyClasses' import validAttr from '../utils/validAttr' import isTag from '../utils/isTag' import isStyledComponent from '../utils/isStyledComponent' import getComponentName from '../utils/getComponentName' import type { RuleSet, Target } from '../types' import AbstractStyledComponent from './AbstractStyledComponent' import { CHANNEL } from './ThemeProvider' import StyleSheet, { CONTEXT_KEY } from './StyleSheet' const escapeRegex = /[[\].#*$><+~=|^:(),"'`]/g const multiDashRegex = /--+/g export default (ComponentStyle: Function, constructWithOptions: Function) => { /* We depend on components having unique IDs */ const identifiers = {} const generateId = (_displayName: string) => { const displayName = typeof _displayName !== 'string' ? 'sc' : _displayName .replace(escapeRegex, '-') // Replace all possible CSS selectors .replace(multiDashRegex, '-') // Replace multiple -- with single - const nr = (identifiers[displayName] || 0) + 1 identifiers[displayName] = nr const hash = ComponentStyle.generateName(displayName + nr) return `${displayName}-${hash}` } class BaseStyledComponent extends AbstractStyledComponent { static target: Target static styledComponentId: string static attrs: Object static componentStyle: Object static warnTooManyClasses: Function attrs = {} state = { theme: null, generatedClassName: '', } buildExecutionContext(theme: any, props: any) { const { attrs } = this.constructor const context = { ...props, theme } if (attrs === undefined) { return context } this.attrs = Object.keys(attrs).reduce((acc, key) => { const attr = attrs[key] // eslint-disable-next-line no-param-reassign acc[key] = typeof attr === 'function' ? attr(context) : attr return acc }, {}) return { ...context, ...this.attrs } } generateAndInjectStyles(theme: any, props: any) { const { componentStyle, warnTooManyClasses } = this.constructor const executionContext = this.buildExecutionContext(theme, props) const styleSheet = this.context[CONTEXT_KEY] || StyleSheet.instance const className = componentStyle.generateAndInjectStyles(executionContext, styleSheet) if (warnTooManyClasses !== undefined) warnTooManyClasses(className) return className } componentWillMount() { // If there is a theme in the context, subscribe to the event emitter. This // is necessary due to pure components blocking context updates, this circumvents // that by updating when an event is emitted if (this.context[CHANNEL]) { const subscribe = this.context[CHANNEL] this.unsubscribe = subscribe(nextTheme => { // This will be called once immediately // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. const { defaultProps } = this.constructor const isDefaultTheme = defaultProps && this.props.theme === defaultProps.theme const theme = this.props.theme && !isDefaultTheme ? this.props.theme : nextTheme const generatedClassName = this.generateAndInjectStyles(theme, this.props) this.setState({ theme, generatedClassName }) }) } else { const theme = this.props.theme || {} const generatedClassName = this.generateAndInjectStyles( theme, this.props, ) this.setState({ theme, generatedClassName }) } } componentWillReceiveProps(nextProps: { theme?: Theme, [key: string]: any }) { this.setState((oldState) => { // Props should take precedence over ThemeProvider, which should take precedence over // defaultProps, but React automatically puts defaultProps on props. const { defaultProps } = this.constructor const isDefaultTheme = defaultProps && nextProps.theme === defaultProps.theme const theme = nextProps.theme && !isDefaultTheme ? nextProps.theme : oldState.theme const generatedClassName = this.generateAndInjectStyles(theme, nextProps) return { theme, generatedClassName } }) } componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe() } } render() { const { innerRef } = this.props const { generatedClassName } = this.state const { styledComponentId, target } = this.constructor const isTargetTag = isTag(target) const className = [ this.props.className, styledComponentId, this.attrs.className, generatedClassName, ].filter(Boolean).join(' ') const baseProps = { ...this.attrs, className, } if (isStyledComponent(target)) { baseProps.innerRef = innerRef } else { baseProps.ref = innerRef } const propsForElement = Object .keys(this.props) .reduce((acc, propName) => { // Don't pass through non HTML tags through to HTML elements // always omit innerRef if ( propName !== 'innerRef' && propName !== 'className' && (!isTargetTag || validAttr(propName)) ) { // eslint-disable-next-line no-param-reassign acc[propName] = this.props[propName] } return acc }, baseProps) return createElement(target, propsForElement) } } const createStyledComponent = ( target: Target, options: Object, rules: RuleSet, ) => { const { displayName = isTag(target) ? `styled.${target}` : `Styled(${getComponentName(target)})`, componentId = generateId(options.displayName), ParentComponent = BaseStyledComponent, rules: extendingRules, attrs, } = options const styledComponentId = (options.displayName && options.componentId) ? `${options.displayName}-${options.componentId}` : componentId let warnTooManyClasses if (typeof process !== 'undefined' && process.env.NODE_ENV !== 'production') { warnTooManyClasses = createWarnTooManyClasses(displayName) } const componentStyle = new ComponentStyle( extendingRules === undefined ? rules : extendingRules.concat(rules), styledComponentId, ) class StyledComponent extends ParentComponent { static contextTypes = { [CHANNEL]: PropTypes.func, [CONTEXT_KEY]: PropTypes.instanceOf(StyleSheet), } static displayName = displayName static styledComponentId = styledComponentId static attrs = attrs static componentStyle = componentStyle static warnTooManyClasses = warnTooManyClasses static target = target static withComponent(tag) { const { displayName: _, componentId: __, ...optionsToCopy } = options const newOptions = { ...optionsToCopy, ParentComponent: StyledComponent } return createStyledComponent(tag, newOptions, rules) } static get extend() { const { displayName: _, componentId: __, rules: rulesFromOptions, ...optionsToCopy } = options const newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules) const newOptions = { ...optionsToCopy, rules: newRules, ParentComponent: StyledComponent, } return constructWithOptions(createStyledComponent, target, newOptions) } } return StyledComponent } return createStyledComponent }
'use strict'; // Use applicaion configuration module to register a new module ApplicationConfiguration.registerModule('shop-fruits');
/* * Copyright (c) 2015 by Rafael Angel Aznar Aparici (rafaaznar at gmail dot com) * * openAUSIAS: The stunning micro-library that helps you to develop easily * AJAX web applications by using Java and jQuery * openAUSIAS is distributed under the MIT License (MIT) * Sources at https://github.com/rafaelaznar/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ 'use strict'; moduloAsignatura.controller('AsignaturaNewController', ['$scope', '$routeParams', '$location', 'serverService', 'sharedSpaceService', '$filter', function ($scope, $routeParams, $location, serverService, sharedSpaceService, $filter) { $scope.ob = 'asignatura'; $scope.op = 'new'; $scope.result = null; $scope.title = "Edición de asignatura"; $scope.icon = "fa-file-text-o"; $scope.obj = {}; $scope.obj.obj_curso = {"id": $routeParams.id}; if (sharedSpaceService.getFase() == 0) { if ($routeParams.curso && $routeParams.curso > 0) { $scope.obj.obj_curso.id = $routeParams.curso; } } else { $scope.obj = sharedSpaceService.getObject(); sharedSpaceService.setFase(0); } $scope.save = function () { serverService.getDataFromPromise(serverService.promise_setOne($scope.ob, {json: JSON.stringify(serverService.array_identificarArray($scope.obj))})).then(function (data) { $scope.result = data; }); }; $scope.$watch('obj.obj_curso.id', function () { if ($scope.obj) { serverService.getDataFromPromise(serverService.promise_getOne('curso', $scope.obj.obj_curso.id)).then(function (data2) { $scope.obj.obj_curso = data2.message; }); } }); $scope.back = function () { window.history.back(); }; $scope.close = function () { $location.path('/home'); }; $scope.plist = function () { $location.path('/asignaturaxcurso/plist/'+$scope.obj.obj_curso.id); }; }]);
import React from 'react'; import { connect } from 'react-redux'; import styled from 'styled-components'; import { openModal } from '../../actions'; // styles & icons import { colors, fonts } from '../../styles'; const Wrapper = styled.div` display: block; `; const ButtonSD = styled.button` position: absolute; top: 15px; right: ${props => (props.onlyText ? '10px' : '115px')}; padding: 10px 20px; background-color: ${colors.lightGray}; color: ${colors.secondaryText}; border-radius: 3px; text-transform: uppercase; font-family: ${fonts.latoRegular}; text-align: center; font-size: 12px; border: none; &:focus { outline: none; } &:hover { cursor: pointer; } @media print { display: none; } `; class ScrubberButton extends React.Component { onClick () { const { openModal } = this.props; openModal(this.props.info); } render () { return ( <Wrapper> <ButtonSD onClick={this.onClick.bind(this)} onlyText={this.props.onlyText} > SHOW DIFFS </ButtonSD> </Wrapper> ); } } const mapStateToProps = state => { return { scrubber: state.scrubber }; }; const mapDispatchToProps = dispatch => { return { openModal: value => { dispatch(openModal(value)); } }; }; const ScrubberButtonContainer = connect(mapStateToProps, mapDispatchToProps)( ScrubberButton ); export default ScrubberButtonContainer;
'use strict'; var HttpApiError = require('error').HttpApiError; module.exports = function(req, res, next) { var clientId = +req.params.clientId || -1; if (clientId === -1) { return next(new HttpApiError(400, 'Wrong client id')); } req.clientId = clientId; next(); };
var flickr = require('..')(function auth() { /* noop */ }); var assert = require('assert'); describe('flickr.photos.setContentType', function () { it('requires "photo_id"', function () { assert.throws(function () { flickr.photos.setContentType({ content_type: '_' }); }, function (err) { return err.message === 'Missing required argument "photo_id"'; }); }); it('requires "content_type"', function () { assert.throws(function () { flickr.photos.setContentType({ photo_id: '_' }); }, function (err) { return err.message === 'Missing required argument "content_type"'; }); }); it('returns a Request instance', function () { var req = flickr.photos.setContentType({ photo_id: '_', content_type: '_' }); assert.equal(req.method, 'POST'); assert.equal(req.url, 'https://api.flickr.com/services/rest'); assert.equal(req.params.format, 'json'); assert.equal(req.params.nojsoncallback, '1'); assert.equal(req.params.method, 'flickr.photos.setContentType'); assert.equal(req.header['Content-Type'], 'text/plain'); assert.equal(req.params.photo_id, '_'); assert.equal(req.params.content_type, '_'); }); });
module.exports = { module: { name: 'pipDialogs', styles: 'index', export: 'pip.dialogs', standalone: 'pip.dialogs' }, build: { js: false, ts: false, tsd: true, bundle: true, html: true, sass: true, lib: true, images: true, dist: false }, browserify: { entries: [ './temp/pip-webui-dialogs-html.min.js', './src/index.ts' ] }, file: { lib: [ '../pip-webui-test/dist/**/*', '../pip-webui-lib/dist/**/*', '../pip-webui-buttons/dist/**/*', // '../pip-webui-csscomponents/dist/**/*', '../pip-webui-services/dist/**/*', // '../pip-webui-lists/dist/**/*', // '../pip-webui-rest/dist/**/*', // '../pip-webui-controls/dist/**/*', // '../pip-webui-nav/dist/**/*', '../pip-webui-layouts/dist/**/*', '../pip-webui-themes/dist/**/*', ] }, samples: { port: 8130 }, api: { port: 8131 } };
// ---------------------------------------------------------------------------- // define controller app.controller( 'settings', ['$scope', '$http', '$translate', '$window', 'Upload', function( $scope, $http, $translate, $window, Upload ) { $http.get( 'themes' ).then( function( res ) { $scope.themes = res.data; }); $http.get( 'portfolio/settings' ).then( function( res ) { $scope.settings = res.data; }); $scope.change = function() { $http.post( 'portfolio/settings', $scope.settings ); }; $scope.destroy = function() { $http.delete( 'portfolio' ).then( function() { $translate( 'settings.destroy.success' ).then( function( trad ) { $window.alert( trad ); $window.document.location.reload( true ); }); }); }; // upload on file select or drop $scope.upload = function (file) { Upload.upload({ url: 'upload', data: { cv: file } }).then( function() { // success $translate( 'settings.uploaded.success' ).then( function( trad ) { $window.alert( trad ); }); }, function() { // error $translate( 'settings.uploaded.error' ).then( function( trad ) { $window.alert( trad ); }); }, function() { // progress event }); }; }]);
/* * Fun times with the Web Worker API * * To be used like new Lemming(function) * to allow for individual functions to run in their own thread (sort of) * returns a promise that resolves when the lemming gets back a result */ (function (global) { 'use strict'; // Can they though? if (typeof window === undefined) { console.log('Lemmings cannot be run in a worker!'); return; } var R = window.R; var lemming = { Task: Task }; function Task(fn, args, context) { if (typeof fn === 'function') { // The object that will be passed to the worker script var workerOptions = {}; var worker = new Worker('lemming-helper.js'); // Stringify the function workerOptions.func = fn.toString(); // TODO: do some typechecking here workerOptions.args = args; workerOptions.context = context; worker.postMessage(JSON.stringify(workerOptions)); return new Promise(function (resolve, reject) { worker.onmessage = function (result) { resolve(result.data); }; }); } } if (typeof exports === 'object') { module.exports = lemming; } else if (typeof define === 'function' && define.amd) { define(function () { return lemming }); } else { global.lemming = lemming; } })(this);
'use strict' const config = require('../config') const exec = require('child_process').exec const treeKill = require('tree-kill') let YELLOW = '\x1b[33m' let BLUE = '\x1b[34m' let END = '\x1b[0m' let isElectronOpen = false function format (command, data, color) { return color + command + END + ' ' + // Two space offset data.toString().trim().replace(/\n/g, '\n' + repeat(' ', command.length + 2)) + '\n' } function repeat (str, times) { return (new Array(times + 1)).join(str) } let children = [] function run (command, color, name) { let child = exec(command) child.stdout.on('data', data => { console.log(format(name, data, color)) /** * Start electron after successful compilation * (prevents electron from opening a blank window that requires refreshing) */ if (/Compiled successfully/g.test(data.toString().trim().replace(/\n/g, '\n' + repeat(' ', command.length + 2))) && !isElectronOpen) { console.log(`${BLUE}Starting electron...\n${END}`) run('cross-env NODE_ENV=development electron app/src/main/index.dev.js', BLUE, 'electron') isElectronOpen = true } }) child.stderr.on('data', data => console.error(format(name, data, color))) child.on('exit', code => exit(code)) children.push(child) } function exit (code) { children.forEach(child => { treeKill(child.pid) }) } console.log(`${YELLOW}Starting webpack-dev-server...\n${END}`) run(`webpack-dev-server --hot --colors --config webpack.renderer.config.js --port ${config.port} --content-base app/dist`, YELLOW, 'webpack')
'use strict' // **Github:** https://github.com/toajs/toa // // **License:** MIT const Toa = require('..') const app = new Toa() app.use(function () { this.body = 'support sync function middleware!\n' }) app.use(function (next) { this.body += 'support thunk function middleware!\n' next() }) app.use(function * () { this.body += yield Promise.resolve('support generator function middleware!\n') }) app.listen(3000, () => console.log('App start at 3000'))