text
stringlengths
2
1.05M
/* Author: Daniel Upshaw URL: http://danieluphaw.com/ */ ;(function ($, window, document, undefined) { "use strict"; var defaults = { css: { // Use {} to bypass adding CSS classes to the container via the plugin (you can use your own CSS files) 'color': '#E7711B', 'text-shadow': '-1px 1px 0 rgba(127, 127, 127, 0.4)' }, container: $('<span>').addClass('star-rating'), // By default, the rating container has class "star-rating" star: $('<i>').addClass('fa fa-star'), star_half: $('<i>').addClass('fa fa-star-half'), star_blank: $('<i>').addClass('fa fa-star-o'), star_half_blank: $('<i>').addClass('fa fa-star-half-o'), /* click: function(rating, event) { // Add some functionality for when a star is clicked var item_id = this.element.closest('.item').attr('id'); var $plugin = this; $.post( 'rate-item.php', { item: item_id, item_rating: rating } ) .done(function(data) { alert('Your rating was stored: ' + rating); $plugin.reload(data.updated_rating); }) .fail(function() { alert('Could not store your rating'); }) .always(function() { }); }, */ hover: function(rating, event) { // Only applies when a click event is defined var lte_rating = this.stars.filter(':lt(' + (rating) + ')'); var gt_rating = this.stars.filter(':gt(' + (rating - 1) + ')'); if(event.type == 'mouseenter') { this.stars.each(function() { $(this).data('class-prev', $(this).attr('class')); }); lte_rating.attr('class', this.options.star.attr('class')); gt_rating.attr('class', this.options.star_blank.attr('class')); } else if (event.type == 'mouseleave') { this.stars.each(function() { $(this).attr('class', $(this).data('class-prev')); }); } }, rating: function() { // Extract the rating from the element var text = this.text().trim(); var matches; if (matches = text.match(/^(?:[^\d]+)?([\d.]+)/i)) { // Format: 3.5 // Format: Rated 3.5 // Format: 3.5/5 stars // Format: Rated 3.5 out of 5 stars // Format: 3.5/5 star rating return matches[1]; } else if (matches = text.match(/^([*]+)/i)) { // Format: ***** return matches[1].length; } return 0; }, // max: 5, // You can optionally use an integer for the maximum rating value max: function() { // If max is a function, use it to extract the maximum rating value from the element var text = this.text().trim(); var matches; if (matches = text.match(/\/(\d+)(?: [\w\s]+)?$/i)) { // Format: 3.5/5 // Format: 3.5/5 stars // Format: 3.5/5 star rating return matches[1]; } else if (matches = text.match(/ (?:out )?of (\d+)(?: [\w\s]+)?$/i)) { // Format: 3.5 of 5 // Format: 3.5 out of 5 // Format: 3.5 out of 5 stars // Format: 3.5 out of 5 points earned return matches[1]; } return false; }, round: function(rating) { // Specify what to do with fractional ratings // Round to the nearest 0.5 return Math.round(rating * 2) / 2; }, title: function() { // Set the title (hover text) on the container return 'Rated ' + this.rating() + (this.max() ? ' out of ' + this.max() : ''); }, render: function() { // The logic performed when the star_rating container is ready to render this.element .hide() .attr('aria-hidden', 'true') .after(this.star_rating); }, remove: function() { // Called if the star rating needs to be removed/destroyed from the elements this.star_rating.remove(); this.element.attr('aria-hidden', null).show(); } }; function Plugin(element, options) { this.element = $(element); this.options = $.extend({}, defaults, options); this._defaults = defaults; this.init(); } $.extend(Plugin.prototype, { init: function () { return this._render(); }, _render: function() { var rounded_rating = this.options.round.call(this, this.rating()); var whole_stars = Math.floor(rounded_rating); // If the fraction after rounding is at least 0.5, add a half star var half_star = (rounded_rating - whole_stars >= 0.5) ? 1 : 0; this.star_rating = this.options.container .clone(false) .css(this.options.css) .attr('aria-label', this.options.title.call(this)) .attr('title', this.options.title.call(this)); this.stars = $(); for (var i = 0; i < whole_stars; i++) { this.stars = this.stars.add(this.options.star.clone(false)); } if (half_star) { this.stars = this.stars.add( this.max ? this.options.star_half_blank.clone(false) : this.options.star_half.clone(false) ); } if (this.max()) { for (var i = whole_stars + half_star; i < this.max(); i++) { this.stars = this.stars.add(this.options.star_blank.clone(false)); } } this.star_rating.append(this.stars); var $plugin = this; // Don't bother with click or hover if we don't have a function for clicking if ($.isFunction(this.options.click)) { this.star_rating.css({'cursor': 'pointer'}); this.stars.hover(function (e) { $plugin.options.hover.call($plugin, $(this).index() + 1, e); }); this.stars.on('click', function (e) { $plugin.options.click.call($plugin, $(this).index() + 1, e); }); } this.options.render.call(this); return this; }, // Get or update the rating rating: function(rating) { if (typeof rating === 'undefined') { // If we haven't initialized the rating yet at all if (typeof this._rating === 'undefined') { this._rating = this.options.rating.call(this.element); } return this._rating; } else { this._rating = rating; return this.reload(); } }, // Get or update the max max: function(max) { if (typeof max === 'undefined') { // If we haven't initialized the max yet at all if (typeof this._max === 'undefined') { this._max = $.isFunction(this.options.max) ? this.options.max.call(this.element) : this.options.max; } return this._max; } else { this._max = max; return this.reload(); } }, reload: function() { this.remove(); return this._render(); }, remove: function() { this.options.remove.call(this); return this; }, // Also removes plugin reference from this.element // Additional functionality below destroy: function() { this.remove(); return this.element; } }); var plugin_name = 'star_rating'; $.fn[plugin_name] = function(options) { var args = arguments; if (!(this instanceof $)) { return $.extend(defaults, options); } if (options === undefined || typeof options === 'object') { return this.each(function () { if (!$.data(this, 'plugin_' + plugin_name)) { $.data(this, 'plugin_' + plugin_name, new Plugin(this, options)); } }); } else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') { var applied; this.each(function() { var instance = $.data(this, 'plugin_' + plugin_name); if (instance instanceof Plugin && $.isFunction(instance[options])) { applied = instance[options].apply(instance, Array.prototype.slice.call(args, 1)); } if (options === 'destroy') { $.data(this, 'plugin_' + plugin_name, null); } }); return applied !== undefined ? applied : this; } }; }(jQuery, window, document));
"use strict"; /* * Copyright 2019 gRPC authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ Object.defineProperty(exports, "__esModule", { value: true }); exports.Server = void 0; const http2 = require("http2"); const constants_1 = require("./constants"); const metadata_1 = require("./metadata"); const server_call_1 = require("./server-call"); const server_credentials_1 = require("./server-credentials"); const resolver_1 = require("./resolver"); const logging = require("./logging"); const subchannel_address_1 = require("./subchannel-address"); const uri_parser_1 = require("./uri-parser"); const channelz_1 = require("./channelz"); const TRACER_NAME = 'server'; function noop() { } function getUnimplementedStatusResponse(methodName) { return { code: constants_1.Status.UNIMPLEMENTED, details: `The server does not implement the method ${methodName}`, metadata: new metadata_1.Metadata(), }; } function getDefaultHandler(handlerType, methodName) { const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); switch (handlerType) { case 'unary': return (call, callback) => { callback(unimplementedStatusResponse, null); }; case 'clientStream': return (call, callback) => { callback(unimplementedStatusResponse, null); }; case 'serverStream': return (call) => { call.emit('error', unimplementedStatusResponse); }; case 'bidi': return (call) => { call.emit('error', unimplementedStatusResponse); }; default: throw new Error(`Invalid handlerType ${handlerType}`); } } class Server { constructor(options) { this.http2ServerList = []; this.handlers = new Map(); this.sessions = new Map(); this.started = false; // Channelz Info this.channelzEnabled = true; this.channelzTrace = new channelz_1.ChannelzTrace(); this.callTracker = new channelz_1.ChannelzCallTracker(); this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); this.options = options !== null && options !== void 0 ? options : {}; if (this.options['grpc.enable_channelz'] === 0) { this.channelzEnabled = false; } this.channelzRef = channelz_1.registerChannelzServer(() => this.getChannelzInfo(), this.channelzEnabled); if (this.channelzEnabled) { this.channelzTrace.addTrace('CT_INFO', 'Server created'); } this.trace('Server constructed'); } getChannelzInfo() { return { trace: this.channelzTrace, callTracker: this.callTracker, listenerChildren: this.listenerChildrenTracker.getChildLists(), sessionChildren: this.sessionChildrenTracker.getChildLists() }; } getChannelzSessionInfoGetter(session) { return () => { var _a, _b, _c; const sessionInfo = this.sessions.get(session); const sessionSocket = session.socket; const remoteAddress = sessionSocket.remoteAddress ? subchannel_address_1.stringToSubchannelAddress(sessionSocket.remoteAddress, sessionSocket.remotePort) : null; const localAddress = sessionSocket.localAddress ? subchannel_address_1.stringToSubchannelAddress(sessionSocket.localAddress, sessionSocket.localPort) : null; let tlsInfo; if (session.encrypted) { const tlsSocket = sessionSocket; const cipherInfo = tlsSocket.getCipher(); const certificate = tlsSocket.getCertificate(); const peerCertificate = tlsSocket.getPeerCertificate(); tlsInfo = { cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, localCertificate: (certificate && 'raw' in certificate) ? certificate.raw : null, remoteCertificate: (peerCertificate && 'raw' in peerCertificate) ? peerCertificate.raw : null }; } else { tlsInfo = null; } const socketInfo = { remoteAddress: remoteAddress, localAddress: localAddress, security: tlsInfo, remoteName: null, streamsStarted: sessionInfo.streamTracker.callsStarted, streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, streamsFailed: sessionInfo.streamTracker.callsFailed, messagesSent: sessionInfo.messagesSent, messagesReceived: sessionInfo.messagesReceived, keepAlivesSent: 0, lastLocalStreamCreatedTimestamp: null, lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, localFlowControlWindow: (_b = session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, remoteFlowControlWindow: (_c = session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null }; return socketInfo; }; } trace(text) { logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); } addProtoService() { throw new Error('Not implemented. Use addService() instead'); } addService(service, implementation) { if (service === null || typeof service !== 'object' || implementation === null || typeof implementation !== 'object') { throw new Error('addService() requires two objects as arguments'); } const serviceKeys = Object.keys(service); if (serviceKeys.length === 0) { throw new Error('Cannot add an empty service to a server'); } serviceKeys.forEach((name) => { const attrs = service[name]; let methodType; if (attrs.requestStream) { if (attrs.responseStream) { methodType = 'bidi'; } else { methodType = 'clientStream'; } } else { if (attrs.responseStream) { methodType = 'serverStream'; } else { methodType = 'unary'; } } let implFn = implementation[name]; let impl; if (implFn === undefined && typeof attrs.originalName === 'string') { implFn = implementation[attrs.originalName]; } if (implFn !== undefined) { impl = implFn.bind(implementation); } else { impl = getDefaultHandler(methodType, name); } const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); if (success === false) { throw new Error(`Method handler for ${attrs.path} already provided.`); } }); } removeService(service) { if (service === null || typeof service !== 'object') { throw new Error('removeService() requires object as argument'); } const serviceKeys = Object.keys(service); serviceKeys.forEach((name) => { const attrs = service[name]; this.unregister(attrs.path); }); } bind(port, creds) { throw new Error('Not implemented. Use bindAsync() instead'); } bindAsync(port, creds, callback) { if (this.started === true) { throw new Error('server is already started'); } if (typeof port !== 'string') { throw new TypeError('port must be a string'); } if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { throw new TypeError('creds must be a ServerCredentials object'); } if (typeof callback !== 'function') { throw new TypeError('callback must be a function'); } const initialPortUri = uri_parser_1.parseUri(port); if (initialPortUri === null) { throw new Error(`Could not parse port "${port}"`); } const portUri = resolver_1.mapUriDefaultScheme(initialPortUri); if (portUri === null) { throw new Error(`Could not get a default scheme for port "${port}"`); } const serverOptions = { maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, }; if ('grpc-node.max_session_memory' in this.options) { serverOptions.maxSessionMemory = this.options['grpc-node.max_session_memory']; } if ('grpc.max_concurrent_streams' in this.options) { serverOptions.settings = { maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], }; } const deferredCallback = (error, port) => { process.nextTick(() => callback(error, port)); }; const setupServer = () => { let http2Server; if (creds._isSecure()) { const secureServerOptions = Object.assign(serverOptions, creds._getSettings()); http2Server = http2.createSecureServer(secureServerOptions); http2Server.on('secureConnection', (socket) => { /* These errors need to be handled by the user of Http2SecureServer, * according to https://github.com/nodejs/node/issues/35824 */ socket.on('error', (e) => { this.trace('An incoming TLS connection closed with error: ' + e.message); }); }); } else { http2Server = http2.createServer(serverOptions); } http2Server.setTimeout(0, noop); this._setupHandlers(http2Server); return http2Server; }; const bindSpecificPort = (addressList, portNum, previousCount) => { if (addressList.length === 0) { return Promise.resolve({ port: portNum, count: previousCount }); } return Promise.all(addressList.map((address) => { this.trace('Attempting to bind ' + subchannel_address_1.subchannelAddressToString(address)); let addr; if (subchannel_address_1.isTcpSubchannelAddress(address)) { addr = { host: address.host, port: portNum, }; } else { addr = address; } const http2Server = setupServer(); return new Promise((resolve, reject) => { const onError = (err) => { this.trace('Failed to bind ' + subchannel_address_1.subchannelAddressToString(address) + ' with error ' + err.message); resolve(err); }; http2Server.once('error', onError); http2Server.listen(addr, () => { const boundAddress = http2Server.address(); let boundSubchannelAddress; if (typeof boundAddress === 'string') { boundSubchannelAddress = { path: boundAddress }; } else { boundSubchannelAddress = { host: boundAddress.address, port: boundAddress.port }; } let channelzRef; channelzRef = channelz_1.registerChannelzSocket(subchannel_address_1.subchannelAddressToString(boundSubchannelAddress), () => { return { localAddress: boundSubchannelAddress, remoteAddress: null, security: null, remoteName: null, streamsStarted: 0, streamsSucceeded: 0, streamsFailed: 0, messagesSent: 0, messagesReceived: 0, keepAlivesSent: 0, lastLocalStreamCreatedTimestamp: null, lastRemoteStreamCreatedTimestamp: null, lastMessageSentTimestamp: null, lastMessageReceivedTimestamp: null, localFlowControlWindow: null, remoteFlowControlWindow: null }; }, this.channelzEnabled); if (this.channelzEnabled) { this.listenerChildrenTracker.refChild(channelzRef); } this.http2ServerList.push({ server: http2Server, channelzRef: channelzRef }); this.trace('Successfully bound ' + subchannel_address_1.subchannelAddressToString(boundSubchannelAddress)); resolve('port' in boundSubchannelAddress ? boundSubchannelAddress.port : portNum); http2Server.removeListener('error', onError); }); }); })).then((results) => { let count = 0; for (const result of results) { if (typeof result === 'number') { count += 1; if (result !== portNum) { throw new Error('Invalid state: multiple port numbers added from single address'); } } } return { port: portNum, count: count + previousCount, }; }); }; const bindWildcardPort = (addressList) => { if (addressList.length === 0) { return Promise.resolve({ port: 0, count: 0 }); } const address = addressList[0]; const http2Server = setupServer(); return new Promise((resolve, reject) => { const onError = (err) => { this.trace('Failed to bind ' + subchannel_address_1.subchannelAddressToString(address) + ' with error ' + err.message); resolve(bindWildcardPort(addressList.slice(1))); }; http2Server.once('error', onError); http2Server.listen(address, () => { const boundAddress = http2Server.address(); const boundSubchannelAddress = { host: boundAddress.address, port: boundAddress.port }; let channelzRef; channelzRef = channelz_1.registerChannelzSocket(subchannel_address_1.subchannelAddressToString(boundSubchannelAddress), () => { return { localAddress: boundSubchannelAddress, remoteAddress: null, security: null, remoteName: null, streamsStarted: 0, streamsSucceeded: 0, streamsFailed: 0, messagesSent: 0, messagesReceived: 0, keepAlivesSent: 0, lastLocalStreamCreatedTimestamp: null, lastRemoteStreamCreatedTimestamp: null, lastMessageSentTimestamp: null, lastMessageReceivedTimestamp: null, localFlowControlWindow: null, remoteFlowControlWindow: null }; }, this.channelzEnabled); if (this.channelzEnabled) { this.listenerChildrenTracker.refChild(channelzRef); } this.http2ServerList.push({ server: http2Server, channelzRef: channelzRef }); this.trace('Successfully bound ' + subchannel_address_1.subchannelAddressToString(boundSubchannelAddress)); resolve(bindSpecificPort(addressList.slice(1), boundAddress.port, 1)); http2Server.removeListener('error', onError); }); }); }; const resolverListener = { onSuccessfulResolution: (addressList, serviceConfig, serviceConfigError) => { // We only want one resolution result. Discard all future results resolverListener.onSuccessfulResolution = () => { }; if (addressList.length === 0) { deferredCallback(new Error(`No addresses resolved for port ${port}`), 0); return; } let bindResultPromise; if (subchannel_address_1.isTcpSubchannelAddress(addressList[0])) { if (addressList[0].port === 0) { bindResultPromise = bindWildcardPort(addressList); } else { bindResultPromise = bindSpecificPort(addressList, addressList[0].port, 0); } } else { // Use an arbitrary non-zero port for non-TCP addresses bindResultPromise = bindSpecificPort(addressList, 1, 0); } bindResultPromise.then((bindResult) => { if (bindResult.count === 0) { const errorString = `No address added out of total ${addressList.length} resolved`; logging.log(constants_1.LogVerbosity.ERROR, errorString); deferredCallback(new Error(errorString), 0); } else { if (bindResult.count < addressList.length) { logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); } deferredCallback(null, bindResult.port); } }, (error) => { const errorString = `No address added out of total ${addressList.length} resolved`; logging.log(constants_1.LogVerbosity.ERROR, errorString); deferredCallback(new Error(errorString), 0); }); }, onError: (error) => { deferredCallback(new Error(error.details), 0); }, }; const resolver = resolver_1.createResolver(portUri, resolverListener, this.options); resolver.updateResolution(); } forceShutdown() { // Close the server if it is still running. for (const { server: http2Server, channelzRef: ref } of this.http2ServerList) { if (http2Server.listening) { http2Server.close(() => { if (this.channelzEnabled) { this.listenerChildrenTracker.unrefChild(ref); channelz_1.unregisterChannelzRef(ref); } }); } } this.started = false; // Always destroy any available sessions. It's possible that one or more // tryShutdown() calls are in progress. Don't wait on them to finish. this.sessions.forEach((channelzInfo, session) => { // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to // recognize destroy(code) as a valid signature. // eslint-disable-next-line @typescript-eslint/no-explicit-any session.destroy(http2.constants.NGHTTP2_CANCEL); }); this.sessions.clear(); if (this.channelzEnabled) { channelz_1.unregisterChannelzRef(this.channelzRef); } } register(name, handler, serialize, deserialize, type) { if (this.handlers.has(name)) { return false; } this.handlers.set(name, { func: handler, serialize, deserialize, type, path: name, }); return true; } unregister(name) { return this.handlers.delete(name); } start() { if (this.http2ServerList.length === 0 || this.http2ServerList.every(({ server: http2Server }) => http2Server.listening !== true)) { throw new Error('server must be bound in order to start'); } if (this.started === true) { throw new Error('server is already started'); } if (this.channelzEnabled) { this.channelzTrace.addTrace('CT_INFO', 'Starting'); } this.started = true; } tryShutdown(callback) { const wrappedCallback = (error) => { if (this.channelzEnabled) { channelz_1.unregisterChannelzRef(this.channelzRef); } callback(error); }; let pendingChecks = 0; function maybeCallback() { pendingChecks--; if (pendingChecks === 0) { wrappedCallback(); } } // Close the server if necessary. this.started = false; for (const { server: http2Server, channelzRef: ref } of this.http2ServerList) { if (http2Server.listening) { pendingChecks++; http2Server.close(() => { if (this.channelzEnabled) { this.listenerChildrenTracker.unrefChild(ref); channelz_1.unregisterChannelzRef(ref); } maybeCallback(); }); } } this.sessions.forEach((channelzInfo, session) => { if (!session.closed) { pendingChecks += 1; session.close(maybeCallback); } }); if (pendingChecks === 0) { wrappedCallback(); } } addHttp2Port() { throw new Error('Not yet implemented'); } /** * Get the channelz reference object for this server. The returned value is * garbage if channelz is disabled for this server. * @returns */ getChannelzRef() { return this.channelzRef; } _setupHandlers(http2Server) { if (http2Server === null) { return; } http2Server.on('stream', (stream, headers) => { var _a; const channelzSessionInfo = this.sessions.get(stream.session); if (this.channelzEnabled) { this.callTracker.addCallStarted(); channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); } const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; if (typeof contentType !== 'string' || !contentType.startsWith('application/grpc')) { stream.respond({ [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, }, { endStream: true }); this.callTracker.addCallFailed(); if (this.channelzEnabled) { channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); } return; } let call = null; try { const path = headers[http2.constants.HTTP2_HEADER_PATH]; const serverAddress = http2Server.address(); let serverAddressString = 'null'; if (serverAddress) { if (typeof serverAddress === 'string') { serverAddressString = serverAddress; } else { serverAddressString = serverAddress.address + ':' + serverAddress.port; } } this.trace('Received call to method ' + path + ' at address ' + serverAddressString); const handler = this.handlers.get(path); if (handler === undefined) { this.trace('No handler registered for method ' + path + '. Sending UNIMPLEMENTED status.'); throw getUnimplementedStatusResponse(path); } call = new server_call_1.Http2ServerCallStream(stream, handler, this.options); call.once('callEnd', (code) => { if (code === constants_1.Status.OK) { this.callTracker.addCallSucceeded(); } else { this.callTracker.addCallFailed(); } }); if (this.channelzEnabled && channelzSessionInfo) { call.once('streamEnd', (success) => { if (success) { channelzSessionInfo.streamTracker.addCallSucceeded(); } else { channelzSessionInfo.streamTracker.addCallFailed(); } }); call.on('sendMessage', () => { channelzSessionInfo.messagesSent += 1; channelzSessionInfo.lastMessageSentTimestamp = new Date(); }); call.on('receiveMessage', () => { channelzSessionInfo.messagesReceived += 1; channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); }); } const metadata = call.receiveMetadata(headers); const encoding = (_a = metadata.get('grpc-encoding')[0]) !== null && _a !== void 0 ? _a : 'identity'; metadata.remove('grpc-encoding'); switch (handler.type) { case 'unary': handleUnary(call, handler, metadata, encoding); break; case 'clientStream': handleClientStreaming(call, handler, metadata, encoding); break; case 'serverStream': handleServerStreaming(call, handler, metadata, encoding); break; case 'bidi': handleBidiStreaming(call, handler, metadata, encoding); break; default: throw new Error(`Unknown handler type: ${handler.type}`); } } catch (err) { if (!call) { call = new server_call_1.Http2ServerCallStream(stream, null, this.options); if (this.channelzEnabled) { this.callTracker.addCallFailed(); channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); } } if (err.code === undefined) { err.code = constants_1.Status.INTERNAL; } call.sendError(err); } }); http2Server.on('session', (session) => { var _a; if (!this.started) { session.destroy(); return; } let channelzRef; channelzRef = channelz_1.registerChannelzSocket((_a = session.socket.remoteAddress) !== null && _a !== void 0 ? _a : 'unknown', this.getChannelzSessionInfoGetter(session), this.channelzEnabled); const channelzSessionInfo = { ref: channelzRef, streamTracker: new channelz_1.ChannelzCallTracker(), messagesSent: 0, messagesReceived: 0, lastMessageSentTimestamp: null, lastMessageReceivedTimestamp: null }; this.sessions.set(session, channelzSessionInfo); const clientAddress = session.socket.remoteAddress; if (this.channelzEnabled) { this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); this.sessionChildrenTracker.refChild(channelzRef); } session.on('close', () => { if (this.channelzEnabled) { this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); this.sessionChildrenTracker.unrefChild(channelzRef); channelz_1.unregisterChannelzRef(channelzRef); } this.sessions.delete(session); }); }); } } exports.Server = Server; async function handleUnary(call, handler, metadata, encoding) { const request = await call.receiveUnaryMessage(encoding); if (request === undefined || call.cancelled) { return; } const emitter = new server_call_1.ServerUnaryCallImpl(call, metadata, request); handler.func(emitter, (err, value, trailer, flags) => { call.sendUnaryMessage(err, value, trailer, flags); }); } function handleClientStreaming(call, handler, metadata, encoding) { const stream = new server_call_1.ServerReadableStreamImpl(call, metadata, handler.deserialize, encoding); function respond(err, value, trailer, flags) { stream.destroy(); call.sendUnaryMessage(err, value, trailer, flags); } if (call.cancelled) { return; } stream.on('error', respond); handler.func(stream, respond); } async function handleServerStreaming(call, handler, metadata, encoding) { const request = await call.receiveUnaryMessage(encoding); if (request === undefined || call.cancelled) { return; } const stream = new server_call_1.ServerWritableStreamImpl(call, metadata, handler.serialize, request); handler.func(stream); } function handleBidiStreaming(call, handler, metadata, encoding) { const stream = new server_call_1.ServerDuplexStreamImpl(call, metadata, handler.serialize, handler.deserialize, encoding); if (call.cancelled) { return; } handler.func(stream); } //# sourceMappingURL=server.js.map
#!/usr/bin/env node "use strict";var inquirer=require("inquirer"),fs=require("fs"),path=require("path"),superagent=require("superagent");require("download-git-repo"),require("adm-zip");var ora=require("ora"),commander=require("commander");function _interopDefaultLegacy(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var inquirer__default=_interopDefaultLegacy(inquirer),fs__default=_interopDefaultLegacy(fs),path__default=_interopDefaultLegacy(path),superagent__default=_interopDefaultLegacy(superagent),ora__default=_interopDefaultLegacy(ora),RepositoryList={"taro-react-kit-2.x":"direct:https://bitbucket.org/JeremyYu_1122/taro-react-kit-2.x/get/master.zip","taro-react-kit-ts-3.x":"direct:https://bitbucket.org/JeremyYu_1122/taro-react-kit-ts-3.x/get/master.zip"};const IS_PRODUCTION="production"===process.env.NODE_ENV,DEV_LAYER=IS_PRODUCTION?__dirname:path__default.default.resolve(__dirname,"..",".."),SAVE_PATH=path__default.default.resolve(DEV_LAYER,"local"),FILE_NAME="repository.json",SAVE_FILE_NAME=path__default.default.resolve(SAVE_PATH,FILE_NAME);async function saveLocalRepository(e,t,r=!1,a,s){initFile();const o=getRepositoryData();return!o[e]&&(o[e]=`https://${r?`${a}:${s}@`:""}${t.replace(/http(s)?:\/?\/?/,"")}`,!!await checkRepositoryIsExists(o[e])&&(fs__default.default.writeFileSync(SAVE_FILE_NAME,JSON.stringify(o),{encoding:"utf-8"}),!0))}function getRepositoryData(){return fs__default.default.existsSync(SAVE_FILE_NAME)?require(SAVE_FILE_NAME):{}}function initFile(){return fs__default.default.existsSync(SAVE_PATH)||fs__default.default.mkdirSync(SAVE_PATH),fs__default.default.existsSync(SAVE_FILE_NAME)||fs__default.default.writeFileSync(SAVE_FILE_NAME,"{}",{encoding:"utf-8"}),!0}async function checkRepositoryIsExists(e){try{return await superagent__default.default.get(e),!0}catch(e){return console.log(e),!1}}Object.keys(Object.assign(RepositoryList,getRepositoryData(),{custom:""}));const SAFE_INQUIRER_LIST=[{type:"input",message:"input your template name",name:"templateName"},{type:"list",message:"choose your repository type",name:"repositoryType",choices:["public","private"]},{type:"input",message:"input your repository url",name:"repositoryUrl"},{type:"input",when({repositoryType:e}){return"private"===e},name:"repositoryUser",message:"input your git username"},{type:"password",when({repositoryType:e}){return"private"===e},name:"repositoryPass",message:"input your git password"}];async function handleSafeRepository(e){const t=ora__default.default("start download template").start();try{var{templateName:r,repositoryType:a,repositoryPass:s,repositoryUser:o,repositoryUrl:i}=e;await saveLocalRepository(r,i,"private"===a,o,s)?t.succeed("save template success"):t.fail("save fail")}catch(e){console.log(e),t.fail("save fail")}}function createCommand(){const e=new commander.Command;return e.version("0.1.1"),e.addHelpText("after","test"),e.parse(process.argv),e}function entry(){inquirer__default.default.prompt(SAFE_INQUIRER_LIST).then(async e=>{handleSafeRepository(e)})}createCommand(),entry();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (_ref) { var _ref$to = _ref.to; var to = _ref$to === undefined ? TO_DEFAULT : _ref$to; var subject = _ref.subject; var html = _ref.html; var callback = arguments.length <= 1 || arguments[1] === undefined ? printResult : arguments[1]; _nodemailer2.default.createTransport(CONF).sendMail({ to: to, subject: subject, html: html, from: FROM_DEFAULT }, callback); }; var _nodemailer = require('nodemailer'); var _nodemailer2 = _interopRequireDefault(_nodemailer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var TO_DEFAULT = '331599158@qq.com'; var FROM_DEFAULT = 'sggdv2015@163.com'; var CONF = { service: '163', auth: { user: 'sggdv2015@163.com', pass: 'etpnxtlrevghccuj' } }; function printResult(err, info) { if (err) { console.log(err); } else { console.log(info.response); } }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-2d22c0b4"],{f20b:function(n,e,u){"use strict";u.r(e);var t,r,c={name:"Home",data:function(){return{}},render:function(n){return n("div",["首页"])}},o=c,a=o,d=u("2877"),i=Object(d["a"])(a,t,r,!1,null,null,null);e["default"]=i.exports}}]);
var searchData= [ ['floatvalue',['FloatValue',['../class_float_value.html',1,'']]], ['function',['Function',['../classerpcgen_1_1_function.html',1,'erpcgen']]], ['functionbase',['FunctionBase',['../classerpcgen_1_1_function_base.html',1,'erpcgen']]], ['functiontype',['FunctionType',['../classerpcgen_1_1_function_type.html',1,'erpcgen']]] ];
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.LC = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowEqual * @typechecks * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var bHasOwnProperty = hasOwnProperty.bind(objB); for (var i = 0; i < keysA.length; i++) { if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } } return true; } module.exports = shallowEqual; },{}],2:[function(require,module,exports){ module.exports = require('react/lib/ReactComponentWithPureRenderMixin'); },{"react/lib/ReactComponentWithPureRenderMixin":3}],3:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentWithPureRenderMixin */ 'use strict'; var shallowCompare = require('./shallowCompare'); /** * If your React component's render function is "pure", e.g. it will render the * same result given the same props and state, provide this Mixin for a * considerable performance boost. * * Most React components have pure render functions. * * Example: * * var ReactComponentWithPureRenderMixin = * require('ReactComponentWithPureRenderMixin'); * React.createClass({ * mixins: [ReactComponentWithPureRenderMixin], * * render: function() { * return <div className={this.props.className}>foo</div>; * } * }); * * Note: This only checks shallow equality for props and state. If these contain * complex data structures this mixin may have false-negatives for deeper * differences. Only mixin to components which have simple props and state, or * use `forceUpdate()` when you know deep data structures have changed. */ var ReactComponentWithPureRenderMixin = { shouldComponentUpdate: function (nextProps, nextState) { return shallowCompare(this, nextProps, nextState); } }; module.exports = ReactComponentWithPureRenderMixin; },{"./shallowCompare":4}],4:[function(require,module,exports){ /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shallowCompare */ 'use strict'; var shallowEqual = require('fbjs/lib/shallowEqual'); /** * Does a shallow comparison for props and state. * See ReactComponentWithPureRenderMixin */ function shallowCompare(instance, nextProps, nextState) { return !shallowEqual(instance.props, nextProps) || !shallowEqual(instance.state, nextState); } module.exports = shallowCompare; },{"fbjs/lib/shallowEqual":1}],5:[function(require,module,exports){ var INFINITE, JSONToShape, LiterallyCanvas, Pencil, actions, bindEvents, createShape, math, ref, renderShapeToContext, renderShapeToSVG, renderSnapshotToImage, renderSnapshotToSVG, shapeToJSON, util, bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }, slice = [].slice, indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; actions = require('./actions'); bindEvents = require('./bindEvents'); math = require('./math'); ref = require('./shapes'), createShape = ref.createShape, shapeToJSON = ref.shapeToJSON, JSONToShape = ref.JSONToShape; renderShapeToContext = require('./canvasRenderer').renderShapeToContext; renderShapeToSVG = require('./svgRenderer').renderShapeToSVG; renderSnapshotToImage = require('./renderSnapshotToImage'); renderSnapshotToSVG = require('./renderSnapshotToSVG'); Pencil = require('../tools/Pencil'); util = require('./util'); INFINITE = 'infinite'; module.exports = LiterallyCanvas = (function() { function LiterallyCanvas(arg1, arg2) { this.setImageSize = bind(this.setImageSize, this); var containerEl, opts; opts = null; containerEl = null; if (arg1 instanceof HTMLElement) { containerEl = arg1; opts = arg2; } else { opts = arg1; } this.opts = opts || {}; this.config = { zoomMin: opts.zoomMin || 0.2, zoomMax: opts.zoomMax || 4.0, zoomStep: opts.zoomStep || 0.2 }; this.colors = { primary: opts.primaryColor || '#000', secondary: opts.secondaryColor || '#fff', background: opts.backgroundColor || 'transparent' }; this.watermarkImage = opts.watermarkImage; this.watermarkScale = opts.watermarkScale || 1; this.backgroundCanvas = document.createElement('canvas'); this.backgroundCtx = this.backgroundCanvas.getContext('2d'); this.canvas = document.createElement('canvas'); this.canvas.style['background-color'] = 'transparent'; this.buffer = document.createElement('canvas'); this.buffer.style['background-color'] = 'transparent'; this.ctx = this.canvas.getContext('2d'); this.bufferCtx = this.buffer.getContext('2d'); this.backingScale = util.getBackingScale(this.ctx); this.backgroundShapes = opts.backgroundShapes || []; this._shapesInProgress = []; this.shapes = []; this.undoStack = []; this.redoStack = []; this.isDragging = false; this.position = { x: 0, y: 0 }; this.scale = 1.0; this.setTool(new this.opts.tools[0](this)); this.width = opts.imageSize.width || INFINITE; this.height = opts.imageSize.height || INFINITE; this.setZoom(this.scale); if (opts.snapshot) { this.loadSnapshot(opts.snapshot); } this.isBound = false; if (containerEl) { this.bindToElement(containerEl); } this.respondToSizeChange = function() {}; } LiterallyCanvas.prototype.bindToElement = function(containerEl) { var ref1, repaintAll; if (this.containerEl) { console.warn("Trying to bind Literally Canvas to a DOM element more than once is unsupported."); return; } this.containerEl = containerEl; this._unsubscribeEvents = bindEvents(this, this.containerEl, this.opts.keyboardShortcuts); this.containerEl.style['background-color'] = this.colors.background; this.containerEl.appendChild(this.backgroundCanvas); this.containerEl.appendChild(this.canvas); this.isBound = true; repaintAll = (function(_this) { return function() { _this.keepPanInImageBounds(); return _this.repaintAllLayers(); }; })(this); this.respondToSizeChange = util.matchElementSize(this.containerEl, [this.backgroundCanvas, this.canvas], this.backingScale, repaintAll); if (this.watermarkImage) { this.watermarkImage.onload = (function(_this) { return function() { return _this.repaintLayer('background'); }; })(this); } if ((ref1 = this.tool) != null) { ref1.didBecomeActive(this); } return repaintAll(); }; LiterallyCanvas.prototype._teardown = function() { var ref1; if ((ref1 = this.tool) != null) { ref1.willBecomeInactive(this); } if (typeof this._unsubscribeEvents === "function") { this._unsubscribeEvents(); } this.tool = null; this.containerEl = null; return this.isBound = false; }; LiterallyCanvas.prototype.trigger = function(name, data) { this.canvas.dispatchEvent(new CustomEvent(name, { detail: data })); return null; }; LiterallyCanvas.prototype.on = function(name, fn) { var wrapper; wrapper = function(e) { return fn(e.detail); }; this.canvas.addEventListener(name, wrapper); return (function(_this) { return function() { return _this.canvas.removeEventListener(name, wrapper); }; })(this); }; LiterallyCanvas.prototype.getRenderScale = function() { return this.scale * this.backingScale; }; LiterallyCanvas.prototype.clientCoordsToDrawingCoords = function(x, y) { return { x: (x * this.backingScale - this.position.x) / this.getRenderScale(), y: (y * this.backingScale - this.position.y) / this.getRenderScale() }; }; LiterallyCanvas.prototype.drawingCoordsToClientCoords = function(x, y) { return { x: x * this.getRenderScale() + this.position.x, y: y * this.getRenderScale() + this.position.y }; }; LiterallyCanvas.prototype.setImageSize = function(width, height) { this.width = width || INFINITE; this.height = height || INFINITE; this.keepPanInImageBounds(); this.repaintAllLayers(); return this.trigger('imageSizeChange', { width: this.width, height: this.height }); }; LiterallyCanvas.prototype.setTool = function(tool) { var ref1; if (this.isBound) { if ((ref1 = this.tool) != null) { ref1.willBecomeInactive(this); } } this.tool = tool; this.trigger('toolChange', { tool: tool }); if (this.isBound) { return this.tool.didBecomeActive(this); } }; LiterallyCanvas.prototype.setShapesInProgress = function(newVal) { return this._shapesInProgress = newVal; }; LiterallyCanvas.prototype.pointerDown = function(x, y) { var p; p = this.clientCoordsToDrawingCoords(x, y); if (this.tool.usesSimpleAPI) { this.tool.begin(p.x, p.y, this); this.isDragging = true; return this.trigger("drawStart", { tool: this.tool }); } else { this.isDragging = true; return this.trigger("lc-pointerdown", { tool: this.tool, x: p.x, y: p.y, rawX: x, rawY: y }); } }; LiterallyCanvas.prototype.pointerMove = function(x, y) { return util.requestAnimationFrame((function(_this) { return function() { var p, ref1; p = _this.clientCoordsToDrawingCoords(x, y); if ((ref1 = _this.tool) != null ? ref1.usesSimpleAPI : void 0) { if (_this.isDragging) { _this.tool["continue"](p.x, p.y, _this); return _this.trigger("drawContinue", { tool: _this.tool }); } } else { if (_this.isDragging) { return _this.trigger("lc-pointerdrag", { tool: _this.tool, x: p.x, y: p.y, rawX: x, rawY: y }); } else { return _this.trigger("lc-pointermove", { tool: _this.tool, x: p.x, y: p.y, rawX: x, rawY: y }); } } }; })(this)); }; LiterallyCanvas.prototype.pointerUp = function(x, y) { var p; p = this.clientCoordsToDrawingCoords(x, y); if (this.tool.usesSimpleAPI) { if (this.isDragging) { this.tool.end(p.x, p.y, this); this.isDragging = false; return this.trigger("drawEnd", { tool: this.tool }); } } else { this.isDragging = false; return this.trigger("lc-pointerup", { tool: this.tool, x: p.x, y: p.y, rawX: x, rawY: y }); } }; LiterallyCanvas.prototype.setColor = function(name, color, triggerColorChangedEvent = true) { this.colors[name] = color; if (!this.isBound) { return; } switch (name) { case 'background': this.containerEl.style.backgroundColor = this.colors.background; this.repaintLayer('background'); break; case 'primary': this.repaintLayer('main'); break; case 'secondary': this.repaintLayer('main'); } if (triggerColorChangedEvent) { this.trigger(name + "ColorChange", this.colors[name]); } if (name === 'background') { return this.trigger("drawingChange"); } }; LiterallyCanvas.prototype.getColor = function(name) { return this.colors[name]; }; LiterallyCanvas.prototype.saveShape = function(shape, triggerShapeSaveEvent, previousShapeId) { if (triggerShapeSaveEvent == null) { triggerShapeSaveEvent = true; } if (previousShapeId == null) { previousShapeId = null; } if (!previousShapeId) { previousShapeId = this.shapes.length ? this.shapes[this.shapes.length - 1].id : null; } this.execute(new actions.AddShapeAction(this, shape, previousShapeId)); if (triggerShapeSaveEvent) { this.trigger('shapeSave', { shape: shape, previousShapeId: previousShapeId }); } return this.trigger('drawingChange'); }; LiterallyCanvas.prototype.pan = function(x, y) { return this.setPan(this.position.x - x, this.position.y - y); }; LiterallyCanvas.prototype.keepPanInImageBounds = function() { var ref1, renderScale, x, y; renderScale = this.getRenderScale(); ref1 = this.position, x = ref1.x, y = ref1.y; if (this.width !== INFINITE) { if (this.canvas.width > this.width * renderScale) { x = (this.canvas.width - this.width * renderScale) / 2; } else { x = Math.max(Math.min(0, x), this.canvas.width - this.width * renderScale); } } if (this.height !== INFINITE) { if (this.canvas.height > this.height * renderScale) { y = (this.canvas.height - this.height * renderScale) / 2; } else { y = Math.max(Math.min(0, y), this.canvas.height - this.height * renderScale); } } return this.position = { x: x, y: y }; }; LiterallyCanvas.prototype.setPan = function(x, y) { this.position = { x: x, y: y }; this.keepPanInImageBounds(); this.repaintAllLayers(); return this.trigger('pan', { x: this.position.x, y: this.position.y }); }; LiterallyCanvas.prototype.zoom = function(factor) { var newScale; newScale = this.scale + factor; newScale = Math.max(newScale, this.config.zoomMin); newScale = Math.min(newScale, this.config.zoomMax); newScale = Math.round(newScale * 100) / 100; return this.setZoom(newScale); }; LiterallyCanvas.prototype.setZoom = function(scale) { var oldScale; oldScale = this.scale; this.scale = scale; this.position.x = math.scalePositionScalar(this.position.x, this.canvas.width, oldScale, this.scale); this.position.y = math.scalePositionScalar(this.position.y, this.canvas.height, oldScale, this.scale); this.keepPanInImageBounds(); this.repaintAllLayers(); return this.trigger('zoom', { oldScale: oldScale, newScale: this.scale }); }; LiterallyCanvas.prototype.setWatermarkImage = function(newImage) { this.watermarkImage = newImage; util.addImageOnload(newImage, (function(_this) { return function() { return _this.repaintLayer('background'); }; })(this)); if (newImage.width) { return this.repaintLayer('background'); } }; LiterallyCanvas.prototype.repaintAllLayers = function() { var i, key, len, ref1; ref1 = ['background', 'main']; for (i = 0, len = ref1.length; i < len; i++) { key = ref1[i]; this.repaintLayer(key); } return null; }; LiterallyCanvas.prototype.repaintLayer = function(repaintLayerKey, dirty) { var retryCallback; if (dirty == null) { dirty = repaintLayerKey === 'main'; } if (!this.isBound) { return; } switch (repaintLayerKey) { case 'background': this.backgroundCtx.clearRect(0, 0, this.backgroundCanvas.width, this.backgroundCanvas.height); retryCallback = (function(_this) { return function() { return _this.repaintLayer('background'); }; })(this); if (this.watermarkImage) { this._renderWatermark(this.backgroundCtx, true, retryCallback); } this.draw(this.backgroundShapes, this.backgroundCtx, retryCallback); break; case 'main': retryCallback = (function(_this) { return function() { return _this.repaintLayer('main', true); }; })(this); if (dirty) { this.buffer.width = this.canvas.width; this.buffer.height = this.canvas.height; this.bufferCtx.clearRect(0, 0, this.buffer.width, this.buffer.height); this.draw(this.shapes, this.bufferCtx, retryCallback); } this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height); if (this.canvas.width > 0 && this.canvas.height > 0) { this.ctx.fillStyle = '#ccc'; this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height); this.clipped(((function(_this) { return function() { _this.ctx.clearRect(0, 0, _this.canvas.width, _this.canvas.height); return _this.ctx.drawImage(_this.buffer, 0, 0); }; })(this)), this.ctx); this.clipped(((function(_this) { return function() { return _this.transformed((function() { var i, len, ref1, results, shape; ref1 = _this._shapesInProgress; results = []; for (i = 0, len = ref1.length; i < len; i++) { shape = ref1[i]; results.push(renderShapeToContext(_this.ctx, shape, { bufferCtx: _this.bufferCtx, shouldOnlyDrawLatest: true })); } return results; }), _this.ctx, _this.bufferCtx); }; })(this)), this.ctx, this.bufferCtx); } } return this.trigger('repaint', { layerKey: repaintLayerKey }); }; LiterallyCanvas.prototype._renderWatermark = function(ctx, worryAboutRetina, retryCallback) { if (worryAboutRetina == null) { worryAboutRetina = true; } if (!this.watermarkImage.width) { this.watermarkImage.onload = retryCallback; return; } ctx.save(); ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2); ctx.scale(this.watermarkScale, this.watermarkScale); if (worryAboutRetina) { ctx.scale(this.backingScale, this.backingScale); } ctx.drawImage(this.watermarkImage, -this.watermarkImage.width / 2, -this.watermarkImage.height / 2); return ctx.restore(); }; LiterallyCanvas.prototype.drawShapeInProgress = function(shape) { this.repaintLayer('main', false); return this.clipped(((function(_this) { return function() { return _this.transformed((function() { return renderShapeToContext(_this.ctx, shape, { bufferCtx: _this.bufferCtx, shouldOnlyDrawLatest: true }); }), _this.ctx, _this.bufferCtx); }; })(this)), this.ctx, this.bufferCtx); }; LiterallyCanvas.prototype.draw = function(shapes, ctx, retryCallback) { var drawShapes; if (!shapes.length) { return; } drawShapes = (function(_this) { return function() { var i, len, results, shape; results = []; for (i = 0, len = shapes.length; i < len; i++) { shape = shapes[i]; results.push(renderShapeToContext(ctx, shape, { retryCallback: retryCallback })); } return results; }; })(this); return this.clipped(((function(_this) { return function() { return _this.transformed(drawShapes, ctx); }; })(this)), ctx); }; LiterallyCanvas.prototype.clipped = function() { var contexts, ctx, fn, height, i, j, len, len1, results, width, x, y; fn = arguments[0], contexts = 2 <= arguments.length ? slice.call(arguments, 1) : []; x = this.width === INFINITE ? 0 : this.position.x; y = this.height === INFINITE ? 0 : this.position.y; width = (function() { switch (this.width) { case INFINITE: return this.canvas.width; default: return this.width * this.getRenderScale(); } }).call(this); height = (function() { switch (this.height) { case INFINITE: return this.canvas.height; default: return this.height * this.getRenderScale(); } }).call(this); for (i = 0, len = contexts.length; i < len; i++) { ctx = contexts[i]; ctx.save(); ctx.beginPath(); ctx.rect(x, y, width, height); ctx.clip(); } fn(); results = []; for (j = 0, len1 = contexts.length; j < len1; j++) { ctx = contexts[j]; results.push(ctx.restore()); } return results; }; LiterallyCanvas.prototype.transformed = function() { var contexts, ctx, fn, i, j, len, len1, results, scale; fn = arguments[0], contexts = 2 <= arguments.length ? slice.call(arguments, 1) : []; for (i = 0, len = contexts.length; i < len; i++) { ctx = contexts[i]; ctx.save(); ctx.translate(Math.floor(this.position.x), Math.floor(this.position.y)); scale = this.getRenderScale(); ctx.scale(scale, scale); } fn(); results = []; for (j = 0, len1 = contexts.length; j < len1; j++) { ctx = contexts[j]; results.push(ctx.restore()); } return results; }; LiterallyCanvas.prototype.clear = function(triggerClearEvent) { var newShapes, oldShapes; if (triggerClearEvent == null) { triggerClearEvent = true; } oldShapes = this.shapes; newShapes = []; this.setShapesInProgress([]); this.execute(new actions.ClearAction(this, oldShapes, newShapes)); this.repaintLayer('main'); if (triggerClearEvent) { this.trigger('clear', null); } return this.trigger('drawingChange', {}); }; LiterallyCanvas.prototype.execute = function(action) { this.undoStack.push(action); action["do"](); return this.redoStack = []; }; LiterallyCanvas.prototype.undo = function(triggerUndoEvent = true) { var action; if (!this.undoStack.length) { return; } action = this.undoStack.pop(); action.undo(); this.redoStack.push(action); if (triggerUndoEvent) { this.trigger('undo', { action: action }); } return this.trigger('drawingChange', {}); }; LiterallyCanvas.prototype.redo = function(triggerRedoEvent = true) { var action; if (!this.redoStack.length) { return; } action = this.redoStack.pop(); this.undoStack.push(action); action["do"](); if (triggerRedoEvent) { this.trigger('redo', { action: action }); } return this.trigger('drawingChange', {}); }; LiterallyCanvas.prototype.canUndo = function() { return !!this.undoStack.length; }; LiterallyCanvas.prototype.canRedo = function() { return !!this.redoStack.length; }; LiterallyCanvas.prototype.getPixel = function(x, y) { var p, pixel; p = this.drawingCoordsToClientCoords(x, y); pixel = this.ctx.getImageData(p.x, p.y, 1, 1).data; if (pixel[3]) { return "rgb(" + pixel[0] + ", " + pixel[1] + ", " + pixel[2] + ")"; } else { return null; } }; LiterallyCanvas.prototype.getContentBounds = function() { return util.getBoundingRect((this.shapes.concat(this.backgroundShapes)).map(function(s) { return s.getBoundingRect(); }), this.width === INFINITE ? 0 : this.width, this.height === INFINITE ? 0 : this.height); }; LiterallyCanvas.prototype.getDefaultImageRect = function(explicitSize, margin) { var s; if (explicitSize == null) { explicitSize = { width: 0, height: 0 }; } if (margin == null) { margin = { top: 0, right: 0, bottom: 0, left: 0 }; } return util.getDefaultImageRect((function() { var i, len, ref1, results; ref1 = this.shapes.concat(this.backgroundShapes); results = []; for (i = 0, len = ref1.length; i < len; i++) { s = ref1[i]; results.push(s.getBoundingRect(this.ctx)); } return results; }).call(this), explicitSize, margin); }; LiterallyCanvas.prototype.getImage = function(opts) { if (opts == null) { opts = {}; } if (opts.includeWatermark == null) { opts.includeWatermark = true; } if (opts.scaleDownRetina == null) { opts.scaleDownRetina = true; } if (opts.scale == null) { opts.scale = 1; } if (!opts.scaleDownRetina) { opts.scale *= this.backingScale; } if (opts.includeWatermark) { opts.watermarkImage = this.watermarkImage; opts.watermarkScale = this.watermarkScale; if (!opts.scaleDownRetina) { opts.watermarkScale *= this.backingScale; } } return renderSnapshotToImage(this.getSnapshot(), opts); }; LiterallyCanvas.prototype.canvasForExport = function() { this.repaintAllLayers(); return util.combineCanvases(this.backgroundCanvas, this.canvas); }; LiterallyCanvas.prototype.canvasWithBackground = function(backgroundImageOrCanvas) { return util.combineCanvases(backgroundImageOrCanvas, this.canvasForExport()); }; LiterallyCanvas.prototype.getSnapshot = function(keys) { var i, k, len, ref1, shape, snapshot; if (keys == null) { keys = null; } if (keys == null) { keys = ['shapes', 'imageSize', 'colors', 'position', 'scale', 'backgroundShapes']; } snapshot = {}; ref1 = ['colors', 'position', 'scale']; for (i = 0, len = ref1.length; i < len; i++) { k = ref1[i]; if (indexOf.call(keys, k) >= 0) { snapshot[k] = this[k]; } } if (indexOf.call(keys, 'shapes') >= 0) { snapshot.shapes = (function() { var j, len1, ref2, results; ref2 = this.shapes; results = []; for (j = 0, len1 = ref2.length; j < len1; j++) { shape = ref2[j]; results.push(shapeToJSON(shape)); } return results; }).call(this); } if (indexOf.call(keys, 'backgroundShapes') >= 0) { snapshot.backgroundShapes = (function() { var j, len1, ref2, results; ref2 = this.backgroundShapes; results = []; for (j = 0, len1 = ref2.length; j < len1; j++) { shape = ref2[j]; results.push(shapeToJSON(shape)); } return results; }).call(this); } if (indexOf.call(keys, 'imageSize') >= 0) { snapshot.imageSize = { width: this.width, height: this.height }; } return snapshot; }; LiterallyCanvas.prototype.getSnapshotJSON = function() { console.warn("lc.getSnapshotJSON() is deprecated. use JSON.stringify(lc.getSnapshot()) instead."); return JSON.stringify(this.getSnapshot()); }; LiterallyCanvas.prototype.getSVGString = function(opts) { if (opts == null) { opts = {}; } return renderSnapshotToSVG(this.getSnapshot(), opts); }; LiterallyCanvas.prototype.loadSnapshot = function(snapshot) { var i, j, k, len, len1, ref1, ref2, s, shape, shapeRepr; if (!snapshot) { return; } if (snapshot.colors) { ref1 = ['primary', 'secondary', 'background']; for (i = 0, len = ref1.length; i < len; i++) { k = ref1[i]; this.setColor(k, snapshot.colors[k]); } } if (snapshot.shapes) { this.shapes = []; ref2 = snapshot.shapes; for (j = 0, len1 = ref2.length; j < len1; j++) { shapeRepr = ref2[j]; shape = JSONToShape(shapeRepr); if (shape) { this.execute(new actions.AddShapeAction(this, shape)); } } } if (snapshot.backgroundShapes) { this.backgroundShapes = (function() { var l, len2, ref3, results; ref3 = snapshot.backgroundShapes; results = []; for (l = 0, len2 = ref3.length; l < len2; l++) { s = ref3[l]; results.push(JSONToShape(s)); } return results; })(); } if (snapshot.imageSize) { this.width = snapshot.imageSize.width; this.height = snapshot.imageSize.height; } if (snapshot.position) { this.position = snapshot.position; } if (snapshot.scale) { this.scale = snapshot.scale; } this.repaintAllLayers(); this.trigger('snapshotLoad'); return this.trigger('drawingChange', {}); }; LiterallyCanvas.prototype.loadSnapshotJSON = function(str) { console.warn("lc.loadSnapshotJSON() is deprecated. use lc.loadSnapshot(JSON.parse(snapshot)) instead."); return this.loadSnapshot(JSON.parse(str)); }; return LiterallyCanvas; })(); },{"../tools/Pencil":48,"./actions":7,"./bindEvents":8,"./canvasRenderer":9,"./math":14,"./renderSnapshotToImage":15,"./renderSnapshotToSVG":16,"./shapes":17,"./svgRenderer":18,"./util":19}],6:[function(require,module,exports){ var TextRenderer, getLinesToRender, getNextLine, parseFontString; require('./fontmetrics.js'); parseFontString = function(font) { var fontFamily, fontItems, fontSize, item, j, len, maybeSize, remainingFontString; fontItems = font.split(' '); fontSize = 0; for (j = 0, len = fontItems.length; j < len; j++) { item = fontItems[j]; maybeSize = parseInt(item.replace("px", ""), 10); if (!isNaN(maybeSize)) { fontSize = maybeSize; } } if (!fontSize) { throw "Font size not found"; } remainingFontString = font.substring(fontItems[0].length + 1).replace('bold ', '').replace('italic ', '').replace('underline ', ''); fontFamily = remainingFontString; return { fontSize: fontSize, fontFamily: fontFamily }; }; getNextLine = function(ctx, text, forcedWidth) { var doesSubstringFit, endIndex, isEndOfString, isNonWord, isWhitespace, lastGoodIndex, lastOkayIndex, nextWordStartIndex, textToHere, wasInWord; if (!text.length) { return ['', '']; } endIndex = 0; lastGoodIndex = 0; lastOkayIndex = 0; wasInWord = false; while (true) { endIndex += 1; isEndOfString = endIndex >= text.length; isWhitespace = (!isEndOfString) && text[endIndex].match(/\s/); isNonWord = isWhitespace || isEndOfString; textToHere = text.substring(0, endIndex); doesSubstringFit = forcedWidth ? ctx.measureTextWidth(textToHere).width <= forcedWidth : true; if (doesSubstringFit) { lastOkayIndex = endIndex; } if (isNonWord && wasInWord) { wasInWord = false; if (doesSubstringFit) { lastGoodIndex = endIndex; } } wasInWord = !isWhitespace; if (isEndOfString || !doesSubstringFit) { if (doesSubstringFit) { return [text, '']; } else if (lastGoodIndex > 0) { nextWordStartIndex = lastGoodIndex + 1; while (nextWordStartIndex < text.length && text[nextWordStartIndex].match('/\s/')) { nextWordStartIndex += 1; } return [text.substring(0, lastGoodIndex), text.substring(nextWordStartIndex)]; } else { return [text.substring(0, lastOkayIndex), text.substring(lastOkayIndex)]; } } } }; getLinesToRender = function(ctx, text, forcedWidth) { var j, len, lines, nextLine, ref, ref1, remainingText, textLine, textSplitOnLines; textSplitOnLines = text.split(/\r\n|\r|\n/g); lines = []; for (j = 0, len = textSplitOnLines.length; j < len; j++) { textLine = textSplitOnLines[j]; ref = getNextLine(ctx, textLine, forcedWidth), nextLine = ref[0], remainingText = ref[1]; if (nextLine) { while (nextLine) { lines.push(nextLine); ref1 = getNextLine(ctx, remainingText, forcedWidth), nextLine = ref1[0], remainingText = ref1[1]; } } else { lines.push(textLine); } } return lines; }; TextRenderer = (function() { function TextRenderer(ctx, text1, font1, forcedWidth1, forcedHeight) { var fontFamily, fontSize, ref; this.text = text1; this.font = font1; this.forcedWidth = forcedWidth1; this.forcedHeight = forcedHeight; ref = parseFontString(this.font), fontFamily = ref.fontFamily, fontSize = ref.fontSize; ctx.font = this.font; ctx.textBaseline = 'baseline'; this.emDashWidth = ctx.measureTextWidth('—', fontSize, fontFamily).width; this.caratWidth = ctx.measureTextWidth('|', fontSize, fontFamily).width; this.lines = getLinesToRender(ctx, this.text, this.forcedWidth); this.metricses = this.lines.map((function(_this) { return function(line) { return ctx.measureText2(line || 'X', fontSize, _this.font); }; })(this)); this.metrics = { ascent: Math.max.apply(Math, this.metricses.map(function(arg) { var ascent; ascent = arg.ascent; return ascent; })), descent: Math.max.apply(Math, this.metricses.map(function(arg) { var descent; descent = arg.descent; return descent; })), fontsize: Math.max.apply(Math, this.metricses.map(function(arg) { var fontsize; fontsize = arg.fontsize; return fontsize; })), leading: Math.max.apply(Math, this.metricses.map(function(arg) { var leading; leading = arg.leading; return leading; })), width: Math.max.apply(Math, this.metricses.map(function(arg) { var width; width = arg.width; return width; })), height: Math.max.apply(Math, this.metricses.map(function(arg) { var height; height = arg.height; return height; })), bounds: { minx: Math.min.apply(Math, this.metricses.map(function(arg) { var bounds; bounds = arg.bounds; return bounds.minx; })), miny: Math.min.apply(Math, this.metricses.map(function(arg) { var bounds; bounds = arg.bounds; return bounds.miny; })), maxx: Math.max.apply(Math, this.metricses.map(function(arg) { var bounds; bounds = arg.bounds; return bounds.maxx; })), maxy: Math.max.apply(Math, this.metricses.map(function(arg) { var bounds; bounds = arg.bounds; return bounds.maxy; })) } }; this.boundingBoxWidth = Math.ceil(this.metrics.width); } TextRenderer.prototype.draw = function(ctx, x, y) { var i, j, len, line, ref, results; ctx.textBaseline = 'top'; ctx.font = this.font; i = 0; ref = this.lines; results = []; for (j = 0, len = ref.length; j < len; j++) { line = ref[j]; ctx.fillText(line, x, y + i * this.metrics.leading); results.push(i += 1); } return results; }; TextRenderer.prototype.getWidth = function(isEditing) { if (isEditing == null) { isEditing = false; } if (this.forcedWidth) { return this.forcedWidth; } else { if (isEditing) { return this.metrics.bounds.maxx + this.caratWidth; } else { return this.metrics.bounds.maxx; } } }; TextRenderer.prototype.getHeight = function() { return this.forcedHeight || (this.metrics.leading * this.lines.length); }; return TextRenderer; })(); module.exports = TextRenderer; },{"./fontmetrics.js":11}],7:[function(require,module,exports){ var AddShapeAction, ClearAction; ClearAction = (function() { function ClearAction(lc1, oldShapes, newShapes1) { this.lc = lc1; this.oldShapes = oldShapes; this.newShapes = newShapes1; } ClearAction.prototype["do"] = function() { this.lc.shapes = this.newShapes; return this.lc.repaintLayer('main'); }; ClearAction.prototype.undo = function() { this.lc.shapes = this.oldShapes; return this.lc.repaintLayer('main'); }; return ClearAction; })(); AddShapeAction = (function() { function AddShapeAction(lc1, shape1, previousShapeId) { this.lc = lc1; this.shape = shape1; this.previousShapeId = previousShapeId != null ? previousShapeId : null; } AddShapeAction.prototype["do"] = function() { var found, i, len, newShapes, ref, shape; if (!this.lc.shapes.length || this.lc.shapes[this.lc.shapes.length - 1].id === this.previousShapeId || this.previousShapeId === null) { this.lc.shapes.push(this.shape); } else { newShapes = []; found = false; ref = this.lc.shapes; for (i = 0, len = ref.length; i < len; i++) { shape = ref[i]; newShapes.push(shape); if (shape.id === this.previousShapeId) { newShapes.push(this.shape); found = true; } } if (!found) { newShapes.push(this.shape); } this.lc.shapes = newShapes; } return this.lc.repaintLayer('main'); }; AddShapeAction.prototype.undo = function() { var i, len, newShapes, ref, shape; if (this.lc.shapes[this.lc.shapes.length - 1].id === this.shape.id) { this.lc.shapes.pop(); } else { newShapes = []; ref = this.lc.shapes; for (i = 0, len = ref.length; i < len; i++) { shape = ref[i]; if (shape.id !== this.shape.id) { newShapes.push(shape); } } lc.shapes = newShapes; } return this.lc.repaintLayer('main'); }; return AddShapeAction; })(); module.exports = { ClearAction: ClearAction, AddShapeAction: AddShapeAction }; },{}],8:[function(require,module,exports){ var bindEvents, buttonIsDown, coordsForTouchEvent, position; coordsForTouchEvent = function(el, e) { var p, tx, ty; tx = e.changedTouches[0].clientX; ty = e.changedTouches[0].clientY; p = el.getBoundingClientRect(); return [tx - p.left, ty - p.top]; }; position = function(el, e) { var p; p = el.getBoundingClientRect(); return { left: e.clientX - p.left, top: e.clientY - p.top }; }; buttonIsDown = function(e) { if (e.buttons != null) { return e.buttons === 1; } else { return e.which > 0; } }; module.exports = bindEvents = function(lc, canvas, panWithKeyboard) { var listener, mouseMoveListener, mouseUpListener, touchEndListener, touchMoveListener, unsubs; if (panWithKeyboard == null) { panWithKeyboard = false; } unsubs = []; mouseMoveListener = (function(_this) { return function(e) { var p; e.preventDefault(); p = position(canvas, e); return lc.pointerMove(p.left, p.top); }; })(this); mouseUpListener = (function(_this) { return function(e) { var p; e.preventDefault(); canvas.onselectstart = function() { return true; }; p = position(canvas, e); lc.pointerUp(p.left, p.top); document.removeEventListener('mousemove', mouseMoveListener); document.removeEventListener('mouseup', mouseUpListener); return canvas.addEventListener('mousemove', mouseMoveListener); }; })(this); canvas.addEventListener('mousedown', (function(_this) { return function(e) { var down, p; if (e.target.tagName.toLowerCase() !== 'canvas') { return; } down = true; e.preventDefault(); canvas.onselectstart = function() { return false; }; p = position(canvas, e); lc.pointerDown(p.left, p.top); canvas.removeEventListener('mousemove', mouseMoveListener); document.addEventListener('mousemove', mouseMoveListener); return document.addEventListener('mouseup', mouseUpListener); }; })(this)); touchMoveListener = function(e) { e.preventDefault(); return lc.pointerMove.apply(lc, coordsForTouchEvent(canvas, e)); }; touchEndListener = function(e) { e.preventDefault(); lc.pointerUp.apply(lc, coordsForTouchEvent(canvas, e)); document.removeEventListener('touchmove', touchMoveListener); document.removeEventListener('touchend', touchEndListener); return document.removeEventListener('touchcancel', touchEndListener); }; canvas.addEventListener('touchstart', function(e) { if (e.target.tagName.toLowerCase() !== 'canvas') { return; } e.preventDefault(); if (e.touches.length === 1) { lc.pointerDown.apply(lc, coordsForTouchEvent(canvas, e)); document.addEventListener('touchmove', touchMoveListener); document.addEventListener('touchend', touchEndListener); return document.addEventListener('touchcancel', touchEndListener); } else { return lc.pointerMove.apply(lc, coordsForTouchEvent(canvas, e)); } }); if (panWithKeyboard) { console.warn("Keyboard panning is deprecated."); listener = function(e) { switch (e.keyCode) { case 37: lc.pan(-10, 0); break; case 38: lc.pan(0, -10); break; case 39: lc.pan(10, 0); break; case 40: lc.pan(0, 10); } return lc.repaintAllLayers(); }; document.addEventListener('keydown', listener); unsubs.push(function() { return document.removeEventListener(listener); }); } return function() { var f, i, len, results; results = []; for (i = 0, len = unsubs.length; i < len; i++) { f = unsubs[i]; results.push(f()); } return results; }; }; },{}],9:[function(require,module,exports){ var _drawRawLinePath, defineCanvasRenderer, drawErasedLinePath, drawErasedLinePathLatest, drawLinePath, drawLinePathLatest, lineEndCapShapes, noop, renderShapeToCanvas, renderShapeToContext, renderers; lineEndCapShapes = require('./lineEndCapShapes'); renderers = {}; defineCanvasRenderer = function(shapeName, drawFunc, drawLatestFunc) { return renderers[shapeName] = { drawFunc: drawFunc, drawLatestFunc: drawLatestFunc }; }; noop = function() {}; renderShapeToContext = function(ctx, shape, opts) { var bufferCtx; if (opts == null) { opts = {}; } if (opts.shouldIgnoreUnsupportedShapes == null) { opts.shouldIgnoreUnsupportedShapes = false; } if (opts.retryCallback == null) { opts.retryCallback = noop; } if (opts.shouldOnlyDrawLatest == null) { opts.shouldOnlyDrawLatest = false; } if (opts.bufferCtx == null) { opts.bufferCtx = null; } bufferCtx = opts.bufferCtx; if (renderers[shape.className]) { if (opts.shouldOnlyDrawLatest && renderers[shape.className].drawLatestFunc) { return renderers[shape.className].drawLatestFunc(ctx, bufferCtx, shape, opts.retryCallback); } else { return renderers[shape.className].drawFunc(ctx, shape, opts.retryCallback); } } else if (opts.shouldIgnoreUnsupportedShapes) { return console.warn("Can't render shape of type " + shape.className + " to canvas"); } else { throw "Can't render shape of type " + shape.className + " to canvas"; } }; renderShapeToCanvas = function(canvas, shape, opts) { return renderShapeToContext(canvas.getContext('2d'), shape, opts); }; defineCanvasRenderer('Rectangle', function(ctx, shape) { var x, y; x = shape.x; y = shape.y; if (shape.strokeWidth % 2 !== 0) { x += 0.5; y += 0.5; } ctx.fillStyle = shape.fillColor; ctx.fillRect(x, y, shape.width, shape.height); ctx.lineWidth = shape.strokeWidth; ctx.strokeStyle = shape.strokeColor; return ctx.strokeRect(x, y, shape.width, shape.height); }); defineCanvasRenderer('Ellipse', function(ctx, shape) { var centerX, centerY, halfHeight, halfWidth; ctx.save(); halfWidth = Math.floor(shape.width / 2); halfHeight = Math.floor(shape.height / 2); centerX = shape.x + halfWidth; centerY = shape.y + halfHeight; ctx.translate(centerX, centerY); ctx.scale(1, Math.abs(shape.height / shape.width)); ctx.beginPath(); ctx.arc(0, 0, Math.abs(halfWidth), 0, Math.PI * 2); ctx.closePath(); ctx.restore(); ctx.fillStyle = shape.fillColor; ctx.fill(); ctx.lineWidth = shape.strokeWidth; ctx.strokeStyle = shape.strokeColor; return ctx.stroke(); }); defineCanvasRenderer('SelectionBox', (function() { var _drawHandle; _drawHandle = function(ctx, arg, handleSize) { var x, y; x = arg.x, y = arg.y; if (handleSize === 0) { return; } ctx.fillStyle = '#fff'; ctx.fillRect(x, y, handleSize, handleSize); ctx.strokeStyle = '#000'; return ctx.strokeRect(x, y, handleSize, handleSize); }; return function(ctx, shape) { _drawHandle(ctx, shape.getTopLeftHandleRect(), shape.handleSize); _drawHandle(ctx, shape.getTopRightHandleRect(), shape.handleSize); _drawHandle(ctx, shape.getBottomLeftHandleRect(), shape.handleSize); _drawHandle(ctx, shape.getBottomRightHandleRect(), shape.handleSize); if (shape.backgroundColor) { ctx.fillStyle = shape.backgroundColor; ctx.fillRect(shape._br.x - shape.margin, shape._br.y - shape.margin, shape._br.width + shape.margin * 2, shape._br.height + shape.margin * 2); } ctx.lineWidth = 1; ctx.strokeStyle = '#000'; ctx.setLineDash([2, 4]); ctx.strokeRect(shape._br.x - shape.margin, shape._br.y - shape.margin, shape._br.width + shape.margin * 2, shape._br.height + shape.margin * 2); return ctx.setLineDash([]); }; })()); defineCanvasRenderer('Image', function(ctx, shape, retryCallback) { if (shape.image.width) { if (shape.scale === 1) { return ctx.drawImage(shape.image, shape.x, shape.y); } else { return ctx.drawImage(shape.image, shape.x, shape.y, shape.image.width * shape.scale, shape.image.height * shape.scale); } } else if (retryCallback) { return shape.image.onload = retryCallback; } }); defineCanvasRenderer('Line', function(ctx, shape) { var arrowWidth, x1, x2, y1, y2; if (shape.x1 === shape.x2 && shape.y1 === shape.y2) { return; } x1 = shape.x1; x2 = shape.x2; y1 = shape.y1; y2 = shape.y2; if (shape.strokeWidth % 2 !== 0) { x1 += 0.5; x2 += 0.5; y1 += 0.5; y2 += 0.5; } ctx.lineWidth = shape.strokeWidth; ctx.strokeStyle = shape.color; ctx.lineCap = shape.capStyle; if (shape.dash) { ctx.setLineDash(shape.dash); } ctx.beginPath(); ctx.moveTo(x1, y1); ctx.lineTo(x2, y2); ctx.stroke(); if (shape.dash) { ctx.setLineDash([]); } arrowWidth = Math.max(shape.strokeWidth * 2.2, 5); if (shape.endCapShapes[0]) { lineEndCapShapes[shape.endCapShapes[0]].drawToCanvas(ctx, x1, y1, Math.atan2(y1 - y2, x1 - x2), arrowWidth, shape.color); } if (shape.endCapShapes[1]) { return lineEndCapShapes[shape.endCapShapes[1]].drawToCanvas(ctx, x2, y2, Math.atan2(y2 - y1, x2 - x1), arrowWidth, shape.color); } }); _drawRawLinePath = function(ctx, points, close, lineCap) { var i, len, point, ref; if (close == null) { close = false; } if (lineCap == null) { lineCap = 'round'; } if (!points.length) { return; } ctx.lineCap = lineCap; ctx.strokeStyle = points[0].color; ctx.lineWidth = points[0].size; ctx.beginPath(); if (points[0].size % 2 === 0) { ctx.moveTo(points[0].x, points[0].y); } else { ctx.moveTo(points[0].x + 0.5, points[0].y + 0.5); } ref = points.slice(1); for (i = 0, len = ref.length; i < len; i++) { point = ref[i]; if (points[0].size % 2 === 0) { ctx.lineTo(point.x, point.y); } else { ctx.lineTo(point.x + 0.5, point.y + 0.5); } } if (close) { return ctx.closePath(); } }; drawLinePath = function(ctx, shape) { _drawRawLinePath(ctx, shape.smoothedPoints); return ctx.stroke(); }; drawLinePathLatest = function(ctx, bufferCtx, shape) { var drawEnd, drawStart, segmentStart; if (shape.tail) { segmentStart = shape.smoothedPoints.length - shape.segmentSize * shape.tailSize; drawStart = segmentStart < shape.segmentSize * 2 ? 0 : segmentStart; drawEnd = segmentStart + shape.segmentSize + 1; _drawRawLinePath(bufferCtx, shape.smoothedPoints.slice(drawStart, drawEnd)); return bufferCtx.stroke(); } else { _drawRawLinePath(bufferCtx, shape.smoothedPoints); return bufferCtx.stroke(); } }; defineCanvasRenderer('LinePath', drawLinePath, drawLinePathLatest); drawErasedLinePath = function(ctx, shape) { ctx.save(); ctx.globalCompositeOperation = "destination-out"; drawLinePath(ctx, shape); return ctx.restore(); }; drawErasedLinePathLatest = function(ctx, bufferCtx, shape) { ctx.save(); ctx.globalCompositeOperation = "destination-out"; bufferCtx.save(); bufferCtx.globalCompositeOperation = "destination-out"; drawLinePathLatest(ctx, bufferCtx, shape); ctx.restore(); return bufferCtx.restore(); }; defineCanvasRenderer('ErasedLinePath', drawErasedLinePath, drawErasedLinePathLatest); defineCanvasRenderer('Text', function(ctx, shape) { if (!shape.renderer) { shape._makeRenderer(ctx); } ctx.fillStyle = shape.color; return shape.renderer.draw(ctx, shape.x, shape.y); }); defineCanvasRenderer('Polygon', function(ctx, shape) { ctx.fillStyle = shape.fillColor; _drawRawLinePath(ctx, shape.points, shape.isClosed, 'butt'); ctx.fill(); return ctx.stroke(); }); module.exports = { defineCanvasRenderer: defineCanvasRenderer, renderShapeToCanvas: renderShapeToCanvas, renderShapeToContext: renderShapeToContext }; },{"./lineEndCapShapes":12}],10:[function(require,module,exports){ 'use strict'; module.exports = { imageURLPrefix: 'lib/img', primaryColor: 'hsla(0, 0%, 0%, 1)', secondaryColor: 'hsla(0, 0%, 100%, 1)', backgroundColor: 'transparent', strokeWidths: [1, 2, 5, 10, 20, 30], defaultStrokeWidth: 5, toolbarPosition: 'top', keyboardShortcuts: false, imageSize: { width: 'infinite', height: 'infinite' }, backgroundShapes: [], watermarkImage: null, watermarkScale: 1, zoomMin: 0.2, zoomMax: 4.0, zoomStep: 0.2, snapshot: null, onInit: function onInit() {}, tools: [require('../tools/Pencil'), require('../tools/Eraser'), require('../tools/Line'), require('../tools/Rectangle'), require('../tools/Ellipse'), require('../tools/Text'), require('../tools/Polygon'), require('../tools/Pan'), require('../tools/Eyedropper')] }; },{"../tools/Ellipse":43,"../tools/Eraser":44,"../tools/Eyedropper":45,"../tools/Line":46,"../tools/Pan":47,"../tools/Pencil":48,"../tools/Polygon":49,"../tools/Rectangle":50,"../tools/Text":52}],11:[function(require,module,exports){ "use strict"; /** This library rewrites the Canvas2D "measureText" function so that it returns a more complete metrics object. This library is licensed under the MIT (Expat) license, the text for which is included below. ** ----------------------------------------------------------------------------- CHANGELOG: 2012-01-21 - Whitespace handling added by Joe Turner (https://github.com/oampo) 2015-06-08 - Various hacks added by Steve Johnson ** ----------------------------------------------------------------------------- Copyright (C) 2011 by Mike "Pomax" Kamermans 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 () { var NAME = "FontMetrics Library"; var VERSION = "1-2012.0121.1300"; // if there is no getComputedStyle, this library won't work. if (!document.defaultView.getComputedStyle) { throw "ERROR: 'document.defaultView.getComputedStyle' not found. This library only works in browsers that can report computed CSS values."; } // store the old text metrics function on the Canvas2D prototype CanvasRenderingContext2D.prototype.measureTextWidth = CanvasRenderingContext2D.prototype.measureText; /** * shortcut function for getting computed CSS values */ var getCSSValue = function getCSSValue(element, property) { return document.defaultView.getComputedStyle(element, null).getPropertyValue(property); }; // debug function var show = function show(canvas, ctx, xstart, w, h, metrics) { document.body.appendChild(canvas); ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)'; ctx.beginPath(); ctx.moveTo(xstart, 0); ctx.lineTo(xstart, h); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(xstart + metrics.bounds.maxx, 0); ctx.lineTo(xstart + metrics.bounds.maxx, h); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, h / 2 - metrics.ascent); ctx.lineTo(w, h / 2 - metrics.ascent); ctx.closePath(); ctx.stroke(); ctx.beginPath(); ctx.moveTo(0, h / 2 + metrics.descent); ctx.lineTo(w, h / 2 + metrics.descent); ctx.closePath(); ctx.stroke(); }; /** * The new text metrics function */ CanvasRenderingContext2D.prototype.measureText2 = function (textstring, fontSize, fontString) { var metrics = this.measureTextWidth(textstring), isSpace = !/\S/.test(textstring); metrics.fontsize = fontSize; // for text lead values, we meaure a multiline text container. var leadDiv = document.createElement("div"); leadDiv.style.position = "absolute"; leadDiv.style.opacity = 0; leadDiv.style.font = fontString; leadDiv.innerHTML = textstring + "<br/>" + textstring; document.body.appendChild(leadDiv); // make some initial guess at the text leading (using the standard TeX ratio) metrics.leading = 1.2 * fontSize; // then we try to get the real value from the browser var leadDivHeight = getCSSValue(leadDiv, "height"); leadDivHeight = leadDivHeight.replace("px", ""); if (leadDivHeight >= fontSize * 2) { metrics.leading = leadDivHeight / 2 | 0; } document.body.removeChild(leadDiv); // if we're not dealing with white space, we can compute metrics if (!isSpace) { // Have characters, so measure the text var canvas = document.createElement("canvas"); var padding = 100; canvas.width = metrics.width + padding; canvas.height = 3 * fontSize; canvas.style.opacity = 1; canvas.style.font = fontString; var ctx = canvas.getContext("2d"); ctx.font = fontString; var w = canvas.width, h = canvas.height, baseline = h / 2; // Set all canvas pixeldata values to 255, with all the content // data being 0. This lets us scan for data[i] != 255. ctx.fillStyle = "white"; ctx.fillRect(-1, -1, w + 2, h + 2); ctx.fillStyle = "black"; ctx.fillText(textstring, padding / 2, baseline); var pixelData = ctx.getImageData(0, 0, w, h).data; // canvas pixel data is w*4 by h*4, because R, G, B and A are separate, // consecutive values in the array, rather than stored as 32 bit ints. var i = 0, w4 = w * 4, len = pixelData.length; // Finding the ascent uses a normal, forward scanline while (++i < len && pixelData[i] === 255) {} var ascent = i / w4 | 0; // Finding the descent uses a reverse scanline i = len - 1; while (--i > 0 && pixelData[i] === 255) {} var descent = i / w4 | 0; // find the min-x coordinate for (i = 0; i < len && pixelData[i] === 255;) { i += w4; if (i >= len) { i = i - len + 4; } } var minx = i % w4 / 4 | 0; // find the max-x coordinate var step = 1; for (i = len - 3; i >= 0 && pixelData[i] === 255;) { i -= w4; if (i < 0) { i = len - 3 - step++ * 4; } } var maxx = i % w4 / 4 + 1 | 0; // set font metrics metrics.ascent = baseline - ascent; metrics.descent = descent - baseline; metrics.bounds = { minx: minx - padding / 2, maxx: maxx - padding / 2, miny: 0, maxy: descent - ascent }; metrics.height = 1 + (descent - ascent); } // if we ARE dealing with whitespace, most values will just be zero. else { // Only whitespace, so we can't measure the text metrics.ascent = 0; metrics.descent = 0; metrics.bounds = { minx: 0, maxx: metrics.width, // Best guess miny: 0, maxy: 0 }; metrics.height = 0; } return metrics; }; })(); },{}],12:[function(require,module,exports){ module.exports = { arrow: (function() { var getPoints; getPoints = function(x, y, angle, width, length) { return [ { x: x + Math.cos(angle + Math.PI / 2) * width / 2, y: y + Math.sin(angle + Math.PI / 2) * width / 2 }, { x: x + Math.cos(angle) * length, y: y + Math.sin(angle) * length }, { x: x + Math.cos(angle - Math.PI / 2) * width / 2, y: y + Math.sin(angle - Math.PI / 2) * width / 2 } ]; }; return { drawToCanvas: function(ctx, x, y, angle, width, color, length) { var points; if (length == null) { length = 0; } length = length || width; ctx.fillStyle = color; ctx.lineWidth = 0; ctx.strokeStyle = 'transparent'; ctx.beginPath(); points = getPoints(x, y, angle, width, length); ctx.moveTo(points[0].x, points[0].y); ctx.lineTo(points[1].x, points[1].y); ctx.lineTo(points[2].x, points[2].y); return ctx.fill(); }, svg: function(x, y, angle, width, color, length) { var points; if (length == null) { length = 0; } length = length || width; points = getPoints(x, y, angle, width, length); return "<polygon fill='" + color + "' stroke='none' points='" + (points.map(function(p) { return p.x + "," + p.y; })) + "' />"; } }; })() }; },{}],13:[function(require,module,exports){ var _, localize, strings; strings = {}; localize = function(localStrings) { return strings = localStrings; }; _ = function(string) { var translation; translation = strings[string]; return translation || string; }; module.exports = { localize: localize, _: _ }; },{}],14:[function(require,module,exports){ var Point, _slope, math, normals, unit, util; Point = require('./shapes').Point; util = require('./util'); math = {}; math.toPoly = function(line) { var i, index, len, n, point, polyLeft, polyRight; polyLeft = []; polyRight = []; index = 0; for (i = 0, len = line.length; i < len; i++) { point = line[i]; n = normals(point, _slope(line, index)); polyLeft = polyLeft.concat([n[0]]); polyRight = [n[1]].concat(polyRight); index += 1; } return polyLeft.concat(polyRight); }; _slope = function(line, index) { var point; if (line.length < 3) { point = { x: 0, y: 0 }; } if (index === 0) { point = _slope(line, index + 1); } else if (index === line.length - 1) { point = _slope(line, index - 1); } else { point = math.diff(line[index - 1], line[index + 1]); } return point; }; math.diff = function(a, b) { return { x: b.x - a.x, y: b.y - a.y }; }; unit = function(vector) { var length; length = math.len(vector); return { x: vector.x / length, y: vector.y / length }; }; normals = function(p, slope) { slope = unit(slope); slope.x = slope.x * p.size / 2; slope.y = slope.y * p.size / 2; return [ { x: p.x - slope.y, y: p.y + slope.x, color: p.color }, { x: p.x + slope.y, y: p.y - slope.x, color: p.color } ]; }; math.len = function(vector) { return Math.sqrt(Math.pow(vector.x, 2) + Math.pow(vector.y, 2)); }; math.scalePositionScalar = function(val, viewportSize, oldScale, newScale) { var newSize, oldSize; oldSize = viewportSize * oldScale; newSize = viewportSize * newScale; return val + (oldSize - newSize) / 2; }; module.exports = math; },{"./shapes":17,"./util":19}],15:[function(require,module,exports){ var INFINITE, JSONToShape, renderWatermark, util; util = require('./util'); JSONToShape = require('./shapes').JSONToShape; INFINITE = 'infinite'; renderWatermark = function(ctx, image, scale) { if (!image.width) { return; } ctx.save(); ctx.translate(ctx.canvas.width / 2, ctx.canvas.height / 2); ctx.scale(scale, scale); ctx.drawImage(image, -image.width / 2, -image.height / 2); return ctx.restore(); }; module.exports = function(snapshot, opts) { var allShapes, backgroundShapes, colors, imageSize, s, shapes, watermarkCanvas, watermarkCtx; if (opts == null) { opts = {}; } if (opts.scale == null) { opts.scale = 1; } shapes = (function() { var i, len, ref, results; ref = snapshot.shapes; results = []; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; results.push(JSONToShape(s)); } return results; })(); backgroundShapes = []; if (snapshot.backgroundShapes) { backgroundShapes = (function() { var i, len, ref, results; ref = snapshot.backgroundShapes; results = []; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; results.push(JSONToShape(s)); } return results; })(); } if (opts.margin == null) { opts.margin = { top: 0, right: 0, bottom: 0, left: 0 }; } imageSize = snapshot.imageSize || { width: INFINITE, height: INFINITE }; colors = snapshot.colors || { background: 'transparent' }; allShapes = shapes.concat(backgroundShapes); watermarkCanvas = document.createElement('canvas'); watermarkCtx = watermarkCanvas.getContext('2d'); if (opts.rect) { opts.rect.x -= opts.margin.left; opts.rect.y -= opts.margin.top; opts.rect.width += opts.margin.left + opts.margin.right; opts.rect.height += opts.margin.top + opts.margin.bottom; } else { opts.rect = util.getDefaultImageRect((function() { var i, len, results; results = []; for (i = 0, len = allShapes.length; i < len; i++) { s = allShapes[i]; results.push(s.getBoundingRect(watermarkCtx)); } return results; })(), imageSize, opts.margin); } watermarkCanvas.width = opts.rect.width * opts.scale; watermarkCanvas.height = opts.rect.height * opts.scale; watermarkCtx.fillStyle = colors.background; watermarkCtx.fillRect(0, 0, watermarkCanvas.width, watermarkCanvas.height); if (!(opts.rect.width && opts.rect.height)) { return null; } if (opts.watermarkImage) { renderWatermark(watermarkCtx, opts.watermarkImage, opts.watermarkScale); } return util.combineCanvases(watermarkCanvas, util.renderShapes(backgroundShapes, opts.rect, opts.scale), util.renderShapes(shapes, opts.rect, opts.scale)); }; },{"./shapes":17,"./util":19}],16:[function(require,module,exports){ var INFINITE, JSONToShape, util; util = require('./util'); JSONToShape = require('./shapes').JSONToShape; INFINITE = 'infinite'; module.exports = function(snapshot, opts) { var allShapes, backgroundShapes, colors, ctx, dummyCanvas, imageSize, s, shapes; if (opts == null) { opts = {}; } shapes = (function() { var i, len, ref, results; ref = snapshot.shapes; results = []; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; results.push(JSONToShape(s)); } return results; })(); backgroundShapes = []; if (snapshot.backgroundShapes) { backgroundShapes = (function() { var i, len, ref, results; ref = snapshot.backgroundShapes; results = []; for (i = 0, len = ref.length; i < len; i++) { s = ref[i]; results.push(JSONToShape(s)); } return results; })(); } if (opts.margin == null) { opts.margin = { top: 0, right: 0, bottom: 0, left: 0 }; } imageSize = snapshot.imageSize || { width: INFINITE, height: INFINITE }; colors = snapshot.colors || { background: 'transparent' }; allShapes = shapes.concat(backgroundShapes); dummyCanvas = document.createElement('canvas'); ctx = dummyCanvas.getContext('2d'); if (opts.rect) { opts.rect.x -= opts.margin.left; opts.rect.y -= opts.margin.top; opts.rect.width += opts.margin.left + opts.margin.right; opts.rect.height += opts.margin.top + opts.margin.bottom; } else { opts.rect = util.getDefaultImageRect((function() { var i, len, results; results = []; for (i = 0, len = allShapes.length; i < len; i++) { s = allShapes[i]; results.push(s.getBoundingRect(ctx)); } return results; })(), imageSize, opts.margin); } return LC.renderShapesToSVG(backgroundShapes.concat(shapes), opts.rect, colors.background); }; },{"./shapes":17,"./util":19}],17:[function(require,module,exports){ var JSONToShape, LinePath, TextRenderer, _createLinePathFromData, _doAllPointsShareStyle, _dual, _mid, _refine, bspline, createShape, defineCanvasRenderer, defineSVGRenderer, defineShape, lineEndCapShapes, linePathFuncs, ref, ref1, renderShapeToContext, renderShapeToSVG, shapeToJSON, shapes, util; util = require('./util'); TextRenderer = require('./TextRenderer'); lineEndCapShapes = require('./lineEndCapShapes'); ref = require('./canvasRenderer'), defineCanvasRenderer = ref.defineCanvasRenderer, renderShapeToContext = ref.renderShapeToContext; ref1 = require('./svgRenderer'), defineSVGRenderer = ref1.defineSVGRenderer, renderShapeToSVG = ref1.renderShapeToSVG; shapes = {}; defineShape = function(name, props) { var Shape, drawFunc, drawLatestFunc, k, legacyDrawFunc, legacyDrawLatestFunc, legacySVGFunc, svgFunc; Shape = function(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) { props.constructor.call(this, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); return this; }; Shape.prototype.className = name; Shape.fromJSON = props.fromJSON; if (props.draw) { legacyDrawFunc = props.draw; legacyDrawLatestFunc = props.draw || function(ctx, bufferCtx, retryCallback) { return this.draw(ctx, bufferCtx, retryCallback); }; drawFunc = function(ctx, shape, retryCallback) { return legacyDrawFunc.call(shape, ctx, retryCallback); }; drawLatestFunc = function(ctx, bufferCtx, shape, retryCallback) { return legacyDrawLatestFunc.call(shape, ctx, bufferCtx, retryCallback); }; delete props.draw; if (props.drawLatest) { delete props.drawLatest; } defineCanvasRenderer(name, drawFunc, drawLatestFunc); } if (props.toSVG) { legacySVGFunc = props.toSVG; svgFunc = function(shape) { return legacySVGFunc.call(shape); }; delete props.toSVG; defineSVGRenderer(name, svgFunc); } Shape.prototype.draw = function(ctx, retryCallback) { return renderShapeToContext(ctx, this, { retryCallback: retryCallback }); }; Shape.prototype.drawLatest = function(ctx, bufferCtx, retryCallback) { return renderShapeToContext(ctx, this, { retryCallback: retryCallback, bufferCtx: bufferCtx, shouldOnlyDrawLatest: true }); }; Shape.prototype.toSVG = function() { return renderShapeToSVG(this); }; for (k in props) { if (k !== 'fromJSON') { Shape.prototype[k] = props[k]; } } shapes[name] = Shape; return Shape; }; createShape = function(name, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p) { var s; s = new shapes[name](a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p); s.id = util.getGUID(); return s; }; JSONToShape = function(arg) { var className, data, id, shape; className = arg.className, data = arg.data, id = arg.id; if (className in shapes) { shape = shapes[className].fromJSON(data); if (shape) { if (id) { shape.id = id; } return shape; } else { console.log('Unreadable shape:', className, data); return null; } } else { console.log("Unknown shape:", className, data); return null; } }; shapeToJSON = function(shape) { return { className: shape.className, data: shape.toJSON(), id: shape.id }; }; bspline = function(points, order) { if (!order) { return points; } return bspline(_dual(_dual(_refine(points))), order - 1); }; _refine = function(points) { var index, len, point, q, refined; points = [points[0]].concat(points).concat(util.last(points)); refined = []; index = 0; for (q = 0, len = points.length; q < len; q++) { point = points[q]; refined[index * 2] = point; if (points[index + 1]) { refined[index * 2 + 1] = _mid(point, points[index + 1]); } index += 1; } return refined; }; _dual = function(points) { var dualed, index, len, point, q; dualed = []; index = 0; for (q = 0, len = points.length; q < len; q++) { point = points[q]; if (points[index + 1]) { dualed[index] = _mid(point, points[index + 1]); } index += 1; } return dualed; }; _mid = function(a, b) { return createShape('Point', { x: a.x + ((b.x - a.x) / 2), y: a.y + ((b.y - a.y) / 2), size: a.size + ((b.size - a.size) / 2), color: a.color }); }; defineShape('Image', { constructor: function(args) { if (args == null) { args = {}; } this.x = args.x || 0; this.y = args.y || 0; this.scale = args.scale || 1; return this.image = args.image || null; }, getBoundingRect: function() { return { x: this.x, y: this.y, width: this.image.width * this.scale, height: this.image.height * this.scale }; }, toJSON: function() { return { x: this.x, y: this.y, imageSrc: this.image.src, imageObject: this.image, scale: this.scale }; }, fromJSON: function(data) { var img, ref2; img = null; if ((ref2 = data.imageObject) != null ? ref2.width : void 0) { img = data.imageObject; } else { img = new Image(); img.src = data.imageSrc; } return createShape('Image', { x: data.x, y: data.y, image: img, scale: data.scale }); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x = this.x - moveInfo.xDiff; return this.y = this.y - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { if (upperLeft == null) { upperLeft = {}; } this.x = upperLeft.x; return this.y = upperLeft.y; } }); defineShape('Rectangle', { constructor: function(args) { if (args == null) { args = {}; } this.x = args.x || 0; this.y = args.y || 0; this.width = args.width || 0; this.height = args.height || 0; this.strokeWidth = args.strokeWidth || 1; this.strokeColor = args.strokeColor || 'black'; return this.fillColor = args.fillColor || 'transparent'; }, getBoundingRect: function() { return { x: this.x - this.strokeWidth / 2, y: this.y - this.strokeWidth / 2, width: this.width + this.strokeWidth, height: this.height + this.strokeWidth }; }, toJSON: function() { return { x: this.x, y: this.y, width: this.width, height: this.height, strokeWidth: this.strokeWidth, strokeColor: this.strokeColor, fillColor: this.fillColor }; }, fromJSON: function(data) { return createShape('Rectangle', data); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x = this.x - moveInfo.xDiff; return this.y = this.y - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { if (upperLeft == null) { upperLeft = {}; } this.x = upperLeft.x; return this.y = upperLeft.y; } }); defineShape('Ellipse', { constructor: function(args) { if (args == null) { args = {}; } this.x = args.x || 0; this.y = args.y || 0; this.width = args.width || 0; this.height = args.height || 0; this.strokeWidth = args.strokeWidth || 1; this.strokeColor = args.strokeColor || 'black'; return this.fillColor = args.fillColor || 'transparent'; }, getBoundingRect: function() { return { x: this.x - this.strokeWidth / 2, y: this.y - this.strokeWidth / 2, width: this.width + this.strokeWidth, height: this.height + this.strokeWidth }; }, toJSON: function() { return { x: this.x, y: this.y, width: this.width, height: this.height, strokeWidth: this.strokeWidth, strokeColor: this.strokeColor, fillColor: this.fillColor }; }, fromJSON: function(data) { return createShape('Ellipse', data); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x = this.x - moveInfo.xDiff; return this.y = this.y - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { if (upperLeft == null) { upperLeft = {}; } this.x = upperLeft.x; return this.y = upperLeft.y; } }); defineShape('Line', { constructor: function(args) { if (args == null) { args = {}; } this.x1 = args.x1 || 0; this.y1 = args.y1 || 0; this.x2 = args.x2 || 0; this.y2 = args.y2 || 0; this.strokeWidth = args.strokeWidth || 1; this.color = args.color || 'black'; this.capStyle = args.capStyle || 'round'; this.endCapShapes = args.endCapShapes || [null, null]; return this.dash = args.dash || null; }, getBoundingRect: function() { return { x: Math.min(this.x1, this.x2) - this.strokeWidth / 2, y: Math.min(this.y1, this.y2) - this.strokeWidth / 2, width: Math.abs(this.x2 - this.x1) + this.strokeWidth / 2, height: Math.abs(this.y2 - this.y1) + this.strokeWidth / 2 }; }, toJSON: function() { return { x1: this.x1, y1: this.y1, x2: this.x2, y2: this.y2, strokeWidth: this.strokeWidth, color: this.color, capStyle: this.capStyle, dash: this.dash, endCapShapes: this.endCapShapes }; }, fromJSON: function(data) { return createShape('Line', data); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x1 = this.x1 - moveInfo.xDiff; this.y1 = this.y1 - moveInfo.yDiff; this.x2 = this.x2 - moveInfo.xDiff; return this.y2 = this.y2 - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { var br, xDiff, yDiff; if (upperLeft == null) { upperLeft = {}; } br = this.getBoundingRect(); xDiff = br.x - upperLeft.x; yDiff = br.y - upperLeft.y; return this.move({ xDiff: xDiff, yDiff: yDiff }); } }); _doAllPointsShareStyle = function(points) { var color, len, point, q, size; if (!points.length) { return false; } size = points[0].size; color = points[0].color; for (q = 0, len = points.length; q < len; q++) { point = points[q]; if (!(point.size === size && point.color === color)) { console.log(size, color, point.size, point.color); } if (!(point.size === size && point.color === color)) { return false; } } return true; }; _createLinePathFromData = function(shapeName, data) { var pointData, points, smoothedPoints, x, y; points = null; if (data.points) { points = (function() { var len, q, ref2, results; ref2 = data.points; results = []; for (q = 0, len = ref2.length; q < len; q++) { pointData = ref2[q]; results.push(JSONToShape(pointData)); } return results; })(); } else if (data.pointCoordinatePairs) { points = (function() { var len, q, ref2, ref3, results; ref2 = data.pointCoordinatePairs; results = []; for (q = 0, len = ref2.length; q < len; q++) { ref3 = ref2[q], x = ref3[0], y = ref3[1]; results.push(JSONToShape({ className: 'Point', data: { x: x, y: y, size: data.pointSize, color: data.pointColor, smooth: data.smooth } })); } return results; })(); } smoothedPoints = null; if (data.smoothedPointCoordinatePairs) { smoothedPoints = (function() { var len, q, ref2, ref3, results; ref2 = data.smoothedPointCoordinatePairs; results = []; for (q = 0, len = ref2.length; q < len; q++) { ref3 = ref2[q], x = ref3[0], y = ref3[1]; results.push(JSONToShape({ className: 'Point', data: { x: x, y: y, size: data.pointSize, color: data.pointColor, smooth: data.smooth } })); } return results; })(); } if (!points[0]) { return null; } return createShape(shapeName, { points: points, smoothedPoints: smoothedPoints, order: data.order, tailSize: data.tailSize, smooth: data.smooth }); }; linePathFuncs = { constructor: function(args) { var len, point, points, q, results; if (args == null) { args = {}; } points = args.points || []; this.order = args.order || 3; this.tailSize = args.tailSize || 3; this.smooth = 'smooth' in args ? args.smooth : true; this.segmentSize = Math.pow(2, this.order); this.sampleSize = this.tailSize + 1; if (args.smoothedPoints) { this.points = args.points; return this.smoothedPoints = args.smoothedPoints; } else { this.points = []; results = []; for (q = 0, len = points.length; q < len; q++) { point = points[q]; results.push(this.addPoint(point)); } return results; } }, getBoundingRect: function() { return util.getBoundingRect(this.points.map(function(p) { return { x: p.x - p.size / 2, y: p.y - p.size / 2, width: p.size, height: p.size }; })); }, toJSON: function() { var p, point; if (_doAllPointsShareStyle(this.points)) { return { order: this.order, tailSize: this.tailSize, smooth: this.smooth, pointCoordinatePairs: (function() { var len, q, ref2, results; ref2 = this.points; results = []; for (q = 0, len = ref2.length; q < len; q++) { point = ref2[q]; results.push([point.x, point.y]); } return results; }).call(this), smoothedPointCoordinatePairs: (function() { var len, q, ref2, results; ref2 = this.smoothedPoints; results = []; for (q = 0, len = ref2.length; q < len; q++) { point = ref2[q]; results.push([point.x, point.y]); } return results; }).call(this), pointSize: this.points[0].size, pointColor: this.points[0].color }; } else { return { order: this.order, tailSize: this.tailSize, smooth: this.smooth, points: (function() { var len, q, ref2, results; ref2 = this.points; results = []; for (q = 0, len = ref2.length; q < len; q++) { p = ref2[q]; results.push(shapeToJSON(p)); } return results; }).call(this) }; } }, fromJSON: function(data) { return _createLinePathFromData('LinePath', data); }, addPoint: function(point) { this.points.push(point); if (!this.smooth) { this.smoothedPoints = this.points; return; } if (!this.smoothedPoints || this.points.length < this.sampleSize) { return this.smoothedPoints = bspline(this.points, this.order); } else { this.tail = util.last(bspline(util.last(this.points, this.sampleSize), this.order), this.segmentSize * this.tailSize); return this.smoothedPoints = this.smoothedPoints.slice(0, this.smoothedPoints.length - this.segmentSize * (this.tailSize - 1)).concat(this.tail); } }, move: function(moveInfo) { var len, pt, pts, q; if (moveInfo == null) { moveInfo = {}; } if (!this.smooth) { pts = this.points; } else { pts = this.smoothedPoints; } for (q = 0, len = pts.length; q < len; q++) { pt = pts[q]; pt.move(moveInfo); } return this.points = this.smoothedPoints; }, setUpperLeft: function(upperLeft) { var br, xDiff, yDiff; if (upperLeft == null) { upperLeft = {}; } br = this.getBoundingRect(); xDiff = br.x - upperLeft.x; yDiff = br.y - upperLeft.y; return this.move({ xDiff: xDiff, yDiff: yDiff }); } }; LinePath = defineShape('LinePath', linePathFuncs); defineShape('ErasedLinePath', { constructor: linePathFuncs.constructor, toJSON: linePathFuncs.toJSON, addPoint: linePathFuncs.addPoint, getBoundingRect: linePathFuncs.getBoundingRect, fromJSON: function(data) { return _createLinePathFromData('ErasedLinePath', data); } }); defineShape('Point', { constructor: function(args) { if (args == null) { args = {}; } this.x = args.x || 0; this.y = args.y || 0; this.size = args.size || 0; return this.color = args.color || ''; }, getBoundingRect: function() { return { x: this.x - this.size / 2, y: this.y - this.size / 2, width: this.size, height: this.size }; }, toJSON: function() { return { x: this.x, y: this.y, size: this.size, color: this.color }; }, fromJSON: function(data) { return createShape('Point', data); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x = this.x - moveInfo.xDiff; return this.y = this.y - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { if (upperLeft == null) { upperLeft = {}; } this.x = upperLeft.x; return this.y = upperLeft.y; } }); defineShape('Polygon', { constructor: function(args) { var len, point, q, ref2, results; if (args == null) { args = {}; } this.points = args.points; this.fillColor = args.fillColor || 'white'; this.strokeColor = args.strokeColor || 'black'; this.strokeWidth = args.strokeWidth; this.dash = args.dash || null; if (args.isClosed == null) { args.isClosed = true; } this.isClosed = args.isClosed; ref2 = this.points; results = []; for (q = 0, len = ref2.length; q < len; q++) { point = ref2[q]; point.color = this.strokeColor; results.push(point.size = this.strokeWidth); } return results; }, addPoint: function(x, y) { return this.points.push(LC.createShape('Point', { x: x, y: y })); }, getBoundingRect: function() { return util.getBoundingRect(this.points.map(function(p) { return p.getBoundingRect(); })); }, toJSON: function() { return { strokeWidth: this.strokeWidth, fillColor: this.fillColor, strokeColor: this.strokeColor, dash: this.dash, isClosed: this.isClosed, pointCoordinatePairs: this.points.map(function(p) { return [p.x, p.y]; }) }; }, fromJSON: function(data) { data.points = data.pointCoordinatePairs.map(function(arg) { var x, y; x = arg[0], y = arg[1]; return createShape('Point', { x: x, y: y, size: data.strokeWidth, color: data.strokeColor }); }); return createShape('Polygon', data); }, move: function(moveInfo) { var len, pt, q, ref2, results; if (moveInfo == null) { moveInfo = {}; } ref2 = this.points; results = []; for (q = 0, len = ref2.length; q < len; q++) { pt = ref2[q]; results.push(pt.move(moveInfo)); } return results; }, setUpperLeft: function(upperLeft) { var br, xDiff, yDiff; if (upperLeft == null) { upperLeft = {}; } br = this.getBoundingRect(); xDiff = br.x - upperLeft.x; yDiff = br.y - upperLeft.y; return this.move({ xDiff: xDiff, yDiff: yDiff }); } }); defineShape('Text', { constructor: function(args) { if (args == null) { args = {}; } this.x = args.x || 0; this.y = args.y || 0; this.v = args.v || 0; this.text = args.text || ''; this.color = args.color || 'black'; this.font = args.font || '18px sans-serif'; this.forcedWidth = args.forcedWidth || null; return this.forcedHeight = args.forcedHeight || null; }, _makeRenderer: function(ctx) { ctx.lineHeight = 1.2; this.renderer = new TextRenderer(ctx, this.text, this.font, this.forcedWidth, this.forcedHeight); if (this.v < 1) { console.log('repairing baseline'); this.v = 1; this.x -= this.renderer.metrics.bounds.minx; return this.y -= this.renderer.metrics.leading - this.renderer.metrics.descent; } }, setText: function(text) { this.text = text; return this.renderer = null; }, setFont: function(font) { this.font = font; return this.renderer = null; }, setPosition: function(x, y) { this.x = x; return this.y = y; }, setSize: function(forcedWidth, forcedHeight) { this.forcedWidth = Math.max(forcedWidth, 0); this.forcedHeight = Math.max(forcedHeight, 0); return this.renderer = null; }, enforceMaxBoundingRect: function(lc) { var br, dx, lcBoundingRect; br = this.getBoundingRect(lc.ctx); lcBoundingRect = { x: -lc.position.x / lc.scale, y: -lc.position.y / lc.scale, width: lc.canvas.width / lc.scale, height: lc.canvas.height / lc.scale }; if (br.x + br.width > lcBoundingRect.x + lcBoundingRect.width) { dx = br.x - lcBoundingRect.x; this.forcedWidth = lcBoundingRect.width - dx - 10; return this.renderer = null; } }, getBoundingRect: function(ctx, isEditing) { if (isEditing == null) { isEditing = false; } if (!this.renderer) { if (ctx) { this._makeRenderer(ctx); } else { throw "Must pass ctx if text hasn't been rendered yet"; } } return { x: Math.floor(this.x), y: Math.floor(this.y), width: Math.ceil(this.renderer.getWidth(true)), height: Math.ceil(this.renderer.getHeight()) }; }, toJSON: function() { return { x: this.x, y: this.y, text: this.text, color: this.color, font: this.font, forcedWidth: this.forcedWidth, forcedHeight: this.forcedHeight, v: this.v }; }, fromJSON: function(data) { return createShape('Text', data); }, move: function(moveInfo) { if (moveInfo == null) { moveInfo = {}; } this.x = this.x - moveInfo.xDiff; return this.y = this.y - moveInfo.yDiff; }, setUpperLeft: function(upperLeft) { if (upperLeft == null) { upperLeft = {}; } this.x = upperLeft.x; return this.y = upperLeft.y; } }); defineShape('SelectionBox', { constructor: function(args) { if (args == null) { args = {}; } this.shape = args.shape; if (args.handleSize != null) { this.handleSize = args.handleSize; } else { this.handleSize = 10; } this.margin = 4; this.backgroundColor = args.backgroundColor || null; return this._br = this.shape.getBoundingRect(args.ctx); }, toJSON: function() { return { shape: shapeToJSON(this.shape), backgroundColor: this.backgroundColor }; }, fromJSON: function(arg) { var backgroundColor, handleSize, margin, shape; shape = arg.shape, handleSize = arg.handleSize, margin = arg.margin, backgroundColor = arg.backgroundColor; return createShape('SelectionBox', { shape: JSONToShape(shape), backgroundColor: backgroundColor }); }, getTopLeftHandleRect: function() { return { x: this._br.x - this.handleSize - this.margin, y: this._br.y - this.handleSize - this.margin, width: this.handleSize, height: this.handleSize }; }, getBottomLeftHandleRect: function() { return { x: this._br.x - this.handleSize - this.margin, y: this._br.y + this._br.height + this.margin, width: this.handleSize, height: this.handleSize }; }, getTopRightHandleRect: function() { return { x: this._br.x + this._br.width + this.margin, y: this._br.y - this.handleSize - this.margin, width: this.handleSize, height: this.handleSize }; }, getBottomRightHandleRect: function() { return { x: this._br.x + this._br.width + this.margin, y: this._br.y + this._br.height + this.margin, width: this.handleSize, height: this.handleSize }; }, getBoundingRect: function() { return { x: this._br.x - this.margin, y: this._br.y - this.margin, width: this._br.width + this.margin * 2, height: this._br.height + this.margin * 2 }; } }); module.exports = { defineShape: defineShape, createShape: createShape, JSONToShape: JSONToShape, shapeToJSON: shapeToJSON }; },{"./TextRenderer":6,"./canvasRenderer":9,"./lineEndCapShapes":12,"./svgRenderer":18,"./util":19}],18:[function(require,module,exports){ var defineSVGRenderer, lineEndCapShapes, renderShapeToSVG, renderers; lineEndCapShapes = require('./lineEndCapShapes'); renderers = {}; defineSVGRenderer = function(shapeName, shapeToSVGFunc) { return renderers[shapeName] = shapeToSVGFunc; }; renderShapeToSVG = function(shape, opts) { if (opts == null) { opts = {}; } if (opts.shouldIgnoreUnsupportedShapes == null) { opts.shouldIgnoreUnsupportedShapes = false; } if (renderers[shape.className]) { return renderers[shape.className](shape); } else if (opts.shouldIgnoreUnsupportedShapes) { console.warn("Can't render shape of type " + shape.className + " to SVG"); return ""; } else { throw "Can't render shape of type " + shape.className + " to SVG"; } }; defineSVGRenderer('Rectangle', function(shape) { var height, width, x, x1, x2, y, y1, y2; x1 = shape.x; y1 = shape.y; x2 = shape.x + shape.width; y2 = shape.y + shape.height; x = Math.min(x1, x2); y = Math.min(y1, y2); width = Math.max(x1, x2) - x; height = Math.max(y1, y2) - y; if (shape.strokeWidth % 2 !== 0) { x += 0.5; y += 0.5; } return "<rect x='" + x + "' y='" + y + "' width='" + width + "' height='" + height + "' stroke='" + shape.strokeColor + "' fill='" + shape.fillColor + "' stroke-width='" + shape.strokeWidth + "' />"; }); defineSVGRenderer('SelectionBox', function(shape) { return ""; }); defineSVGRenderer('Ellipse', function(shape) { var centerX, centerY, halfHeight, halfWidth; halfWidth = Math.floor(shape.width / 2); halfHeight = Math.floor(shape.height / 2); centerX = shape.x + halfWidth; centerY = shape.y + halfHeight; return "<ellipse cx='" + centerX + "' cy='" + centerY + "' rx='" + (Math.abs(halfWidth)) + "' ry='" + (Math.abs(halfHeight)) + "' stroke='" + shape.strokeColor + "' fill='" + shape.fillColor + "' stroke-width='" + shape.strokeWidth + "' />"; }); defineSVGRenderer('Image', function(shape) { return "<image x='" + shape.x + "' y='" + shape.y + "' width='" + (shape.image.naturalWidth * shape.scale) + "' height='" + (shape.image.naturalHeight * shape.scale) + "' xlink:href='" + shape.image.src + "' />"; }); defineSVGRenderer('Line', function(shape) { var arrowWidth, capString, dashString, x1, x2, y1, y2; dashString = shape.dash ? "stroke-dasharray='" + (shape.dash.join(', ')) + "'" : ''; capString = ''; arrowWidth = Math.max(shape.strokeWidth * 2.2, 5); x1 = shape.x1; x2 = shape.x2; y1 = shape.y1; y2 = shape.y2; if (shape.strokeWidth % 2 !== 0) { x1 += 0.5; x2 += 0.5; y1 += 0.5; y2 += 0.5; } if (shape.endCapShapes[0]) { capString += lineEndCapShapes[shape.endCapShapes[0]].svg(x1, y1, Math.atan2(y1 - y2, x1 - x2), arrowWidth, shape.color); } if (shape.endCapShapes[1]) { capString += lineEndCapShapes[shape.endCapShapes[1]].svg(x2, y2, Math.atan2(y2 - y1, x2 - x1), arrowWidth, shape.color); } return "<g> <line x1='" + x1 + "' y1='" + y1 + "' x2='" + x2 + "' y2='" + y2 + "' " + dashString + " stroke-linecap='" + shape.capStyle + "' stroke='" + shape.color + "' stroke-width='" + shape.strokeWidth + "' /> " + capString + " </g>"; }); defineSVGRenderer('LinePath', function(shape) { return "<polyline fill='none' points='" + (shape.smoothedPoints.map(function(p) { var offset; offset = p.strokeWidth % 2 === 0 ? 0.0 : 0.5; return (p.x + offset) + "," + (p.y + offset); }).join(' ')) + "' stroke='" + shape.points[0].color + "' stroke-linecap='round' stroke-width='" + shape.points[0].size + "' />"; }); defineSVGRenderer('ErasedLinePath', function(shape) { return ""; }); defineSVGRenderer('Polygon', function(shape) { if (shape.isClosed) { return "<polygon fill='" + shape.fillColor + "' points='" + (shape.points.map(function(p) { var offset; offset = p.strokeWidth % 2 === 0 ? 0.0 : 0.5; return (p.x + offset) + "," + (p.y + offset); }).join(' ')) + "' stroke='" + shape.strokeColor + "' stroke-width='" + shape.strokeWidth + "' />"; } else { return "<polyline fill='" + shape.fillColor + "' points='" + (shape.points.map(function(p) { var offset; offset = p.strokeWidth % 2 === 0 ? 0.0 : 0.5; return (p.x + offset) + "," + (p.y + offset); }).join(' ')) + "' stroke='none' /> <polyline fill='none' points='" + (shape.points.map(function(p) { var offset; offset = p.strokeWidth % 2 === 0 ? 0.0 : 0.5; return (p.x + offset) + "," + (p.y + offset); }).join(' ')) + "' stroke='" + shape.strokeColor + "' stroke-width='" + shape.strokeWidth + "' />"; } }); defineSVGRenderer('Text', function(shape) { var heightString, textSplitOnLines, widthString; widthString = shape.forcedWidth ? "width='" + shape.forcedWidth + "px'" : ""; heightString = shape.forcedHeight ? "height='" + shape.forcedHeight + "px'" : ""; textSplitOnLines = shape.text.split(/\r\n|\r|\n/g); if (shape.renderer) { textSplitOnLines = shape.renderer.lines; } return "<text x='" + shape.x + "' y='" + shape.y + "' " + widthString + " " + heightString + " fill='" + shape.color + "' style='font: " + shape.font + ";'> " + (textSplitOnLines.map((function(_this) { return function(line, i) { var dy; dy = i === 0 ? 0 : '1.2em'; return "<tspan x='" + shape.x + "' dy='" + dy + "' alignment-baseline='text-before-edge'> " + line + " </tspan>"; }; })(this)).join('')) + " </text>"; }); module.exports = { defineSVGRenderer: defineSVGRenderer, renderShapeToSVG: renderShapeToSVG }; },{"./lineEndCapShapes":12}],19:[function(require,module,exports){ var renderShapeToContext, renderShapeToSVG, slice, util, slice1 = [].slice; slice = Array.prototype.slice; renderShapeToContext = require('./canvasRenderer').renderShapeToContext; renderShapeToSVG = require('./svgRenderer').renderShapeToSVG; util = { addImageOnload: function(img, fn) { var oldOnload; oldOnload = img.onload; img.onload = function() { if (typeof oldOnload === "function") { oldOnload(); } return fn(); }; return img; }, last: function(array, n) { if (n == null) { n = null; } if (n) { return slice.call(array, Math.max(array.length - n, 0)); } else { return array[array.length - 1]; } }, classSet: function(classNameToIsPresent) { var classNames, key; classNames = []; for (key in classNameToIsPresent) { if (classNameToIsPresent[key]) { classNames.push(key); } } return classNames.join(' '); }, matchElementSize: function(elementToMatch, elementsToResize, scale, callback) { var resize; if (callback == null) { callback = function() {}; } resize = (function(_this) { return function() { var el, i, len; for (i = 0, len = elementsToResize.length; i < len; i++) { el = elementsToResize[i]; el.style.width = elementToMatch.offsetWidth + "px"; el.style.height = elementToMatch.offsetHeight + "px"; if (el.width != null) { el.setAttribute('width', el.offsetWidth * scale); el.setAttribute('height', el.offsetHeight * scale); } } return callback(); }; })(this); elementToMatch.addEventListener('resize', resize); window.addEventListener('resize', resize); window.addEventListener('orientationchange', resize); resize(); return resize; }, combineCanvases: function() { var c, canvas, canvases, ctx, i, j, len, len1; canvases = 1 <= arguments.length ? slice1.call(arguments, 0) : []; c = document.createElement('canvas'); c.width = canvases[0].width; c.height = canvases[0].height; for (i = 0, len = canvases.length; i < len; i++) { canvas = canvases[i]; c.width = Math.max(canvas.width, c.width); c.height = Math.max(canvas.height, c.height); } ctx = c.getContext('2d'); for (j = 0, len1 = canvases.length; j < len1; j++) { canvas = canvases[j]; ctx.drawImage(canvas, 0, 0); } return c; }, renderShapes: function(shapes, bounds, scale, canvas) { var ctx, i, len, shape; if (scale == null) { scale = 1; } if (canvas == null) { canvas = null; } canvas = canvas || document.createElement('canvas'); canvas.width = bounds.width * scale; canvas.height = bounds.height * scale; ctx = canvas.getContext('2d'); ctx.translate(-bounds.x * scale, -bounds.y * scale); ctx.scale(scale, scale); for (i = 0, len = shapes.length; i < len; i++) { shape = shapes[i]; renderShapeToContext(ctx, shape); } return canvas; }, renderShapesToSVG: function(shapes, arg, backgroundColor) { var height, width, x, y; x = arg.x, y = arg.y, width = arg.width, height = arg.height; return ("<svg xmlns='http://www.w3.org/2000/svg' width='" + width + "' height='" + height + "' viewBox='0 0 " + width + " " + height + "'> <rect width='" + width + "' height='" + height + "' x='0' y='0' fill='" + backgroundColor + "' /> <g transform='translate(" + (-x) + ", " + (-y) + ")'> " + (shapes.map(renderShapeToSVG).join('')) + " </g> </svg>").replace(/(\r\n|\n|\r)/gm, ""); }, getBoundingRect: function(rects, width, height) { var i, len, maxX, maxY, minX, minY, rect; if (!rects.length) { return { x: 0, y: 0, width: 0 || width, height: 0 || height }; } minX = rects[0].x; minY = rects[0].y; maxX = rects[0].x + rects[0].width; maxY = rects[0].y + rects[0].height; for (i = 0, len = rects.length; i < len; i++) { rect = rects[i]; minX = Math.floor(Math.min(rect.x, minX)); minY = Math.floor(Math.min(rect.y, minY)); maxX = Math.ceil(Math.max(maxX, rect.x + rect.width)); maxY = Math.ceil(Math.max(maxY, rect.y + rect.height)); } minX = width ? 0 : minX; minY = height ? 0 : minY; maxX = width || maxX; maxY = height || maxY; return { x: minX, y: minY, width: maxX - minX, height: maxY - minY }; }, getDefaultImageRect: function(shapeBoundingRects, explicitSize, margin) { var height, rect, width; if (explicitSize == null) { explicitSize = { width: 0, height: 0 }; } if (margin == null) { margin = { top: 0, right: 0, bottom: 0, left: 0 }; } width = explicitSize.width, height = explicitSize.height; rect = util.getBoundingRect(shapeBoundingRects, width === 'infinite' ? 0 : width, height === 'infinite' ? 0 : height); rect.x -= margin.left; rect.y -= margin.top; rect.width += margin.left + margin.right; rect.height += margin.top + margin.bottom; return rect; }, getBackingScale: function(context) { if (window.devicePixelRatio == null) { return 1; } if (!(window.devicePixelRatio > 1)) { return 1; } return window.devicePixelRatio; }, requestAnimationFrame: (window.requestAnimationFrame || window.setTimeout).bind(window), getGUID: (function() { var s4; s4 = function() { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }; return function() { return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); }; })(), requestAnimationFrame: function(f) { if (window.requestAnimationFrame) { return window.requestAnimationFrame(f); } if (window.webkitRequestAnimationFrame) { return window.webkitRequestAnimationFrame(f); } if (window.mozRequestAnimationFrame) { return window.mozRequestAnimationFrame(f); } return setTimeout(f, 0); }, cancelAnimationFrame: function(f) { if (window.cancelAnimationFrame) { return window.cancelAnimationFrame(f); } if (window.webkitCancelRequestAnimationFrame) { return window.webkitCancelRequestAnimationFrame(f); } if (window.webkitCancelAnimationFrame) { return window.webkitCancelAnimationFrame(f); } if (window.mozCancelAnimationFrame) { return window.mozCancelAnimationFrame(f); } return clearTimeout(f); } }; module.exports = util; },{"./canvasRenderer":9,"./svgRenderer":18}],20:[function(require,module,exports){ 'use strict'; (function () { function CustomEvent(event, params) { params = params || { bubbles: false, cancelable: false, detail: undefined }; var evt = document.createEvent('CustomEvent'); evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail); return evt; }; CustomEvent.prototype = window.CustomEvent.prototype; window.CustomEvent = CustomEvent; })(); },{}],21:[function(require,module,exports){ "use strict"; var hasWarned = false; if (!CanvasRenderingContext2D.prototype.setLineDash) { CanvasRenderingContext2D.prototype.setLineDash = function () { // no-op if (!hasWarned) { console.warn("context2D.setLineDash is a no-op in this browser."); hasWarned = true; } }; } module.exports = null; },{}],22:[function(require,module,exports){ var LiterallyCanvasModel, LiterallyCanvasReactComponent, baseTools, canvasRenderer, conversion, defaultImageURLPrefix, defaultOptions, defaultTools, defineOptionsStyle, init, initReactDOM, initWithoutGUI, localize, registerJQueryPlugin, renderSnapshotToImage, renderSnapshotToSVG, setDefaultImageURLPrefix, shapes, svgRenderer, tools, util; require('./ie_customevent'); require('./ie_setLineDash'); LiterallyCanvasModel = require('./core/LiterallyCanvas'); defaultOptions = require('./core/defaultOptions'); canvasRenderer = require('./core/canvasRenderer'); svgRenderer = require('./core/svgRenderer'); shapes = require('./core/shapes'); util = require('./core/util'); renderSnapshotToImage = require('./core/renderSnapshotToImage'); renderSnapshotToSVG = require('./core/renderSnapshotToSVG'); localize = require('./core/localization').localize; LiterallyCanvasReactComponent = require('./reactGUI/LiterallyCanvas'); initReactDOM = require('./reactGUI/initDOM'); require('./optionsStyles/font'); require('./optionsStyles/stroke-width'); require('./optionsStyles/line-options-and-stroke-width'); require('./optionsStyles/polygon-and-stroke-width'); require('./optionsStyles/stroke-or-fill'); require('./optionsStyles/null'); defineOptionsStyle = require('./optionsStyles/optionsStyles').defineOptionsStyle; conversion = { snapshotToShapes: function(snapshot) { var i, len, ref, results, shape; ref = snapshot.shapes; results = []; for (i = 0, len = ref.length; i < len; i++) { shape = ref[i]; results.push(shapes.JSONToShape(shape)); } return results; }, snapshotJSONToShapes: function(json) { return conversion.snapshotToShapes(JSON.parse(json)); } }; baseTools = require('./tools/base'); tools = { Pencil: require('./tools/Pencil'), Eraser: require('./tools/Eraser'), Line: require('./tools/Line'), Rectangle: require('./tools/Rectangle'), Ellipse: require('./tools/Ellipse'), Text: require('./tools/Text'), Polygon: require('./tools/Polygon'), Pan: require('./tools/Pan'), Eyedropper: require('./tools/Eyedropper'), SelectShape: require('./tools/SelectShape'), Tool: baseTools.Tool, ToolWithStroke: baseTools.ToolWithStroke }; defaultTools = defaultOptions.tools; defaultImageURLPrefix = defaultOptions.imageURLPrefix; setDefaultImageURLPrefix = function(newDefault) { defaultImageURLPrefix = newDefault; return defaultOptions.imageURLPrefix = newDefault; }; init = function(el, opts) { var child, i, len, opt, ref; if (opts == null) { opts = {}; } for (opt in defaultOptions) { if (!(opt in opts)) { opts[opt] = defaultOptions[opt]; } } ref = el.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; el.removeChild(child); } return require('./reactGUI/initDOM')(el, opts); }; initWithoutGUI = function(el, opts) { var drawingViewElement, lc, originalClassName; originalClassName = el.className; if ([' ', ' '].join(el.className).indexOf(' literally ') === -1) { el.className = el.className + ' literally'; } el.className = el.className + ' toolbar-hidden'; drawingViewElement = document.createElement('div'); drawingViewElement.className = 'lc-drawing'; el.appendChild(drawingViewElement); lc = new LiterallyCanvasModel(drawingViewElement, opts); lc.teardown = function() { var child, i, len, ref; lc._teardown(); ref = el.children; for (i = 0, len = ref.length; i < len; i++) { child = ref[i]; el.removeChild(child); } return el.className = originalClassName; }; if ('onInit' in opts) { opts.onInit(lc); } return lc; }; registerJQueryPlugin = function(_$) { return _$.fn.literallycanvas = function(opts) { if (opts == null) { opts = {}; } this.each((function(_this) { return function(ix, el) { return el.literallycanvas = init(el, opts); }; })(this)); return this; }; }; if (typeof window !== 'undefined') { window.LC = { init: init }; if (window.$) { registerJQueryPlugin(window.$); } } module.exports = { init: init, registerJQueryPlugin: registerJQueryPlugin, util: util, tools: tools, setDefaultImageURLPrefix: setDefaultImageURLPrefix, defaultTools: defaultTools, defineOptionsStyle: defineOptionsStyle, LiterallyCanvasReactComponent: LiterallyCanvasReactComponent, defineShape: shapes.defineShape, createShape: shapes.createShape, JSONToShape: shapes.JSONToShape, shapeToJSON: shapes.shapeToJSON, defineCanvasRenderer: canvasRenderer.defineCanvasRenderer, renderShapeToContext: canvasRenderer.renderShapeToContext, renderShapeToCanvas: canvasRenderer.renderShapeToCanvas, renderShapesToCanvas: util.renderShapes, defineSVGRenderer: svgRenderer.defineSVGRenderer, renderShapeToSVG: svgRenderer.renderShapeToSVG, renderShapesToSVG: util.renderShapesToSVG, snapshotToShapes: conversion.snapshotToShapes, snapshotJSONToShapes: conversion.snapshotJSONToShapes, renderSnapshotToImage: renderSnapshotToImage, renderSnapshotToSVG: renderSnapshotToSVG, localize: localize }; },{"./core/LiterallyCanvas":5,"./core/canvasRenderer":9,"./core/defaultOptions":10,"./core/localization":13,"./core/renderSnapshotToImage":15,"./core/renderSnapshotToSVG":16,"./core/shapes":17,"./core/svgRenderer":18,"./core/util":19,"./ie_customevent":20,"./ie_setLineDash":21,"./optionsStyles/font":23,"./optionsStyles/line-options-and-stroke-width":24,"./optionsStyles/null":25,"./optionsStyles/optionsStyles":26,"./optionsStyles/polygon-and-stroke-width":27,"./optionsStyles/stroke-or-fill":28,"./optionsStyles/stroke-width":29,"./reactGUI/LiterallyCanvas":32,"./reactGUI/initDOM":42,"./tools/Ellipse":43,"./tools/Eraser":44,"./tools/Eyedropper":45,"./tools/Line":46,"./tools/Pan":47,"./tools/Pencil":48,"./tools/Polygon":49,"./tools/Rectangle":50,"./tools/SelectShape":51,"./tools/Text":52,"./tools/base":53}],23:[function(require,module,exports){ var ALL_FONTS, FONT_NAME_TO_VALUE, MONOSPACE_FONTS, OTHER_FONTS, React, SANS_SERIF_FONTS, SERIF_FONTS, _, defineOptionsStyle, i, j, l, len, len1, len2, len3, m, name, ref, ref1, ref2, ref3, value; React = require('../reactGUI/React-shim'); defineOptionsStyle = require('./optionsStyles').defineOptionsStyle; _ = require('../core/localization')._; SANS_SERIF_FONTS = [['Arial', 'Arial,"Helvetica Neue",Helvetica,sans-serif'], ['Arial Black', '"Arial Black","Arial Bold",Gadget,sans-serif'], ['Arial Narrow', '"Arial Narrow",Arial,sans-serif'], ['Gill Sans', '"Gill Sans","Gill Sans MT",Calibri,sans-serif'], ['Helvetica', '"Helvetica Neue",Helvetica,Arial,sans-serif'], ['Impact', 'Impact,Haettenschweiler,"Franklin Gothic Bold",Charcoal,"Helvetica Inserat","Bitstream Vera Sans Bold","Arial Black",sans-serif'], ['Tahoma', 'Tahoma,Verdana,Segoe,sans-serif'], ['Trebuchet MS', '"Trebuchet MS","Lucida Grande","Lucida Sans Unicode","Lucida Sans",Tahoma,sans-serif'], ['Verdana', 'Verdana,Geneva,sans-serif']].map(function(arg) { var name, value; name = arg[0], value = arg[1]; return { name: _(name), value: value }; }); SERIF_FONTS = [['Baskerville', 'Baskerville,"Baskerville Old Face","Hoefler Text",Garamond,"Times New Roman",serif'], ['Garamond', 'Garamond,Baskerville,"Baskerville Old Face","Hoefler Text","Times New Roman",serif'], ['Georgia', 'Georgia,Times,"Times New Roman",serif'], ['Hoefler Text', '"Hoefler Text","Baskerville Old Face",Garamond,"Times New Roman",serif'], ['Lucida Bright', '"Lucida Bright",Georgia,serif'], ['Palatino', 'Palatino,"Palatino Linotype","Palatino LT STD","Book Antiqua",Georgia,serif'], ['Times New Roman', 'TimesNewRoman,"Times New Roman",Times,Baskerville,Georgia,serif']].map(function(arg) { var name, value; name = arg[0], value = arg[1]; return { name: _(name), value: value }; }); MONOSPACE_FONTS = [['Consolas/Monaco', 'Consolas,monaco,"Lucida Console",monospace'], ['Courier New', '"Courier New",Courier,"Lucida Sans Typewriter","Lucida Typewriter",monospace'], ['Lucida Sans Typewriter', '"Lucida Sans Typewriter","Lucida Console",monaco,"Bitstream Vera Sans Mono",monospace']].map(function(arg) { var name, value; name = arg[0], value = arg[1]; return { name: _(name), value: value }; }); OTHER_FONTS = [['Copperplate', 'Copperplate,"Copperplate Gothic Light",fantasy'], ['Papyrus', 'Papyrus,fantasy'], ['Script', '"Brush Script MT",cursive']].map(function(arg) { var name, value; name = arg[0], value = arg[1]; return { name: _(name), value: value }; }); ALL_FONTS = [[_('Sans Serif'), SANS_SERIF_FONTS], [_('Serif'), SERIF_FONTS], [_('Monospace'), MONOSPACE_FONTS], [_('Other'), OTHER_FONTS]]; FONT_NAME_TO_VALUE = {}; for (i = 0, len = SANS_SERIF_FONTS.length; i < len; i++) { ref = SANS_SERIF_FONTS[i], name = ref.name, value = ref.value; FONT_NAME_TO_VALUE[name] = value; } for (j = 0, len1 = SERIF_FONTS.length; j < len1; j++) { ref1 = SERIF_FONTS[j], name = ref1.name, value = ref1.value; FONT_NAME_TO_VALUE[name] = value; } for (l = 0, len2 = MONOSPACE_FONTS.length; l < len2; l++) { ref2 = MONOSPACE_FONTS[l], name = ref2.name, value = ref2.value; FONT_NAME_TO_VALUE[name] = value; } for (m = 0, len3 = OTHER_FONTS.length; m < len3; m++) { ref3 = OTHER_FONTS[m], name = ref3.name, value = ref3.value; FONT_NAME_TO_VALUE[name] = value; } defineOptionsStyle('font', React.createClass({ displayName: 'FontOptions', getInitialState: function() { return { isItalic: false, isBold: false, fontName: 'Helvetica', fontSizeIndex: 4 }; }, getFontSizes: function() { return [9, 10, 12, 14, 18, 24, 36, 48, 64, 72, 96, 144, 288]; }, updateTool: function(newState) { var fontSize, items, k; if (newState == null) { newState = {}; } for (k in this.state) { if (!(k in newState)) { newState[k] = this.state[k]; } } fontSize = this.getFontSizes()[newState.fontSizeIndex]; items = []; if (newState.isItalic) { items.push('italic'); } if (newState.isBold) { items.push('bold'); } items.push(fontSize + "px"); items.push(FONT_NAME_TO_VALUE[newState.fontName]); this.props.lc.tool.font = items.join(' '); return this.props.lc.trigger('setFont', items.join(' ')); }, handleFontSize: function(event) { var newState; newState = { fontSizeIndex: event.target.value }; this.setState(newState); return this.updateTool(newState); }, handleFontFamily: function(event) { var newState; newState = { fontName: event.target.selectedOptions[0].innerHTML }; this.setState(newState); return this.updateTool(newState); }, handleItalic: function(event) { var newState; newState = { isItalic: !this.state.isItalic }; this.setState(newState); return this.updateTool(newState); }, handleBold: function(event) { var newState; newState = { isBold: !this.state.isBold }; this.setState(newState); return this.updateTool(newState); }, componentDidMount: function() { return this.updateTool(); }, render: function() { var br, div, input, label, lc, optgroup, option, ref4, select, span; lc = this.props.lc; ref4 = React.DOM, div = ref4.div, input = ref4.input, select = ref4.select, option = ref4.option, br = ref4.br, label = ref4.label, span = ref4.span, optgroup = ref4.optgroup; return div({ className: 'lc-font-settings' }, select({ value: this.state.fontSizeIndex, onChange: this.handleFontSize }, this.getFontSizes().map((function(_this) { return function(size, ix) { return option({ value: ix, key: ix }, size + "px"); }; })(this))), select({ value: this.state.fontName, onChange: this.handleFontFamily }, ALL_FONTS.map((function(_this) { return function(arg) { var fonts, label; label = arg[0], fonts = arg[1]; return optgroup({ key: label, label: label }, fonts.map(function(family, ix) { return option({ value: family.name, key: ix }, family.name); })); }; })(this))), span({}, label({ htmlFor: 'italic' }, _("italic")), input({ type: 'checkbox', id: 'italic', checked: this.state.isItalic, onChange: this.handleItalic })), span({}, label({ htmlFor: 'bold' }, _("bold")), input({ type: 'checkbox', id: 'bold', checked: this.state.isBold, onChange: this.handleBold }))); } })); module.exports = {}; },{"../core/localization":13,"../reactGUI/React-shim":35,"./optionsStyles":26}],24:[function(require,module,exports){ var React, StrokeWidthPicker, classSet, createSetStateOnEventMixin, defineOptionsStyle; React = require('../reactGUI/React-shim'); defineOptionsStyle = require('./optionsStyles').defineOptionsStyle; StrokeWidthPicker = React.createFactory(require('../reactGUI/StrokeWidthPicker')); createSetStateOnEventMixin = require('../reactGUI/createSetStateOnEventMixin'); classSet = require('../core/util').classSet; defineOptionsStyle('line-options-and-stroke-width', React.createClass({ displayName: 'LineOptionsAndStrokeWidth', getState: function() { return { strokeWidth: this.props.tool.strokeWidth, isDashed: this.props.tool.isDashed, hasEndArrow: this.props.tool.hasEndArrow }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('toolChange')], render: function() { var arrowButtonClass, dashButtonClass, div, img, li, ref, style, toggleIsDashed, togglehasEndArrow, ul; ref = React.DOM, div = ref.div, ul = ref.ul, li = ref.li, img = ref.img; toggleIsDashed = (function(_this) { return function() { _this.props.tool.isDashed = !_this.props.tool.isDashed; return _this.setState(_this.getState()); }; })(this); togglehasEndArrow = (function(_this) { return function() { _this.props.tool.hasEndArrow = !_this.props.tool.hasEndArrow; return _this.setState(_this.getState()); }; })(this); dashButtonClass = classSet({ 'square-toolbar-button': true, 'selected': this.state.isDashed }); arrowButtonClass = classSet({ 'square-toolbar-button': true, 'selected': this.state.hasEndArrow }); style = { float: 'left', margin: 1 }; return div({}, div({ className: dashButtonClass, onClick: toggleIsDashed, style: style }, img({ src: this.props.imageURLPrefix + "/dashed-line.png" })), div({ className: arrowButtonClass, onClick: togglehasEndArrow, style: style }, img({ src: this.props.imageURLPrefix + "/line-with-arrow.png" })), StrokeWidthPicker({ tool: this.props.tool, lc: this.props.lc })); } })); module.exports = {}; },{"../core/util":19,"../reactGUI/React-shim":35,"../reactGUI/StrokeWidthPicker":37,"../reactGUI/createSetStateOnEventMixin":40,"./optionsStyles":26}],25:[function(require,module,exports){ var React, defineOptionsStyle; React = require('../reactGUI/React-shim'); defineOptionsStyle = require('./optionsStyles').defineOptionsStyle; defineOptionsStyle('null', React.createClass({ displayName: 'NoOptions', render: function() { return React.DOM.div(); } })); module.exports = {}; },{"../reactGUI/React-shim":35,"./optionsStyles":26}],26:[function(require,module,exports){ var React, defineOptionsStyle, optionsStyles; React = require('../reactGUI/React-shim'); optionsStyles = {}; defineOptionsStyle = function(name, style) { return optionsStyles[name] = React.createFactory(style); }; module.exports = { optionsStyles: optionsStyles, defineOptionsStyle: defineOptionsStyle }; },{"../reactGUI/React-shim":35}],27:[function(require,module,exports){ var React, StrokeWidthPicker, createSetStateOnEventMixin, defineOptionsStyle; React = require('../reactGUI/React-shim'); defineOptionsStyle = require('./optionsStyles').defineOptionsStyle; StrokeWidthPicker = React.createFactory(require('../reactGUI/StrokeWidthPicker')); createSetStateOnEventMixin = require('../reactGUI/createSetStateOnEventMixin'); defineOptionsStyle('polygon-and-stroke-width', React.createClass({ displayName: 'PolygonAndStrokeWidth', getState: function() { return { strokeWidth: this.props.tool.strokeWidth, inProgress: false }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('toolChange')], componentDidMount: function() { var hidePolygonTools, showPolygonTools, unsubscribeFuncs; unsubscribeFuncs = []; this.unsubscribe = (function(_this) { return function() { var func, i, len, results; results = []; for (i = 0, len = unsubscribeFuncs.length; i < len; i++) { func = unsubscribeFuncs[i]; results.push(func()); } return results; }; })(this); showPolygonTools = (function(_this) { return function() { if (!_this.state.inProgress) { return _this.setState({ inProgress: true }); } }; })(this); hidePolygonTools = (function(_this) { return function() { return _this.setState({ inProgress: false }); }; })(this); unsubscribeFuncs.push(this.props.lc.on('lc-polygon-started', showPolygonTools)); return unsubscribeFuncs.push(this.props.lc.on('lc-polygon-stopped', hidePolygonTools)); }, componentWillUnmount: function() { return this.unsubscribe(); }, render: function() { var div, img, lc, polygonCancel, polygonFinishClosed, polygonFinishOpen, polygonToolStyle, ref; lc = this.props.lc; ref = React.DOM, div = ref.div, img = ref.img; polygonFinishOpen = (function(_this) { return function() { return lc.trigger('lc-polygon-finishopen'); }; })(this); polygonFinishClosed = (function(_this) { return function() { return lc.trigger('lc-polygon-finishclosed'); }; })(this); polygonCancel = (function(_this) { return function() { return lc.trigger('lc-polygon-cancel'); }; })(this); polygonToolStyle = {}; if (!this.state.inProgress) { polygonToolStyle = { display: 'none' }; } return div({}, div({ className: 'polygon-toolbar horz-toolbar', style: polygonToolStyle }, div({ className: 'square-toolbar-button', onClick: polygonFinishOpen }, img({ src: this.props.imageURLPrefix + "/polygon-open.png" })), div({ className: 'square-toolbar-button', onClick: polygonFinishClosed }, img({ src: this.props.imageURLPrefix + "/polygon-closed.png" })), div({ className: 'square-toolbar-button', onClick: polygonCancel }, img({ src: this.props.imageURLPrefix + "/polygon-cancel.png" }))), div({}, StrokeWidthPicker({ tool: this.props.tool, lc: this.props.lc }))); } })); module.exports = {}; },{"../reactGUI/React-shim":35,"../reactGUI/StrokeWidthPicker":37,"../reactGUI/createSetStateOnEventMixin":40,"./optionsStyles":26}],28:[function(require,module,exports){ 'use strict'; var React = require('../reactGUI/React-shim'); var _require = require('./optionsStyles'); var defineOptionsStyle = _require.defineOptionsStyle; var createSetStateOnEventMixin = require('../reactGUI/createSetStateOnEventMixin'); var _ = require('../core/localization')._; defineOptionsStyle('stroke-or-fill', React.createClass({ displayName: 'StrokeOrFillPicker', getState: function getState() { return { strokeOrFill: 'stroke' }; }, getInitialState: function getInitialState() { return this.getState(); }, mixins: [createSetStateOnEventMixin('toolChange')], onChange: function onChange(e) { if (e.target.id == 'stroke-or-fill-stroke') { this.props.lc.tool.strokeOrFill = 'stroke'; } else { this.props.lc.tool.strokeOrFill = 'fill'; } this.setState(this.getState()); }, render: function render() { var lc = this.props.lc; return React.createElement( 'form', null, React.createElement( 'span', null, ' ', _('Color to change:'), ' ' ), React.createElement( 'span', null, React.createElement('input', { type: 'radio', name: 'stroke-or-fill', value: 'stroke', id: 'stroke-or-fill-stroke', onChange: this.onChange, checked: lc.tool.strokeOrFill == 'stroke' }), React.createElement( 'label', { htmlFor: 'stroke-or-fill-stroke', className: 'label' }, ' ', _("stroke") ) ), React.createElement( 'span', null, React.createElement('input', { type: 'radio', name: 'stroke-or-fill', value: 'fill', id: 'stroke-or-fill-fill', onChange: this.onChange, checked: lc.tool.strokeOrFill == 'fill' }), React.createElement( 'label', { htmlFor: 'stroke-or-fill-fill', className: 'label' }, ' ', _("fill") ) ) ); } })); module.exports = {}; },{"../core/localization":13,"../reactGUI/React-shim":35,"../reactGUI/createSetStateOnEventMixin":40,"./optionsStyles":26}],29:[function(require,module,exports){ var StrokeWidthPicker, defineOptionsStyle; defineOptionsStyle = require('./optionsStyles').defineOptionsStyle; StrokeWidthPicker = require('../reactGUI/StrokeWidthPicker'); defineOptionsStyle('stroke-width', StrokeWidthPicker); module.exports = {}; },{"../reactGUI/StrokeWidthPicker":37,"./optionsStyles":26}],30:[function(require,module,exports){ var ClearButton, React, _, classSet, createSetStateOnEventMixin; React = require('./React-shim'); createSetStateOnEventMixin = require('./createSetStateOnEventMixin'); _ = require('../core/localization')._; classSet = require('../core/util').classSet; ClearButton = React.createClass({ displayName: 'ClearButton', getState: function() { return { isEnabled: this.props.lc.canUndo() }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('drawingChange')], render: function() { var className, div, lc, onClick; div = React.DOM.div; lc = this.props.lc; className = classSet({ 'lc-clear': true, 'toolbar-button': true, 'fat-button': true, 'disabled': !this.state.isEnabled }); onClick = lc.canUndo() ? ((function(_this) { return function() { return lc.clear(); }; })(this)) : function() {}; return div({ className: className, onClick: onClick }, _('Clear')); } }); module.exports = ClearButton; },{"../core/localization":13,"../core/util":19,"./React-shim":35,"./createSetStateOnEventMixin":40}],31:[function(require,module,exports){ var ColorGrid, ColorWell, PureRenderMixin, React, _, cancelAnimationFrame, classSet, getHSLAString, getHSLString, parseHSLAString, ref, requestAnimationFrame; React = require('./React-shim'); PureRenderMixin = require('react-addons-pure-render-mixin'); ref = require('../core/util'), classSet = ref.classSet, requestAnimationFrame = ref.requestAnimationFrame, cancelAnimationFrame = ref.cancelAnimationFrame; _ = require('../core/localization')._; parseHSLAString = function(s) { var components, firstParen, insideParens, lastParen; if (s === 'transparent') { return { hue: 0, sat: 0, light: 0, alpha: 0 }; } if ((s != null ? s.substring(0, 4) : void 0) !== 'hsla') { return null; } firstParen = s.indexOf('('); lastParen = s.indexOf(')'); insideParens = s.substring(firstParen + 1, lastParen - firstParen + 4); components = (function() { var j, len, ref1, results; ref1 = insideParens.split(','); results = []; for (j = 0, len = ref1.length; j < len; j++) { s = ref1[j]; results.push(s.trim()); } return results; })(); return { hue: parseInt(components[0], 10), sat: parseInt(components[1].substring(0, components[1].length - 1), 10), light: parseInt(components[2].substring(0, components[2].length - 1), 10), alpha: parseFloat(components[3]) }; }; getHSLAString = function(arg) { var alpha, hue, light, sat; hue = arg.hue, sat = arg.sat, light = arg.light, alpha = arg.alpha; return "hsla(" + hue + ", " + sat + "%, " + light + "%, " + alpha + ")"; }; getHSLString = function(arg) { var hue, light, sat; hue = arg.hue, sat = arg.sat, light = arg.light; return "hsl(" + hue + ", " + sat + "%, " + light + "%)"; }; ColorGrid = React.createFactory(React.createClass({ displayName: 'ColorGrid', mixins: [PureRenderMixin], render: function() { var div; div = React.DOM.div; return div({}, this.props.rows.map((function(_this) { return function(row, ix) { return div({ className: 'color-row', key: ix, style: { width: 20 * row.length } }, row.map(function(cellColor, ix2) { var alpha, className, colorString, colorStringNoAlpha, hue, light, sat, update; hue = cellColor.hue, sat = cellColor.sat, light = cellColor.light, alpha = cellColor.alpha; colorString = getHSLAString(cellColor); colorStringNoAlpha = "hsl(" + hue + ", " + sat + "%, " + light + "%)"; className = classSet({ 'color-cell': true, 'selected': _this.props.selectedColor === colorString }); update = function(e) { _this.props.onChange(cellColor, colorString); e.stopPropagation(); return e.preventDefault(); }; return div({ className: className, onTouchStart: update, onTouchMove: update, onClick: update, style: { backgroundColor: colorStringNoAlpha }, key: ix2 }); })); }; })(this))); } })); ColorWell = React.createClass({ displayName: 'ColorWell', mixins: [PureRenderMixin], getInitialState: function() { var colorString, hsla; colorString = this.props.lc.colors[this.props.colorName]; hsla = parseHSLAString(colorString); if (hsla == null) { hsla = {}; } if (hsla.alpha == null) { hsla.alpha = 1; } if (hsla.sat == null) { hsla.sat = 100; } if (hsla.hue == null) { hsla.hue = 0; } if (hsla.light == null) { hsla.light = 50; } return { colorString: colorString, alpha: hsla.alpha, sat: hsla.sat === 0 ? 100 : hsla.sat, isPickerVisible: false, hsla: hsla }; }, componentDidMount: function() { return this.unsubscribe = this.props.lc.on(this.props.colorName + "ColorChange", (function(_this) { return function() { var colorString; colorString = _this.props.lc.colors[_this.props.colorName]; _this.setState({ colorString: colorString }); return _this.setHSLAFromColorString(colorString); }; })(this)); }, componentWillUnmount: function() { return this.unsubscribe(); }, setHSLAFromColorString: function(c) { var hsla; hsla = parseHSLAString(c); if (hsla) { return this.setState({ hsla: hsla, alpha: hsla.alpha, sat: hsla.sat }); } else { return this.setState({ hsla: null, alpha: 1, sat: 100 }); } }, closePicker: function() { return this.setState({ isPickerVisible: false }); }, togglePicker: function() { var isPickerVisible, shouldResetSat; isPickerVisible = !this.state.isPickerVisible; shouldResetSat = isPickerVisible && this.state.sat === 0; this.setHSLAFromColorString(this.state.colorString); return this.setState({ isPickerVisible: isPickerVisible, sat: shouldResetSat ? 100 : this.state.sat }); }, setColor: function(c) { this.setState({ colorString: c }); this.setHSLAFromColorString(c); return this.props.lc.setColor(this.props.colorName, c); }, setAlpha: function(alpha) { var hsla; this.setState({ alpha: alpha }); if (this.state.hsla) { hsla = this.state.hsla; hsla.alpha = alpha; this.setState({ hsla: hsla }); return this.setColor(getHSLAString(hsla)); } }, setSat: function(sat) { var hsla; this.setState({ sat: sat }); if (isNaN(sat)) { throw "SAT"; } if (this.state.hsla) { hsla = this.state.hsla; hsla.sat = sat; this.setState({ hsla: hsla }); return this.setColor(getHSLAString(hsla)); } }, render: function() { var br, div, label, ref1; ref1 = React.DOM, div = ref1.div, label = ref1.label, br = ref1.br; return div({ className: classSet({ 'color-well': true, 'open': this.state.isPickerVisible }), onMouseLeave: this.closePicker, style: { float: 'left', textAlign: 'center' } }, label({ float: 'left' }, this.props.label), br({}), div({ className: classSet({ 'color-well-color-container': true, 'selected': this.state.isPickerVisible }), style: { backgroundColor: 'white' }, onClick: this.togglePicker }, div({ className: 'color-well-checker color-well-checker-top-left' }), div({ className: 'color-well-checker color-well-checker-bottom-right', style: { left: '50%', top: '50%' } }), div({ className: 'color-well-color', style: { backgroundColor: this.state.colorString } }, " ")), this.renderPicker()); }, renderPicker: function() { var div, hue, i, input, j, label, len, onSelectColor, ref1, ref2, renderColor, renderLabel, rows; ref1 = React.DOM, div = ref1.div, label = ref1.label, input = ref1.input; if (!this.state.isPickerVisible) { return null; } renderLabel = (function(_this) { return function(text) { return div({ className: 'color-row label', key: text, style: { lineHeight: '20px', height: 16 } }, text); }; })(this); renderColor = (function(_this) { return function() { var checkerboardURL; checkerboardURL = _this.props.lc.opts.imageURLPrefix + "/checkerboard-8x8.png"; return div({ className: 'color-row', key: "color", style: { position: 'relative', backgroundImage: "url(" + checkerboardURL + ")", backgroundRepeat: 'repeat', height: 24 } }, div({ style: { position: 'absolute', top: 0, right: 0, bottom: 0, left: 0, backgroundColor: _this.state.colorString } })); }; })(this); rows = []; rows.push((function() { var j, results; results = []; for (i = j = 0; j <= 100; i = j += 10) { results.push({ hue: 0, sat: 0, light: i, alpha: this.state.alpha }); } return results; }).call(this)); ref2 = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330]; for (j = 0, len = ref2.length; j < len; j++) { hue = ref2[j]; rows.push((function() { var k, results; results = []; for (i = k = 10; k <= 90; i = k += 8) { results.push({ hue: hue, sat: this.state.sat, light: i, alpha: this.state.alpha }); } return results; }).call(this)); } onSelectColor = (function(_this) { return function(hsla, s) { return _this.setColor(s); }; })(this); return div({ className: 'color-picker-popup' }, renderColor(), renderLabel(_("alpha")), input({ type: 'range', min: 0, max: 1, step: 0.01, value: this.state.alpha, onChange: (function(_this) { return function(e) { return _this.setAlpha(parseFloat(e.target.value)); }; })(this) }), renderLabel(_("saturation")), input({ type: 'range', min: 0, max: 100, value: this.state.sat, max: 100, onChange: (function(_this) { return function(e) { return _this.setSat(parseInt(e.target.value, 10)); }; })(this) }), ColorGrid({ rows: rows, selectedColor: this.state.colorString, onChange: onSelectColor })); } }); module.exports = ColorWell; },{"../core/localization":13,"../core/util":19,"./React-shim":35,"react-addons-pure-render-mixin":2}],32:[function(require,module,exports){ 'use strict'; var React = require('../reactGUI/React-shim'); var _require = require('../reactGUI/ReactDOM-shim'); var findDOMNode = _require.findDOMNode; var _require2 = require('../core/util'); var classSet = _require2.classSet; var Picker = require('./Picker'); var Options = require('./Options'); var createToolButton = require('./createToolButton'); var LiterallyCanvasModel = require('../core/LiterallyCanvas'); var defaultOptions = require('../core/defaultOptions'); require('../optionsStyles/font'); require('../optionsStyles/stroke-width'); require('../optionsStyles/line-options-and-stroke-width'); require('../optionsStyles/polygon-and-stroke-width'); require('../optionsStyles/null'); var CanvasContainer = React.createClass({ displayName: 'CanvasContainer', shouldComponentUpdate: function shouldComponentUpdate() { // Avoid React trying to control this DOM return false; }, render: function render() { return React.createElement('div', { key: 'literallycanvas', className: 'lc-drawing with-gui' }); } }); var LiterallyCanvas = React.createClass({ displayName: 'LiterallyCanvas', getDefaultProps: function getDefaultProps() { return defaultOptions; }, bindToModel: function bindToModel() { var canvasContainerEl = findDOMNode(this.canvas); var opts = this.props; this.lc.bindToElement(canvasContainerEl); if (typeof this.lc.opts.onInit === 'function') { this.lc.opts.onInit(this.lc); } }, componentWillMount: function componentWillMount() { var _this = this; if (this.lc) return; if (this.props.lc) { this.lc = this.props.lc; } else { this.lc = new LiterallyCanvasModel(this.props); } this.toolButtonComponents = this.lc.opts.tools.map(function (ToolClass) { return createToolButton(new ToolClass(_this.lc)); }); }, componentDidMount: function componentDidMount() { if (!this.lc.isBound) { this.bindToModel(); } }, componentWillUnmount: function componentWillUnmount() { if (this.lc) { this.lc._teardown(); } }, render: function render() { var _this2 = this; var lc = this.lc; var toolButtonComponents = this.toolButtonComponents; var props = this.props; var _lc$opts = this.lc.opts; var imageURLPrefix = _lc$opts.imageURLPrefix; var toolbarPosition = _lc$opts.toolbarPosition; var pickerProps = { lc: lc, toolButtonComponents: toolButtonComponents, imageURLPrefix: imageURLPrefix }; var topOrBottomClassName = classSet({ 'toolbar-at-top': toolbarPosition === 'top', 'toolbar-at-bottom': toolbarPosition === 'bottom', 'toolbar-hidden': toolbarPosition === 'hidden' }); return React.createElement( 'div', { className: 'literally ' + topOrBottomClassName }, React.createElement(CanvasContainer, { ref: function ref(item) { return _this2.canvas = item; } }), React.createElement(Picker, pickerProps), React.createElement(Options, { lc: lc, imageURLPrefix: imageURLPrefix }) ); } }); module.exports = LiterallyCanvas; },{"../core/LiterallyCanvas":5,"../core/defaultOptions":10,"../core/util":19,"../optionsStyles/font":23,"../optionsStyles/line-options-and-stroke-width":24,"../optionsStyles/null":25,"../optionsStyles/polygon-and-stroke-width":27,"../optionsStyles/stroke-width":29,"../reactGUI/React-shim":35,"../reactGUI/ReactDOM-shim":36,"./Options":33,"./Picker":34,"./createToolButton":41}],33:[function(require,module,exports){ var Options, React, createSetStateOnEventMixin, optionsStyles; React = require('./React-shim'); createSetStateOnEventMixin = require('./createSetStateOnEventMixin'); optionsStyles = require('../optionsStyles/optionsStyles').optionsStyles; Options = React.createClass({ displayName: 'Options', getState: function() { var ref; return { style: (ref = this.props.lc.tool) != null ? ref.optionsStyle : void 0, tool: this.props.lc.tool }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('toolChange')], renderBody: function() { var style; style = "" + this.state.style; return optionsStyles[style] && optionsStyles[style]({ lc: this.props.lc, tool: this.state.tool, imageURLPrefix: this.props.imageURLPrefix }); }, render: function() { var div; div = React.DOM.div; return div({ className: 'lc-options horz-toolbar' }, this.renderBody()); } }); module.exports = Options; },{"../optionsStyles/optionsStyles":26,"./React-shim":35,"./createSetStateOnEventMixin":40}],34:[function(require,module,exports){ var ClearButton, ColorPickers, ColorWell, Picker, React, UndoRedoButtons, ZoomButtons, _; React = require('./React-shim'); ClearButton = React.createFactory(require('./ClearButton')); UndoRedoButtons = React.createFactory(require('./UndoRedoButtons')); ZoomButtons = React.createFactory(require('./ZoomButtons')); _ = require('../core/localization')._; ColorWell = React.createFactory(require('./ColorWell')); ColorPickers = React.createFactory(React.createClass({ displayName: 'ColorPickers', render: function() { var div, lc; lc = this.props.lc; div = React.DOM.div; return div({ className: 'lc-color-pickers' }, ColorWell({ lc: lc, colorName: 'primary', label: _('stroke') }), ColorWell({ lc: lc, colorName: 'secondary', label: _('fill') }), ColorWell({ lc: lc, colorName: 'background', label: _('bg') })); } })); Picker = React.createClass({ displayName: 'Picker', getInitialState: function() { return { selectedToolIndex: 0 }; }, renderBody: function() { var div, imageURLPrefix, lc, ref, toolButtonComponents; div = React.DOM.div; ref = this.props, toolButtonComponents = ref.toolButtonComponents, lc = ref.lc, imageURLPrefix = ref.imageURLPrefix; return div({ className: 'lc-picker-contents' }, toolButtonComponents.map((function(_this) { return function(component, ix) { return component({ lc: lc, imageURLPrefix: imageURLPrefix, key: ix, isSelected: ix === _this.state.selectedToolIndex, onSelect: function(tool) { lc.setTool(tool); return _this.setState({ selectedToolIndex: ix }); } }); }; })(this)), toolButtonComponents.length % 2 !== 0 ? div({ className: 'toolbar-button thin-button disabled' }) : void 0, div({ style: { position: 'absolute', bottom: 0, left: 0, right: 0 } }, ColorPickers({ lc: this.props.lc }), UndoRedoButtons({ lc: lc, imageURLPrefix: imageURLPrefix }), ZoomButtons({ lc: lc, imageURLPrefix: imageURLPrefix }), ClearButton({ lc: lc }))); }, render: function() { var div; div = React.DOM.div; return div({ className: 'lc-picker' }, this.renderBody()); } }); module.exports = Picker; },{"../core/localization":13,"./ClearButton":30,"./ColorWell":31,"./React-shim":35,"./UndoRedoButtons":38,"./ZoomButtons":39}],35:[function(require,module,exports){ var React, error; try { React = require('react'); } catch (error) { React = window.React; } if (React == null) { throw "Can't find React"; } module.exports = React; },{"react":"react"}],36:[function(require,module,exports){ var ReactDOM, error, error1; try { ReactDOM = require('react-dom'); } catch (error) { ReactDOM = window.ReactDOM; } if (ReactDOM == null) { try { ReactDOM = require('react'); } catch (error1) { ReactDOM = window.React; } } if (ReactDOM == null) { throw "Can't find ReactDOM"; } module.exports = ReactDOM; },{"react":"react","react-dom":"react-dom"}],37:[function(require,module,exports){ var React, classSet, createSetStateOnEventMixin; React = require('./React-shim'); createSetStateOnEventMixin = require('../reactGUI/createSetStateOnEventMixin'); classSet = require('../core/util').classSet; module.exports = React.createClass({ displayName: 'StrokeWidthPicker', getState: function(tool) { if (tool == null) { tool = this.props.tool; } return { strokeWidth: tool.strokeWidth }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('toolDidUpdateOptions')], componentWillReceiveProps: function(props) { return this.setState(this.getState(props.tool)); }, render: function() { var circle, div, li, ref, strokeWidths, svg, ul; ref = React.DOM, ul = ref.ul, li = ref.li, svg = ref.svg, circle = ref.circle, div = ref.div; strokeWidths = this.props.lc.opts.strokeWidths; return div({}, strokeWidths.map((function(_this) { return function(strokeWidth, ix) { var buttonClassName, buttonSize; buttonClassName = classSet({ 'square-toolbar-button': true, 'selected': strokeWidth === _this.state.strokeWidth }); buttonSize = 28; return div({ key: strokeWidth }, div({ className: buttonClassName, onClick: function() { return _this.props.lc.trigger('setStrokeWidth', strokeWidth); } }, svg({ width: buttonSize - 2, height: buttonSize - 2, viewPort: "0 0 " + strokeWidth + " " + strokeWidth, version: "1.1", xmlns: "http://www.w3.org/2000/svg" }, circle({ cx: Math.ceil(buttonSize / 2 - 1), cy: Math.ceil(buttonSize / 2 - 1), r: strokeWidth / 2 })))); }; })(this))); } }); },{"../core/util":19,"../reactGUI/createSetStateOnEventMixin":40,"./React-shim":35}],38:[function(require,module,exports){ var React, RedoButton, UndoButton, UndoRedoButtons, classSet, createSetStateOnEventMixin, createUndoRedoButtonComponent; React = require('./React-shim'); createSetStateOnEventMixin = require('./createSetStateOnEventMixin'); classSet = require('../core/util').classSet; createUndoRedoButtonComponent = function(undoOrRedo) { return React.createClass({ displayName: undoOrRedo === 'undo' ? 'UndoButton' : 'RedoButton', getState: function() { return { isEnabled: (function() { switch (false) { case undoOrRedo !== 'undo': return this.props.lc.canUndo(); case undoOrRedo !== 'redo': return this.props.lc.canRedo(); } }).call(this) }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('drawingChange')], render: function() { var className, div, imageURLPrefix, img, lc, onClick, ref, ref1, src, style, title; ref = React.DOM, div = ref.div, img = ref.img; ref1 = this.props, lc = ref1.lc, imageURLPrefix = ref1.imageURLPrefix; title = undoOrRedo === 'undo' ? 'Undo' : 'Redo'; className = ("lc-" + undoOrRedo + " ") + classSet({ 'toolbar-button': true, 'thin-button': true, 'disabled': !this.state.isEnabled }); onClick = (function() { switch (false) { case !!this.state.isEnabled: return function() {}; case undoOrRedo !== 'undo': return function() { return lc.undo(); }; case undoOrRedo !== 'redo': return function() { return lc.redo(); }; } }).call(this); src = imageURLPrefix + "/" + undoOrRedo + ".png"; style = { backgroundImage: "url(" + src + ")" }; return div({ className: className, onClick: onClick, title: title, style: style }); } }); }; UndoButton = React.createFactory(createUndoRedoButtonComponent('undo')); RedoButton = React.createFactory(createUndoRedoButtonComponent('redo')); UndoRedoButtons = React.createClass({ displayName: 'UndoRedoButtons', render: function() { var div; div = React.DOM.div; return div({ className: 'lc-undo-redo' }, UndoButton(this.props), RedoButton(this.props)); } }); module.exports = UndoRedoButtons; },{"../core/util":19,"./React-shim":35,"./createSetStateOnEventMixin":40}],39:[function(require,module,exports){ var React, ZoomButtons, ZoomInButton, ZoomOutButton, classSet, createSetStateOnEventMixin, createZoomButtonComponent; React = require('./React-shim'); createSetStateOnEventMixin = require('./createSetStateOnEventMixin'); classSet = require('../core/util').classSet; createZoomButtonComponent = function(inOrOut) { return React.createClass({ displayName: inOrOut === 'in' ? 'ZoomInButton' : 'ZoomOutButton', getState: function() { return { isEnabled: (function() { switch (false) { case inOrOut !== 'in': return this.props.lc.scale < this.props.lc.config.zoomMax; case inOrOut !== 'out': return this.props.lc.scale > this.props.lc.config.zoomMin; } }).call(this) }; }, getInitialState: function() { return this.getState(); }, mixins: [createSetStateOnEventMixin('zoom')], render: function() { var className, div, imageURLPrefix, img, lc, onClick, ref, ref1, src, style, title; ref = React.DOM, div = ref.div, img = ref.img; ref1 = this.props, lc = ref1.lc, imageURLPrefix = ref1.imageURLPrefix; title = inOrOut === 'in' ? 'Zoom in' : 'Zoom out'; className = ("lc-zoom-" + inOrOut + " ") + classSet({ 'toolbar-button': true, 'thin-button': true, 'disabled': !this.state.isEnabled }); onClick = (function() { switch (false) { case !!this.state.isEnabled: return function() {}; case inOrOut !== 'in': return function() { return lc.zoom(lc.config.zoomStep); }; case inOrOut !== 'out': return function() { return lc.zoom(-lc.config.zoomStep); }; } }).call(this); src = imageURLPrefix + "/zoom-" + inOrOut + ".png"; style = { backgroundImage: "url(" + src + ")" }; return div({ className: className, onClick: onClick, title: title, style: style }); } }); }; ZoomOutButton = React.createFactory(createZoomButtonComponent('out')); ZoomInButton = React.createFactory(createZoomButtonComponent('in')); ZoomButtons = React.createClass({ displayName: 'ZoomButtons', render: function() { var div; div = React.DOM.div; return div({ className: 'lc-zoom' }, ZoomOutButton(this.props), ZoomInButton(this.props)); } }); module.exports = ZoomButtons; },{"../core/util":19,"./React-shim":35,"./createSetStateOnEventMixin":40}],40:[function(require,module,exports){ var React, createSetStateOnEventMixin; React = require('./React-shim'); module.exports = createSetStateOnEventMixin = function(eventName) { return { componentDidMount: function() { return this.unsubscribe = this.props.lc.on(eventName, (function(_this) { return function() { return _this.setState(_this.getState()); }; })(this)); }, componentWillUnmount: function() { return this.unsubscribe(); } }; }; },{"./React-shim":35}],41:[function(require,module,exports){ var React, _, classSet, createToolButton; React = require('./React-shim'); classSet = require('../core/util').classSet; _ = require('../core/localization')._; createToolButton = function(tool) { var displayName, imageName; displayName = tool.name; imageName = tool.iconName; return React.createFactory(React.createClass({ displayName: displayName, getDefaultProps: function() { return { isSelected: false, lc: null }; }, componentWillMount: function() { if (this.props.isSelected) { return this.props.lc.setTool(tool); } }, render: function() { var className, div, imageURLPrefix, img, isSelected, onSelect, ref, ref1, src; ref = React.DOM, div = ref.div, img = ref.img; ref1 = this.props, imageURLPrefix = ref1.imageURLPrefix, isSelected = ref1.isSelected, onSelect = ref1.onSelect; className = classSet({ 'lc-pick-tool': true, 'toolbar-button': true, 'thin-button': true, 'selected': isSelected }); src = imageURLPrefix + "/" + imageName + ".png"; return div({ className: className, style: { 'backgroundImage': "url(" + src + ")" }, onClick: (function() { return onSelect(tool); }), title: _(displayName) }); } })); }; module.exports = createToolButton; },{"../core/localization":13,"../core/util":19,"./React-shim":35}],42:[function(require,module,exports){ 'use strict'; var React = require('./React-shim'); var ReactDOM = require('./ReactDOM-shim'); var LiterallyCanvasModel = require('../core/LiterallyCanvas'); var LiterallyCanvasReactComponent = require('./LiterallyCanvas'); function init(el, opts) { var originalClassName = el.className; var lc = new LiterallyCanvasModel(opts); ReactDOM.render(React.createElement(LiterallyCanvasReactComponent, { lc: lc }), el); lc.teardown = function () { lc._teardown(); for (var i = 0; i < el.children.length; i++) { el.removeChild(el.children[i]); } el.className = originalClassName; }; return lc; } module.exports = init; },{"../core/LiterallyCanvas":5,"./LiterallyCanvas":32,"./React-shim":35,"./ReactDOM-shim":36}],43:[function(require,module,exports){ var Ellipse, ToolWithStroke, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ToolWithStroke = require('./base').ToolWithStroke; createShape = require('../core/shapes').createShape; module.exports = Ellipse = (function(superClass) { extend(Ellipse, superClass); function Ellipse() { return Ellipse.__super__.constructor.apply(this, arguments); } Ellipse.prototype.name = 'Ellipse'; Ellipse.prototype.iconName = 'ellipse'; Ellipse.prototype.begin = function(x, y, lc) { return this.currentShape = createShape('Ellipse', { x: x, y: y, strokeWidth: this.strokeWidth, strokeColor: lc.getColor('primary'), fillColor: lc.getColor('secondary') }); }; Ellipse.prototype["continue"] = function(x, y, lc) { this.currentShape.width = x - this.currentShape.x; this.currentShape.height = y - this.currentShape.y; return lc.drawShapeInProgress(this.currentShape); }; Ellipse.prototype.end = function(x, y, lc) { return lc.saveShape(this.currentShape); }; return Ellipse; })(ToolWithStroke); },{"../core/shapes":17,"./base":53}],44:[function(require,module,exports){ var Eraser, Pencil, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Pencil = require('./Pencil'); createShape = require('../core/shapes').createShape; module.exports = Eraser = (function(superClass) { extend(Eraser, superClass); function Eraser() { return Eraser.__super__.constructor.apply(this, arguments); } Eraser.prototype.name = 'Eraser'; Eraser.prototype.iconName = 'eraser'; Eraser.prototype.makePoint = function(x, y, lc) { return createShape('Point', { x: x, y: y, size: this.strokeWidth, color: '#000' }); }; Eraser.prototype.makeShape = function() { return createShape('ErasedLinePath'); }; return Eraser; })(Pencil); },{"../core/shapes":17,"./Pencil":48}],45:[function(require,module,exports){ var Eyedropper, Tool, getPixel, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Tool = require('./base').Tool; getPixel = function(ctx, arg) { var pixel, x, y; x = arg.x, y = arg.y; pixel = ctx.getImageData(x, y, 1, 1).data; if (pixel[3]) { return "rgb(" + pixel[0] + ", " + pixel[1] + ", " + pixel[2] + ")"; } else { return null; } }; module.exports = Eyedropper = (function(superClass) { extend(Eyedropper, superClass); Eyedropper.prototype.name = 'Eyedropper'; Eyedropper.prototype.iconName = 'eyedropper'; Eyedropper.prototype.optionsStyle = 'stroke-or-fill'; function Eyedropper(lc) { Eyedropper.__super__.constructor.call(this, lc); this.strokeOrFill = 'stroke'; } Eyedropper.prototype.readColor = function(x, y, lc) { var canvas, color, newColor, offset; offset = lc.getDefaultImageRect(); canvas = lc.getImage(); newColor = getPixel(canvas.getContext('2d'), { x: x - offset.x, y: y - offset.y }); color = newColor || lc.getColor('background'); if (this.strokeOrFill === 'stroke') { return lc.setColor('primary', newColor); } else { return lc.setColor('secondary', newColor); } }; Eyedropper.prototype.begin = function(x, y, lc) { return this.readColor(x, y, lc); }; Eyedropper.prototype["continue"] = function(x, y, lc) { return this.readColor(x, y, lc); }; return Eyedropper; })(Tool); },{"./base":53}],46:[function(require,module,exports){ var Line, ToolWithStroke, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ToolWithStroke = require('./base').ToolWithStroke; createShape = require('../core/shapes').createShape; module.exports = Line = (function(superClass) { extend(Line, superClass); function Line() { return Line.__super__.constructor.apply(this, arguments); } Line.prototype.name = 'Line'; Line.prototype.iconName = 'line'; Line.prototype.optionsStyle = 'line-options-and-stroke-width'; Line.prototype.begin = function(x, y, lc) { return this.currentShape = createShape('Line', { x1: x, y1: y, x2: x, y2: y, strokeWidth: this.strokeWidth, dash: (function() { switch (false) { case !this.isDashed: return [this.strokeWidth * 2, this.strokeWidth * 4]; default: return null; } }).call(this), endCapShapes: this.hasEndArrow ? [null, 'arrow'] : null, color: lc.getColor('primary') }); }; Line.prototype["continue"] = function(x, y, lc) { this.currentShape.x2 = x; this.currentShape.y2 = y; return lc.drawShapeInProgress(this.currentShape); }; Line.prototype.end = function(x, y, lc) { return lc.saveShape(this.currentShape); }; return Line; })(ToolWithStroke); },{"../core/shapes":17,"./base":53}],47:[function(require,module,exports){ var Pan, Tool, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Tool = require('./base').Tool; createShape = require('../core/shapes').createShape; module.exports = Pan = (function(superClass) { extend(Pan, superClass); function Pan() { return Pan.__super__.constructor.apply(this, arguments); } Pan.prototype.name = 'Pan'; Pan.prototype.iconName = 'pan'; Pan.prototype.usesSimpleAPI = false; Pan.prototype.didBecomeActive = function(lc) { var unsubscribeFuncs; unsubscribeFuncs = []; this.unsubscribe = (function(_this) { return function() { var func, i, len, results; results = []; for (i = 0, len = unsubscribeFuncs.length; i < len; i++) { func = unsubscribeFuncs[i]; results.push(func()); } return results; }; })(this); unsubscribeFuncs.push(lc.on('lc-pointerdown', (function(_this) { return function(arg) { var rawX, rawY; rawX = arg.rawX, rawY = arg.rawY; _this.oldPosition = lc.position; return _this.pointerStart = { x: rawX, y: rawY }; }; })(this))); return unsubscribeFuncs.push(lc.on('lc-pointerdrag', (function(_this) { return function(arg) { var dp, rawX, rawY; rawX = arg.rawX, rawY = arg.rawY; dp = { x: (rawX - _this.pointerStart.x) * lc.backingScale, y: (rawY - _this.pointerStart.y) * lc.backingScale }; return lc.setPan(_this.oldPosition.x + dp.x, _this.oldPosition.y + dp.y); }; })(this))); }; Pan.prototype.willBecomeInactive = function(lc) { return this.unsubscribe(); }; return Pan; })(Tool); },{"../core/shapes":17,"./base":53}],48:[function(require,module,exports){ var Pencil, ToolWithStroke, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ToolWithStroke = require('./base').ToolWithStroke; createShape = require('../core/shapes').createShape; module.exports = Pencil = (function(superClass) { extend(Pencil, superClass); function Pencil() { return Pencil.__super__.constructor.apply(this, arguments); } Pencil.prototype.name = 'Pencil'; Pencil.prototype.iconName = 'pencil'; Pencil.prototype.eventTimeThreshold = 10; Pencil.prototype.begin = function(x, y, lc) { this.color = lc.getColor('primary'); this.currentShape = this.makeShape(); this.currentShape.addPoint(this.makePoint(x, y, lc)); return this.lastEventTime = Date.now(); }; Pencil.prototype["continue"] = function(x, y, lc) { var timeDiff; timeDiff = Date.now() - this.lastEventTime; if (timeDiff > this.eventTimeThreshold) { this.lastEventTime += timeDiff; this.currentShape.addPoint(this.makePoint(x, y, lc)); return lc.drawShapeInProgress(this.currentShape); } }; Pencil.prototype.end = function(x, y, lc) { lc.saveShape(this.currentShape); return this.currentShape = void 0; }; Pencil.prototype.makePoint = function(x, y, lc) { return createShape('Point', { x: x, y: y, size: this.strokeWidth, color: this.color }); }; Pencil.prototype.makeShape = function() { return createShape('LinePath'); }; return Pencil; })(ToolWithStroke); },{"../core/shapes":17,"./base":53}],49:[function(require,module,exports){ var Polygon, ToolWithStroke, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ToolWithStroke = require('./base').ToolWithStroke; createShape = require('../core/shapes').createShape; module.exports = Polygon = (function(superClass) { extend(Polygon, superClass); function Polygon() { return Polygon.__super__.constructor.apply(this, arguments); } Polygon.prototype.name = 'Polygon'; Polygon.prototype.iconName = 'polygon'; Polygon.prototype.usesSimpleAPI = false; Polygon.prototype.didBecomeActive = function(lc) { var onDown, onMove, onUp, polygonCancel, polygonFinishClosed, polygonFinishOpen, polygonUnsubscribeFuncs; Polygon.__super__.didBecomeActive.call(this, lc); polygonUnsubscribeFuncs = []; this.polygonUnsubscribe = (function(_this) { return function() { var func, i, len, results; results = []; for (i = 0, len = polygonUnsubscribeFuncs.length; i < len; i++) { func = polygonUnsubscribeFuncs[i]; results.push(func()); } return results; }; })(this); this.points = null; this.maybePoint = null; onUp = (function(_this) { return function() { if (_this._getWillFinish()) { return _this._close(lc); } lc.trigger('lc-polygon-started'); if (_this.points) { _this.points.push(_this.maybePoint); } else { _this.points = [_this.maybePoint]; } _this.maybePoint = { x: _this.maybePoint.x, y: _this.maybePoint.y }; lc.setShapesInProgress(_this._getShapes(lc)); return lc.repaintLayer('main'); }; })(this); onMove = (function(_this) { return function(arg) { var x, y; x = arg.x, y = arg.y; if (_this.maybePoint) { _this.maybePoint.x = x; _this.maybePoint.y = y; lc.setShapesInProgress(_this._getShapes(lc)); return lc.repaintLayer('main'); } }; })(this); onDown = (function(_this) { return function(arg) { var x, y; x = arg.x, y = arg.y; _this.maybePoint = { x: x, y: y }; lc.setShapesInProgress(_this._getShapes(lc)); return lc.repaintLayer('main'); }; })(this); polygonFinishOpen = (function(_this) { return function() { _this.maybePoint = { x: Infinity, y: Infinity }; return _this._close(lc); }; })(this); polygonFinishClosed = (function(_this) { return function() { _this.maybePoint = _this.points[0]; return _this._close(lc); }; })(this); polygonCancel = (function(_this) { return function() { return _this._cancel(lc); }; })(this); polygonUnsubscribeFuncs.push(lc.on('drawingChange', (function(_this) { return function() { return _this._cancel(lc); }; })(this))); polygonUnsubscribeFuncs.push(lc.on('lc-pointerdown', onDown)); polygonUnsubscribeFuncs.push(lc.on('lc-pointerdrag', onMove)); polygonUnsubscribeFuncs.push(lc.on('lc-pointermove', onMove)); polygonUnsubscribeFuncs.push(lc.on('lc-pointerup', onUp)); polygonUnsubscribeFuncs.push(lc.on('lc-polygon-finishopen', polygonFinishOpen)); polygonUnsubscribeFuncs.push(lc.on('lc-polygon-finishclosed', polygonFinishClosed)); return polygonUnsubscribeFuncs.push(lc.on('lc-polygon-cancel', polygonCancel)); }; Polygon.prototype.willBecomeInactive = function(lc) { Polygon.__super__.willBecomeInactive.call(this, lc); if (this.points || this.maybePoint) { this._cancel(lc); } return this.polygonUnsubscribe(); }; Polygon.prototype._getArePointsClose = function(a, b) { return (Math.abs(a.x - b.x) + Math.abs(a.y - b.y)) < 10; }; Polygon.prototype._getWillClose = function() { if (!(this.points && this.points.length > 1)) { return false; } if (!this.maybePoint) { return false; } return this._getArePointsClose(this.points[0], this.maybePoint); }; Polygon.prototype._getWillFinish = function() { if (!(this.points && this.points.length > 1)) { return false; } if (!this.maybePoint) { return false; } return this._getArePointsClose(this.points[0], this.maybePoint) || this._getArePointsClose(this.points[this.points.length - 1], this.maybePoint); }; Polygon.prototype._cancel = function(lc) { lc.trigger('lc-polygon-stopped'); this.maybePoint = null; this.points = null; lc.setShapesInProgress([]); return lc.repaintLayer('main'); }; Polygon.prototype._close = function(lc) { lc.trigger('lc-polygon-stopped'); lc.setShapesInProgress([]); if (this.points.length > 2) { lc.saveShape(this._getShape(lc, false)); } this.maybePoint = null; return this.points = null; }; Polygon.prototype._getShapes = function(lc, isInProgress) { var shape; if (isInProgress == null) { isInProgress = true; } shape = this._getShape(lc, isInProgress); if (shape) { return [shape]; } else { return []; } }; Polygon.prototype._getShape = function(lc, isInProgress) { var points; if (isInProgress == null) { isInProgress = true; } points = []; if (this.points) { points = points.concat(this.points); } if ((!isInProgress) && points.length < 3) { return null; } if (isInProgress && this.maybePoint) { points.push(this.maybePoint); } if (points.length > 1) { return createShape('Polygon', { isClosed: this._getWillClose(), strokeColor: lc.getColor('primary'), fillColor: lc.getColor('secondary'), strokeWidth: this.strokeWidth, points: points.map(function(xy) { return createShape('Point', xy); }) }); } else { return null; } }; Polygon.prototype.optionsStyle = 'polygon-and-stroke-width'; return Polygon; })(ToolWithStroke); },{"../core/shapes":17,"./base":53}],50:[function(require,module,exports){ var Rectangle, ToolWithStroke, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; ToolWithStroke = require('./base').ToolWithStroke; createShape = require('../core/shapes').createShape; module.exports = Rectangle = (function(superClass) { extend(Rectangle, superClass); function Rectangle() { return Rectangle.__super__.constructor.apply(this, arguments); } Rectangle.prototype.name = 'Rectangle'; Rectangle.prototype.iconName = 'rectangle'; Rectangle.prototype.begin = function(x, y, lc) { return this.currentShape = createShape('Rectangle', { x: x, y: y, strokeWidth: this.strokeWidth, strokeColor: lc.getColor('primary'), fillColor: lc.getColor('secondary') }); }; Rectangle.prototype["continue"] = function(x, y, lc) { this.currentShape.width = x - this.currentShape.x; this.currentShape.height = y - this.currentShape.y; return lc.drawShapeInProgress(this.currentShape); }; Rectangle.prototype.end = function(x, y, lc) { return lc.saveShape(this.currentShape); }; return Rectangle; })(ToolWithStroke); },{"../core/shapes":17,"./base":53}],51:[function(require,module,exports){ var SelectShape, Tool, createShape, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Tool = require('./base').Tool; createShape = require('../core/shapes').createShape; module.exports = SelectShape = (function(superClass) { extend(SelectShape, superClass); SelectShape.prototype.name = 'SelectShape'; SelectShape.prototype.usesSimpleAPI = false; function SelectShape(lc) { this.selectCanvas = document.createElement('canvas'); this.selectCanvas.style['background-color'] = 'transparent'; this.selectCtx = this.selectCanvas.getContext('2d'); } SelectShape.prototype.didBecomeActive = function(lc) { var onDown, onDrag, onUp, selectShapeUnsubscribeFuncs; selectShapeUnsubscribeFuncs = []; this._selectShapeUnsubscribe = (function(_this) { return function() { var func, j, len, results; results = []; for (j = 0, len = selectShapeUnsubscribeFuncs.length; j < len; j++) { func = selectShapeUnsubscribeFuncs[j]; results.push(func()); } return results; }; })(this); onDown = (function(_this) { return function(arg) { var br, shapeIndex, x, y; x = arg.x, y = arg.y; _this.didDrag = false; shapeIndex = _this._getPixel(x, y, lc, _this.selectCtx); _this.selectedShape = lc.shapes[shapeIndex]; if (_this.selectedShape != null) { lc.trigger('shapeSelected', { selectedShape: _this.selectedShape }); lc.setShapesInProgress([ _this.selectedShape, createShape('SelectionBox', { shape: _this.selectedShape, handleSize: 0 }) ]); lc.repaintLayer('main'); br = _this.selectedShape.getBoundingRect(); return _this.dragOffset = { x: x - br.x, y: y - br.y }; } }; })(this); onDrag = (function(_this) { return function(arg) { var x, y; x = arg.x, y = arg.y; if (_this.selectedShape != null) { _this.didDrag = true; _this.selectedShape.setUpperLeft({ x: x - _this.dragOffset.x, y: y - _this.dragOffset.y }); lc.setShapesInProgress([ _this.selectedShape, createShape('SelectionBox', { shape: _this.selectedShape, handleSize: 0 }) ]); return lc.repaintLayer('main'); } }; })(this); onUp = (function(_this) { return function(arg) { var x, y; x = arg.x, y = arg.y; if (_this.didDrag) { _this.didDrag = false; lc.trigger('shapeMoved', { shape: _this.selectedShape }); lc.trigger('drawingChange', {}); lc.repaintLayer('main'); return _this._drawSelectCanvas(lc); } }; })(this); selectShapeUnsubscribeFuncs.push(lc.on('lc-pointerdown', onDown)); selectShapeUnsubscribeFuncs.push(lc.on('lc-pointerdrag', onDrag)); selectShapeUnsubscribeFuncs.push(lc.on('lc-pointerup', onUp)); return this._drawSelectCanvas(lc); }; SelectShape.prototype.willBecomeInactive = function(lc) { this._selectShapeUnsubscribe(); return lc.setShapesInProgress([]); }; SelectShape.prototype._drawSelectCanvas = function(lc) { var shapes; this.selectCanvas.width = lc.canvas.width; this.selectCanvas.height = lc.canvas.height; this.selectCtx.clearRect(0, 0, this.selectCanvas.width, this.selectCanvas.height); shapes = lc.shapes.map((function(_this) { return function(shape, index) { return createShape('SelectionBox', { shape: shape, handleSize: 0, backgroundColor: "#" + (_this._intToHex(index)) }); }; })(this)); return lc.draw(shapes, this.selectCtx); }; SelectShape.prototype._intToHex = function(i) { return ("000000" + (i.toString(16))).slice(-6); }; SelectShape.prototype._getPixel = function(x, y, lc, ctx) { var p, pixel; p = lc.drawingCoordsToClientCoords(x, y); pixel = ctx.getImageData(p.x, p.y, 1, 1).data; if (pixel[3]) { return parseInt(this._rgbToHex(pixel[0], pixel[1], pixel[2]), 16); } else { return null; } }; SelectShape.prototype._componentToHex = function(c) { var hex; hex = c.toString(16); return ("0" + hex).slice(-2); }; SelectShape.prototype._rgbToHex = function(r, g, b) { return "" + (this._componentToHex(r)) + (this._componentToHex(g)) + (this._componentToHex(b)); }; return SelectShape; })(Tool); },{"../core/shapes":17,"./base":53}],52:[function(require,module,exports){ var Text, Tool, createShape, getIsPointInBox, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Tool = require('./base').Tool; createShape = require('../core/shapes').createShape; getIsPointInBox = function(point, box) { if (point.x < box.x) { return false; } if (point.y < box.y) { return false; } if (point.x > box.x + box.width) { return false; } if (point.y > box.y + box.height) { return false; } return true; }; module.exports = Text = (function(superClass) { extend(Text, superClass); Text.prototype.name = 'Text'; Text.prototype.iconName = 'text'; function Text() { this.text = ''; this.font = 'bold 18px sans-serif'; this.currentShape = null; this.currentShapeState = null; this.initialShapeBoundingRect = null; this.dragAction = null; this.didDrag = false; } Text.prototype.didBecomeActive = function(lc) { var switchAway, unsubscribeFuncs, updateInputEl; unsubscribeFuncs = []; this.unsubscribe = (function(_this) { return function() { var func, i, len, results; results = []; for (i = 0, len = unsubscribeFuncs.length; i < len; i++) { func = unsubscribeFuncs[i]; results.push(func()); } return results; }; })(this); switchAway = (function(_this) { return function() { _this._ensureNotEditing(lc); _this._clearCurrentShape(lc); return lc.repaintLayer('main'); }; })(this); updateInputEl = (function(_this) { return function() { return _this._updateInputEl(lc); }; })(this); unsubscribeFuncs.push(lc.on('drawingChange', switchAway)); unsubscribeFuncs.push(lc.on('zoom', updateInputEl)); unsubscribeFuncs.push(lc.on('imageSizeChange', updateInputEl)); unsubscribeFuncs.push(lc.on('snapshotLoad', (function(_this) { return function() { _this._clearCurrentShape(lc); return lc.repaintLayer('main'); }; })(this))); unsubscribeFuncs.push(lc.on('primaryColorChange', (function(_this) { return function(newColor) { if (!_this.currentShape) { return; } _this.currentShape.color = newColor; _this._updateInputEl(lc); return lc.repaintLayer('main'); }; })(this))); return unsubscribeFuncs.push(lc.on('setFont', (function(_this) { return function(font) { if (!_this.currentShape) { return; } _this.font = font; _this.currentShape.setFont(font); _this._setShapesInProgress(lc); _this._updateInputEl(lc); return lc.repaintLayer('main'); }; })(this))); }; Text.prototype.willBecomeInactive = function(lc) { if (this.currentShape) { this._ensureNotEditing(lc); this.commit(lc); } return this.unsubscribe(); }; Text.prototype.setText = function(text) { return this.text = text; }; Text.prototype._ensureNotEditing = function(lc) { if (this.currentShapeState === 'editing') { return this._exitEditingState(lc); } }; Text.prototype._clearCurrentShape = function(lc) { this.currentShape = null; this.initialShapeBoundingRect = null; this.currentShapeState = null; return lc.setShapesInProgress([]); }; Text.prototype.commit = function(lc) { if (this.currentShape.text) { lc.saveShape(this.currentShape); } this._clearCurrentShape(lc); return lc.repaintLayer('main'); }; Text.prototype._getSelectionShape = function(ctx, backgroundColor) { if (backgroundColor == null) { backgroundColor = null; } return createShape('SelectionBox', { shape: this.currentShape, ctx: ctx, backgroundColor: backgroundColor }); }; Text.prototype._setShapesInProgress = function(lc) { switch (this.currentShapeState) { case 'selected': return lc.setShapesInProgress([this._getSelectionShape(lc.ctx), this.currentShape]); case 'editing': return lc.setShapesInProgress([this._getSelectionShape(lc.ctx, '#fff')]); default: return lc.setShapesInProgress([this.currentShape]); } }; Text.prototype.begin = function(x, y, lc) { var br, point, selectionBox, selectionShape; this.dragAction = 'none'; this.didDrag = false; if (this.currentShapeState === 'selected' || this.currentShapeState === 'editing') { br = this.currentShape.getBoundingRect(lc.ctx); selectionShape = this._getSelectionShape(lc.ctx); selectionBox = selectionShape.getBoundingRect(); point = { x: x, y: y }; if (getIsPointInBox(point, br)) { this.dragAction = 'move'; } if (getIsPointInBox(point, selectionShape.getBottomRightHandleRect())) { this.dragAction = 'resizeBottomRight'; } if (getIsPointInBox(point, selectionShape.getTopLeftHandleRect())) { this.dragAction = 'resizeTopLeft'; } if (getIsPointInBox(point, selectionShape.getBottomLeftHandleRect())) { this.dragAction = 'resizeBottomLeft'; } if (getIsPointInBox(point, selectionShape.getTopRightHandleRect())) { this.dragAction = 'resizeTopRight'; } if (this.dragAction === 'none' && this.currentShapeState === 'editing') { this.dragAction = 'stop-editing'; this._exitEditingState(lc); } } else { this.color = lc.getColor('primary'); this.currentShape = createShape('Text', { x: x, y: y, text: this.text, color: this.color, font: this.font, v: 1 }); this.dragAction = 'place'; this.currentShapeState = 'selected'; } if (this.dragAction === 'none') { this.commit(lc); return; } this.initialShapeBoundingRect = this.currentShape.getBoundingRect(lc.ctx); this.dragOffset = { x: x - this.initialShapeBoundingRect.x, y: y - this.initialShapeBoundingRect.y }; this._setShapesInProgress(lc); return lc.repaintLayer('main'); }; Text.prototype["continue"] = function(x, y, lc) { var br, brBottom, brRight; if (this.dragAction === 'none') { return; } br = this.initialShapeBoundingRect; brRight = br.x + br.width; brBottom = br.y + br.height; switch (this.dragAction) { case 'place': this.currentShape.x = x; this.currentShape.y = y; this.didDrag = true; break; case 'move': this.currentShape.x = x - this.dragOffset.x; this.currentShape.y = y - this.dragOffset.y; this.didDrag = true; break; case 'resizeBottomRight': this.currentShape.setSize(x - (this.dragOffset.x - this.initialShapeBoundingRect.width) - br.x, y - (this.dragOffset.y - this.initialShapeBoundingRect.height) - br.y); break; case 'resizeTopLeft': this.currentShape.setSize(brRight - x + this.dragOffset.x, brBottom - y + this.dragOffset.y); this.currentShape.setPosition(x - this.dragOffset.x, y - this.dragOffset.y); break; case 'resizeBottomLeft': this.currentShape.setSize(brRight - x + this.dragOffset.x, y - (this.dragOffset.y - this.initialShapeBoundingRect.height) - br.y); this.currentShape.setPosition(x - this.dragOffset.x, this.currentShape.y); break; case 'resizeTopRight': this.currentShape.setSize(x - (this.dragOffset.x - this.initialShapeBoundingRect.width) - br.x, brBottom - y + this.dragOffset.y); this.currentShape.setPosition(this.currentShape.x, y - this.dragOffset.y); } this._setShapesInProgress(lc); lc.repaintLayer('main'); return this._updateInputEl(lc); }; Text.prototype.end = function(x, y, lc) { if (!this.currentShape) { return; } this.currentShape.setSize(this.currentShape.forcedWidth, 0); if (this.currentShapeState === 'selected') { if (this.dragAction === 'place' || (this.dragAction === 'move' && !this.didDrag)) { this._enterEditingState(lc); } } this._setShapesInProgress(lc); lc.repaintLayer('main'); return this._updateInputEl(lc); }; Text.prototype._enterEditingState = function(lc) { var onChange; this.currentShapeState = 'editing'; if (this.inputEl) { throw "State error"; } this.inputEl = document.createElement('textarea'); this.inputEl.className = 'text-tool-input'; this.inputEl.style.position = 'absolute'; this.inputEl.style.transformOrigin = '0px 0px'; this.inputEl.style.backgroundColor = 'transparent'; this.inputEl.style.border = 'none'; this.inputEl.style.outline = 'none'; this.inputEl.style.margin = '0'; this.inputEl.style.padding = '4px'; this.inputEl.style.zIndex = '1000'; this.inputEl.style.overflow = 'hidden'; this.inputEl.style.resize = 'none'; this.inputEl.value = this.currentShape.text; this.inputEl.addEventListener('mousedown', function(e) { return e.stopPropagation(); }); this.inputEl.addEventListener('touchstart', function(e) { return e.stopPropagation(); }); onChange = (function(_this) { return function(e) { _this.currentShape.setText(e.target.value); _this.currentShape.enforceMaxBoundingRect(lc); _this._setShapesInProgress(lc); lc.repaintLayer('main'); _this._updateInputEl(lc); return e.stopPropagation(); }; })(this); this.inputEl.addEventListener('keydown', (function(_this) { return function() { return _this._updateInputEl(lc, true); }; })(this)); this.inputEl.addEventListener('keyup', onChange); this.inputEl.addEventListener('change', onChange); this._updateInputEl(lc); lc.containerEl.appendChild(this.inputEl); this.inputEl.focus(); return this._setShapesInProgress(lc); }; Text.prototype._exitEditingState = function(lc) { this.currentShapeState = 'selected'; lc.containerEl.removeChild(this.inputEl); this.inputEl = null; this._setShapesInProgress(lc); return lc.repaintLayer('main'); }; Text.prototype._updateInputEl = function(lc, withMargin) { var br, transformString; if (withMargin == null) { withMargin = false; } if (!this.inputEl) { return; } br = this.currentShape.getBoundingRect(lc.ctx, true); this.inputEl.style.font = this.currentShape.font; this.inputEl.style.color = this.currentShape.color; this.inputEl.style.left = (lc.position.x / lc.backingScale + br.x * lc.scale - 4) + "px"; this.inputEl.style.top = (lc.position.y / lc.backingScale + br.y * lc.scale - 4) + "px"; if (withMargin && !this.currentShape.forcedWidth) { this.inputEl.style.width = (br.width + 10 + this.currentShape.renderer.emDashWidth) + "px"; } else { this.inputEl.style.width = (br.width + 12) + "px"; } if (withMargin) { this.inputEl.style.height = (br.height + 10 + this.currentShape.renderer.metrics.leading) + "px"; } else { this.inputEl.style.height = (br.height + 10) + "px"; } transformString = "scale(" + lc.scale + ")"; this.inputEl.style.transform = transformString; this.inputEl.style.webkitTransform = transformString; this.inputEl.style.MozTransform = transformString; this.inputEl.style.msTransform = transformString; return this.inputEl.style.OTransform = transformString; }; Text.prototype.optionsStyle = 'font'; return Text; })(Tool); },{"../core/shapes":17,"./base":53}],53:[function(require,module,exports){ var Tool, ToolWithStroke, tools, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; tools = {}; tools.Tool = Tool = (function() { function Tool() {} Tool.prototype.name = null; Tool.prototype.iconName = null; Tool.prototype.usesSimpleAPI = true; Tool.prototype.begin = function(x, y, lc) {}; Tool.prototype["continue"] = function(x, y, lc) {}; Tool.prototype.end = function(x, y, lc) {}; Tool.prototype.optionsStyle = null; Tool.prototype.didBecomeActive = function(lc) {}; Tool.prototype.willBecomeInactive = function(lc) {}; return Tool; })(); tools.ToolWithStroke = ToolWithStroke = (function(superClass) { extend(ToolWithStroke, superClass); function ToolWithStroke(lc) { this.strokeWidth = lc.opts.defaultStrokeWidth; } ToolWithStroke.prototype.optionsStyle = 'stroke-width'; ToolWithStroke.prototype.didBecomeActive = function(lc) { var unsubscribeFuncs; unsubscribeFuncs = []; this.unsubscribe = (function(_this) { return function() { var func, i, len, results; results = []; for (i = 0, len = unsubscribeFuncs.length; i < len; i++) { func = unsubscribeFuncs[i]; results.push(func()); } return results; }; })(this); return unsubscribeFuncs.push(lc.on('setStrokeWidth', (function(_this) { return function(strokeWidth) { _this.strokeWidth = strokeWidth; return lc.trigger('toolDidUpdateOptions'); }; })(this))); }; ToolWithStroke.prototype.willBecomeInactive = function(lc) { return this.unsubscribe(); }; return ToolWithStroke; })(Tool); module.exports = tools; },{}]},{},[22])(22) });
module.exports = { theme: require('@scaffold/cli/src/common/theme'), };
const mongoose = require("mongoose"); const User = mongoose.model( "User", new mongoose.Schema({ username: String, email: String, name: String, title: String, company: { type: mongoose.Schema.Types.ObjectId, ref: "Company" }, status:{ message: String, availability: { type: mongoose.Schema.Types.ObjectId, ref: "Availability" } }, password: String, roles: [ { type: mongoose.Schema.Types.ObjectId, ref: "Role" } ], style: { type: mongoose.Schema.Types.ObjectId, ref: "Style" }, image: String }) ); User.findAllUsers = async () => {return await User.find().select('-password').populate("status.availability style")}; module.exports = User;
// Representative is the person who fills the form. 'use strict'; var memoize = require('memoizee/plain') , defineBusinessProcess = require('./base') , definePerson = require('../person'); module.exports = memoize(function (db/*, options*/) { var options = Object(arguments[1]) , BusinessProcess = defineBusinessProcess(db, options) , Person = definePerson(db, options); BusinessProcess.prototype.define('representative', { type: Person, nested: true }); BusinessProcess.prototype.representative.setProperties({ email: function () { if (!this.master.user) { return; } return this.master.user.email; }, firstName: function (_observe) { if (!this.master.user) { return; } return _observe(this.master.user._firstName); }, lastName: function (_observe) { if (!this.master.user) { return; } return _observe(this.master.user._lastName); } }); return BusinessProcess; }, { normalizer: require('memoizee/normalizers/get-1')() });
import _ from 'lodash'; import React, { Component } from 'react'; import { BrowserRouter as Router, Route, Redirect } from 'react-router-dom'; import 'semantic-ui-css/semantic.min.css' import Index from './components'; import NewSeans from './components/NewSeans'; class RouterComp extends Component { constructor(props){ super(props); this.state = { } } render() { return ( <Router> <Route exact path="/" component={Index} /> <Route exact path="/newSeans" component={NewSeans} /> </Router> ) } } export default RouterComp;
import React from 'react'; import { connect } from 'react-redux'; import { ActionCreators as UndoActionCreators } from 'redux-undo'; import PropTypes from 'prop-types'; import Sortable from 'sortablejs'; // import fileDownload from 'react-file-download'; // Actions import { toggleMenu } from '../../actions/menu'; import { getSections, addSection, removeSection, sortSection, removeAllSections } from '../../actions/sections'; import { updateUser, getUser } from '../../actions/users' ; import { toggleAlert } from '../../actions/app' ; // Styles import styles from '../../styles/builder.scss'; import mainStyles from '../../styles/main.scss'; // Components import common from '../../services/common'; import Item from '../../components/Item'; import Settings from '../../components/Settings'; import Publish from '../../components/Publish'; // Libs import $ from 'jquery'; const mapStateToProps = (state) => { return { menu: state.menu, settings: state.users.settings, user: state.users, sections: state.sections, fullSections: state.sections.present.fullSections, containSections: state.sections.present.containSections, footerSections: state.sections.present.footerSections, canUndo: state.sections.past.length > 0, canRedo: state.sections.future.length > 0, canExport: state.sections.present.fullSections.length > 0 || state.sections.present.containSections.length > 0, canClear: state.sections.present.fullSections.length > 0 || state.sections.present.containSections.length > 0 }; }; const mapDispatchToProps = dispatch => { return { onToggleMenu: menu => dispatch(toggleMenu(menu)), onAddSection: (section, index, target) => dispatch(addSection(section, index, target)), onRemoveSection: (section, index, target) => dispatch(removeSection(section, index, target)), onSortSection: (newIndex, oldIndex, target) => dispatch(sortSection(newIndex, oldIndex, target)), onUpdateUser: (user) => dispatch(updateUser(user)), onRemoveAll: () => dispatch(removeAllSections()), onUndo: () => dispatch(UndoActionCreators.undo()), onRedo: () => dispatch(UndoActionCreators.redo()), onGetUser: (id) => dispatch(getUser(id)), onGetSections: (id) => dispatch(getSections(id)), onToggleAlert: () => dispatch(toggleAlert()) }; }; class Builder extends React.Component { constructor(props) { super(props); this.onAdd = this.onAdd.bind(this); this.onUpdate = this.onUpdate.bind(this); this.handleKeyDown = this.handleKeyDown.bind(this); this.onSaveAll = this.onSaveAll.bind(this); this.state = { url: window.location.href, copyText: 'Share', saveText: 'Save all', publishing: false }; } componentDidMount() { const full = document.getElementById('builderFull'); const contain = document.getElementById('builderContain'); const footer = document.getElementById('builderFooter'); Sortable.create(full, { group: { name: 'builderFull', put: 'items' }, onAdd: this.onAdd, onUpdate: this.onUpdate }); Sortable.create(contain, { group: { name: 'builderContain', put: 'items' }, onAdd: this.onAdd, onUpdate: this.onUpdate }); Sortable.create(footer, { group: { name: 'builderFooter', put: 'items' }, onAdd: this.onAdd, onUpdate: this.onUpdate }); const uid = this.props.params.uid; if (uid) { this.props.onGetUser(uid); this.props.onGetSections(uid); } document.addEventListener('keydown', this.handleKeyDown); } onSaveAll() { this.props.user.sections = this.props.sections.present; this.props.onUpdateUser(this.props.user); this.setState({ saveText: 'Saved.' }); setTimeout(() => { this.setState({saveText: 'Save all'}); }, 2000); } onExport() { // fileDownload('your content here!', 'index.html'); this.onSaveAll(); this.props.onToggleAlert(); // this.setState({ // publishing: true // }); } renderSections(sections) { const me = sections; if (me) { return me.map((s) => { const id = common.makeid(); return <Item key={id} section={s} />; }); } return ''; } handleKeyDown(event) { const charCode = String.fromCharCode(event.which).toLowerCase(); if ((event.ctrlKey || event.metaKey) && charCode === 'y') { if (this.props.canRedo) { this.props.onRedo(); } } else if ((event.ctrlKey || event.metaKey) && charCode === 'z') { if (this.props.canUndo) { this.props.onUndo(); } } } getTarget(id) { if (id === 'builderFull') { return 'fullSections'; } if (id === 'builderContain') { return 'containSections'; } return 'footerSections'; } onShare() { const url = window.location.href; this.setState({ url: url }); const input = document.getElementById('hiddenInput'); input.select(); document.execCommand('copy'); this.props.onToggleAlert(); } onUpdate(evt) { const listId = evt.to.getAttribute('id'); const target = this.getTarget(listId); this.props.onSortSection(evt.newIndex, evt.oldIndex, target); } onAdd(evt) { const id = $(evt.item).attr('data-id'); const sectionId = common.makeid(); const listId = evt.to.getAttribute('id'); const target = this.getTarget(listId); let section = null; this.props.menu.categories.map((c) => { c.items.map((s) => { if (String(s.id) === String(id)) { section = Object.assign({}, s); } }); }); section.sectionId = sectionId; this.props.onAddSection(section, evt.newIndex, target); $(evt.item).remove(); } showButton() { let el = null; if (!this.props.menu.showMenu) { el = (<img className={styles.icon__plus} onClick={() => this.props.onToggleMenu(true)} src="/app/assets/images/plus.png"/>); } return el; } showRightBtns() { const disableUndo = this.props.canUndo ? '' : 'disabled'; const disableRedo = this.props.canRedo ? '' : 'disabled'; const disableClearExport = this.props.canClear ? '' : 'disabled'; return ( <div className={[styles.rightBtns, 'noselect'].join(' ')}> <div onClick={() => this.props.onUndo()} className={[mainStyles.circleBtn, disableUndo].join(' ')}> <span className={mainStyles.dark}>Undo</span> <img className={mainStyles.circleInactive} src="/app/assets/images/undo-gray.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/undo-dark.svg"/> </div> <div onClick={() => this.props.onRedo()} className={[mainStyles.circleBtn, disableRedo].join(' ')}> <span className={mainStyles.dark}>Redo</span> <img className={mainStyles.circleInactive} src="/app/assets/images/redo-gray.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/redo-dark.svg"/> </div> <Settings /> <div onClick={() => this.onShare()} className={[mainStyles.circleBtn, disableClearExport].join(' ')}> <span className={mainStyles.green}>{this.state.copyText}</span> <img className={mainStyles.circleInactive} src="/app/assets/images/share-black.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/share-green.svg"/> <input onChange={this.onShare} type="text" value={this.state.url} id="hiddenInput" /> </div> <div onClick={() => this.onExport()} className={[mainStyles.circleBtn, disableClearExport].join(' ')}> <span className={mainStyles.green}>Export</span> <img className={mainStyles.circleInactive} src="/app/assets/images/download-black.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/download-green.svg"/> </div> <div onClick={() => this.props.onRemoveAll()} className={[mainStyles.circleBtn, disableClearExport].join(' ')}> <span className={mainStyles.red}>Clear all</span> <img className={mainStyles.circleInactive} src="/app/assets/images/delete-black.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/delete-red.svg"/> </div> <div onClick={() => this.onSaveAll()} className={[mainStyles.circleBtn, disableClearExport].join(' ')}> <span className={mainStyles.green}>{this.state.saveText}</span> <img className={mainStyles.circleInactive} src="/app/assets/images/save-black.svg"/> <img className={mainStyles.circleActive} src="/app/assets/images/save-green.svg"/> </div> </div> ); } renderPlaceHolder(sections, text) { if (!sections.length) { return ( <div> <img className={styles.placeImg} onClick={() => this.props.onToggleMenu(true)} src="/app/assets/images/plus.svg"/> <h2 className={styles.textPlaceHolder}>{text}</h2> </div> ); } return ''; } showSmallArrow() { if (this.props.containSections.length === 0 || (!this.props.settings.gradients.color1 && !this.props.settings.gradients.color2)) { return ''; } let style = {}; if (this.props.settings.gradients.color2) { style.borderTopColor = this.props.settings.gradients.color2; } else if (this.props.settings.gradients.color1) { style.borderTopColor = this.props.settings.gradients.color1; } return ( <div style={style} className={styles.smallArrow}></div> ); } getStyles() { const style = {}; if (this.props.containSections.length) { if (this.props.settings.gradients.color1 && this.props.settings.gradients.color2) { style.background = 'linear-gradient(' + this.props.settings.gradients.color1 + ',' + this.props.settings.gradients.color2 + ')'; } else if (this.props.settings.gradients.color1) { style.background = this.props.settings.gradients.color1; } else if (this.props.settings.gradients.color2) { style.background = this.props.settings.gradients.color2; } style.paddingTop = this.props.settings.padding.paddingTop; style.paddingLeft = this.props.settings.padding.paddingLeft; style.paddingBottom = this.props.settings.padding.paddingBottom; style.paddingRight = this.props.settings.padding.paddingRight; } return style; } renderPublish() { if (this.state.publishing) { return ( <Publish /> ); } return ''; } render() { const style = this.getStyles(); return ( <div className={styles.builder} onKeyDown={this.handleKeyDown}> <div className={styles.plus}> {this.showButton()} </div> {this.showRightBtns()} <div className={[styles.builderBox, mainStyles.noselect].join(' ')}> <div className={styles.builderBox__header}> <div></div><div></div><div></div> </div> {this.renderPlaceHolder(this.props.fullSections, 'Full Width Section')} <ul id="builderFull" className={styles.builderBox__content}> {this.renderSections(this.props.fullSections)} </ul> </div> <div className={[styles.builderBox, mainStyles.noselect, 'noMarginBox'].join(' ')}> {this.renderPlaceHolder(this.props.containSections, 'Contained Width Section')} <ul style={style} id="builderContain" className={styles.builderBox__content}> {this.showSmallArrow()} {this.renderSections(this.props.containSections)} </ul> </div> <div className={[styles.builderBox, mainStyles.noselect, 'noMarginBox'].join(' ')}> {this.renderPlaceHolder(this.props.footerSections, 'Footer Section')} <ul id="builderFooter" className={styles.builderBox__content}> {this.renderSections(this.props.footerSections)} </ul> </div> </div> ); } } Builder.propTypes = { onToggleMenu: PropTypes.func, onAddSection: PropTypes.func, onRemoveSection: PropTypes.func, onSortSection: PropTypes.func, onRemoveAll: PropTypes.func, onUpdateUser: PropTypes.func, onUndo: PropTypes.func, onRedo: PropTypes.func, onGetUser: PropTypes.func, onGetSections: PropTypes.func, onToggleAlert: PropTypes.func, menu: PropTypes.object, settings: PropTypes.object, user: PropTypes.object, sections: PropTypes.object, canUndo: PropTypes.bool, canRedo: PropTypes.bool, canClear: PropTypes.bool, fullSections: PropTypes.array, containSections: PropTypes.array, footerSections: PropTypes.array, params: PropTypes.object }; export default connect( mapStateToProps, mapDispatchToProps )(Builder);
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* eslint-disable stdlib/capitalized-comments */ 'use strict'; // MODULES // var trunc = require( './../../../../base/special/trunc' ); var truncf = require( './../../../../base/special/truncf' ); var identity = require( './../../../../base/special/identity' ); // MAIN // var data = [ // NOTE: the following **must** match the order in `./types.json`. The order should be according to likelihood of use (e.g., if `float64` arrays are more likely, then `float64` types/data should come before `uint8`). // float64 trunc, trunc, // float32 truncf, trunc, trunc, // generic trunc, // int32 identity, identity, identity, // int16 identity, identity, identity, identity, identity, // int8 identity, identity, identity, identity, identity, identity, // uint32 identity, identity, identity, // uint16 identity, identity, identity, identity, identity, identity, // uint8 identity, identity, identity, identity, identity, identity, identity, identity, identity, // uint8c identity, identity, identity, identity, identity, identity, identity, identity, identity ]; // EXPORTS // module.exports = data;
export default class Behavior { constructor() { this.action = null this.subject = null this.reply = null } getReply() { return this.reply } setReply(value) { this.reply = value return this } getSubject() { return this.subject } setSubject(value) { this.subject = value return this } getAction() { return this.action } setAction(value) { this.action = value return this } }
;(function(window,UNDEF){ "use strict"; function scenes(Mojo){ const {Sprites:_S, Scenes:_Z, FX:T, Input:_I, Game:_G, Arcade:_2d, v2:_V, ute:_,is}=Mojo; const int=Math.floor, ceil=Math.ceil; const sin=Math.sin, cos=Math.cos; const GREEN=_S.color("green"); const GREY=_S.color("grey"); const RED=_S.color("red"); _Z.scene("level1",{ __init(){ //let road= 0.6; //width of road, 60% of screen width _G.middle=0.5; _G.carPos=0; //_G.clipWidth= road * 0.15; //_G.roadWidth= road / 2; //half of road //_G.leftGrass= (_G.middle- _G.roadWidth - _G.clipWidth) * _G.arena.width; //_G.leftClip= (_G.middle- _G.roadWidth) * _G.arena.width; //_G.rightClip= (_G.middle+ _G.roadWidth) * _G.arena.width; //_G.rightGrass= (_G.middle+ _G.roadWidth + _G.clipWidth) * _G.arena.width; }, project(y){ let scale= y/_G.arena.height/2; _G.roadWidth= 0.1 + scale*0.8; _G.clipWidth= _G.roadWidth * 0.15; _G.roadWidth= _G.roadWidth*0.5; //half of road _G.middle= 0.5; _G.leftGrass= (_G.middle- _G.roadWidth - _G.clipWidth) * _G.arena.width; _G.leftClip= (_G.middle- _G.roadWidth) * _G.arena.width; _G.rightClip= (_G.middle+ _G.roadWidth) * _G.arena.width; _G.rightGrass= (_G.middle+ _G.roadWidth + _G.clipWidth) * _G.arena.width; return scale; }, __draw(){ let W=_G.arena.width, H=_G.arena.height, W2=W/2, H2= _G.arena.height/2; for(let scale,row,y=0; y < H2;++y){ scale= this.project(y); row= H2+y; this.__drawLine(0,row,_G.leftGrass,row,GREEN); this.__drawLine(_G.leftGrass,row,_G.leftClip,row,RED); this.__drawLine(_G.leftClip,row,_G.rightClip,row,GREY); this.__drawLine(_G.rightClip,row,_G.rightGrass,row,RED); this.__drawLine(_G.rightGrass,row,W,row,GREEN); } let carX= W2 + W*_G.carPos/2 - _G.car.width/2; _G.car.x=carX; _G.car.y=H*0.9 - _G.car.height; }, __drawLine(x1,y1,x2,y2,c){ this.gfx.lineStyle(1,c); this.gfx.moveTo(x1,y1); this.gfx.lineTo(x2,y2); }, setup(){ _G.arena={x:0,y:0,width:Mojo.width,height:Mojo.height}; _G.car=_S.rect(40,60,_S.color("white")); this.__init(); this.insert(this.gfx=_S.graphics()); this.insert(_G.car); }, postUpdate(dt){ this.gfx.clear() && this.__draw(); } },{}); } window.addEventListener("load",()=> MojoH5({ arena: {width: 640, height: 320}, scaleToWindow:"max", scaleFit:"x", //fps:30, start(Mojo){ scenes(Mojo); Mojo.Scenes.run("level1"); } })); })(this);
import _ from 'lodash'; import { fs, system, logger, util } from 'appium-support'; import log from '../logger'; import { exec, SubProcess } from 'teen_process'; import { checkPortStatus } from 'portscanner'; import http from 'http'; import net from 'net'; import B from 'bluebird'; import { waitForCondition } from 'asyncbox'; import { spawn } from 'child_process'; import url from 'url'; const commands = {}; const RECORDING_INTERVAL_SEC = 5; const STREAMING_STARTUP_TIMEOUT_MS = 5000; const GSTREAMER_BINARY = `gst-launch-1.0${system.isWindows() ? '.exe' : ''}`; const GST_INSPECT_BINARY = `gst-inspect-1.0${system.isWindows() ? '.exe' : ''}`; const REQUIRED_GST_PLUGINS = { avdec_h264: 'gst-libav', h264parse: 'gst-plugins-bad', jpegenc: 'gst-plugins-good', tcpserversink: 'gst-plugins-base', multipartmux: 'gst-plugins-good', }; const SCREENRECORD_BINARY = 'screenrecord'; const GST_TUTORIAL_URL = 'https://gstreamer.freedesktop.org/documentation/installing/index.html'; const DEFAULT_HOST = '127.0.0.1'; const TCP_HOST = '127.0.0.1'; const DEFAULT_PORT = 8093; const DEFAULT_QUALITY = 70; const DEFAULT_BITRATE = 4000000; // 4 Mbps const BOUNDARY_STRING = '--2ae9746887f170b8cf7c271047ce314c'; const ADB_SCREEN_STREAMING_FEATURE = 'adb_screen_streaming'; function createStreamingLogger (streamName, udid) { return logger.getLogger(`${streamName}@` + _.truncate(udid, { length: 8, omission: '', })); } async function verifyStreamingRequirements (adb) { if (!_.trim(await adb.shell(['which', SCREENRECORD_BINARY]))) { throw new Error( `The required '${SCREENRECORD_BINARY}' binary is not available on the device under test`); } const gstreamerCheckPromises = []; for (const binaryName of [GSTREAMER_BINARY, GST_INSPECT_BINARY]) { gstreamerCheckPromises.push((async () => { try { await fs.which(binaryName); } catch (e) { throw new Error(`The '${binaryName}' binary is not available in the PATH on the host system. ` + `See ${GST_TUTORIAL_URL} for more details on how to install it.`); } })()); } await B.all(gstreamerCheckPromises); const moduleCheckPromises = []; for (const [name, modName] of _.toPairs(REQUIRED_GST_PLUGINS)) { moduleCheckPromises.push((async () => { const {stdout} = await exec(GST_INSPECT_BINARY, [name]); if (!_.includes(stdout, modName)) { throw new Error( `The required GStreamer plugin '${name}' from '${modName}' module is not installed. ` + `See ${GST_TUTORIAL_URL} for more details on how to install it.`); } })()); } await B.all(moduleCheckPromises); } async function getDeviceInfo (adb) { const output = await adb.shell(['dumpsys', 'display']); const result = {}; for (const [key, pattern] of [ ['width', /\bdeviceWidth=(\d+)/], ['height', /\bdeviceHeight=(\d+)/], ['fps', /\bfps=(\d+)/], ]) { const match = pattern.exec(output); if (!match) { log.debug(output); throw new Error(`Cannot parse the device ${key} from the adb command output. ` + `Check the server log for more details.`); } result[key] = parseInt(match[1], 10); } result.udid = adb.curDeviceId; return result; } async function initDeviceStreamingProc (adb, deviceInfo, opts = {}) { const { width, height, bitRate, } = opts; const adjustedWidth = parseInt(width, 10) || deviceInfo.width; const adjustedHeight = parseInt(height, 10) || deviceInfo.height; const adjustedBitrate = parseInt(bitRate, 10) || DEFAULT_BITRATE; let screenRecordCmd = SCREENRECORD_BINARY + ` --output-format=h264` + // 5 seconds is fine to detect rotation changes ` --time-limit=${RECORDING_INTERVAL_SEC}`; if (width || height) { screenRecordCmd += ` --size=${adjustedWidth}x${adjustedHeight}`; } if (bitRate) { screenRecordCmd += ` --bit-rate=${adjustedBitrate}`; } const adbArgs = [ ...adb.executable.defaultArgs, 'exec-out', // The loop is required, because by default the maximum record duration // for screenrecord is always limited `while true; do ${screenRecordCmd} -; done`, ]; const deviceStreaming = spawn(adb.executable.path, adbArgs); deviceStreaming.on('exit', (code, signal) => { log.debug(`Device streaming process exited with code ${code}, signal ${signal}`); }); let isStarted = false; const deviceStreamingLogger = createStreamingLogger(SCREENRECORD_BINARY, deviceInfo.udid); const errorsListener = (chunk) => { const stderr = chunk.toString(); if (_.trim(stderr)) { deviceStreamingLogger.debug(stderr); } }; deviceStreaming.stderr.on('data', errorsListener); const startupListener = (chunk) => { if (!isStarted) { isStarted = !_.isEmpty(chunk); } }; deviceStreaming.stdout.on('data', startupListener); try { log.info(`Starting device streaming: ${util.quote([adb.executable.path, ...adbArgs])}`); await waitForCondition(() => isStarted, { waitMs: STREAMING_STARTUP_TIMEOUT_MS, intervalMs: 300, }); } catch (e) { log.errorAndThrow( `Cannot start the screen streaming process. Original error: ${e.message}`); } finally { deviceStreaming.stderr.removeListener('data', errorsListener); deviceStreaming.stdout.removeListener('data', startupListener); } return deviceStreaming; } async function initGstreamerPipeline (deviceStreamingProc, deviceInfo, opts = {}) { const { width, height, quality, tcpPort, considerRotation, logPipelineDetails, } = opts; const adjustedWidth = parseInt(width, 10) || deviceInfo.width; const adjustedHeight = parseInt(height, 10) || deviceInfo.height; const gstreamerPipeline = new SubProcess(GSTREAMER_BINARY, [ '-v', 'fdsrc', 'fd=0', '!', 'video/x-h264,' + `width=${considerRotation ? Math.max(adjustedWidth, adjustedHeight) : adjustedWidth},` + `height=${considerRotation ? Math.max(adjustedWidth, adjustedHeight) : adjustedHeight},` + `framerate=${deviceInfo.fps}/1,` + 'byte-stream=true', '!', 'h264parse', '!', 'queue', 'leaky=downstream', '!', 'avdec_h264', '!', 'queue', 'leaky=downstream', '!', 'jpegenc', `quality=${quality}`, '!', 'multipartmux', `boundary=${BOUNDARY_STRING}`, '!', 'tcpserversink', `host=${TCP_HOST}`, `port=${tcpPort}`, ], { stdio: [deviceStreamingProc.stdout, 'pipe', 'pipe'] }); gstreamerPipeline.on('exit', (code, signal) => { log.debug(`Pipeline streaming process exited with code ${code}, signal ${signal}`); }); const gstreamerLogger = createStreamingLogger('gst', deviceInfo.udid); const gstOutputListener = (stdout, stderr) => { if (_.trim(stderr || stdout)) { gstreamerLogger.debug(stderr || stdout); } }; gstreamerPipeline.on('output', gstOutputListener); let didFail = false; try { log.info(`Starting GStreamer pipeline: ${gstreamerPipeline.rep}`); await gstreamerPipeline.start(0); await waitForCondition(async () => { try { return (await checkPortStatus(tcpPort, TCP_HOST)) === 'open'; } catch (ign) { return false; } }, { waitMs: STREAMING_STARTUP_TIMEOUT_MS, intervalMs: 300, }); } catch (e) { didFail = true; log.errorAndThrow( `Cannot start the screen streaming pipeline. Original error: ${e.message}`); } finally { if (!logPipelineDetails || didFail) { gstreamerPipeline.removeListener('output', gstOutputListener); } } return gstreamerPipeline; } function extractRemoteAddress (req) { return req.headers['x-forwarded-for'] || req.socket.remoteAddress || req.connection.remoteAddress || req.connection.socket.remoteAddress; } /** * @typedef {Object} StartScreenStreamingOptions * * @property {?number} width - The scaled width of the device's screen. If unset then the script will assign it * to the actual screen width measured in pixels. * @property {?number} height - The scaled height of the device's screen. If unset then the script will assign it * to the actual screen height measured in pixels. * @property {?number} bitRate - The video bit rate for the video, in bits per second. * The default value is 4000000 (4 Mb/s). You can increase the bit rate to improve video quality, * but doing so results in larger movie files. * @property {?string} host [127.0.0.1] - The IP address/host name to start the MJPEG server on. * You can set it to `0.0.0.0` to trigger the broadcast on all available network interfaces. * @property {?string} pathname - The HTTP request path the MJPEG server should be available on. * If unset then any pathname on the given `host`/`port` combination will work. Note that the value * should always start with a single slash: `/` * @property {?number} tcpPort [8094] - The port number to start the internal TCP MJPEG broadcast on. * This type of broadcast always starts on the loopback interface (`127.0.0.1`). * @property {?number} port [8093] - The port number to start the MJPEG server on. * @property {?number} quality [70] - The quality value for the streamed JPEG images. * This number should be in range [1, 100], where 100 is the best quality. * @property {?boolean} considerRotation [false] - If set to `true` then GStreamer pipeline will * increase the dimensions of the resulting images to properly fit images in both landscape and * portrait orientations. Set it to `true` if the device rotation is not going to be the same during the * broadcasting session. * @property {?boolean} logPipelineDetails [false] - Whether to log GStreamer pipeline events into * the standard log output. Might be useful for debugging purposes. */ /** * Starts device screen broadcast by creating MJPEG server. * Multiple calls to this method have no effect unless the previous streaming * session is stopped. * This method only works if the `adb_screen_streaming` feature is * enabled on the server side. * * @param {?StartScreenStreamingOptions} options - The available options. * @throws {Error} If screen streaming has failed to start or * is not supported on the host system or * the corresponding server feature is not enabled. */ commands.mobileStartScreenStreaming = async function mobileStartScreenStreaming (options = {}) { this.ensureFeatureEnabled(ADB_SCREEN_STREAMING_FEATURE); const { width, height, bitRate, host = DEFAULT_HOST, port = DEFAULT_PORT, pathname, tcpPort = DEFAULT_PORT + 1, quality = DEFAULT_QUALITY, considerRotation = false, logPipelineDetails = false, } = options; if (_.isUndefined(this._screenStreamingProps)) { await verifyStreamingRequirements(this.adb); } if (!_.isEmpty(this._screenStreamingProps)) { log.info(`The screen streaming session is already running. ` + `Stop it first in order to start a new one.`); return; } if ((await checkPortStatus(port, host)) === 'open') { log.info(`The port #${port} at ${host} is busy. ` + `Assuming the screen streaming is already running`); return; } if ((await checkPortStatus(tcpPort, TCP_HOST)) === 'open') { log.errorAndThrow(`The port #${tcpPort} at ${TCP_HOST} is busy. ` + `Make sure there are no leftovers from previous sessions.`); } this._screenStreamingProps = null; const deviceInfo = await getDeviceInfo(this.adb); const deviceStreamingProc = await initDeviceStreamingProc(this.adb, deviceInfo, { width, height, bitRate, }); let gstreamerPipeline; try { gstreamerPipeline = await initGstreamerPipeline(deviceStreamingProc, deviceInfo, { width, height, quality, tcpPort, considerRotation, logPipelineDetails, }); } catch (e) { if (deviceStreamingProc.kill(0)) { deviceStreamingProc.kill(); } throw e; } let mjpegSocket; let mjpegServer; try { await new B((resolve, reject) => { mjpegSocket = net.createConnection(tcpPort, TCP_HOST, () => { log.info(`Successfully connected to MJPEG stream at tcp://${TCP_HOST}:${tcpPort}`); mjpegServer = http.createServer((req, res) => { const remoteAddress = extractRemoteAddress(req); const currentPathname = url.parse(req.url).pathname; log.info(`Got an incoming screen bradcasting request from ${remoteAddress} ` + `(${req.headers['user-agent'] || 'User Agent unknown'}) at ${currentPathname}`); if (pathname && currentPathname !== pathname) { log.info('Rejecting the broadcast request since it does not match the given pathname'); res.writeHead(404, { Connection: 'close', 'Content-Type': 'text/plain; charset=utf-8', }); res.write(`'${currentPathname}' did not match any known endpoints`); res.end(); return; } log.info('Starting MJPEG broadcast'); res.writeHead(200, { 'Cache-Control': 'no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0', Pragma: 'no-cache', Connection: 'close', 'Content-Type': `multipart/x-mixed-replace; boundary=${BOUNDARY_STRING}` }); mjpegSocket.pipe(res); }); mjpegServer.on('error', (e) => { log.warn(e); reject(e); }); mjpegServer.on('close', () => { log.debug(`MJPEG server at http://${host}:${port} has been closed`); }); mjpegServer.on('listening', () => { log.info(`Successfully started MJPEG server at http://${host}:${port}`); resolve(); }); mjpegServer.listen(port, host); }); mjpegSocket.on('error', (e) => { log.error(e); reject(e); }); }).timeout(STREAMING_STARTUP_TIMEOUT_MS, `Cannot connect to the streaming server within ${STREAMING_STARTUP_TIMEOUT_MS}ms`); } catch (e) { if (deviceStreamingProc.kill(0)) { deviceStreamingProc.kill(); } if (gstreamerPipeline.isRunning) { await gstreamerPipeline.stop(); } if (mjpegSocket) { mjpegSocket.destroy(); } if (mjpegServer && mjpegServer.listening) { mjpegServer.close(); } throw e; } this._screenStreamingProps = { deviceStreamingProc, gstreamerPipeline, mjpegSocket, mjpegServer, }; }; /** * Stop screen streaming. * If no screen streaming server has been started then nothing is done. */ commands.mobileStopScreenStreaming = async function mobileStopScreenStreaming (/* options = {} */) { if (_.isEmpty(this._screenStreamingProps)) { if (!_.isUndefined(this._screenStreamingProps)) { log.debug(`Screen streaming is not running. There is nothing to stop`); } return; } const { deviceStreamingProc, gstreamerPipeline, mjpegSocket, mjpegServer, } = this._screenStreamingProps; try { mjpegSocket.end(); if (mjpegServer.listening) { mjpegServer.close(); } if (deviceStreamingProc.kill(0)) { deviceStreamingProc.kill('SIGINT'); } if (gstreamerPipeline.isRunning) { try { await gstreamerPipeline.stop('SIGINT'); } catch (e) { log.warn(e); try { await gstreamerPipeline.stop('SIGKILL'); } catch (e1) { log.error(e1); } } } log.info(`Successfully terminated the screen streaming MJPEG server`); } finally { this._screenStreamingProps = null; } }; export default commands;
export default config => ({ autoCollapseDisabled: false, collapsedBreakpoint: 'md', secondaryAutoCollapseDisabled: false, secondaryCollapseBreakpoint: 'md', heightAdjustmentDisabled: false, ...config, });
'use strict'; const test = require('@putout/test')(__dirname, { 'remove-useless-types': require('..'), }); test('remove usless types: report', (t) => { t.report('unused', '"Point" is defined but never used'); t.end(); }); test('remove usless types: transform', (t) => { t.transform('unused', '\n\n'); t.end(); }); test('remove usless types: no transform: used', (t) => { t.noTransform('used'); t.end(); }); test('remove usless types: no transform: not defined', (t) => { t.noTransform('not-defined'); t.end(); }); test('remove usless types: no transform: export', (t) => { t.noTransform('export'); t.end(); }); test('remove usless types: no transform: export', (t) => { t.noTransform('export-named'); t.end(); }); test('remove usless types: no transform: export default', (t) => { t.noTransform('export-default'); t.end(); }); test('remove usless types: no transform: export default object', (t) => { t.noTransform('export-default-object'); t.end(); }); test('remove usless types: no transform: bubling', (t) => { t.noTransform('bubling'); t.end(); });
import React, { Component } from 'react'; import { View, Text, Switch } from 'react-native'; import PropTypes from 'prop-types'; import Icon from 'react-native-vector-icons/MaterialCommunityIcons'; import Touchable from '../Touchable'; import styles from './styles'; import sharedStyles from '../../styles/sharedStyles'; class ListItem extends Component { constructor(props) { super(props); } shouldComponentUpdate(nextProps) { if ( this.props.icon === nextProps.icon && this.props.firstLine === nextProps.firstLine && this.props.secondLine === nextProps.secondLine && this.props.actionComponent === nextProps.actionComponent && this.props.contentComponent === nextProps.contentComponent && this.props.isSwitchable === nextProps.isSwitchable && this.props.switchInitialValue === nextProps.switchInitialValue && this.props.onPress === nextProps.onPress && this.props.onActionPress === nextProps.onActionPress ) { return false; } return true; } render() { const ContainerComponent = props => this.getContainer(props); const IconComponent = this.getIcon(); const ContentComponent = this.getContent(); const ActionComponent = props => this.getAction(props); return ( <ContainerComponent> <IconComponent /> <ContentComponent /> <ActionComponent /> </ContainerComponent> ); } getContainer = props => { const { onPress } = this.props; if (onPress !== null && typeof onPress === 'function') { return ( <View style={styles.container}> <Touchable onPress={onPress} delayPressIn={0} style={{ flex: 1 }}> <View style={styles.wrapper}>{props.children}</View> </Touchable> </View> ); } return <View style={[styles.container, styles.wrapper]}>{props.children}</View>; }; getIcon() { const { icon } = this.props; if (icon === null) { return () => null; } if (typeof icon === 'object') { const IconComponent = () => icon; return () => ( <View style={styles.iconWrapper}> <View style={styles.icon}> <IconComponent style={styles.icon} size={24} /> </View> </View> ); } return () => ( <View style={styles.iconWrapper}> <View style={styles.icon}> <Icon style={styles.icon} name={icon} size={24} /> </View> </View> ); } getContent() { const { firstLine, secondLine, contentComponent } = this.props; if (contentComponent !== null && typeof contentComponent === 'object') { const ContentComponent = () => contentComponent; return () => ( <View style={styles.contentWrapper}> <ContentComponent /> </View> ); } const heightStyle = secondLine !== null ? styles.contentMultilines : null; return () => ( <View style={[styles.contentWrapper, heightStyle]}> {firstLine !== null ? ( <Text style={styles.firstLine} numberOfLines={1}> {firstLine} </Text> ) : null} {secondLine !== null ? ( <Text style={styles.secondLine} numberOfLines={1}> {secondLine} </Text> ) : null} </View> ); } getAction = props => { const { actionComponent, onActionPress, isSwitchable, switchInitialValue } = this.props; if (isSwitchable) { return ( <View style={styles.actionWrapper}> <Switch value={switchInitialValue} onValueChange={() => onActionPress()} onTintColor={sharedStyles.ACCENT_COLOR_LIGHT} thumbTintColor={sharedStyles.ACCENT_COLOR} /> </View> ); } if (actionComponent !== null && typeof actionComponent === 'object') { const ActionComponent = () => actionComponent; return ( <View style={styles.actionWrapper}> <ActionComponent onPress={() => onActionPress()} onValueChange={() => onActionPress()} {...props} /> </View> ); } return null; }; } ListItem.propTypes = { icon: PropTypes.oneOfType([PropTypes.element, PropTypes.string]), firstLine: PropTypes.string, secondLine: PropTypes.string, contentComponent: PropTypes.element, actionComponent: PropTypes.element, isSwitchable: PropTypes.bool, switchInitialValue: PropTypes.bool, onPress: PropTypes.func, onActionPress: PropTypes.func }; ListItem.defaultProps = { icon: null, firstLine: null, secondLine: null, contentComponent: null, actionComponent: null, isSwitchable: false, switchInitialValue: false, onPress: null, onActionPress: null }; export default ListItem;
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M13 3c-4.97 0-9 4.03-9 9H1l4 3.99L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z" /><path d="M12 8v5l4.25 2.52.77-1.28-3.52-2.09V8z" /></React.Fragment> , 'RestoreOutlined');
'use strict'; var should = require('chai').should(); var P2P = require('../../'); var builder = P2P.Messages.builder; var bitcore = require('ulitecore-lib'); describe('Messages Builder', function() { describe('@constructor', function() { it('should return commands based on default', function() { // instantiate var b = builder(); should.exist(b); }); it('should return commands with customizations', function() { // instantiate var b = builder({ network: bitcore.Networks.testnet, Block: bitcore.Block, Transaction: bitcore.Transaction }); should.exist(b); }); }); });
import Promise from 'es6-promise/lib/es6-promise/promise'; // Return the first non-falsy result from an array of // maybe-sync, maybe-promise-returning functions export default function first ( candidates ) { return function ( ...args ) { return candidates.reduce( ( promise, candidate ) => { return promise.then( result => result != null ? result : Promise.resolve( candidate( ...args ) ) ); }, Promise.resolve() ); } }
/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) Vue.component('example-component', require('./components/ExampleComponent.vue').default); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ const app = new Vue({ el: '#app', }); var app = new Vue({ el: '#test', data: { searchWord: 'Hello World!' }, methods: { searchStation: function (e) { alert(this.searchWord) } } })
module.exports = function (grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { main: { src: 'js/<%= pkg.name %>.js', dest: 'js/<%= pkg.name %>.min.js' } }, less: { expanded: { options: { paths: ["css"] }, files: { "css/<%= pkg.name %>.css": "less/<%= pkg.name %>.less" } }, minified: { options: { paths: ["css"], cleancss: true }, files: { "css/<%= pkg.name %>.min.css": "less/<%= pkg.name %>.less" } } }, banner: '/*!\n' + ' * <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)\n' + ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' */\n', usebanner: { dist: { options: { position: 'top', banner: '<%= banner %>' }, files: { src: ['css/<%= pkg.name %>.css', 'css/<%= pkg.name %>.min.css', 'js/<%= pkg.name %>.min.js'] } } }, htmlmin: { dist: { options: { removeCommentsFromCDATA: true, removeComments: true, collapseWhitespace: true, collapseBooleanAttributes: true, removeAttributeQuotes: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeOptionalTags: true }, files: [{ expand: true, src: [ '_site/*.html', '_site/**/*.html', '_site/**/**/**/**/*.html', ], dest: '' }] } }, watch: { scripts: { files: ['js/<%= pkg.name %>.js'], tasks: ['uglify'], options: { spawn: false, }, }, less: { files: ['less/*.less'], tasks: ['less'], options: { spawn: false, } }, }, }); // Load the plugins. grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-less'); grunt.loadNpmTasks('grunt-banner'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-htmlmin'); // Default task(s). grunt.registerTask('default', ['uglify', 'less', 'usebanner','htmlmin']); };
let path = require('path'); let fs = require('fs'); module.exports = { 'init': function(browser) { browser .url('file://' + path.join(__dirname, 'index.html')) .waitForElementVisible('body', 1000) .pause(300) .assert.value('input', '0.5,0.5/0,0') .end(); } };
/* eslint-env mocha */ /* eslint-disable no-console, no-unused-expressions */ import Web3 from 'web3'; import { expect } from 'chai'; import Sigmate from '../src'; import { accountsObject } from './_harness'; describe('balances', () => { it('should correctly set up the balances', (done) => { const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545')); const fundAccounts = 1337; new Sigmate({ accounts: accountsObject, web3, fundAccounts }).then((sigmate) => { return Promise.all(Object.keys(accountsObject).map((name) => { return new Promise((resolve) => { const account = sigmate.accounts[name]; const targetAmount = isNaN(accountsObject[name].balance) ? fundAccounts : accountsObject[name].balance; expect(account.minimumFunding).to.equal(targetAmount); web3.eth.getBalance(account.address, (err, balance) => { expect(balance.toNumber()).to.equal(targetAmount); resolve(); }); }); })).then(() => { done(); }); }); }).timeout(1000 * 60); });
console.log("Functions pt.2"); let sayHello = function(name) {console.log(`Hello there ${name}`)}; sayHello("Jhon"); // storing function in array let numberStats = [ (num) => num > 0 ? "Positive" : "Negative", (num) => num % 2 === 0 ? "Even" : "Odd" ]; console.log(numberStats[0](10)); console.log(numberStats[1](14)); // functions as argument to other functions function calculator(calculateFunc, num1, num2){ return calculateFunc(num1, num2); } function sum(num1, num2) {return num1 + num2}; function difference(num1, num2) {return num1 - num2}; console.log(calculator(sum, 10, 15)); console.log(calculator(difference, 100, 55)); // returning function from another function function calculatorTwo(operator){ switch(operator){ case "+": return (num1, num2) => num1 + num2; case "-": return (num1, num2) => num1 - num2; default: console.log("Wrong operator!"); return null; } }; let resultFunction = calculatorTwo("+"); console.log(resultFunction(11,2)); console.log(calculatorTwo("-")(5,2)); // function with properties and methods function saySomething(name){ return `Hello there ${name}`; } saySomething.defaultName = "Boby"; saySomething.description = "This is a function that greets a person"; console.log(saySomething(saySomething.defaultName)); let someText = [ "I am learning JavaScript", "Loving Dogs", "Amazing Planet Earth", "I will be a great JavaScript Developer" ]; function longestString(args){ console.log(args[0]); console.log(args[1]); console.log(args[2]); let longest = ''; for(let i = 0; i < args.length; i++){ if(args[i].length > longest.length){ longest = args[i]; } } return longest; }; console.log("Longest argument is:", longestString(someText)); // high-order functions console.log("------- HOF forEach --------"); let someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; for(let i = 0; i < someNumbers.length; i++){ console.log(someNumbers[i]); }; console.log("With forEach:"); someNumbers.forEach(function(element){ console.log(element); }); let students = [ {firstName: "Bojan", lastName: "Trpcevski", email: "bojan@example.mk", age: 25}, {firstName: "George", lastName: "Dimitrov", email: "george@example.mk", age: 19}, {firstName: "Martina", lastName: "Jovanovska", email: "martina@example.mk", age: 22}, {firstName: "Stefan", lastName: "Kronevski", email: "stefan@example.mk", age: 24}, {firstName: "Martina", lastName: "Vujovska", email: "martina.v@example.mk", age: 19} ]; for(let student of students){ console.log(`Student: ${student.firstName} ${student.lastName} | ${student.email}`); }; console.log("With forEach:"); students.forEach(function(student){ console.log(`Student: ${student.firstName} ${student.lastName} | ${student.email}`); }); // Example that we cannot return with forEach let studentsNewArray = students.forEach(function(student){ return `Student: ${student.firstName}`; }); console.log(studentsNewArray); // undefined with forEach we cannot return values // high-order function: filter console.log("------- HOF filter --------"); let movies = [ { name: "The Dark Knight", year: 2008, rating: 9.0 }, { name: "Inception", year: 2010, rating: 8.8 }, { name: "The Hobbit", year: 2013, rating: 8.3 }, { name:"Dune", year:2021, rating:7.2 }, { name: "Fifty shades of gray", year: 2010, rating: 4 }, { name: "The Matrix", year: 1999, rating: 7.5 }, { name: "Casino", year: 1995, rating: 8.2 } ]; let goodMovies = []; for(let i = 0; i < movies.length; i++){ if(movies[i].rating > 8){ goodMovies.push(movies[i]); } }; console.log(goodMovies); console.log("With HOF Filter:"); let goodMoviesFiltred = movies.filter(function(element){ if(element.rating > 8){ return element; } }); console.log(goodMoviesFiltred); let moviesAbove2k = movies.filter(x => x.year > 1999); console.log(moviesAbove2k); let moviesBelow2k = movies.filter((x) => { return x.year < 2000; }); console.log(moviesBelow2k); let studentsAbove20 = students.filter(function(element){ if(element.age > 20){ return element; } }); console.log(studentsAbove20); // high-order function: MAP console.log("------ HOF Map ------"); let mappedMovies = []; for(let i = 0; i < movies.length; i++){ if(movies[i].year > 1988){ mappedMovies.push({ movieName: movies[i].name, movieYear: movies[i].year, movieRating: movies[i].rating }); } }; console.log(mappedMovies); let mappedMoviesNew = moviesAbove2k.map(function(element){ return { mName: element.name, mRating: element.rating } }); console.log(mappedMoviesNew); let dataFromMovies = movies.map(function(element){ return `${element.name} | ${element.year}`; }); console.log(dataFromMovies); let mappedMovies2 = movies.map(function(movie){ return{ movie_name: movie.name, movie_year: movie.year, movie_old: `The movie is: ${2022 - movie.year} old` } }); console.log(mappedMovies2); let filtredAndMappedMovies = movies.filter(function(element){ return element.year > 1999; }).map(function(el){ return {movieName: el.name, movieYear: el.year}; }); console.log(filtredAndMappedMovies); let filtredAndMappedMoviesNew = movies .filter(movie => movie.year > 2010) .map(el => el); console.log(filtredAndMappedMoviesNew); // high-order function: Reduce console.log("--------- HOF Reduce -------"); someNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let totalSum = 0; for(let number of someNumbers){ totalSum += number; } console.log(totalSum); let calculationWithReduce = someNumbers.reduce(function(total, currentNumber){ return total += currentNumber; }); console.log(calculationWithReduce); let moviesRatingReduced = movies .map(x => x.rating) .reduce((totalRating, ratingItem) =>{ return totalRating += ratingItem; }); console.log(moviesRatingReduced); console.log(`Average movie rating is: ${Math.floor(moviesRatingReduced / movies.length)}`); let academyStudents = [ { id: 1, firstName: "Frasquito", lastName: "Koop", email: "fkoop0@ow.ly", gender: "Male", city: "Benzilan", averageGrade: 4, age: 33 }, { id: 2, firstName: "Mirilla", lastName: "Heazel", email: "mheazel1@forbes.com", gender: "Female", city: "Buena Esperanza", averageGrade: 3, age: 37 }, { id: 3, firstName: "Edie", lastName: "Butler-Bowdon", email: "ebutlerbowdon2@hhs.gov", gender: "Female", city: "Cigembong", averageGrade: 2, age: 14 }, { id: 4, firstName: "Stearn", lastName: "Chrstine", email: "schrstine3@google.co.jp", gender: "Male", city: "Charras", averageGrade: 2, age: 34 }, { id: 5, firstName: "Leslie", lastName: "Portigall", email: "lportigall4@java.com", gender: "Male", city: "Resende", averageGrade: 5, age: 19 }, { id: 6, firstName: "Andros", lastName: "Dorgon", email: "adorgon5@sbwire.com", gender: "Male", city: "Pila", averageGrade: 3, age: 17 }, { id: 7, firstName: "Jervis", lastName: "Yitshak", email: "jyitshak6@gizmodo.com", gender: "Male", city: "Lâm Thao", averageGrade: 4, age: 17 }, { id: 8, firstName: "Carolyne", lastName: "Kilday", email: "ckilday7@time.com", gender: "Female", city: "Carbajales", averageGrade: 3, age: 23 } ]; let onlyHighGraders = academyStudents .filter(student => student.averageGrade > 2) .map(student => student.averageGrade) .reduce((totalSum, grade) =>{ return totalSum += grade; }); console.log(onlyHighGraders); // high-order function: sort console.log("------ HOF Sort -------"); let randomNumbers = [5, 2, 1, 4, 9, 6, 8]; console.log(randomNumbers); randomNumbers.sort(); // only works for arrays with primitive values = default sorting. console.log(randomNumbers); let sortedMoviesASC = movies.sort(function(movie1, movie2){ return movie1.year - movie2.year; }); console.log(sortedMoviesASC); let sortedMoviesDESC = movies.sort((movie1, movie2) =>{ return movie2.year - movie1.year; }); console.log(sortedMoviesDESC); let ourListOfMovies = movies .filter(x => x.rating > 7) .map(x => x) .sort((movie1, movie2) => movie1.year - movie2.year); console.log(ourListOfMovies);
import React from "react"; import PropTypes from "prop-types"; import clsx from "clsx"; import styled from "styled-components"; import Tab from "@material-ui/core/Tab"; import { withTheme } from "dry/theme"; import setPropTypes from "dry/utils/setPropTypes"; function DryTab(props) { const { className, ...restProps } = props; const clsxName = clsx(className, {}); return <Tab {...restProps} className={clsxName} />; } DryTab.defaultProps = { className: "" }; DryTab.propTypes = { className: PropTypes.string }; const StyledTab = styled(DryTab)``; const ThemedStyledTab = withTheme(StyledTab); setPropTypes("DryTab", Tab, ThemedStyledTab); export default ThemedStyledTab;
'use strict'; /** * Affiliate.js service * * @description: A set of functions similar to controller's actions to avoid code duplication. */ // Public dependencies. const _ = require('lodash'); module.exports = { /** * @api {post} /affiliate/share Share Affiliate link with other users * @apiVersion 0.0.1 * @apiName share * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} user User's information. * @apiParam {Object} body Affiliate mail body. * * @apiSuccess HTTP/1.1 200 Sucess. * * @apiError Unauthorized Only authenticated customer can share affiliate link. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ share: async(user, body) => { return await strapi.plugins.email.services.email.affiliateRequest(body.email, user.username, {affiliateId: user.affiliateId}); }, /** * @api {get} /affiliate Fetch user's affiliate details * @apiVersion 0.0.1 * @apiName fetchAll * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} user User's information. * * @apiExample Example usage: * curl -i http://localhost:1337/affiliate * * @apiSuccess {Array} affiliateObjects The Array of affiliate objects. * @apiSuccess {ObjectId} _id Object Id of Affiliate. * @apiSuccess {Integer} amount Affiliate amount. * @apiSuccess {Boolean} withdrawn Whether Affiliate amount withdraw or not. * @apiSuccess {Date} expiry Maturity period of affiliate. * @apiSuccess {Object} affiliatedUser User that has been affiliated. * @apiSuccess {Object} affiliatedByUser User that affiliated. * @apiSuccess {String} status Affiliate status. * @apiSuccess {Date} createdAt Affiliate creation date. * @apiSuccess {Date} updatedAt Affiliate updation date. * * @apiError Unauthorized Only authenticated customer can fetch their all affiliates. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ fetchAll: (user) => { const query = { affiliatedByUser: user?user._id:null }; const convertedParams = strapi.utils.models.convertParams('affiliate', query); return Affiliate .find() .where(convertedParams.where) .sort(convertedParams.sort) .skip(convertedParams.start) .limit(convertedParams.limit) .populate(_.keys(_.groupBy(_.reject(strapi.models.affiliate.associations, {autoPopulate: false}), 'alias')).join(' ')); }, /** * @api {get} /affiliate/:_id Fetch user's affiliate details * @apiVersion 0.0.1 * @apiName fetch * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} params Id of affiliate requested. * * @apiExample Example usage: * curl -i http://localhost:1337/affiliate/:id * * @apiSuccess {ObjectId} _id Object Id of Affiliate. * @apiSuccess {Integer} amount Affiliate amount. * @apiSuccess {Boolean} withdrawn Whether Affiliate amount withdraw or not. * @apiSuccess {Date} expiry Maturity period of affiliate. * @apiSuccess {Object} affiliatedUser User that has been affiliated. * @apiSuccess {Object} affiliatedByUser User that affiliated. * @apiSuccess {String} status Affiliate status. * @apiSuccess {Date} createdAt Affiliate creation date. * @apiSuccess {Date} updatedAt Affiliate updation date. * * @apiError Unauthorized Only authenticated customer can fetch single affiliate. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ fetch: (params) => { return Affiliate .findOne(_.pick(params, _.keys(Affiliate.schema.paths))) .populate(_.keys(_.groupBy(_.reject(strapi.models.affiliate.associations, {autoPopulate: false}), 'alias')).join(' ')); }, /** * @api {post} /affiliate Creates user's affiliate * @apiVersion 0.0.1 * @apiName add * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} values Object defining values for new Affiliate. * * @apiSuccess {ObjectId} _id Object Id of Affiliate. * @apiSuccess {Integer} amount Affiliate amount. * @apiSuccess {Boolean} withdrawn Whether Affiliate amount withdraw or not. * @apiSuccess {Date} expiry Maturity period of affiliate. * @apiSuccess {Object} affiliatedUser User that has been affiliated. * @apiSuccess {Object} affiliatedByUser User that affiliated. * @apiSuccess {String} status Affiliate status. * @apiSuccess {Date} createdAt Affiliate creation date. * @apiSuccess {Date} updatedAt Affiliate updation date. * * @apiError Unauthorized Only authenticated customer can fetch single affiliate. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ add: async (values) => { const data = await Affiliate.create(_.omit(values, _.keys(_.groupBy(strapi.models.affiliate.associations, 'alias')))); return data; }, /** * @api {put} /affiliate Updates affiliate with new info * @apiVersion 0.0.1 * @apiName edit * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} params Object defining Affiliate Id. * @apiParam {Object} values Object defining values for update. * * @apiSuccess {string} ok Found data. * @apiSuccess {string} nModified Number of modified docs. * @apiSuccess {string} n Number of not modified docs. * * @apiError Unauthorized Only authenticated customer can update single affiliate. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ edit: async (params, values) => { // Note: The current method will return the full response of Mongo. // To get the updated object, you have to execute the `findOne()` method // or use the `findOneOrUpdate()` method with `{ new:true }` option. return Affiliate.update(params, values, { multi: true }); }, /** * @api {delete} /affiliate Delete affiliate * @apiVersion 0.0.1 * @apiName remove * @apiGroup Affiliate * @apiPermission Customer * * * @apiParam {Object} params Object defining Affiliate Id. * * @apiSuccess {Object} data Deleted doc gets returned. * * @apiError Unauthorized Only authenticated customer can delete affiliate. * @apiError NotFound The <code>id</code> of the User was not found. * * @apiErrorExample Response (example): * HTTP/1.1 401 Unauthorized * Vary: Origin * Content-Type: application/json; charset=utf-8 * X-Powered-By: Strapi <strapi.io> * Content-Length: 66 * Date: Tue, 02 Oct 2018 14:14:54 GMT * Connection: keep-alive * { * "statusCode":401,"error":"Unauthorized","message":"Unauthorized" * } */ remove: async params => { // Note: To get the full response of Mongo, use the `remove()` method // or add spent the parameter `{ passRawResult: true }` as second argument. const data = await Affiliate.findOneAndRemove(params, {}) .populate(_.keys(_.groupBy(_.reject(strapi.models.affiliate.associations, {autoPopulate: false}), 'alias')).join(' ')); _.forEach(Affiliate.associations, async association => { const search = (_.endsWith(association.nature, 'One')) ? { [association.via]: data._id } : { [association.via]: { $in: [data._id] } }; const update = (_.endsWith(association.nature, 'One')) ? { [association.via]: null } : { $pull: { [association.via]: data._id } }; await strapi.models[association.model || association.collection].update( search, update, { multi: true }); }); return data; } };
// JavaScript Document $(document).ready(function() { $('header').removeClass("headerBg"); $("#about_banner h2").animate({ "margin-left":"0px", "opacity":1 },800); $("#about_banner span").animate({ "margin-left":"0px", "opacity":1 },800); window.addEventListener('scroll', function(){ var topHeight = 600; var st = this.scrollY; //console.log("st--",st); // var titleDr = $("#titleDr").offset().top - topHeight; // var titleMedicalTr = $("#titleMedicalTr").offset().top - topHeight; // var titleDrTime = $("#titleDrTime").offset().top - topHeight; // var titleEnvironment = $("#titleEnvironment").offset().top - topHeight; // var titleConsultation = $("#titleConsultation").offset().top - topHeight; // var gmimg1 = $("#titleEnvironment").offset().top - topHeight - 100; // var gmimg2 = $("#titleEnvironment").offset().top - topHeight - 100; // var gmimg3 = $("#gmimg2").offset().top - topHeight - 100; // var gmimg4 = $("#gmimg3").offset().top - topHeight - 100; // var gmimg5 = $("#gmimg4").offset().top - topHeight - 100; // console.log("topHeight--",topHeight); // // 判斷是向上捲動,而且捲軸超過 200px $("#toTop").hide(); if( st > topHeight) { $("#toTop").fadeTo(400,1); }else { $("#toTop").hide(); } if(st >= offsetBelieve){ $('.indexNav a').removeClass("action"); $('.indexNav a:nth-of-type(1)').addClass("action"); // $(".drsDesc .col").animate({ // "top":"0px" // },1200); } if(st >= offsetEnergic) { $('.indexNav a').removeClass("action"); $('.indexNav a:nth-of-type(2)').addClass("action"); $("#index_energic h2").animate({ "margin-left":"0px", "opacity":1 },800); $("#index_energic p").animate({ "margin-right":"0px", "opacity":1 },800); } if(st >= offsetSuccess){ $('.indexNav a').removeClass("action"); $('.indexNav a:nth-of-type(3)').addClass("action"); $("#index_success h2").animate({ "margin-left":"0px", "opacity":1 },800); $("#index_success p").animate({ "margin-right":"0px", "opacity":1 },800); } if(st >= offsetTeamwork){ $('.indexNav a').removeClass("action"); $('.indexNav a:nth-of-type(4)').addClass("action"); $("#index_teamwork h2").animate({ "margin-left":"0px", "opacity":1 },800); $("#index_teamwork p").animate({ "margin-right":"0px", "opacity":1 },800); } // if(st >= offsetFooter){ // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(5)').addClass("action"); // } // if( st > titleMedicalTr) { // var itemName = $(".dm .title .hr"); // itemName.addClass("hrAnimat"); // animateUnderLine(itemName,800); // // $(".dm .title .hr").animate({ // // width:'100%', // // opacity:'1' // // },800); // } // if( st > titleMedicalTr+100) { // $("#serv1").addClass(" servmove"); // } // if( st > titleDrTime) { // var itemName = $(".fm .hr"); // itemName.addClass("hrAnimat"); // animateUnderLine(itemName,800); // // $(".fm .hr").animate({ // // width:'100%', // // opacity:'1' // // },800); // } // if( st > titleEnvironment) { // var itemName = $(".gm .hr"); // itemName.addClass("hrAnimat"); // // $(".gm .hr").animate({ // // width:'300px', // // opacity:'1' // // },800); // } // if( st > gmimg1) { // $("#gmimg1").animate({ // "margin-top":"0px", // opacity:1 // },800); // } // if( st > gmimg2) { // $("#gmimg2").animate({ // "margin-top":"0px", // opacity:1 // },800); // } // if( st > gmimg3) { // $("#gmimg3").animate({ // "margin-top":"0px", // opacity:1 // },800); // } // if( st > gmimg4) { // $("#gmimg4").animate({ // "margin-top":"0px", // opacity:1 // },800); // } // if( st > gmimg5) { // $("#gmimg5").animate({ // "margin-top":"0px", // opacity:1 // },800); // } // if( st > gmimg5) { //titleConsultation // if($(window).width() > 640){ // var itemName = $(".hm .title .hr"); // itemName.addClass("hrAnimat"); // animateUnderLine(itemName,800); // } // // $(".hm .title .hr").animate({ // // width:'100%', // // opacity:'1' // // },800); // } }); $('.menu li').each(function(){ $(this).click(function(){ $('.menu li').removeClass(" menuclick"); $(this).addClass(" menuclick"); var thisTit = $(this).attr("menuno"); $(this).attr("viewed","true"); if(thisTit != null){ var thisOffsetTop = $("#" + thisTit).offset().top - 80; $('body,html').animate({ //scrollTop: pgBoxTop scrollTop: thisOffsetTop },200); } closeAppMenu(); }); }); $('.bbhover').each(function(){ var thisEle = $(this).find(".hr1"); var state = ""; $(this).hover( function(){ //thisEle.css({"background":"#fff"}); thisEle.animate({ opacity:'1' },400); }, function(){ //thisEle.css({"opacity":"0","background":"unset"}); thisEle.animate({ opacity:'0' },400); } ); $(this).click(function(){ //menu動作 $('.bbhover').removeClass(" bbclick"); $(this).addClass(" bbclick"); $('.bbhover .hr1').css({"width":"100%","opacity":"0"}); thisEle.css({"width":"100%","opacity":"1"}); //顯示內文 // console.log($(this)); var thisNo = $(this).attr("cnt"); var thisBlock = $("#serv" + thisNo); $(".serv").hide(); $("#serv" + thisNo).show(); $("#serv" + thisNo).addClass(" servmove"); $("#servLeft").attr("no",thisNo); $("#servRight").attr("no",thisNo); // $("#serv" + thisNo).animate({ // opacity:'1', // top:"0" // },800); // var strItemLeftHtml = ''; // strItemLeftHtml += '<div class="arrowBox">'; // strItemLeftHtml += '<i class="fas fa-arrow-circle-left" onclick="prevServ('+ thisNo +')" style="font-size:36px"></i>'; // strItemLeftHtml += '<i class="fas fa-arrow-circle-right" onclick="nextServ('+ thisNo +')" style="font-size:36px"></i>'; // strItemLeftHtml += '</div>'; // $(".em .container").append(strItemLeftHtml); }); }); $(".calmenu li").each(function(){ $(this).click(function(){ // console.log($(this)); $('.calmenu li').removeClass(" active"); $(this).addClass(" active"); var thisNo = $(this).attr("no"); var thisEle = $("#tb" + thisNo); $('.cal table').css({"display":"none"}); if(thisNo != null){ thisEle.fadeTo(400,1); } }); }); //---------------------------------------- //index.html 上方隱藏主選單 $(".menu_open").on("click", function(){ //alert("msg"); $(".menu_main").animate({ left:'5px', opacity:'1' }); }); $(".btn_hide").on("click", function(){ $(".menu_main").animate({ left:'-220px', opacity:'1' }); }); }); function goTop(){ $('.menu li').removeClass(" menuclick"); $('body,html').animate({ scrollTop: 0 },400); } function animateUnderLine(eleName,speed){ // eleName.animate({ // width:'100px', // opacity:'1' // },speed); } function animateUnderLineClear(eleName,speed){ eleName.animate({ width:'0%', opacity:'0' },speed); } function nextSection(){ var thisNo = parseInt($(".calmenu li.active").attr("no")); thisNo = thisNo + 1; SectionFn(thisNo); } function prevSection(){ var thisNo = parseInt($(".calmenu li.active").attr("no")); thisNo = thisNo - 1; SectionFn(thisNo); // var total = $(".calmenu li").length; // if(thisNo != null){ // $(".calmenu li").each(function(){ // if($(this).attr("no") == thisNo.toString()){ // //alert(thisNo); // $(".calmenu li").css({"display":"none"}); // $('.calmenu li').removeClass(" active"); // $(this).addClass(" active"); // $(this).fadeTo(400,1); // $('.cal table').css({"display":"none"}); // var thisEle = $("#tb" + thisNo); // thisEle.fadeTo(400,1); // } // }); // } } function SectionFn(thisNo){ var total = $(".calmenu li").length; if(thisNo != null){ $(".calmenu li").each(function(){ if($(this).attr("no") == thisNo.toString()){ //alert(thisNo); $(".calmenu li").css({"display":"none"}); $('.calmenu li').removeClass(" active"); $(this).addClass(" active"); $(this).fadeTo(400,1); $('.cal table').css({"display":"none"}); var thisEle = $("#tb" + thisNo); thisEle.fadeTo(400,1); } }); } } function openAppMenu(){ $(".menuOpen").hide(); $(".menuClose").show(); $(".menuGrp").slideDown(); // $(".menuGrp").animate({ // "left":"0%" // },400); //$("body").append("<div class='mask'></div>"); } function closeAppMenu(){ $(".menuOpen").show(); $(".menuClose").hide(); $(".menuGrp").slideUp(); // $(".menuGrp").animate({ // "left":"-100%" // },400); // $(".mask").animate({ // "left":"-100%" // },400); // //$(".mask").remove(); } function prevServ(){ var thisNo = $("#servLeft").attr("no"); $(".serv").removeClass(" servmove"); $(".serv").removeClass(" servmoveLeft"); $(".serv").removeClass(" servmoveRight"); if(thisNo != null){ thisNo = parseInt(thisNo) - 1; $('.bbhover').each(function(){ if($(this).attr("cnt") == thisNo){ $('.bbhover').removeClass(" bbclick"); $(this).addClass(" bbclick"); } }); $(".container .serv").each(function(){ if($(this).attr("id") == "serv"+thisNo){ $(".serv").hide(); $("#serv" + thisNo).show(); $("#serv" + thisNo).addClass(" servmoveLeft"); $("#servRight").attr("no",thisNo); $("#servLeft").attr("no",thisNo); } }); } } function nextServ(){ var thisNo = $("#servRight").attr("no"); $(".serv").removeClass(" servmove"); $(".serv").removeClass(" servmoveLeft"); $(".em .serv").removeClass(" servmoveRight"); if(thisNo != null){ thisNo = parseInt(thisNo) + 1; $('.bbhover').each(function(){ if($(this).attr("cnt") == thisNo){ $('.bbhover').removeClass(" bbclick"); $(this).addClass(" bbclick"); } }); $(".container .serv").each(function(){ if($(this).attr("id") == "serv"+thisNo){ $(".serv").hide(); $("#serv" + thisNo).show(); $(".em #serv" + thisNo).addClass(" servmoveRight"); $("#servRight").attr("no",thisNo); $("#servLeft").attr("no",thisNo); } }); } } // function bbClick(){ // // $(this).click(function(){ // // var thisEle = $(this).find(".hr"); // // alert(thisEle); // // $('.bbhover').removeClass(" bbclick"); // // $(this).addClass(" bbclick"); // // thisEle.css({"width":"100% !important","opacity":"1 !important"}); // // }); // } function goTop(){ $('body,html').animate({ scrollTop: 0 },800); } function goPgTitle(thisTitle){ // console.log("index_believe--",$("#index_believe").offset().top); // console.log("index_energic--",$("#index_energic").offset().top); // console.log("index_success--",$("#index_success").offset().top); // console.log("index_teamwork--",$("#index_teamwork").offset().top); var offsetBelieve = $("#index_believe").offset().top; var offsetEnergic = $("#index_energic").offset().top; var offsetSuccess = $("#index_success").offset().top; var offsetTeamwork = $("#index_teamwork").offset().top; var offsetFooter = $("#index_footer").offset().top; if(thisTitle == 'index_energic'){ $('body,html').animate({ scrollTop: offsetEnergic },600); // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(2)').addClass("action"); }else if(thisTitle == 'index_success'){ $('body,html').animate({ scrollTop: offsetSuccess },600); // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(3)').addClass("action"); }else if(thisTitle == 'index_teamwork'){ $('body,html').animate({ scrollTop: offsetTeamwork },600); // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(4)').addClass("action"); }else if(thisTitle == 'index_footer'){ $('body,html').animate({ scrollTop: offsetFooter },600); // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(4)').addClass("action"); }else{ $('body,html').animate({ scrollTop: 0 },600); // $('.indexNav a').removeClass("action"); // $('.indexNav a:nth-of-type(1)').addClass("action"); } }
// dependencies import React, { useContext, useState } from 'react'; import { Tooltip } from '@material-ui/core'; import { Rating } from '@material-ui/lab'; // local modules import { addReview } from '../../services/gamesService'; import { AuthContext } from '../../contexts/authContext'; import { isIncluded } from '../../helpers/listsHelpers'; // styled components import { ReviewsContainer, BtnSpan, Textarea } from '../../styles/GameDetail.styled'; import { Button } from '../../styles/Form'; import { usePaperStyles } from '../../styles/Global'; export const NewReview = ({ gameID, updateGame, reviews }) => { const { user } = useContext(AuthContext); const classes = usePaperStyles(); const [review, setReview] = useState({ content: '', rating: 0 }); const handleSubmit = async e => { e.preventDefault(); const game = await addReview(gameID, review); updateGame(game); setReview({ content: '', rating: 0 }); }; return ( <> {user && !user.isAdmin && ( <ReviewsContainer className={classes.root}> <p className="paper-title">Share your thoughts with other players</p> <form onSubmit={handleSubmit}> <Rating name="rating" value={review.rating} onChange={(e, newValue) => { setReview({ ...review, rating: newValue }); }} precision={0.5} disabled={ !isIncluded(gameID, user.gamesPlayed) || reviews.some(review => review.author.username === user.username) } /> <div className="txt-container"> <Textarea name="content" value={review.content} rows="7" style={{ width: '100%' }} onChange={e => setReview({ ...review, content: e.target.value })} placeholder="Did you like it? Would you recommend it?" disabled={ !isIncluded(gameID, user.gamesPlayed) || reviews.some(review => review.author.username === user.username) } required /> </div> <Tooltip title={ !isIncluded(gameID, user.gamesPlayed) ? 'You have to play it before making a review' : reviews.some(review => review.author.username === user.username) ? 'You should edit or delete your review before posting again' : '' }> <BtnSpan allowed={ !isIncluded(gameID, user.gamesPlayed) || reviews.some(review => review.author.username === user.username) }> <Button type="submit" disabled={ !isIncluded(gameID, user.gamesPlayed) || reviews.some(review => review.author.username === user.username) } style={ !isIncluded(gameID, user.gamesPlayed) || reviews.some(review => review.author.username === user.username) ? { pointerEvents: 'none' } : {} }> Publish </Button> </BtnSpan> </Tooltip> </form> </ReviewsContainer> )} </> ); };
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.window = global.window || {})); }(this, (function (exports) { 'use strict'; var _svgPathExp = /[achlmqstvz]|(-?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig, _numbersExp = /(?:(-)?\d*\.?\d*(?:e[\-+]?\d+)?)[0-9]/ig, _scientific = /[\+\-]?\d*\.?\d+e[\+\-]?\d+/ig, _selectorExp = /(^[#\.][a-z]|[a-y][a-z])/i, _DEG2RAD = Math.PI / 180, _RAD2DEG = 180 / Math.PI, _sin = Math.sin, _cos = Math.cos, _abs = Math.abs, _sqrt = Math.sqrt, _atan2 = Math.atan2, _largeNum = 1e8, _isString = function _isString(value) { return typeof value === "string"; }, _isNumber = function _isNumber(value) { return typeof value === "number"; }, _isUndefined = function _isUndefined(value) { return typeof value === "undefined"; }, _temp = {}, _temp2 = {}, _roundingNum = 1e5, _wrapProgress = function _wrapProgress(progress) { return Math.round((progress + _largeNum) % 1 * _roundingNum) / _roundingNum || (progress < 0 ? 0 : 1); }, _round = function _round(value) { return Math.round(value * _roundingNum) / _roundingNum || 0; }, _roundPrecise = function _roundPrecise(value) { return Math.round(value * 1e10) / 1e10 || 0; }, _splitSegment = function _splitSegment(rawPath, segIndex, i, t) { var segment = rawPath[segIndex], shift = t === 1 ? 6 : subdivideSegment(segment, i, t); if (shift && shift + i + 2 < segment.length) { rawPath.splice(segIndex, 0, segment.slice(0, i + shift + 2)); segment.splice(0, i + shift); return 1; } }, _reverseRawPath = function _reverseRawPath(rawPath, skipOuter) { var i = rawPath.length; skipOuter || rawPath.reverse(); while (i--) { rawPath[i].reversed || reverseSegment(rawPath[i]); } }, _copyMetaData = function _copyMetaData(source, copy) { copy.totalLength = source.totalLength; if (source.samples) { copy.samples = source.samples.slice(0); copy.lookup = source.lookup.slice(0); copy.minLength = source.minLength; copy.resolution = source.resolution; } else if (source.totalPoints) { copy.totalPoints = source.totalPoints; } return copy; }, _appendOrMerge = function _appendOrMerge(rawPath, segment) { var index = rawPath.length, prevSeg = rawPath[index - 1] || [], l = prevSeg.length; if (index && segment[0] === prevSeg[l - 2] && segment[1] === prevSeg[l - 1]) { segment = prevSeg.concat(segment.slice(2)); index--; } rawPath[index] = segment; }; function getRawPath(value) { value = _isString(value) && _selectorExp.test(value) ? document.querySelector(value) || value : value; var e = value.getAttribute ? value : 0, rawPath; if (e && (value = value.getAttribute("d"))) { if (!e._gsPath) { e._gsPath = {}; } rawPath = e._gsPath[value]; return rawPath && !rawPath._dirty ? rawPath : e._gsPath[value] = stringToRawPath(value); } return !value ? console.warn("Expecting a <path> element or an SVG path data string") : _isString(value) ? stringToRawPath(value) : _isNumber(value[0]) ? [value] : value; } function copyRawPath(rawPath) { var a = [], i = 0; for (; i < rawPath.length; i++) { a[i] = _copyMetaData(rawPath[i], rawPath[i].slice(0)); } return _copyMetaData(rawPath, a); } function reverseSegment(segment) { var i = 0, y; segment.reverse(); for (; i < segment.length; i += 2) { y = segment[i]; segment[i] = segment[i + 1]; segment[i + 1] = y; } segment.reversed = !segment.reversed; } var _createPath = function _createPath(e, ignore) { var path = document.createElementNS("http://www.w3.org/2000/svg", "path"), attr = [].slice.call(e.attributes), i = attr.length, name; ignore = "," + ignore + ","; while (--i > -1) { name = attr[i].nodeName.toLowerCase(); if (ignore.indexOf("," + name + ",") < 0) { path.setAttributeNS(null, name, attr[i].nodeValue); } } return path; }, _typeAttrs = { rect: "rx,ry,x,y,width,height", circle: "r,cx,cy", ellipse: "rx,ry,cx,cy", line: "x1,x2,y1,y2" }, _attrToObj = function _attrToObj(e, attrs) { var props = attrs ? attrs.split(",") : [], obj = {}, i = props.length; while (--i > -1) { obj[props[i]] = +e.getAttribute(props[i]) || 0; } return obj; }; function convertToPath(element, swap) { var type = element.tagName.toLowerCase(), circ = 0.552284749831, data, x, y, r, ry, path, rcirc, rycirc, points, w, h, x2, x3, x4, x5, x6, y2, y3, y4, y5, y6, attr; if (type === "path" || !element.getBBox) { return element; } path = _createPath(element, "x,y,width,height,cx,cy,rx,ry,r,x1,x2,y1,y2,points"); attr = _attrToObj(element, _typeAttrs[type]); if (type === "rect") { r = attr.rx; ry = attr.ry || r; x = attr.x; y = attr.y; w = attr.width - r * 2; h = attr.height - ry * 2; if (r || ry) { x2 = x + r * (1 - circ); x3 = x + r; x4 = x3 + w; x5 = x4 + r * circ; x6 = x4 + r; y2 = y + ry * (1 - circ); y3 = y + ry; y4 = y3 + h; y5 = y4 + ry * circ; y6 = y4 + ry; data = "M" + x6 + "," + y3 + " V" + y4 + " C" + [x6, y5, x5, y6, x4, y6, x4 - (x4 - x3) / 3, y6, x3 + (x4 - x3) / 3, y6, x3, y6, x2, y6, x, y5, x, y4, x, y4 - (y4 - y3) / 3, x, y3 + (y4 - y3) / 3, x, y3, x, y2, x2, y, x3, y, x3 + (x4 - x3) / 3, y, x4 - (x4 - x3) / 3, y, x4, y, x5, y, x6, y2, x6, y3].join(",") + "z"; } else { data = "M" + (x + w) + "," + y + " v" + h + " h" + -w + " v" + -h + " h" + w + "z"; } } else if (type === "circle" || type === "ellipse") { if (type === "circle") { r = ry = attr.r; rycirc = r * circ; } else { r = attr.rx; ry = attr.ry; rycirc = ry * circ; } x = attr.cx; y = attr.cy; rcirc = r * circ; data = "M" + (x + r) + "," + y + " C" + [x + r, y + rycirc, x + rcirc, y + ry, x, y + ry, x - rcirc, y + ry, x - r, y + rycirc, x - r, y, x - r, y - rycirc, x - rcirc, y - ry, x, y - ry, x + rcirc, y - ry, x + r, y - rycirc, x + r, y].join(",") + "z"; } else if (type === "line") { data = "M" + attr.x1 + "," + attr.y1 + " L" + attr.x2 + "," + attr.y2; } else if (type === "polyline" || type === "polygon") { points = (element.getAttribute("points") + "").match(_numbersExp) || []; x = points.shift(); y = points.shift(); data = "M" + x + "," + y + " L" + points.join(","); if (type === "polygon") { data += "," + x + "," + y + "z"; } } path.setAttribute("d", rawPathToString(path._gsRawPath = stringToRawPath(data))); if (swap && element.parentNode) { element.parentNode.insertBefore(path, element); element.parentNode.removeChild(element); } return path; } function getRotationAtBezierT(segment, i, t) { var a = segment[i], b = segment[i + 2], c = segment[i + 4], x; a += (b - a) * t; b += (c - b) * t; a += (b - a) * t; x = b + (c + (segment[i + 6] - c) * t - b) * t - a; a = segment[i + 1]; b = segment[i + 3]; c = segment[i + 5]; a += (b - a) * t; b += (c - b) * t; a += (b - a) * t; return _round(_atan2(b + (c + (segment[i + 7] - c) * t - b) * t - a, x) * _RAD2DEG); } function sliceRawPath(rawPath, start, end) { end = _isUndefined(end) ? 1 : _roundPrecise(end) || 0; start = _roundPrecise(start) || 0; var loops = Math.max(0, ~~(_abs(end - start) - 1e-8)), path = copyRawPath(rawPath); if (start > end) { start = 1 - start; end = 1 - end; _reverseRawPath(path); path.totalLength = 0; } if (start < 0 || end < 0) { var offset = Math.abs(~~Math.min(start, end)) + 1; start += offset; end += offset; } path.totalLength || cacheRawPathMeasurements(path); var wrap = end > 1, s = getProgressData(path, start, _temp, true), e = getProgressData(path, end, _temp2), eSeg = e.segment, sSeg = s.segment, eSegIndex = e.segIndex, sSegIndex = s.segIndex, ei = e.i, si = s.i, sameSegment = sSegIndex === eSegIndex, sameBezier = ei === si && sameSegment, wrapsBehind, sShift, eShift, i, copy, totalSegments, l, j; if (wrap || loops) { wrapsBehind = eSegIndex < sSegIndex || sameSegment && ei < si || sameBezier && e.t < s.t; if (_splitSegment(path, sSegIndex, si, s.t)) { sSegIndex++; if (!wrapsBehind) { eSegIndex++; if (sameBezier) { e.t = (e.t - s.t) / (1 - s.t); ei = 0; } else if (sameSegment) { ei -= si; } } } if (1 - (end - start) < 1e-5) { eSegIndex = sSegIndex - 1; } else if (!e.t && eSegIndex) { eSegIndex--; } else if (_splitSegment(path, eSegIndex, ei, e.t) && wrapsBehind) { sSegIndex++; } if (s.t === 1) { sSegIndex = (sSegIndex + 1) % path.length; } copy = []; totalSegments = path.length; l = 1 + totalSegments * loops; j = sSegIndex; l += (totalSegments - sSegIndex + eSegIndex) % totalSegments; for (i = 0; i < l; i++) { _appendOrMerge(copy, path[j++ % totalSegments]); } path = copy; } else { eShift = e.t === 1 ? 6 : subdivideSegment(eSeg, ei, e.t); if (start !== end) { sShift = subdivideSegment(sSeg, si, sameBezier ? s.t / e.t : s.t); sameSegment && (eShift += sShift); eSeg.splice(ei + eShift + 2); (sShift || si) && sSeg.splice(0, si + sShift); i = path.length; while (i--) { (i < sSegIndex || i > eSegIndex) && path.splice(i, 1); } } else { eSeg.angle = getRotationAtBezierT(eSeg, ei + eShift, 0); ei += eShift; s = eSeg[ei]; e = eSeg[ei + 1]; eSeg.length = eSeg.totalLength = 0; eSeg.totalPoints = path.totalPoints = 8; eSeg.push(s, e, s, e, s, e, s, e); } } path.totalLength = 0; return path; } function measureSegment(segment, startIndex, bezierQty) { startIndex = startIndex || 0; if (!segment.samples) { segment.samples = []; segment.lookup = []; } var resolution = ~~segment.resolution || 12, inc = 1 / resolution, endIndex = bezierQty ? startIndex + bezierQty * 6 + 1 : segment.length, x1 = segment[startIndex], y1 = segment[startIndex + 1], samplesIndex = startIndex ? startIndex / 6 * resolution : 0, samples = segment.samples, lookup = segment.lookup, min = (startIndex ? segment.minLength : _largeNum) || _largeNum, prevLength = samples[samplesIndex + bezierQty * resolution - 1], length = startIndex ? samples[samplesIndex - 1] : 0, i, j, x4, x3, x2, xd, xd1, y4, y3, y2, yd, yd1, inv, t, lengthIndex, l, segLength; samples.length = lookup.length = 0; for (j = startIndex + 2; j < endIndex; j += 6) { x4 = segment[j + 4] - x1; x3 = segment[j + 2] - x1; x2 = segment[j] - x1; y4 = segment[j + 5] - y1; y3 = segment[j + 3] - y1; y2 = segment[j + 1] - y1; xd = xd1 = yd = yd1 = 0; if (_abs(x4) < 1e-5 && _abs(y4) < 1e-5 && _abs(x2) + _abs(y2) < 1e-5) { if (segment.length > 8) { segment.splice(j, 6); j -= 6; endIndex -= 6; } } else { for (i = 1; i <= resolution; i++) { t = inc * i; inv = 1 - t; xd = xd1 - (xd1 = (t * t * x4 + 3 * inv * (t * x3 + inv * x2)) * t); yd = yd1 - (yd1 = (t * t * y4 + 3 * inv * (t * y3 + inv * y2)) * t); l = _sqrt(yd * yd + xd * xd); if (l < min) { min = l; } length += l; samples[samplesIndex++] = length; } } x1 += x4; y1 += y4; } if (prevLength) { prevLength -= length; for (; samplesIndex < samples.length; samplesIndex++) { samples[samplesIndex] += prevLength; } } if (samples.length && min) { segment.totalLength = segLength = samples[samples.length - 1] || 0; segment.minLength = min; l = lengthIndex = 0; for (i = 0; i < segLength; i += min) { lookup[l++] = samples[lengthIndex] < i ? ++lengthIndex : lengthIndex; } } else { segment.totalLength = samples[0] = 0; } return startIndex ? length - samples[startIndex / 2 - 1] : length; } function cacheRawPathMeasurements(rawPath, resolution) { var pathLength, points, i; for (i = pathLength = points = 0; i < rawPath.length; i++) { rawPath[i].resolution = ~~resolution || 12; points += rawPath[i].length; pathLength += measureSegment(rawPath[i]); } rawPath.totalPoints = points; rawPath.totalLength = pathLength; return rawPath; } function subdivideSegment(segment, i, t) { if (t <= 0 || t >= 1) { return 0; } var ax = segment[i], ay = segment[i + 1], cp1x = segment[i + 2], cp1y = segment[i + 3], cp2x = segment[i + 4], cp2y = segment[i + 5], bx = segment[i + 6], by = segment[i + 7], x1a = ax + (cp1x - ax) * t, x2 = cp1x + (cp2x - cp1x) * t, y1a = ay + (cp1y - ay) * t, y2 = cp1y + (cp2y - cp1y) * t, x1 = x1a + (x2 - x1a) * t, y1 = y1a + (y2 - y1a) * t, x2a = cp2x + (bx - cp2x) * t, y2a = cp2y + (by - cp2y) * t; x2 += (x2a - x2) * t; y2 += (y2a - y2) * t; segment.splice(i + 2, 4, _round(x1a), _round(y1a), _round(x1), _round(y1), _round(x1 + (x2 - x1) * t), _round(y1 + (y2 - y1) * t), _round(x2), _round(y2), _round(x2a), _round(y2a)); segment.samples && segment.samples.splice(i / 6 * segment.resolution | 0, 0, 0, 0, 0, 0, 0, 0); return 6; } function getProgressData(rawPath, progress, decoratee, pushToNextIfAtEnd) { decoratee = decoratee || {}; rawPath.totalLength || cacheRawPathMeasurements(rawPath); if (progress < 0 || progress > 1) { progress = _wrapProgress(progress); } var segIndex = 0, segment = rawPath[0], samples, resolution, length, min, max, i, t; if (!progress) { t = i = segIndex = 0; segment = rawPath[0]; } else if (progress === 1) { t = 1; segIndex = rawPath.length - 1; segment = rawPath[segIndex]; i = segment.length - 8; } else { if (rawPath.length > 1) { length = rawPath.totalLength * progress; max = i = 0; while ((max += rawPath[i++].totalLength) < length) { segIndex = i; } segment = rawPath[segIndex]; min = max - segment.totalLength; progress = (length - min) / (max - min) || 0; } samples = segment.samples; resolution = segment.resolution; length = segment.totalLength * progress; i = segment.lookup[~~(length / segment.minLength)] || 0; min = i ? samples[i - 1] : 0; max = samples[i]; if (max < length) { min = max; max = samples[++i]; } t = 1 / resolution * ((length - min) / (max - min) + i % resolution); i = ~~(i / resolution) * 6; if (pushToNextIfAtEnd && t === 1) { if (i + 6 < segment.length) { i += 6; t = 0; } else if (segIndex + 1 < rawPath.length) { i = t = 0; segment = rawPath[++segIndex]; } } } decoratee.t = t; decoratee.i = i; decoratee.path = rawPath; decoratee.segment = segment; decoratee.segIndex = segIndex; return decoratee; } function getPositionOnPath(rawPath, progress, includeAngle, point) { var segment = rawPath[0], result = point || {}, samples, resolution, length, min, max, i, t, a, inv; if (progress < 0 || progress > 1) { progress = _wrapProgress(progress); } if (rawPath.length > 1) { length = rawPath.totalLength * progress; max = i = 0; while ((max += rawPath[i++].totalLength) < length) { segment = rawPath[i]; } min = max - segment.totalLength; progress = (length - min) / (max - min) || 0; } samples = segment.samples; resolution = segment.resolution; length = segment.totalLength * progress; i = segment.lookup[progress < 1 ? ~~(length / segment.minLength) : segment.lookup.length - 1] || 0; min = i ? samples[i - 1] : 0; max = samples[i]; if (max < length) { min = max; max = samples[++i]; } t = 1 / resolution * ((length - min) / (max - min) + i % resolution) || 0; inv = 1 - t; i = ~~(i / resolution) * 6; a = segment[i]; result.x = _round((t * t * (segment[i + 6] - a) + 3 * inv * (t * (segment[i + 4] - a) + inv * (segment[i + 2] - a))) * t + a); result.y = _round((t * t * (segment[i + 7] - (a = segment[i + 1])) + 3 * inv * (t * (segment[i + 5] - a) + inv * (segment[i + 3] - a))) * t + a); if (includeAngle) { result.angle = segment.totalLength ? getRotationAtBezierT(segment, i, t >= 1 ? 1 - 1e-9 : t ? t : 1e-9) : segment.angle || 0; } return result; } function transformRawPath(rawPath, a, b, c, d, tx, ty) { var j = rawPath.length, segment, l, i, x, y; while (--j > -1) { segment = rawPath[j]; l = segment.length; for (i = 0; i < l; i += 2) { x = segment[i]; y = segment[i + 1]; segment[i] = x * a + y * c + tx; segment[i + 1] = x * b + y * d + ty; } } rawPath._dirty = 1; return rawPath; } function arcToSegment(lastX, lastY, rx, ry, angle, largeArcFlag, sweepFlag, x, y) { if (lastX === x && lastY === y) { return; } rx = _abs(rx); ry = _abs(ry); var angleRad = angle % 360 * _DEG2RAD, cosAngle = _cos(angleRad), sinAngle = _sin(angleRad), PI = Math.PI, TWOPI = PI * 2, dx2 = (lastX - x) / 2, dy2 = (lastY - y) / 2, x1 = cosAngle * dx2 + sinAngle * dy2, y1 = -sinAngle * dx2 + cosAngle * dy2, x1_sq = x1 * x1, y1_sq = y1 * y1, radiiCheck = x1_sq / (rx * rx) + y1_sq / (ry * ry); if (radiiCheck > 1) { rx = _sqrt(radiiCheck) * rx; ry = _sqrt(radiiCheck) * ry; } var rx_sq = rx * rx, ry_sq = ry * ry, sq = (rx_sq * ry_sq - rx_sq * y1_sq - ry_sq * x1_sq) / (rx_sq * y1_sq + ry_sq * x1_sq); if (sq < 0) { sq = 0; } var coef = (largeArcFlag === sweepFlag ? -1 : 1) * _sqrt(sq), cx1 = coef * (rx * y1 / ry), cy1 = coef * -(ry * x1 / rx), sx2 = (lastX + x) / 2, sy2 = (lastY + y) / 2, cx = sx2 + (cosAngle * cx1 - sinAngle * cy1), cy = sy2 + (sinAngle * cx1 + cosAngle * cy1), ux = (x1 - cx1) / rx, uy = (y1 - cy1) / ry, vx = (-x1 - cx1) / rx, vy = (-y1 - cy1) / ry, temp = ux * ux + uy * uy, angleStart = (uy < 0 ? -1 : 1) * Math.acos(ux / _sqrt(temp)), angleExtent = (ux * vy - uy * vx < 0 ? -1 : 1) * Math.acos((ux * vx + uy * vy) / _sqrt(temp * (vx * vx + vy * vy))); isNaN(angleExtent) && (angleExtent = PI); if (!sweepFlag && angleExtent > 0) { angleExtent -= TWOPI; } else if (sweepFlag && angleExtent < 0) { angleExtent += TWOPI; } angleStart %= TWOPI; angleExtent %= TWOPI; var segments = Math.ceil(_abs(angleExtent) / (TWOPI / 4)), rawPath = [], angleIncrement = angleExtent / segments, controlLength = 4 / 3 * _sin(angleIncrement / 2) / (1 + _cos(angleIncrement / 2)), ma = cosAngle * rx, mb = sinAngle * rx, mc = sinAngle * -ry, md = cosAngle * ry, i; for (i = 0; i < segments; i++) { angle = angleStart + i * angleIncrement; x1 = _cos(angle); y1 = _sin(angle); ux = _cos(angle += angleIncrement); uy = _sin(angle); rawPath.push(x1 - controlLength * y1, y1 + controlLength * x1, ux + controlLength * uy, uy - controlLength * ux, ux, uy); } for (i = 0; i < rawPath.length; i += 2) { x1 = rawPath[i]; y1 = rawPath[i + 1]; rawPath[i] = x1 * ma + y1 * mc + cx; rawPath[i + 1] = x1 * mb + y1 * md + cy; } rawPath[i - 2] = x; rawPath[i - 1] = y; return rawPath; } function stringToRawPath(d) { var a = (d + "").replace(_scientific, function (m) { var n = +m; return n < 0.0001 && n > -0.0001 ? 0 : n; }).match(_svgPathExp) || [], path = [], relativeX = 0, relativeY = 0, twoThirds = 2 / 3, elements = a.length, points = 0, errorMessage = "ERROR: malformed path: " + d, i, j, x, y, command, isRelative, segment, startX, startY, difX, difY, beziers, prevCommand, flag1, flag2, line = function line(sx, sy, ex, ey) { difX = (ex - sx) / 3; difY = (ey - sy) / 3; segment.push(sx + difX, sy + difY, ex - difX, ey - difY, ex, ey); }; if (!d || !isNaN(a[0]) || isNaN(a[1])) { console.log(errorMessage); return path; } for (i = 0; i < elements; i++) { prevCommand = command; if (isNaN(a[i])) { command = a[i].toUpperCase(); isRelative = command !== a[i]; } else { i--; } x = +a[i + 1]; y = +a[i + 2]; if (isRelative) { x += relativeX; y += relativeY; } if (!i) { startX = x; startY = y; } if (command === "M") { if (segment) { if (segment.length < 8) { path.length -= 1; } else { points += segment.length; } } relativeX = startX = x; relativeY = startY = y; segment = [x, y]; path.push(segment); i += 2; command = "L"; } else if (command === "C") { if (!segment) { segment = [0, 0]; } if (!isRelative) { relativeX = relativeY = 0; } segment.push(x, y, relativeX + a[i + 3] * 1, relativeY + a[i + 4] * 1, relativeX += a[i + 5] * 1, relativeY += a[i + 6] * 1); i += 6; } else if (command === "S") { difX = relativeX; difY = relativeY; if (prevCommand === "C" || prevCommand === "S") { difX += relativeX - segment[segment.length - 4]; difY += relativeY - segment[segment.length - 3]; } if (!isRelative) { relativeX = relativeY = 0; } segment.push(difX, difY, x, y, relativeX += a[i + 3] * 1, relativeY += a[i + 4] * 1); i += 4; } else if (command === "Q") { difX = relativeX + (x - relativeX) * twoThirds; difY = relativeY + (y - relativeY) * twoThirds; if (!isRelative) { relativeX = relativeY = 0; } relativeX += a[i + 3] * 1; relativeY += a[i + 4] * 1; segment.push(difX, difY, relativeX + (x - relativeX) * twoThirds, relativeY + (y - relativeY) * twoThirds, relativeX, relativeY); i += 4; } else if (command === "T") { difX = relativeX - segment[segment.length - 4]; difY = relativeY - segment[segment.length - 3]; segment.push(relativeX + difX, relativeY + difY, x + (relativeX + difX * 1.5 - x) * twoThirds, y + (relativeY + difY * 1.5 - y) * twoThirds, relativeX = x, relativeY = y); i += 2; } else if (command === "H") { line(relativeX, relativeY, relativeX = x, relativeY); i += 1; } else if (command === "V") { line(relativeX, relativeY, relativeX, relativeY = x + (isRelative ? relativeY - relativeX : 0)); i += 1; } else if (command === "L" || command === "Z") { if (command === "Z") { x = startX; y = startY; segment.closed = true; } if (command === "L" || _abs(relativeX - x) > 0.5 || _abs(relativeY - y) > 0.5) { line(relativeX, relativeY, x, y); if (command === "L") { i += 2; } } relativeX = x; relativeY = y; } else if (command === "A") { flag1 = a[i + 4]; flag2 = a[i + 5]; difX = a[i + 6]; difY = a[i + 7]; j = 7; if (flag1.length > 1) { if (flag1.length < 3) { difY = difX; difX = flag2; j--; } else { difY = flag2; difX = flag1.substr(2); j -= 2; } flag2 = flag1.charAt(1); flag1 = flag1.charAt(0); } beziers = arcToSegment(relativeX, relativeY, +a[i + 1], +a[i + 2], +a[i + 3], +flag1, +flag2, (isRelative ? relativeX : 0) + difX * 1, (isRelative ? relativeY : 0) + difY * 1); i += j; if (beziers) { for (j = 0; j < beziers.length; j++) { segment.push(beziers[j]); } } relativeX = segment[segment.length - 2]; relativeY = segment[segment.length - 1]; } else { console.log(errorMessage); } } i = segment.length; if (i < 6) { path.pop(); i = 0; } else if (segment[0] === segment[i - 2] && segment[1] === segment[i - 1]) { segment.closed = true; } path.totalPoints = points + i; return path; } function flatPointsToSegment(points, curviness) { if (curviness === void 0) { curviness = 1; } var x = points[0], y = 0, segment = [x, y], i = 2; for (; i < points.length; i += 2) { segment.push(x, y, points[i], y = (points[i] - x) * curviness / 2, x = points[i], -y); } return segment; } function pointsToSegment(points, curviness, cornerThreshold) { _abs(points[0] - points[2]) < 1e-4 && _abs(points[1] - points[3]) < 1e-4 && (points = points.slice(2)); var l = points.length - 2, x = +points[0], y = +points[1], nextX = +points[2], nextY = +points[3], segment = [x, y, x, y], dx2 = nextX - x, dy2 = nextY - y, closed = Math.abs(points[l] - x) < 0.001 && Math.abs(points[l + 1] - y) < 0.001, prevX, prevY, angle, slope, i, dx1, dx3, dy1, dy3, d1, d2, a, b, c; if (isNaN(cornerThreshold)) { cornerThreshold = Math.PI / 10; } if (closed) { points.push(nextX, nextY); nextX = x; nextY = y; x = points[l - 2]; y = points[l - 1]; points.unshift(x, y); l += 4; } curviness = curviness || curviness === 0 ? +curviness : 1; for (i = 2; i < l; i += 2) { prevX = x; prevY = y; x = nextX; y = nextY; nextX = +points[i + 2]; nextY = +points[i + 3]; if (x === nextX && y === nextY) { continue; } dx1 = dx2; dy1 = dy2; dx2 = nextX - x; dy2 = nextY - y; dx3 = nextX - prevX; dy3 = nextY - prevY; a = dx1 * dx1 + dy1 * dy1; b = dx2 * dx2 + dy2 * dy2; c = dx3 * dx3 + dy3 * dy3; angle = Math.acos((a + b - c) / _sqrt(4 * a * b)); d2 = angle / Math.PI * curviness; d1 = _sqrt(a) * d2; d2 *= _sqrt(b); if (x !== prevX || y !== prevY) { if (angle > cornerThreshold) { slope = _atan2(dy3, dx3); segment.push(_round(x - _cos(slope) * d1), _round(y - _sin(slope) * d1), _round(x), _round(y), _round(x + _cos(slope) * d2), _round(y + _sin(slope) * d2)); } else { slope = _atan2(dy1, dx1); segment.push(_round(x - _cos(slope) * d1), _round(y - _sin(slope) * d1)); slope = _atan2(dy2, dx2); segment.push(_round(x), _round(y), _round(x + _cos(slope) * d2), _round(y + _sin(slope) * d2)); } } } x !== nextX || y !== nextY || segment.length < 4 ? segment.push(_round(nextX), _round(nextY), _round(nextX), _round(nextY)) : segment.length -= 2; if (closed) { segment.splice(0, 6); segment.length = segment.length - 6; } return segment; } function rawPathToString(rawPath) { if (_isNumber(rawPath[0])) { rawPath = [rawPath]; } var result = "", l = rawPath.length, sl, s, i, segment; for (s = 0; s < l; s++) { segment = rawPath[s]; result += "M" + _round(segment[0]) + "," + _round(segment[1]) + " C"; sl = segment.length; for (i = 2; i < sl; i++) { result += _round(segment[i++]) + "," + _round(segment[i++]) + " " + _round(segment[i++]) + "," + _round(segment[i++]) + " " + _round(segment[i++]) + "," + _round(segment[i]) + " "; } if (segment.closed) { result += "z"; } } return result; } var _doc, _win, _docElement, _body, _divContainer, _svgContainer, _identityMatrix, _transformProp = "transform", _transformOriginProp = _transformProp + "Origin", _hasOffsetBug, _setDoc = function _setDoc(element) { var doc = element.ownerDocument || element; if (!(_transformProp in element.style) && "msTransform" in element.style) { _transformProp = "msTransform"; _transformOriginProp = _transformProp + "Origin"; } while (doc.parentNode && (doc = doc.parentNode)) {} _win = window; _identityMatrix = new Matrix2D(); if (doc) { _doc = doc; _docElement = doc.documentElement; _body = doc.body; var d1 = doc.createElement("div"), d2 = doc.createElement("div"); _body.appendChild(d1); d1.appendChild(d2); d1.style.position = "static"; d1.style[_transformProp] = "translate3d(0,0,1px)"; _hasOffsetBug = d2.offsetParent !== d1; _body.removeChild(d1); } return doc; }, _forceNonZeroScale = function _forceNonZeroScale(e) { var a, cache; while (e && e !== _body) { cache = e._gsap; cache && cache.uncache && cache.get(e, "x"); if (cache && !cache.scaleX && !cache.scaleY && cache.renderTransform) { cache.scaleX = cache.scaleY = 1e-4; cache.renderTransform(1, cache); a ? a.push(cache) : a = [cache]; } e = e.parentNode; } return a; }, _svgTemps = [], _divTemps = [], _getDocScrollTop = function _getDocScrollTop() { return _win.pageYOffset || _doc.scrollTop || _docElement.scrollTop || _body.scrollTop || 0; }, _getDocScrollLeft = function _getDocScrollLeft() { return _win.pageXOffset || _doc.scrollLeft || _docElement.scrollLeft || _body.scrollLeft || 0; }, _svgOwner = function _svgOwner(element) { return element.ownerSVGElement || ((element.tagName + "").toLowerCase() === "svg" ? element : null); }, _isFixed = function _isFixed(element) { if (_win.getComputedStyle(element).position === "fixed") { return true; } element = element.parentNode; if (element && element.nodeType === 1) { return _isFixed(element); } }, _createSibling = function _createSibling(element, i) { if (element.parentNode && (_doc || _setDoc(element))) { var svg = _svgOwner(element), ns = svg ? svg.getAttribute("xmlns") || "http://www.w3.org/2000/svg" : "http://www.w3.org/1999/xhtml", type = svg ? i ? "rect" : "g" : "div", x = i !== 2 ? 0 : 100, y = i === 3 ? 100 : 0, css = "position:absolute;display:block;pointer-events:none;margin:0;padding:0;", e = _doc.createElementNS ? _doc.createElementNS(ns.replace(/^https/, "http"), type) : _doc.createElement(type); if (i) { if (!svg) { if (!_divContainer) { _divContainer = _createSibling(element); _divContainer.style.cssText = css; } e.style.cssText = css + "width:0.1px;height:0.1px;top:" + y + "px;left:" + x + "px"; _divContainer.appendChild(e); } else { _svgContainer || (_svgContainer = _createSibling(element)); e.setAttribute("width", 0.01); e.setAttribute("height", 0.01); e.setAttribute("transform", "translate(" + x + "," + y + ")"); _svgContainer.appendChild(e); } } return e; } throw "Need document and parent."; }, _consolidate = function _consolidate(m) { var c = new Matrix2D(), i = 0; for (; i < m.numberOfItems; i++) { c.multiply(m.getItem(i).matrix); } return c; }, _placeSiblings = function _placeSiblings(element, adjustGOffset) { var svg = _svgOwner(element), isRootSVG = element === svg, siblings = svg ? _svgTemps : _divTemps, parent = element.parentNode, container, m, b, x, y, cs; if (element === _win) { return element; } siblings.length || siblings.push(_createSibling(element, 1), _createSibling(element, 2), _createSibling(element, 3)); container = svg ? _svgContainer : _divContainer; if (svg) { b = isRootSVG ? { x: 0, y: 0 } : element.getBBox(); m = element.transform ? element.transform.baseVal : {}; if (m.numberOfItems) { m = m.numberOfItems > 1 ? _consolidate(m) : m.getItem(0).matrix; x = m.a * b.x + m.c * b.y; y = m.b * b.x + m.d * b.y; } else { m = _identityMatrix; x = b.x; y = b.y; } if (adjustGOffset && element.tagName.toLowerCase() === "g") { x = y = 0; } (isRootSVG ? svg : parent).appendChild(container); container.setAttribute("transform", "matrix(" + m.a + "," + m.b + "," + m.c + "," + m.d + "," + (m.e + x) + "," + (m.f + y) + ")"); } else { x = y = 0; if (_hasOffsetBug) { m = element.offsetParent; b = element; while (b && (b = b.parentNode) && b !== m && b.parentNode) { if ((_win.getComputedStyle(b)[_transformProp] + "").length > 4) { x = b.offsetLeft; y = b.offsetTop; b = 0; } } } cs = _win.getComputedStyle(element); if (cs.position !== "absolute") { m = element.offsetParent; while (parent && parent !== m) { x += parent.scrollLeft || 0; y += parent.scrollTop || 0; parent = parent.parentNode; } } b = container.style; b.top = element.offsetTop - y + "px"; b.left = element.offsetLeft - x + "px"; b[_transformProp] = cs[_transformProp]; b[_transformOriginProp] = cs[_transformOriginProp]; b.position = cs.position === "fixed" ? "fixed" : "absolute"; element.parentNode.appendChild(container); } return container; }, _setMatrix = function _setMatrix(m, a, b, c, d, e, f) { m.a = a; m.b = b; m.c = c; m.d = d; m.e = e; m.f = f; return m; }; var Matrix2D = function () { function Matrix2D(a, b, c, d, e, f) { if (a === void 0) { a = 1; } if (b === void 0) { b = 0; } if (c === void 0) { c = 0; } if (d === void 0) { d = 1; } if (e === void 0) { e = 0; } if (f === void 0) { f = 0; } _setMatrix(this, a, b, c, d, e, f); } var _proto = Matrix2D.prototype; _proto.inverse = function inverse() { var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f, determinant = a * d - b * c || 1e-10; return _setMatrix(this, d / determinant, -b / determinant, -c / determinant, a / determinant, (c * f - d * e) / determinant, -(a * f - b * e) / determinant); }; _proto.multiply = function multiply(matrix) { var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f, a2 = matrix.a, b2 = matrix.c, c2 = matrix.b, d2 = matrix.d, e2 = matrix.e, f2 = matrix.f; return _setMatrix(this, a2 * a + c2 * c, a2 * b + c2 * d, b2 * a + d2 * c, b2 * b + d2 * d, e + e2 * a + f2 * c, f + e2 * b + f2 * d); }; _proto.clone = function clone() { return new Matrix2D(this.a, this.b, this.c, this.d, this.e, this.f); }; _proto.equals = function equals(matrix) { var a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f; return a === matrix.a && b === matrix.b && c === matrix.c && d === matrix.d && e === matrix.e && f === matrix.f; }; _proto.apply = function apply(point, decoratee) { if (decoratee === void 0) { decoratee = {}; } var x = point.x, y = point.y, a = this.a, b = this.b, c = this.c, d = this.d, e = this.e, f = this.f; decoratee.x = x * a + y * c + e || 0; decoratee.y = x * b + y * d + f || 0; return decoratee; }; return Matrix2D; }(); function getGlobalMatrix(element, inverse, adjustGOffset, includeScrollInFixed) { if (!element || !element.parentNode || (_doc || _setDoc(element)).documentElement === element) { return new Matrix2D(); } var zeroScales = _forceNonZeroScale(element), svg = _svgOwner(element), temps = svg ? _svgTemps : _divTemps, container = _placeSiblings(element, adjustGOffset), b1 = temps[0].getBoundingClientRect(), b2 = temps[1].getBoundingClientRect(), b3 = temps[2].getBoundingClientRect(), parent = container.parentNode, isFixed = !includeScrollInFixed && _isFixed(element), m = new Matrix2D((b2.left - b1.left) / 100, (b2.top - b1.top) / 100, (b3.left - b1.left) / 100, (b3.top - b1.top) / 100, b1.left + (isFixed ? 0 : _getDocScrollLeft()), b1.top + (isFixed ? 0 : _getDocScrollTop())); parent.removeChild(container); if (zeroScales) { b1 = zeroScales.length; while (b1--) { b2 = zeroScales[b1]; b2.scaleX = b2.scaleY = 0; b2.renderTransform(1, b2); } } return inverse ? m.inverse() : m; } /*! * MotionPathPlugin 3.6.1 * https://greensock.com * * @license Copyright 2008-2021, GreenSock. All rights reserved. * Subject to the terms at https://greensock.com/standard-license or for * Club GreenSock members, the agreement issued with that membership. * @author: Jack Doyle, jack@greensock.com */ var _xProps = "x,translateX,left,marginLeft,xPercent".split(","), _yProps = "y,translateY,top,marginTop,yPercent".split(","), _DEG2RAD$1 = Math.PI / 180, gsap, PropTween, _getUnit, _toArray, _getGSAP = function _getGSAP() { return gsap || typeof window !== "undefined" && (gsap = window.gsap) && gsap.registerPlugin && gsap; }, _populateSegmentFromArray = function _populateSegmentFromArray(segment, values, property, mode) { var l = values.length, si = mode === 2 ? 0 : mode, i = 0, v; for (; i < l; i++) { segment[si] = v = parseFloat(values[i][property]); mode === 2 && (segment[si + 1] = 0); si += 2; } return segment; }, _getPropNum = function _getPropNum(target, prop, unit) { return parseFloat(target._gsap.get(target, prop, unit || "px")) || 0; }, _relativize = function _relativize(segment) { var x = segment[0], y = segment[1], i; for (i = 2; i < segment.length; i += 2) { x = segment[i] += x; y = segment[i + 1] += y; } }, _segmentToRawPath = function _segmentToRawPath(plugin, segment, target, x, y, slicer, vars, unitX, unitY) { if (vars.type === "cubic") { segment = [segment]; } else { segment.unshift(_getPropNum(target, x, unitX), y ? _getPropNum(target, y, unitY) : 0); vars.relative && _relativize(segment); var pointFunc = y ? pointsToSegment : flatPointsToSegment; segment = [pointFunc(segment, vars.curviness)]; } segment = slicer(_align(segment, target, vars)); _addDimensionalPropTween(plugin, target, x, segment, "x", unitX); y && _addDimensionalPropTween(plugin, target, y, segment, "y", unitY); return cacheRawPathMeasurements(segment, vars.resolution || (vars.curviness === 0 ? 20 : 12)); }, _emptyFunc = function _emptyFunc(v) { return v; }, _numExp = /[-+\.]*\d+[\.e\-\+]*\d*[e\-\+]*\d*/g, _originToPoint = function _originToPoint(element, origin, parentMatrix) { var m = getGlobalMatrix(element), svg, x, y; if ((element.tagName + "").toLowerCase() === "svg") { svg = element.viewBox.baseVal; x = svg.x; y = svg.y; svg.width || (svg = { width: +element.getAttribute("width"), height: +element.getAttribute("height") }); } else { svg = origin && element.getBBox && element.getBBox(); x = y = 0; } if (origin && origin !== "auto") { x += origin.push ? origin[0] * (svg ? svg.width : element.offsetWidth || 0) : origin.x; y += origin.push ? origin[1] * (svg ? svg.height : element.offsetHeight || 0) : origin.y; } return parentMatrix.apply(x || y ? m.apply({ x: x, y: y }) : { x: m.e, y: m.f }); }, _getAlignMatrix = function _getAlignMatrix(fromElement, toElement, fromOrigin, toOrigin) { var parentMatrix = getGlobalMatrix(fromElement.parentNode, true, true), m = parentMatrix.clone().multiply(getGlobalMatrix(toElement)), fromPoint = _originToPoint(fromElement, fromOrigin, parentMatrix), _originToPoint2 = _originToPoint(toElement, toOrigin, parentMatrix), x = _originToPoint2.x, y = _originToPoint2.y, p; m.e = m.f = 0; if (toOrigin === "auto" && toElement.getTotalLength && toElement.tagName.toLowerCase() === "path") { p = toElement.getAttribute("d").match(_numExp) || []; p = m.apply({ x: +p[0], y: +p[1] }); x += p.x; y += p.y; } if (p || toElement.getBBox && fromElement.getBBox && toElement.ownerSVGElement === fromElement.ownerSVGElement) { p = m.apply(toElement.getBBox()); x -= p.x; y -= p.y; } m.e = x - fromPoint.x; m.f = y - fromPoint.y; return m; }, _align = function _align(rawPath, target, _ref) { var align = _ref.align, matrix = _ref.matrix, offsetX = _ref.offsetX, offsetY = _ref.offsetY, alignOrigin = _ref.alignOrigin; var x = rawPath[0][0], y = rawPath[0][1], curX = _getPropNum(target, "x"), curY = _getPropNum(target, "y"), alignTarget, m, p; if (!rawPath || !rawPath.length) { return getRawPath("M0,0L0,0"); } if (align) { if (align === "self" || (alignTarget = _toArray(align)[0] || target) === target) { transformRawPath(rawPath, 1, 0, 0, 1, curX - x, curY - y); } else { if (alignOrigin && alignOrigin[2] !== false) { gsap.set(target, { transformOrigin: alignOrigin[0] * 100 + "% " + alignOrigin[1] * 100 + "%" }); } else { alignOrigin = [_getPropNum(target, "xPercent") / -100, _getPropNum(target, "yPercent") / -100]; } m = _getAlignMatrix(target, alignTarget, alignOrigin, "auto"); p = m.apply({ x: x, y: y }); transformRawPath(rawPath, m.a, m.b, m.c, m.d, curX + m.e - (p.x - m.e), curY + m.f - (p.y - m.f)); } } if (matrix) { transformRawPath(rawPath, matrix.a, matrix.b, matrix.c, matrix.d, matrix.e, matrix.f); } else if (offsetX || offsetY) { transformRawPath(rawPath, 1, 0, 0, 1, offsetX || 0, offsetY || 0); } return rawPath; }, _addDimensionalPropTween = function _addDimensionalPropTween(plugin, target, property, rawPath, pathProperty, forceUnit) { var cache = target._gsap, harness = cache.harness, alias = harness && harness.aliases && harness.aliases[property], prop = alias && alias.indexOf(",") < 0 ? alias : property, pt = plugin._pt = new PropTween(plugin._pt, target, prop, 0, 0, _emptyFunc, 0, cache.set(target, prop, plugin)); pt.u = _getUnit(cache.get(target, prop, forceUnit)) || 0; pt.path = rawPath; pt.pp = pathProperty; plugin._props.push(prop); }, _sliceModifier = function _sliceModifier(start, end) { return function (rawPath) { return start || end !== 1 ? sliceRawPath(rawPath, start, end) : rawPath; }; }; var MotionPathPlugin = { version: "3.6.1", name: "motionPath", register: function register(core, Plugin, propTween) { gsap = core; _getUnit = gsap.utils.getUnit; _toArray = gsap.utils.toArray; PropTween = propTween; }, init: function init(target, vars) { if (!gsap) { console.warn("Please gsap.registerPlugin(MotionPathPlugin)"); return false; } if (!(typeof vars === "object" && !vars.style) || !vars.path) { vars = { path: vars }; } var rawPaths = [], _vars = vars, path = _vars.path, autoRotate = _vars.autoRotate, unitX = _vars.unitX, unitY = _vars.unitY, x = _vars.x, y = _vars.y, firstObj = path[0], slicer = _sliceModifier(vars.start, "end" in vars ? vars.end : 1), rawPath, p; this.rawPaths = rawPaths; this.target = target; if (this.rotate = autoRotate || autoRotate === 0) { this.rOffset = parseFloat(autoRotate) || 0; this.radians = !!vars.useRadians; this.rProp = vars.rotation || "rotation"; this.rSet = target._gsap.set(target, this.rProp, this); this.ru = _getUnit(target._gsap.get(target, this.rProp)) || 0; } if (Array.isArray(path) && !("closed" in path) && typeof firstObj !== "number") { for (p in firstObj) { if (!x && ~_xProps.indexOf(p)) { x = p; } else if (!y && ~_yProps.indexOf(p)) { y = p; } } if (x && y) { rawPaths.push(_segmentToRawPath(this, _populateSegmentFromArray(_populateSegmentFromArray([], path, x, 0), path, y, 1), target, x, y, slicer, vars, unitX || _getUnit(path[0][x]), unitY || _getUnit(path[0][y]))); } else { x = y = 0; } for (p in firstObj) { p !== x && p !== y && rawPaths.push(_segmentToRawPath(this, _populateSegmentFromArray([], path, p, 2), target, p, 0, slicer, vars, _getUnit(path[0][p]))); } } else { rawPath = slicer(_align(getRawPath(vars.path), target, vars)); cacheRawPathMeasurements(rawPath, vars.resolution); rawPaths.push(rawPath); _addDimensionalPropTween(this, target, vars.x || "x", rawPath, "x", vars.unitX || "px"); _addDimensionalPropTween(this, target, vars.y || "y", rawPath, "y", vars.unitY || "px"); } }, render: function render(ratio, data) { var rawPaths = data.rawPaths, i = rawPaths.length, pt = data._pt; if (ratio > 1) { ratio = 1; } else if (ratio < 0) { ratio = 0; } while (i--) { getPositionOnPath(rawPaths[i], ratio, !i && data.rotate, rawPaths[i]); } while (pt) { pt.set(pt.t, pt.p, pt.path[pt.pp] + pt.u, pt.d, ratio); pt = pt._next; } data.rotate && data.rSet(data.target, data.rProp, rawPaths[0].angle * (data.radians ? _DEG2RAD$1 : 1) + data.rOffset + data.ru, data, ratio); }, getLength: function getLength(path) { return cacheRawPathMeasurements(getRawPath(path)).totalLength; }, sliceRawPath: sliceRawPath, getRawPath: getRawPath, pointsToSegment: pointsToSegment, stringToRawPath: stringToRawPath, rawPathToString: rawPathToString, transformRawPath: transformRawPath, getGlobalMatrix: getGlobalMatrix, getPositionOnPath: getPositionOnPath, cacheRawPathMeasurements: cacheRawPathMeasurements, convertToPath: function convertToPath$1(targets, swap) { return _toArray(targets).map(function (target) { return convertToPath(target, swap !== false); }); }, convertCoordinates: function convertCoordinates(fromElement, toElement, point) { var m = getGlobalMatrix(toElement, true, true).multiply(getGlobalMatrix(fromElement)); return point ? m.apply(point) : m; }, getAlignMatrix: _getAlignMatrix, getRelativePosition: function getRelativePosition(fromElement, toElement, fromOrigin, toOrigin) { var m = _getAlignMatrix(fromElement, toElement, fromOrigin, toOrigin); return { x: m.e, y: m.f }; }, arrayToRawPath: function arrayToRawPath(value, vars) { vars = vars || {}; var segment = _populateSegmentFromArray(_populateSegmentFromArray([], value, vars.x || "x", 0), value, vars.y || "y", 1); vars.relative && _relativize(segment); return [vars.type === "cubic" ? segment : pointsToSegment(segment, vars.curviness)]; } }; _getGSAP() && gsap.registerPlugin(MotionPathPlugin); exports.MotionPathPlugin = MotionPathPlugin; exports.default = MotionPathPlugin; Object.defineProperty(exports, '__esModule', { value: true }); })));
import {SurfaceAnalystService} from '../../../src/common/iServer/SurfaceAnalystService'; import {DatasetSurfaceAnalystParameters} from '../../../src/common/iServer/DatasetSurfaceAnalystParameters'; import {GeometrySurfaceAnalystParameters} from '../../../src/common/iServer/GeometrySurfaceAnalystParameters'; import {SurfaceAnalystParametersSetting} from '../../../src/common/iServer/SurfaceAnalystParametersSetting'; import {DataReturnOption} from '../../../src/common/iServer/DataReturnOption'; import {Util} from '../../../src/common/commontypes/Util'; import {Point} from '../../../src/common/commontypes/geometry/Point'; import {SmoothMethod} from '../../../src/common/REST'; import {SurfaceAnalystMethod} from '../../../src/common/REST'; import {FetchRequest} from '../../../src/common/util/FetchRequest'; var spatialAnalystURL = "http://supermap:8090/iserver/services/spatialanalyst-sample/restjsr/spatialanalyst"; var surfaceAnalystEventArgsSystem = null, serviceFailedEventArgsSystem = null; var surfaceAnalystCompleted = (surfaceAnalystEventArgs) => { surfaceAnalystEventArgsSystem = surfaceAnalystEventArgs; }; var surfaceAnalystFailed = (serviceFailedEventArgs) => { serviceFailedEventArgsSystem = serviceFailedEventArgs; }; var initSurfaceService = () => { return new SurfaceAnalystService(spatialAnalystURL, { eventListeners: { "processCompleted": surfaceAnalystCompleted, 'processFailed': surfaceAnalystFailed } }); }; describe('SurfaceAnalystService', () => { var originalTimeout; beforeEach(() => { originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL; jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000; Util.lastSeqID = 0; }); afterEach(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout; surfaceAnalystEventArgsSystem = null; serviceFailedEventArgsSystem = null; }); //点数据集提取等值线 it('Dataset_ISOLINE', (done) => { var surfaceAnalystParameters = new SurfaceAnalystParametersSetting({ datumValue: 0, interval: 2, resampleTolerance: 0, smoothMethod: SmoothMethod.BSPLINE, smoothness: 3, clipRegion: null }); var params = new DatasetSurfaceAnalystParameters({ extractParameter: surfaceAnalystParameters, dataset: "SamplesP@Interpolation", resolution: 3000, zValueFieldName: "AVG_TMP", surfaceAnalystMethod: SurfaceAnalystMethod.ISOLINE, resultSetting: new DataReturnOption({expectCount: 1}) }); var surfaceAnalystService = initSurfaceService(); expect(surfaceAnalystService).not.toBeNull(); expect(surfaceAnalystService.url).toEqual(spatialAnalystURL); spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => { expect(method).toBe('POST'); expect(testUrl).toBe(spatialAnalystURL + "/datasets/SamplesP@Interpolation/isoline.json?returnContent=true"); var expectParams = "{'resolution':3000,'extractParameter':{'datumValue':0,'interval':2,'resampleTolerance':0,'smoothMethod':\"BSPLINE\",'smoothness':3},'resultSetting':{'expectCount':1,'dataset':null,'dataReturnMode':\"RECORDSET_ONLY\",'deleteExistResultDataset':true},'zValueFieldName':\"AVG_TMP\",'filterQueryParameter':{'attributeFilter':null,'name':null,'joinItems':null,'linkItems':null,'ids':null,'orderBy':null,'groupBy':null,'fields':null}}"; expect(params).toBe(expectParams); expect(options).not.toBeNull(); return Promise.resolve(new Response(surfaceAnalystEscapedJson)); }); surfaceAnalystService.processAsync(params); setTimeout(() => { var surfaceAnalystResult = surfaceAnalystEventArgsSystem.result; expect(surfaceAnalystResult).not.toBeNull(); expect(surfaceAnalystResult.succeed).toBeTruthy(); expect(surfaceAnalystResult.recordset.features.type).toEqual("FeatureCollection"); var features = surfaceAnalystResult.recordset.features.features; expect(features.length).toBeGreaterThan(0); for (var i = 0; i < features.length; i++) { expect(features[i].type).toEqual("Feature"); expect(features[i].id).not.toBeNull(); expect(features[i].properties).not.toBeNull(); expect(features[i].geometry.type).toEqual("LineString"); var coordinates = features[i].geometry.coordinates; expect(coordinates.length).toBeGreaterThan(0); for (var j = 0; j < coordinates.length; j++) { expect(coordinates[j].length).toEqual(2); } } var fieldCaptions = surfaceAnalystResult.recordset.fieldCaptions.length; expect(fieldCaptions).toBeGreaterThan(0); expect(surfaceAnalystResult.recordset.fieldTypes.length).toEqual(fieldCaptions); expect(surfaceAnalystResult.recordset.fields.length).toEqual(fieldCaptions); surfaceAnalystService.destroy(); expect(surfaceAnalystService.EVENT_TYPES == null).toBeTruthy(); expect(surfaceAnalystService.events == null).toBeTruthy(); expect(surfaceAnalystService.lastResult == null).toBeTruthy(); expect(surfaceAnalystService.eventListeners == null).toBeTruthy(); params.destroy(); surfaceAnalystService.destroy(); done(); }, 1000); }); //点数据集提取等值面 it('Dataset_ISOREGION', (done) => { var surfaceAnalystParameters = new SurfaceAnalystParametersSetting({ datumValue: 70, interval: 100, resampleTolerance: 0.7, smoothMethod: SmoothMethod.BSPLINE, smoothness: 3 }); var params = new DatasetSurfaceAnalystParameters({ extractParameter: surfaceAnalystParameters, dataset: "SamplesP@Interpolation", resolution: 3000, zValueFieldName: "AVG_WTR", surfaceAnalystMethod: SurfaceAnalystMethod.ISOREGION, resultSetting: new DataReturnOption({expectCount: 1}) }); spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => { expect(method).toBe('POST'); expect(testUrl).toBe(spatialAnalystURL + "/datasets/SamplesP@Interpolation/isoregion.json?returnContent=true"); var expectParams = "{'resolution':3000,'extractParameter':{'datumValue':70,'interval':100,'resampleTolerance':0.7,'smoothMethod':\"BSPLINE\",'smoothness':3},'resultSetting':{'expectCount':1,'dataset':null,'dataReturnMode':\"RECORDSET_ONLY\",'deleteExistResultDataset':true},'zValueFieldName':\"AVG_WTR\",'filterQueryParameter':{'attributeFilter':null,'name':null,'joinItems':null,'linkItems':null,'ids':null,'orderBy':null,'groupBy':null,'fields':null}}"; expect(params).toBe(expectParams); expect(options).not.toBeNull(); return Promise.resolve(new Response(surfaceAnalysis_Dataset_ISOREGION)); }); var surfaceAnalystService = initSurfaceService(); surfaceAnalystService.processAsync(params); setTimeout(() => { var surfaceAnalystResult = surfaceAnalystEventArgsSystem.result.recordset.features; expect(surfaceAnalystResult).not.toBeNull(); expect(surfaceAnalystResult.features).not.toBeNull(); expect(surfaceAnalystResult.type).toBe("FeatureCollection"); surfaceAnalystService.destroy(); params.destroy(); done(); }, 1000); }); //对象提取等值线 it('Geometry_ISOLINE', (done) => { var surfaceAnalystParameters = new SurfaceAnalystParametersSetting({ datumValue: -3, interval: 0.5, resampleTolerance: 0.7, smoothMethod: SmoothMethod.BSPLINE, smoothness: 3 }); var params = new GeometrySurfaceAnalystParameters({ extractParameter: surfaceAnalystParameters, points: [new Point(-4000, 2000), new Point(-4500, 2000), new Point(-3000, 3000), new Point(-3000, 2000), new Point(-2500, 2500), new Point(-2000, 2000), new Point(-2000, 3000), new Point(-2000, 2000), new Point(2000, 4000), new Point(0, 0) ], resolution: 3000, zValues: [-3, -2, 0, -1, -3, 0, 1, 0, 1, 1], surfaceAnalystMethod: SurfaceAnalystMethod.ISOLINE, resultSetting: new DataReturnOption({ expectCount: 1 }) }); spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => { expect(method).toBe('POST'); expect(testUrl).toBe(spatialAnalystURL + "/geometry/isoline.json?returnContent=true"); var expectParams = "{'resolution':3000,'extractParameter':{'datumValue':-3,'interval':0.5,'resampleTolerance':0.7,'smoothMethod':\"BSPLINE\",'smoothness':3},'resultSetting':{'expectCount':1,'dataset':null,'dataReturnMode':\"RECORDSET_ONLY\",'deleteExistResultDataset':true},'surfaceAnalystMethod':\"ISOLINE\",'points':[{'id':\"SuperMap.Geometry_1\",'bounds':null,'SRID':null,'x':-4000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_2\",'bounds':null,'SRID':null,'x':-4500,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_3\",'bounds':null,'SRID':null,'x':-3000,'y':3000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_4\",'bounds':null,'SRID':null,'x':-3000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_5\",'bounds':null,'SRID':null,'x':-2500,'y':2500,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_6\",'bounds':null,'SRID':null,'x':-2000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_7\",'bounds':null,'SRID':null,'x':-2000,'y':3000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_8\",'bounds':null,'SRID':null,'x':-2000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_9\",'bounds':null,'SRID':null,'x':2000,'y':4000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_10\",'bounds':null,'SRID':null,'x':0,'y':0,'tag':null,'type':\"Point\"}],'zValues':[-3,-2,0,-1,-3,0,1,0,1,1]}"; expect(params).toBe(expectParams); expect(options).not.toBeNull(); return Promise.resolve(new Response(surfaceAnalysis_Geometry_ISOLINE)); }); var surfaceAnalystService = initSurfaceService(); surfaceAnalystService.processAsync(params); setTimeout(() => { expect(surfaceAnalystEventArgsSystem.type).toBe("processCompleted"); expect(surfaceAnalystEventArgsSystem.result.dataset).toBeNull(); expect(surfaceAnalystEventArgsSystem.result.succeed).toBe(true); var surfaceAnalystResult = surfaceAnalystEventArgsSystem.result.recordset.features; expect(surfaceAnalystResult).not.toBeNull(); expect(surfaceAnalystResult.features).not.toBeNull(); expect(surfaceAnalystResult.type).toBe("FeatureCollection"); surfaceAnalystService.destroy(); params.destroy(); done(); }, 1000); }); //对象提取等值面 it('Geometry_ISOREGION', (done) => { var surfaceAnalystParameters = new SurfaceAnalystParametersSetting({ datumValue: -3, interval: 0.5, resampleTolerance: 0.7, smoothMethod: SmoothMethod.BSPLINE, smoothness: 3 }); var params = new GeometrySurfaceAnalystParameters({ extractParameter: surfaceAnalystParameters, points: [new Point(-4000, 2000), new Point(-4500, 2000), new Point(-3000, 3000), new Point(-3000, 2000), new Point(-2500, 2500), new Point(-2000, 2000), new Point(-2000, 3000), new Point(-2000, 2000), new Point(2000, 4000), new Point(0, 0) ], resolution: 3000, zValues: [-3, 0, 10, 20, 13, 8, 5, 20, 10, 15], surfaceAnalystMethod: SurfaceAnalystMethod.ISOREGION, resultSetting: new DataReturnOption({ expectCount: 1 }) }); spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => { expect(method).toBe('POST'); expect(testUrl).toBe(spatialAnalystURL + "/geometry/isoregion.json?returnContent=true"); var expectParams = "{'resolution':3000,'extractParameter':{'datumValue':-3,'interval':0.5,'resampleTolerance':0.7,'smoothMethod':\"BSPLINE\",'smoothness':3},'resultSetting':{'expectCount':1,'dataset':null,'dataReturnMode':\"RECORDSET_ONLY\",'deleteExistResultDataset':true},'surfaceAnalystMethod':\"ISOREGION\",'points':[{'id':\"SuperMap.Geometry_1\",'bounds':null,'SRID':null,'x':-4000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_2\",'bounds':null,'SRID':null,'x':-4500,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_3\",'bounds':null,'SRID':null,'x':-3000,'y':3000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_4\",'bounds':null,'SRID':null,'x':-3000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_5\",'bounds':null,'SRID':null,'x':-2500,'y':2500,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_6\",'bounds':null,'SRID':null,'x':-2000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_7\",'bounds':null,'SRID':null,'x':-2000,'y':3000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_8\",'bounds':null,'SRID':null,'x':-2000,'y':2000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_9\",'bounds':null,'SRID':null,'x':2000,'y':4000,'tag':null,'type':\"Point\"},{'id':\"SuperMap.Geometry_10\",'bounds':null,'SRID':null,'x':0,'y':0,'tag':null,'type':\"Point\"}],'zValues':[-3,0,10,20,13,8,5,20,10,15]}"; expect(params).toBe(expectParams); expect(options).not.toBeNull(); return Promise.resolve(new Response(surfaceAnalysis_Geometry_ISOREGION)); }); var surfaceAnalystService = initSurfaceService(); surfaceAnalystService.processAsync(params); setTimeout(() => { expect(surfaceAnalystEventArgsSystem.type).toBe("processCompleted"); expect(surfaceAnalystEventArgsSystem.result.dataset).toBeNull(); expect(surfaceAnalystEventArgsSystem.result.succeed).toBe(true); var surfaceAnalystResult = surfaceAnalystEventArgsSystem.result.recordset.features; expect(surfaceAnalystResult).not.toBeNull(); expect(surfaceAnalystResult.features).not.toBeNull(); expect(surfaceAnalystResult.type).toBe("FeatureCollection"); surfaceAnalystService.destroy(); params.destroy(); done(); }, 1000); }); //失败 it('fail', (done) => { var surfaceAnalystParameters = new SurfaceAnalystParametersSetting({ datumValue: 70, interval: 100, resampleTolerance: 0.7, smoothMethod: SmoothMethod.BSPLINE, smoothness: 3 }); var params = new DatasetSurfaceAnalystParameters({ extractParameter: surfaceAnalystParameters, dataset: "SamplesP1@Interpolation", resolution: 3000, zValueFieldName: "AVG_WTR" }); spyOn(FetchRequest, 'commit').and.callFake((method, testUrl, params, options) => { expect(method).toBe('POST'); expect(testUrl).toBe(spatialAnalystURL + "/datasets/SamplesP1@Interpolation/isoline.json?returnContent=true"); var escapedJson = "{\"succeed\":false,\"error\":{\"code\":400,\"errorMsg\":\"数据集SamplesP1@Interpolation不存在\"}}"; return Promise.resolve(new Response(escapedJson)); }); var surfaceAnalystService = initSurfaceService(); surfaceAnalystService.processAsync(params); setTimeout(() => { expect(serviceFailedEventArgsSystem.type).toBe("processFailed"); expect(serviceFailedEventArgsSystem.error.errorMsg).toBe("数据集SamplesP1@Interpolation不存在"); expect(serviceFailedEventArgsSystem.error.code).toEqual(400); surfaceAnalystService.destroy(); params.destroy(); done(); }, 1000); }) });
(function (factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object') { // Node/CommonJS style for Browserify module.exports = factory; } else { // Browser globals factory(jQuery); } }( /** * @param {jQuery} $ */ function($) { // disable drop open behavior $('html').on('dragover drop', function(e) { e.preventDefault() }); $.fn.scrollbars = function(a,b,c) { if(window.isMobile || window.isTouch) {//} && window.isTouch) { switch(a) { case 'scrollTo': return this.scrollTop(b); // case 'update': // return this.mCustomScrollbar('update'); case '': return this; default: console.log('SCROLLBARS: ',a,b,c) if(typeof a == 'object' && typeof b == 'undefined') { this.css('overflow', 'auto') } return this; } } else { return this.mCustomScrollbar(a,b,c); } } $.fn.calendar = function (opt,val) { var self = this; if(typeof opt === 'string' && typeof val !== 'undefined') switch(opt) { // setter | method with args // return this; } else if(typeof opt === 'string') switch(opt) { // getter | method with no args // return; } var def = { date: new Date(), autoSelect: false, select: function(date) {}, toggle: function(y, m) {}, } var current = { y: def.date.getFullYear(), m: def.date.getMonth()+1, d: def.date.getDate(), } var selected = { y: 0, m: 0, d: 0, } $(this).prop('selected', selected); def = $.extend(def, opt); var weekDays = 'Sun Mon Tue Wed Thu Fri Sat'.split(' '); var yearMonths = 'January February March April May June July August September October November December'.split(' '); var yearMonthsShort = 'Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec'.split(' '); var today = new Date(); var todayDate = today.getDate(); var makeMonth = function(y,m,d) { var body = $('<table>') .addClass('month-body') // .appendTo(month) var week = $('<thead>') .addClass('month-week') .appendTo(body) .append('<tr></tr>') .find('tr') var days = $('<tbody>') .addClass('month-days') .appendTo(body) for(i=0;i<7;i++) { week.append('<th>'+weekDays[i]+'</th>'); } var date = new Date(y,m-1,1); var today = new Date(); var todayDate = today.getDate(); var thisMonth = !!(today.getMonth()+1 === m && today.getFullYear() === y); // date.setFullYear(y,m-1,1); var numDays = (new Date(y,m,0)).getDate(); var numWeeks = Math.ceil((numDays + date.getDay())/7); var day = 1; // console.log(date.getDay(), date.getMonth(), numDays); // for(var i=0; i<numWeeks; i++) { for(var i=0; i<6; i++) { var wk = $('<tr>').appendTo(days); for(var j=0;j<7;j++) { if((i===0 && j<date.getDay()) || (day>numDays)) { wk.append('<td></td>') // wk.append('<td class="fade"> - </td>') // continue; } else { $('<td>') .text(day < 10 ? '0'+day : day) // .addClass(day === d ? 'active' : '') .addClass(thisMonth && day === todayDate ? 'today' : '') .attr('data-date', day) // .ripple({ type: 'icon' }) .appendTo(wk) .click(function(e) { $(this).parent().parent().find('.active').removeClass('active') $(this).addClass('active') selectDate(y, m, parseInt($(this).attr('data-date'))) }) day++; } } // if(wk.text().trim() === '' && days.children(':first').text().split(' ').join('').split('0').join('').length === 7) wk.prependTo(days); if(i === 5 && days.children(':first').text().split(' ').join('').split('0').join('').length === 7) wk.prependTo(days); } // days.find('td[data-date]').ripple({ type: 'centered' }) days.find('td[data-date]').ripple() if(def.autoSelect) { days.find('td[data-date="'+d+'"]').click()//.addClass('active') } return body; } var selectDate = function(y,m,d) { selected.d = d; selected.m = m; selected.y = y; var dt = new Date(y,m-1,d); def.select.bind(self)(dt); } var bringMonth = function(p_n,y,m,d) { isMoving = true; month.addClass('no-overflow'); yMon.text(yearMonths[m-1]+' '+y) yrnm.text(y) yrbd.find('.active').removeClass('active') yrbd.find('[data-month="'+m+'"]').addClass('active') if(d === null && y === selected.y && m === selected.m) d = selected.d; var mon = makeMonth(y,m,d) .addClass(p_n) .insertBefore(body) def.toggle.bind(self)(current.y, current.m); // requestAnimationFrame(function() { setTimeout(function() { mon.addClass('come') }, 1000/60) body.one('transitionend', function(e) { body.remove() body = mon; body.removeClass(p_n+' come') month.removeClass('no-overflow'); // def.toggle.bind(self)(current.y, current.m); isMoving = false; }) } var showYearPicker = function(e) { year.addClass('visible') } var hideYearPicker = function(e) { year.removeClass('visible') } var isMoving = false; var date = def.date; // var month = $('<div>') var month = $(this[0]) .addClass('nao-month') // .appendTo(dpkr) var btn1 = $('<button>') .addClass('ic ic-arrow-angle-left') .ripple() .attr('title', 'Previous month') .click(function(e) { e.preventDefault(); if(isMoving) return; current.m = current.m-1 === 0 ? 12 : current.m-1; current.y = current.m === 12 ? current.y-1 : current.y; bringMonth('prev', current.y, current.m, null); }) .focus(hideYearPicker) var btn2 = $('<button>') .addClass('ic ic-arrow-angle-right') .ripple() .attr('title', 'Next month') .click(function(e) { e.preventDefault(); if(isMoving) return; current.m = current.m+1 === 13 ? 1 : current.m+1; current.y = current.m === 1 ? current.y+1 : current.y; bringMonth('next', current.y, current.m, null); }) .focus(hideYearPicker) var btn3 = $('<button>') .addClass('btn ic ic-arrow-circle-angle-down') .ripple() .attr('title', 'View current month') .click(function(e) { e.preventDefault(); if(isMoving) return; var dt = new Date(); if(dt.getFullYear() === current.y && dt.getMonth()+1 === current.m) return; var dr = current.y*12+current.m > dt.getFullYear()*12+dt.getMonth()+1 ? 'prev' : 'next'; current.y = dt.getFullYear(); current.m = dt.getMonth()+1; bringMonth(dr, current.y, current.m, null); }) .focus(hideYearPicker) var btn4 = $('<button>') .addClass('btn ic ic-target') .ripple() .attr('title', 'View selected date') .click(function(e) { e.preventDefault(); if(isMoving) return; if(selected.d < 1) return; if(selected.y === current.y && selected.m === current.m) return; var dr = current.y*12+current.m > selected.y*12+selected.m ? 'prev' : 'next'; current.y = selected.y; current.m = selected.m; bringMonth(dr, current.y, current.m, null); }) .focus(hideYearPicker) var yMon = $('<div>') .text(yearMonths[date.getMonth()]+' '+date.getFullYear()) .attr('title', 'Select year and month') .click(showYearPicker) var head = $('<div>') .addClass('month-head') // .text(yearMonths[date.getMonth()]+' '+date.getFullYear()) .append(btn1) .append(btn3) .append(btn2) .append(btn4) .append(yMon) .appendTo(month) var body = makeMonth(current.y, current.m, (opt && opt.date) ? current.d : null) .appendTo(month) var togg = def.toggle.bind(self)(current.y, current.m); var year = $('<div>') .addClass('year-month') .prependTo(month) var yrnx = $('<button>') // .addClass('span') .addClass('ic ic-arrow-angle-right') .ripple() .click(function(e) { e.preventDefault(); if(isMoving) return; current.y++; yrnm.text(current.y) bringMonth('next', current.y, current.m, null); }) .focus(showYearPicker) var yrpv = $('<button>') // .addClass('span') .addClass('ic ic-arrow-angle-left') .ripple() .click(function(e) { e.preventDefault(); if(isMoving) return; current.y--; yrnm.text(current.y) bringMonth('prev', current.y, current.m, null); }) .focus(showYearPicker) var yrnm = $('<div>') .text(current.y) .attr('title', 'Go back to calendar') .click(hideYearPicker) var yrhd = $('<div>') .addClass('month-head') // .addClass('year-head') .append(yrpv) .append(yrnx) .append(yrnm) .appendTo(year) var yrbd = $('<table>') .addClass('year-body') .appendTo(year) .html('<tbody></tbody>') .find('tbody') var yrft = $('<div>') .addClass('year-footer ic ic-arrow-circle-angle-up') // .text('okay') .attr('title', 'Go back to calendar') .ripple() .appendTo(year) .click(function(e) { year.removeClass('visible') }) for(var i=0; i<4; i++) { var row = $('<tr>').appendTo(yrbd) for(var j=0; j<3; j++) { var idx = i*3+j; var col = $('<td>') .text(yearMonths[idx]) .attr('data-month', idx+1) .addClass(current.m === idx+1 ? 'active' : '') .appendTo(row) .ripple() .click(function(e) { if(isMoving) return; var mm = parseInt($(this).attr('data-month')) if(mm == current.m) return; var dr = current.m > mm ? 'prev' : 'next'; current.m = mm; $(this).parent().parent().find('.active').removeClass('active') $(this).addClass('active') bringMonth(dr, current.y, current.m, null); }) } } return this; } return $; }));
/* ** Copyright (c) 2020, Oracle and/or its affiliates. ** Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl. */ console.info('Loaded Console Javascript'); const okitVersion = '0.14.1'; const okitReleaseDate = '18th November 2020'; // Validation const validate_error_colour = "#ff4d4d"; const validate_warning_colour = "#ffd633"; function hideNavMenu() { $(jqId('navigation_menu')).removeClass('okit-navigation-menu-show'); } function checkForUpdate() { $.getJSON('https://raw.githubusercontent.com/oracle/oci-designer-toolkit/master/okitweb/static/okit/json/release.json', function(resp) { const release = resp.release.split('.'); const version = okitVersion.split('.'); if ((Number(release[0]) > Number(version[0])) || (Number(release[0]) === Number(version[0]) && Number(release[1]) > Number(version[1])) || (Number(release[0]) === Number(version[0]) && Number(release[1]) === Number(version[01]) && Number(release[2]) > Number(version[2])) ) { console.info('OKIT Update Available'); $(jqId('okit_update')).text(`Update: OKIT ${resp.release} Available for Download`); $(jqId('okit_update')).attr(`href`, `https://github.com/oracle/oci-designer-toolkit/tree/${resp.tag}`); } }); } function showConfigErrors() { let msg = okitOciConfig.results.join('\n'); alert(msg); } $(document).ready(function() { /* ** Add handler functionality */ console.info('Adding Console Handlers'); $(jqId('navigation_menu_button')).click(function(e) { e.preventDefault(); $(jqId('navigation_menu')).toggleClass('okit-navigation-menu-show'); }); $(jqId('navigation_menu')).click(function(e) { e.preventDefault(); $(jqId('navigation_menu')).removeClass('okit-navigation-menu-show'); }); $(jqId('okit_version')).text('Version: ' + okitVersion + ' (' + okitReleaseDate + ')'); $('li.dropdown').on('mouseover', function() { let menuX = $(this).position().left; let menuY = $(this).position().top; let scrollX = $('#navigation_menu').scrollLeft(); let scrollY = $('#navigation_menu').scrollTop(); let width = $(this).innerWidth(); let navX = $('#navigation_menu').offset().left; let navY = $('#navigation_menu').offset().top; let $slideout = $('> .dropdown-content', $(this)); $slideout.css('position', 'absolute'); $slideout.css('top', menuY + scrollY); $slideout.css('left', menuX + width); }); checkForUpdate(); });
// @flow import React, { Component } from 'react'; import { connect } from 'react-redux'; import type { Dispatch } from 'redux'; import { setWindowAlwaysOnTop } from '../actions'; import ToggleWithLabel from './ToggleWithLabel'; type Props = { /** * Redux dispatch. */ dispatch: Dispatch<*>; /** * Window Always on Top value in (redux) state. */ _alwaysOnTopWindowEnabled: boolean; }; /** * Window always open on top placed in Settings Drawer. */ class AlwaysOnTopWindowToggle extends Component<Props> { /** * Initializes a new {@code AlwaysOnTopWindowToggle} instance. * * @inheritdoc */ constructor(props) { super(props); this._onAlwaysOnTopWindowToggleChange = this._onAlwaysOnTopWindowToggleChange.bind(this); } /** * Render function of component. * * @returns {ReactElement} */ render() { return ( <ToggleWithLabel isDefaultChecked = { this.props._alwaysOnTopWindowEnabled } label = 'Fenêtre toujours au-dessus' onChange = { this._onAlwaysOnTopWindowToggleChange } value = { this.props._alwaysOnTopWindowEnabled } /> ); } _onAlwaysOnTopWindowToggleChange: (*) => void; /** * Toggles alwaysOnTopWindowEnabled. * * @returns {void} */ _onAlwaysOnTopWindowToggleChange() { const { _alwaysOnTopWindowEnabled } = this.props; const newState = !_alwaysOnTopWindowEnabled; this.props.dispatch(setWindowAlwaysOnTop(newState)); } } /** * Maps (parts of) the redux state to the React props. * * @param {Object} state - The redux state. * @returns {{ * _alwaysOnTopWindowEnabled: boolean, * }} */ function _mapStateToProps(state: Object) { return { _alwaysOnTopWindowEnabled: state.settings.alwaysOnTopWindowEnabled }; } export default connect(_mapStateToProps)(AlwaysOnTopWindowToggle);
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import formatNumber from './format_number'; describe('format byte', () => { test('zero', () => { expect(formatNumber(0, 'byte')).toMatchInlineSnapshot(`"0.00 B"`); }); test('mb', () => { expect(formatNumber(181142512, 'byte')).toMatchInlineSnapshot(`"172.75 MB"`); }); test('gb', () => { expect(formatNumber(273727485000, 'byte')).toMatchInlineSnapshot(`"254.93 GB"`); }); }); describe('format ms', () => { test('zero', () => { expect(formatNumber(0, 'ms')).toMatchInlineSnapshot(`"0.00 ms"`); }); test('sub ms', () => { expect(formatNumber(0.128, 'ms')).toMatchInlineSnapshot(`"0.13 ms"`); }); test('many ms', () => { expect(formatNumber(3030.284, 'ms')).toMatchInlineSnapshot(`"3030.28 ms"`); }); }); describe('format integer', () => { test('zero', () => { expect(formatNumber(0, 'integer')).toMatchInlineSnapshot(`"0"`); }); test('sub integer', () => { expect(formatNumber(0.728, 'integer')).toMatchInlineSnapshot(`"1"`); }); test('many integer', () => { expect(formatNumber(3030.284, 'integer')).toMatchInlineSnapshot(`"3030"`); }); });
import React, { useState, useEffect } from 'react' import withStyles from '@material-ui/core/styles/withStyles' import { SignOutIcon } from './icons' import { Link } from 'react-router-dom' import logo from '../big-logo.png' import Input from '@material-ui/core/Input' import Done from '@material-ui/icons/Done' import Close from '@material-ui/icons/Close' import FormControl from '@material-ui/core/FormControl'; import FormHelperText from '@material-ui/core/FormHelperText'; import { patchProfile } from '../services/api'; function Header ({ className, classes, email, signOut, patchProfileSuccess }) { const [editingEmail, setEditingEmail] = useState(false) const [newEmail, setNewEmail] = useState(email) const [emailError, setEmailError] = useState(null) const [formSubmitted, setFormSubmitted] = useState(false) const onSignOut = e => { e.preventDefault() signOut() } const editEmail = e => { setNewEmail(email) setEmailError(null) setEditingEmail(true) setFormSubmitted(false) } const cancelEditingEmail = e => setEditingEmail(false) const onNewEmailChange = e => { const { value } = e.target setNewEmail(value) if (!value) { setEmailError('Required') } else if (!/\S+@\S+\.\S+/.test(value)) { setEmailError('Invalid') } else { setEmailError(null) } } const submitNewEmail = e => { e.preventDefault() setFormSubmitted(true) if (email === newEmail) { return setEditingEmail(false) } if (emailError) { return; } patchProfile({ email: newEmail }) .then(response => { setNewEmail(email) setEditingEmail(false) patchProfileSuccess(response) }) .catch((error = {}) => { if (error.status === 400) { return setEmailError('Taken') } setEmailError('Internal error :(') }) } return ( <div className={`${className} ${classes.container}`}> <Link to="/" className={classes.logo}><img src={logo} alt="GitPunch" width="150px"/></Link> <span className={classes.spacer}></span> { email && ( editingEmail ? ( <form noValidate onSubmit={submitNewEmail} style={{ alignItems: 'center', display: 'flex', height: '32px' }}> <FormControl error={emailError && formSubmitted}> <div style={{ height: 0, visibility: 'hidden' }}>{email}</div> <Input value={newEmail} autoFocus={true} onChange={onNewEmailChange} /> {emailError && formSubmitted && <FormHelperText style={{ position: 'absolute', top: '100%', left: 0 }}>{emailError}</FormHelperText>} </FormControl> <button type="submit" className="soft" ><Done /></button> <button className="soft" onClick={cancelEditingEmail}><Close /></button> </form> ) : ( <span style={{ alignItems: 'center', display: 'flex', height: '32px' }}> <span style={{ display: 'inline-block', paddingRight: '34px', cursor: 'pointer', letterSpacing: 'normal' }} testid="current-user-email" onClick={editEmail}>{email}</span> <button style={{ display: 'inline-flex' }} className="soft" onClick={onSignOut}>{SignOutIcon()}</button> </span> ) ) } </div> ) } export default withStyles(theme => ({ container: { alignItems: 'center', background: 'linear-gradient(to bottom, rgba(53,114,156,0.2) 1%,rgba(207,207,207,0) 100%)', display: 'flex', marginBottom: theme.spacing(6), [theme.breakpoints.down('xs')]: { flexDirection: 'column', marginBottom: theme.spacing(4) } }, spacer: { flex: 1, [theme.breakpoints.down('xs')]: { height: theme.spacing(2) } }, logo: { ...theme.typography.h5, border: 'none', display: 'inline-block', marginRight: '1rem' } }))(Header)
'use strict' // in-picture project: Ben Tamir var gQuestsBank = [ { opt: ['This is a dog', 'This is a cat'], correctOptIndex: 2 }, { opt: ['My name is Bert', 'My name is Ernie'], correctOptIndex: 1 }, { opt: ['Best coding lang ever', 'Java what?'], correctOptIndex: 1 } , ]; var gCurrQuestIdx = 0; function initGame() { renderQuest(gCurrQuestIdx, gQuestsBank); } function renderQuest(currQuestIdx, questsBank) { var elPictureArea = document.querySelector('.picture'); var strHtml = ''; strHtml += '<img src="img/' + (currQuestIdx + 1) + '.jpg">'; elPictureArea.innerHTML = strHtml; for (var i = 0; i < 2; i++) { var elButton = document.querySelector('#b' + (i+1)); console.log(elButton); strHtml = ''; strHtml += '<button onclick="checkAnswer(' + (i+1) + ')">' + questsBank[currQuestIdx].opt[i] + '</button>'; elButton.innerHTML = strHtml; } // var elButtonOne = document.querySelector('#b1'); // strHtml = ''; // strHtml += '<button onclick="checkAnswer(1)">' + questsBank[currQuestIdx].opt[0] + '</button>'; // elButtonOne.innerHTML = strHtml; // var elButtonTwo = document.querySelector('#b2'); // strHtml = ''; // strHtml += '<button onclick="checkAnswer(2)">' + questsBank[currQuestIdx].opt[1] + '</button>'; // elButtonTwo.innerHTML = strHtml; } function checkAnswer(optIdx) { if (optIdx === gQuestsBank[gCurrQuestIdx].correctOptIndex) { gCurrQuestIdx++ if (gCurrQuestIdx >= gQuestsBank.length) { var elPictureArea = document.querySelector('.picture'); var strHtml = '<img src="img/done.jpg">'; elPictureArea.innerHTML = strHtml; var elButtons = document.querySelector('.buttons'); elButtons.classList.add('hide'); console.log('you won'); } else renderQuest(gCurrQuestIdx, gQuestsBank); } else alert('Try again') //console.log('wrong'); } function goBack() { window.history.back(); }
// Karma configuration const gulpConfig = require('./gulpfile.config.json'); module.exports = function(config) { const karmaConfig = { // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ `${gulpConfig.src}/**/*.js`, 'bower_components/es6-promise/promise.js', 'bower_components/lodash/lodash.js' ], // list of files to exclude exclude: [ `${gulpConfig.src}/plugin/index.js`, `${gulpConfig.src}/web/**/*.js` ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress', 'coverage', 'junit'], coverageReporter: { reporters: [ {type: 'html', dir: 'coverage/'}, {type: 'cobertura', dir: 'coverage/', subdir: '.'} ] }, junitReporter: { outputDir: 'coverage', // results will be saved as $outputDir/$browserName.xml outputFile: 'TEST-karma.xml', // if included, results will be saved as $outputDir/$browserName/$outputFile suite: '<%= projectName %>', // suite will become the package name attribute in xml testsuite element useBrowserName: false // add browser name to report and classes names }, // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['PhantomJS'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false, // Concurrency level // how many browser should be started simultaneous concurrency: Infinity }; // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor karmaConfig.preprocessors[`${gulpConfig.src}/**/*.js`] = ['coverage']; config.set(karmaConfig); };
//! moment.js locale configuration //! locale : Spanish(United State) [es-us] //! author : bustta : https://github.com/bustta import moment from '../moment'; var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_'), monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_'); export default moment.defineLocale('es-us', { months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'), monthsShort : function (m, format) { if (!m) { return monthsShortDot; } else if (/-MMM-/.test(format)) { return monthsShort[m.month()]; } else { return monthsShortDot[m.month()]; } }, monthsParseExact : true, weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'), weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'), weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'H:mm', LTS : 'H:mm:ss', L : 'MM/DD/YYYY', LL : 'MMMM [de] D [de] YYYY', LLL : 'MMMM [de] D [de] YYYY H:mm', LLLL : 'dddd, MMMM [de] D [de] YYYY H:mm' }, calendar : { sameDay : function () { return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextDay : function () { return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, nextWeek : function () { return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastDay : function () { return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, lastWeek : function () { return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT'; }, sameElse : 'L' }, relativeTime : { future : 'en %s', past : 'hace %s', s : 'unos segundos', m : 'un minuto', mm : '%d minutos', h : 'una hora', hh : '%d horas', d : 'un día', dd : '%d días', M : 'un mes', MM : '%d meses', y : 'un año', yy : '%d años' }, dayOfMonthOrdinalParse : /\d{1,2}º/, ordinal : '%dº', week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } });
'use babel'; import React from 'react' import IconBase from './IconBase' export default function Emoji_1f60b(props) { return ( <IconBase viewBox="0 0 64 64" {...props}> <g><path fill="#FFDD67" d="M62 31.996C62 48.566 48.566 62 32 62 15.432 62 2 48.566 2 31.996 2 15.434 15.432 2 32 2c16.566 0 30 13.428 30 29.996z"/><path fill="#FF717F" d="M42.004 47.881c-5.027-5.027-2.777-2.779 2.525-8.082 5.307-5.301 3.055-7.553 8.082-2.527 5.023 5.027 5.174 9.926 2.244 12.855-2.929 2.928-7.826 2.779-12.851-2.246z"/><path fill="#E2596C" d="M45.59 38.738l6.849 8.973-8.97-6.852z"/><g fill="#664E27"><path d="M28.526 24.854c-1.859-5.111-4.66-7.669-7.461-7.669s-5.602 2.558-7.461 7.669c-.184.515.775 1.443 1.254.938 1.803-1.901 3.957-2.658 6.207-2.658s4.404.757 6.207 2.658c.479.506 1.438-.423 1.254-.938zM50.396 24.854c-1.859-5.111-4.66-7.669-7.461-7.669s-5.602 2.558-7.461 7.669c-.184.515.775 1.443 1.254.938 1.803-1.901 3.957-2.658 6.207-2.658s4.404.757 6.207 2.658c.478.506 1.437-.423 1.254-.938z"/></g><path fill="#664E27" d="M48.11 33.02c-4.328 6.107-9.451 7.644-16.11 7.644s-11.782-1.536-16.11-7.644c-.604-.85-2.19-.315-1.84.919 2.273 8.005 10 12.668 17.95 12.668s15.677-4.663 17.95-12.668c.351-1.235-1.236-1.769-1.84-.919z"/></g> </IconBase> ); }
import React from 'react'; import PropTypes from 'prop-types'; import Humburger from './humburger/Humburger'; import LeftNav from './leftNav/LeftNav'; import RightNav from './rightNav/RightNav'; const NavigationBar = ({ brand, navModel, handleLeftNavItemClick, handleRightNavItemClick, userIsAuthenticated }) => { return ( <nav className="navbar navbar-default"> <div className="containersCustom"> <div className="navbar-header"> { <Humburger /> } <a className="navbar-brand"> {brand} </a> </div> <div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul className="nav navbar-nav"> { <LeftNav leftLinks={navModel.leftLinks} onLeftNavButtonClick={handleLeftNavItemClick} userIsAuthenticated={userIsAuthenticated} /> } </ul> <ul className="nav navbar-nav navbar-right"> { <RightNav rightLinks={navModel.rightLinks} onRightNavButtonClick={handleRightNavItemClick} userIsAuthenticated={userIsAuthenticated} /> } </ul> </div> </div> </nav> ); }; NavigationBar.propTypes = { brand: PropTypes.string, userIsAuthenticated: PropTypes.bool.isRequired, handleLeftNavItemClick: PropTypes.func, handleRightNavItemClick: PropTypes.func, navModel: PropTypes.shape({ leftLinks: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string.isRequired, link : PropTypes.string.isRequired }) ).isRequired, rightLinks: PropTypes.arrayOf( PropTypes.shape({ label: PropTypes.string.isRequired, link : PropTypes.string.isRequired }) ).isRequired }) }; NavigationBar.defaultProps = { brand : 'brand' }; export default NavigationBar;
import * as sel from "../index"; import { MOCK_STATE } from "./mock_state"; describe("test index selector", () => { test("testing selectorMap", () => { expect(sel.selectorMap()).toEqual(expect.any(Function)); expect(sel.selectorMap({ email: sel.email, isAdmin: sel.isAdmin })(MOCK_STATE)).toEqual({ "email": "testme@email.com", "isAdmin": true }); }); });
var rownum = 0; var colnum = 0; var cells = {}; var rows = {}; var headerRows; var headerCells = [{},{},{}]; function createCell() { var tdElem = document.createElement("td"); var input = document.createElement("input"); input.classList.add('cell'); tdElem.appendChild(input); return [tdElem, input]; } function addRow() { var newRow = document.createElement("tr"); var cols = {}; var tdRowHead = document.createElement("td"); //var name = document.createElement("input"); //tdRowHead.appendChild(name); tdRowHead.innerText = rownum + 1; //name.disabled = true; newRow.appendChild(tdRowHead); for (var i = 0; i < colnum; i++) { var newCell = createCell(); cols[i] = newCell[1]; newRow.appendChild(newCell[0]); } document.getElementById("spreadsheet").appendChild(newRow); cells[rownum] = cols; rows[rownum] = newRow; ++rownum; } function addCol() { var headerTd = document.createElement("td"); var headerInp = document.createElement("input"); headerTd.appendChild(headerInp); headerRows[0].appendChild(headerTd); headerCells[0][colnum] = headerInp; var headerTd = document.createElement("td"); var headerInp = document.createElement("input"); headerTd.appendChild(headerInp); headerRows[1].appendChild(headerTd); headerCells[1][colnum] = headerInp; var headerTd = document.createElement("td"); var headerInp = document.createElement("input"); headerTd.appendChild(headerInp); headerRows[2].appendChild(headerTd); headerCells[2][colnum] = headerInp; for (var i = 0; i < rownum; i++) { var newCell = createCell(); cells[i][colnum] = newCell[1]; rows[i].appendChild(newCell[0]); } ++colnum; } function init() { headerRows = [document.getElementById("symbol_label"), document.getElementById("symbol_unit"), document.getElementById("symbol_exp")]; addRow(); addCol(); } function calc() { var colNameIds = {}; for(var c = 0; c < colnum; c++) { if(headerCells[2][c].value.length) { for(var r = 0; r < rownum; r++) { resetLiterals(); for(var key in colNameIds) { literals[key] = readVal(cells[r][colNameIds[key]].value, 0)[1]; } cells[r][c].value = readBrackets(headerCells[2][c].value,0)[1].getValue().stringAbs(); } } if(headerCells[0][c].value.length) { colNameIds[headerCells[0][c].value] = c; } } } function exportLatex() { var tab=""; for(var c=0;c < colnum; c++) { tab += headerCells[0][c].value + headerCells[1][c].value + " & "; } tab += "\\\\\n\\hline\n" for(var r=0; r < rownum; r++) { for(var c=0;c < colnum; c++) { if(c > 0) { tab += " & "; } tab += "$" + readVal(cells[r][c].value.replace("±","#"), 0)[1].stringPerc().replace("#"," \\pm ").replace("±","\\pm") + "$"; } tab += "\\\\\n" } return tab; } function exportCsv() { var tab=""; for(var c=0;c < colnum; c++) { tab += headerCells[0][c].value + headerCells[1][c].value + ", d" + headerCells[0][c].value + headerCells[1][c].value + ", "; } tab += "\n"; for(var r=0; r < rownum; r++) { for(var c=0;c < colnum; c++) { tab += readVal(cells[r][c].value.replace("±","#"), 0)[1].stringAbs().replace("±","#").split("#").join(", ") + ", "; } tab += "\n"; } return tab; } function readSavefile() { var vals = JSON.parse(localStorage.getItem('err_spreadsheet')); for(var r = 0; r < vals.length; r++) { if(rownum <= r) { addRow(); } for(var c = 0; c < vals[r].length; c++) { if(colnum <= c) { addCol(); } cells[r][c].value = vals[r][c]; } } } function createSavefile() { var vals = []; for(var r = 0; r < rownum; r++) { vals.push([]); for(var c = 0; c < colnum; c++) { vals[r].push(cells[r][c].value); } } localStorage.setItem('err_spreadsheet', JSON.stringify(vals)); //return JSON.stringify(vals); }
macDetailCallback("dc4a9ea00000/28",[{"d":"2020-09-09","t":"add","s":"ieee-mam.csv","a":"Room 606, Block B, Bldg. 1, No. 3000 Longdong Avenue., Zhangjiang Hi-Tech Park, Pudong District ShangHai CN 201203","c":"CN","o":"LongSung Technology (Shanghai) Co.,Ltd."}]);
import React from "react" import SmartSocialLink from "./smart-social-link" const mergeLinksToArray = links => { return links.map(link => { Object.keys(link).forEach(key => link[key] === null && delete link[key]) return link }) } const Social = ({ links }) => { const socialLinks = mergeLinksToArray(links) return ( <ul style={{ fontSize: `1.2rem`, listStyle: `none` }}> {socialLinks.map(link => ( <li key={Object.keys(link)}> <SmartSocialLink link={link} linkType={Object.keys(link)} linkUser={link[Object.keys(link)]} /> </li> ))} </ul> ) } export default Social
export { default } from './MDContentExplorer.js';
angular .module('azWebAppApp') .controller('LoginCtrl', function($scope, $rootScope, $uibModal, $state, $window, $location, SessionService, Usuario, ngFB) { console.log($scope, $scope.$close, 'Login'); $scope.credentials = {}; $scope.registration = {}; /** * Metodos para login y registro de usuarios AZ */ $scope.registrar = function() { Usuario.create({ name: $scope.credentials.full_name, username: $scope.credentials.username, password: $scope.credentials.password, email: $scope.credentials.email }, function(user) { console.log(user); var credentials = { username: user.username, password: $scope.credentials.password }; $scope.login(credentials, false); }, function(err) { console.log(err); }) }; $scope.goToLogin = function() { $uibModal.open({ size : 'sm', templateUrl: 'app/views/app/login.html', controller : 'LoginCtrl' }); } $rootScope.login = function (user_credentials, fb) { if(user_credentials) { $scope.credentials.username = user_credentials.username; $scope.credentials.password = user_credentials.password; } SessionService.login($scope.credentials).then(function(response) { if(response.user.entity && !response.user.entity.active) { console.log('error'); } else { console.log('ACAAAAAAAAAAAAAAAAAAAAAA', response); $scope.credentials = {}; $rootScope.$broadcast('user-logged',{data: response.user}); $rootScope.user = response; if (fb) { $window.localStorage.setItem('user', JSON.stringify(user_credentials)); } else { $window.localStorage.setItem('user', JSON.stringify(response)); } window.location.href = '/'; console.log('red'); } }, function(err) { if(user_credentials) { $scope.register(user_credentials); } else { if (err.data.error.code==="LOGIN_FAILED") { //ngToast.show("Error. Por favor chequeá tu usuario y contraseña."); } } }); }; $scope.register = function (user_social) { if(user_social) { $scope.registration = user_social; } $scope.registration.createdDate = new Date().toJSON(); SessionService.register($scope.registration).then(function(response) { //ngToast.show('Bienvenido a AZ!'); $rootScope.$broadcast('user-logged',{data: response.user}); $location.path('/'); }, function(err) { var message,title; if(err.data.error.status===422) { title = "Error de validación"; message = "Alguno de los datos es erroneo. Quizás el email ingresado ya está siendo usado en el sistema."; } else { title = err.statusText; message = err.data.error.message; } // ngToast.alert({ // title: title, // template: message // }); }); }; /** * Metodos para login y registro con openFB */ $scope.openFacebookLogin = function () { console.log('trying to loggin'); ngFB.login({scope: 'email,public_profile'}).then( function (response) { if (response.status === 'connected') { var tokenfb = response.authResponse.accessToken; $scope.me( function(user_data) { if(!user_data.email) { alert("Error, cannot retrieve user email from Facebook"); } else { //console.log(user_data); // we'll create a custom password for the new social oauth user // facebook_user_id + '.' + email + '#_@' + social_facebook_oauth_az.login var new_user = { "email": user_data.email, "username": user_data.email, "name": user_data.name, "register_type": "facebook", "facebook": { "id": user_data.id, "token": tokenfb }, "password": user_data.id + '.' + user_data.email + '#_@' + "social_facebook_oauth_az.login", "picture": user_data.picture.data.url }; $rootScope.login(new_user, true); } }); // $scope.closeLogin(); } else { console.error("Error en login facebook"); //ngToast.show('Error en intento de login con Facebook'); } } ); }; $scope.me = function(cb) { ngFB.api({ path: '/me', params: {fields: 'id,name,email,picture'} }).then( function (user) { cb(user); }, function (error) { //console.log('Facebook error: ' + error.error_description); }); }; /** * Facebook cordova plugin for native facebook login */ //This is the success callback from the login method var fbLoginSuccess = function(response) { if (!response.authResponse){ fbLoginError("Cannot find the authResponse"); return; } var authResponse = response.authResponse; //console.log(authResponse); getFacebookProfileInfo(authResponse) .then(function(profileInfo) { //console.log(profileInfo); //for the purpose of this example I will store user data on local storage SessionService.setUser({ authResponse: authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large" }); $ionicLoading.hide(); $location.path('/'); }, function(fail){ //fail get profile info //console.log('profile info fail', fail); }); }; //This is the fail callback from the login method var fbLoginError = function(error){ console.log('fbLoginError', error); }; //this method is to get the user profile info from the facebook api var getFacebookProfileInfo = function (authResponse) { var info = $q.defer(); facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null, function (response) { //console.log(response); info.resolve(response); }, function (response) { //console.log(response); info.reject(response); } ); return info.promise; }; //This method is executed when the user press the "Login with facebook" button $scope.facebookSignIn = function() { facebookConnectPlugin.getLoginStatus(function(success){ if(success.status === 'connected'){ // the user is logged in and has authenticated your app, and response.authResponse supplies // the user's ID, a valid access token, a signed request, and the time the access token // and signed request each expire //console.log('getLoginStatus', success.status); //check if we have our user saved var user = SessionService.getUser('facebook'); if(!user.userID) { getFacebookProfileInfo(success.authResponse) .then(function(profileInfo) { //for the purpose of this example I will store user data on local storage UserService.setUser({ authResponse: success.authResponse, userID: profileInfo.id, name: profileInfo.name, email: profileInfo.email, picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large" }); $location.path('/'); }, function(fail){ //fail get profile info //console.log('profile info fail', fail); }); }else{ $location.path('/'); } } else { //if (success.status === 'not_authorized') the user is logged in to Facebook, but has not authenticated your app //else The person is not logged into Facebook, so we're not sure if they are logged into this app or not. //console.log('getLoginStatus', success.status); // ngToast.show({ // template: 'Logging in...' // }); //ask the permissions you need. You can learn more about FB permissions here: https://developers.facebook.com/docs/facebook-login/permissions/v2.4 facebookConnectPlugin.login(['email', 'public_profile'], fbLoginSuccess, fbLoginError); } }); }; });
// (c) ammap.com | SVG (in JSON format) map of Kyrgyzstan - High // areas: {id:"KG-B"},{id:"KG-C"},{id:"KG-J"},{id:"KG-N"},{id:"KG-O"},{id:"KG-T"},{id:"KG-Y"} AmCharts.maps.kyrgyzstanHigh={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"69.259411", "topLatitude":"43.256543", "rightLongitude":"80.288715", "bottomLatitude":"39.169714" } }, "g":{ "path":[ { "id":"KG-B", "title":"Batken", "d":"M142.21,279.98l0.97,0.51l2.46,-0.06l1.08,1.54l-0.12,0.89l0.64,0.25l3.48,-0.69l0.38,0.59l2.13,0.56l2.06,1.31l0.19,0.97l2.3,1.02l3.25,-0.45l1.14,3.88l0.91,1.03l2.06,0.4l3.6,-0.34l1.2,-0.91l0.06,-3.08l0.8,-0.57h1.49l1.43,0.8l1.26,2.91l0.63,2.06l-1.09,2.56l1.04,0.9l0.85,2.66h0.8l1.66,-2.17l2.34,-1.6l0.4,0.29l2.74,-2l0.91,-0.4l0.75,0.3l0.54,-0.49l0.03,-1.58l-1.43,-1.03l1.1,-1.75l2.96,-0.3l2.91,1.77l1.22,0.2l2.72,-2.6l2.91,-0.23l-0.27,-1.87l0,0l3.41,-1.63l6.43,-1.77h1.4l0.93,0.75l0.37,1.12l-1.02,4.19l1.49,1.86v0.75l-2.7,1.96l0.65,0.75l4.29,1.68l1.12,1.02l0.47,1.3v1.3l-2.98,2.61l3.07,1.02l0.93,0.65l0.37,1.02l-0.84,2.79l1.3,1.86l0.09,1.21l-1.58,4l0.09,1.3l3.91,0.75l2.61,1.68l1.96,4.94l1.58,2.05h1.3l1.12,-1.4l0.84,-0.28l1.58,0.65l0.28,0.93l1.02,0.84l-1.02,1.12l1.49,1.03l2.24,2.7l0.65,2.51l-0.93,0.65l-0.28,1.96l-2.42,1.58l-5.4,1.77l-0.75,0.93l-2.42,0.28l-2.33,2.79l-3.45,0.84l-0.93,0.75l-3.17,0.93l-2.14,-1.21l-3.26,-0.28l-1.68,0.19l-3.63,1.68l-1.58,-1.68l-3.82,-0.09l-3.54,-2.79l-2.7,-0.37l-3.17,0.47l-2.33,-1.96l-3.35,-0.47l-1.68,-0.75l-1.12,-0.84l-0.47,-1.58l-4.01,-0.56l-1.68,3.26l-1.21,0.75l-5.68,0.56l-0.84,0.56l-2.7,4.75l-0.37,2.89l-0.98,1.34l0,0l-1.41,-0.9l-0.8,0.06l0.06,1.26l-4.11,0.97l-0.69,2l-0.69,0.4l-2.97,-0.29l-2.08,0.8l-0.55,2.28l-1.77,2.11l-1.83,-0.23l-0.69,-1.31h-0.8l-4.11,2.29l-5.44,-0.69l-1.6,0.34l-0.74,0.51l-0.4,1.31l-0.51,5.6l-1.6,2l-1.49,0.34l-2.23,-0.34l-3.88,-2.11l-1.83,3.54l-1.66,-0.34l-0.8,-1.03l-1.03,-0.17l-2.11,1.94l-1.83,0.11l-2.69,-0.91l-2.17,-1.88l0.61,-5.06l-1.41,-1.96l-3.43,-1.88l-2.63,-5.77l-0.97,-0.69l-5.32,-1.02l-2.28,-2.46l-0.97,0.17l-0.8,1.14l-2.23,0.29l-1.17,1.23l-2.37,-0.32l-1.43,1.77l-3.54,-1.65l-1.03,2.1l-1.44,1.22l-1.65,2.67l-3.43,-0.06l-0.91,-0.8l-0.23,-2l-1.6,-1.37l-0.91,-0.06l-2.34,1.71l-0.97,-0.11l-3.43,-3.14l-2.53,1.46l-0.58,1.18l-2.15,-0.46l-1.82,2.68l-1.43,0.11l-1.2,-2.68l-2.11,-0.06l-2.8,-0.97l-0.8,0.51l-0.86,2.74l-1.81,0.81l-5.45,-4.18l-5.08,-1.71l-1.54,0.06l-1.2,1.14l-1.48,0.17l-1.6,-0.46l-0.61,-0.73l-1.34,0.33l-2.07,2.75l-1.28,0.11l-0.82,0.75l0.06,0.8l-1.94,-0.06l-2.87,0.92l-0.87,-0.65l-1.52,0.7l-2.17,-0.74l-0.86,-1.71H9.43l-0.62,2.51l-1.32,1.08l-1.94,-1.54l0.06,-1.88l0.86,-1.09l0.23,-1.6l-2.11,-6.28l-0.06,-4l-0.63,-2.29l-2.8,-3.51l0,-3.73l-1.03,-0.89L0,328.99l4.86,-5.51l-2.29,-3.23l1.31,-3.83l2.34,-1.91l0.63,-1.49l-1.6,-2.4l0.51,-0.69l0.8,0.34l1.14,1.94l1.77,-0.17l1.43,1.03l1.14,1.77l0.29,4.23l2.57,0.4l1.83,-1.57l1.66,-0.31l1.94,0.63l0.4,-0.46l-2.57,-3.94l-0.57,-2.4l0.91,-9.6l0.8,-0.63l1.49,0.11l2.11,1.37l5.03,-2l1.54,0.06l0.34,0.86l1.03,-0.11l1.94,-3.14l3.88,-2.28l4.68,-1.54l3,0.11l3.2,-0.8l6.11,-2.46l1.31,0.06l5.37,3.14l3.83,3.77l1.2,0.11l0.86,-0.91l1.14,0.46l0.23,1.43l1.31,1.43l4.34,-0.34l1.09,0.4l2.46,1.49l1.83,0.17l0.11,1.2l0.63,0.57l4.51,2.46l8.34,2.23l2.06,1.31l0.74,0.69l-0.4,1.43l-2.4,1.31l-3.37,2.86l-0.4,3.43l0.51,1.2l1.03,0.17l-0.15,-2.72l0.49,-1.79l0.69,-0.51l2.17,0.11l4.34,-2.46l-0.23,-1.89l1.31,-1.88l0.74,-6.83l2.17,-0.91l8.11,-1.6l1.09,-1.89l-0.23,-2.46l1.94,-0.69l0.8,0.69l1.57,-0.43l2.48,-1.62l5.54,-2.23l0.9,-2.34l-1.83,-3.08l0.46,-1.09l1.54,-0.51l4.86,-0.17l3.43,-2.11l2.51,-3.08l3.31,-0.34L142.21,279.98zM128.46,291.79l0.58,-1.12l0.04,-1.62l-0.73,-0.96l-0.77,0.96l0.42,2.39L128.46,291.79zM173.68,293.79l0.25,-0.95l-1.9,-0.55v1.25l0.5,0.15L173.68,293.79zM126.11,297.92l0.19,3.08l-0.58,4.32l0.62,2.31l1.16,1.62l1.46,0.85l3.01,0.46l0.85,0.5l0.15,0.85l-0.31,1.27l-1.04,0.42l1.35,2.58l-2.51,2.43l-0.58,1.97l-1.23,0.93l0.27,0.69l2,0.23l1.35,1.19l0.54,-0.66l-0.73,-0.85l0.19,-0.89l0.85,-1.04l1.04,0.23l-0.19,2.12l0.58,0.31l3.59,-0.5l2.39,-2.66l0.15,-0.69l-0.85,-0.85l0.15,-1.08l-0.81,-0.5l-4.16,0.15l-0.08,-0.73l1.46,-0.66l0.39,-0.81l-0.23,-1.08l-1.12,-1.23l1.7,-0.54l2.2,-1.54l0.31,-0.66l-0.35,-1.04l-4.05,2l-0.89,-0.08l-1.58,-6.25l-1.47,-0.66l-0.77,-1l-0.62,-3.2l-1.58,-3.12l-2.16,-1.04l-1.04,0.58l0.19,0.73L126.11,297.92zM178.78,317.91l2.74,-1.92l3.63,0.48l0.96,-2.19l-5.21,-4.32l-0.75,0.89l0.82,2.26l-1.51,1.23l-2.54,0.62l-0.27,1.1L178.78,317.91zM91.24,323.2l-0.61,1.22l1.62,2.84l0.32,2.63l1.04,0.17l2.4,-0.93l0.58,0.35l0.49,0.98l-0.87,2.43l0.26,1.16l2.23,-1.5l2.43,-3.47l3.33,-1.42l1.56,-2.08l-0.43,-1.42l-1.13,-0.23l-3.07,0.84l-2.49,-0.06l-5.44,-1.68L91.24,323.2z" }, { "id":"KG-C", "title":"Chü", "d":"M358.32,1.83L360.32,1.83L362.38,4.51L364.2,4.34L364.2,5.26L364.78,5.66L365.63,6.11L366.6,5.88L367.06,6.68L367.97,6.46L370.32,9.03L373.06,10.05L373.57,10.97L375.57,10.4L376.77,11.43L381.69,12.74L382.14,14.17L386.43,19.54L388.48,21.37L390.37,22.11L391.57,24.28L394.25,26.05L395.68,26.28L397.34,25.54L398.31,25.82L400,24.96L400.97,25.25L406,27.54L407.08,28.62L414.17,32.33L419.37,33.82L422.74,36.16L425.99,37.08L428.33,38.96L432.79,38.73L436.96,39.93L440.09,39.93L445.75,41.19L449.06,40.73L464.6,44.84L466.94,41.47L467.96,40.86L469.42,34.82L471.01,32.79L473.34,30.96L478.82,29.42L480.02,29.76L481.33,31.76L484.24,32.1L486.35,33.76L488.01,33.76L494.01,32.1L498.01,32.22L499.09,33.08L504.58,33.19L505.78,33.88L506.38,37.79L507.6,38.45L509.55,38.56L519.25,35.77L520.17,33.99L520.97,33.46L526.26,34.36L527.59,33.65L530.32,34.36L535.98,34.33L537.58,33.36L538.26,32.19L538.38,30.45L539.13,29.76L543.18,29.48L544.27,27.54L545.12,27.42L550.15,28.28L551.87,27.19L554.94,26.76L556.02,27.22L557.69,29.76L558.78,29.65L561.17,27.62L565.45,27.96L566.71,28.31L567.16,30.42L569.12,30.68L572.02,32.97L571.17,34.28L568.44,34.96L565.26,37.8L563.78,42.57L562.65,43.14L559.92,42.69L549.35,44.05L547.88,44.5L547.19,45.3L544.24,44.96L539.7,47L537.99,47.23L533.11,46.55L530.49,47.69L528.11,47.35L526.29,48.14L522.77,47.57L520.72,48.03L519.7,47.12L517.77,47L517.66,49.28L514.93,49.62L513.34,50.41L510.84,50.07L508.91,52.12L502.32,56.32L500.5,58.37L498,59.5L497.66,62.12L496.64,62.8L495.16,63.25L493.57,62.57L490.27,62.57L488.34,63.02L487.21,63.93L482.66,64.73L481.87,65.64L478,65.52L475.39,66.09L472.89,64.96L470.62,64.61L470.05,65.86L470.62,68.14L470.5,70.18L466.98,70.3L465.62,71.43L464.14,71.43L463.23,72.23L461.76,75.64L458.12,78.25L456.87,79.73L452.89,81.43L451.42,80.52L450.17,80.41L449.6,79.38L449.71,78.36L448.69,78.13L448.24,78.93L446.99,79.5L445.05,80.07L443.12,79.73L441.53,80.29L438.92,78.48L437.78,79.95L434.6,80.07L431.88,81.2L426.88,79.38L423.7,80.18L422.33,79.73L421.42,78.7L418.36,80.86L415.52,80.98L414.38,79.27L413.24,78.93L410.97,80.18L405.86,79.38L404.72,79.95L397.11,80.63L397.45,82.23L399.72,84.84L400.52,87L401.88,88.81L402.34,91.43L401.31,92.22L399.5,91.77L395.75,92.22L394.04,93.02L391.66,96.09L388.93,98.24L386.09,97.79L381.14,99.55L378.75,99.44L375.57,100.23L373.18,99.67L370.46,100.57L367.73,100.8L364.66,100.23L362.73,109.21L363.87,110.23L367.16,111.71L367.5,112.73L366.59,113.07L365.68,114.55L364.21,114.89L362.84,116.03L362.28,117.16L363.18,120.57L362.5,122.27L359.78,123.64L358.82,129.15L356.89,129.49L354.5,128.81L353.14,129.38L352,130.4L350.19,135.85L348.94,136.76L347.46,135.06L349.16,130.17L348.71,129.6L344.85,130.28L343.37,129.94L342.69,128.35L339.96,125.85L338.83,124.04L337.12,125.74L335.98,125.51L334.17,126.31L329.05,126.31L328.26,125.63L325.31,126.31L324.64,125.94L324.64,125.94L324.57,123.89L323.96,123.21L323.5,121L322.44,120.47L319.24,120.01L310.96,121.99L309.74,121.08L308.75,121L307.91,121.91L305.71,121.69L304.42,120.32L302.36,120.47L295.52,118.34L294.07,118.72L292.48,117.35L291.64,113.93L290.42,112.26L282.59,110.13L279.34,110.43L277.11,109.55L277.11,109.55L276.75,107.8L277.24,105.04L273.99,103.86L272.62,101.99L272.91,96.87L273.7,96.18L278.03,97.56L282.46,93.72L283.54,93.52L285.02,94.12L288.56,92.84L292.7,93.92L295.35,91.56L299.49,91.26L303.92,92.74L311.3,90.18L312.48,88.8L312.68,85.65L315.44,82.3L316.13,80.24L316.13,78.37L313.86,76.79L312.58,77.87L311.5,77.68L310.81,75.81L309.73,74.72L308.35,75.02L308.25,77.18L307.17,80.53L306.38,80.83L305.3,80.28L305.43,78.78L302.75,76.21L300.12,71.09L298.92,66.7L298.98,61.33L300.65,56.98L300.98,53.97L303.15,49.73L304.79,47.67L305.54,40.05L305.09,36.56L304.13,34.33L304.59,32.16L307.21,29.53L307.09,24.91L307.9,22.91L311.44,22.05L314.08,20.61L316.24,18.51L319.9,16.62L324.3,13.37L324.96,14.22L326.33,14.68L327.3,13.65L332.75,14.17L334.29,12.62L334.61,11.57L335.16,11.74L337.53,4.91L340.84,6.11L342.15,8.28L343.93,9.19L345.41,8.68L346.95,7.25L354.32,6.86L355.41,6.34L355.86,5.26L353.81,1.6L354.26,0L356.04,1.26z" }, { "id":"KG-J", "title":"Jalal-Abad", "d":"M216.05,101.01L222.85,102.09L224.32,102.97L226.19,105.83L227.57,106.22L231.02,105.24L233.97,107.5L235.74,107.31L239.97,109.57L244.7,109.18L249.72,111.64L255.98,116.46L261,115.87L261.89,112.92L264.64,111.64L266.81,108.68L267.5,108.49L269.07,110.06L271.04,108.78L271.83,110.26L273.21,109.96L274.78,110.55L277.11,109.55L277.11,109.55L279.34,110.43L282.59,110.13L290.42,112.26L291.64,113.93L292.48,117.35L294.07,118.72L295.52,118.34L302.36,120.47L304.42,120.32L305.71,121.69L307.91,121.91L308.75,121L309.74,121.08L310.96,121.99L319.24,120.01L322.44,120.47L323.5,121L323.96,123.21L324.57,123.89L324.64,125.94L324.64,125.94L325.48,126.4L324.26,128.45L320.31,132.56L320.46,133.09L324.26,135.07L325.4,135.14L326.62,134.08L327.23,134.16L329.58,136.36L332.25,135.75L333.16,136.21L336.05,136.21L337.26,137.12L337.72,138.64L337.42,141.76L339.24,145.64L340.84,146.7L344.87,146.7L345.86,147.39L345.32,151.34L345.93,152.79L346.31,157.8L345.4,160.08L344.26,160.16L342.74,158.11L342.74,156.66L343.58,154.91L343.04,153.85L340.69,151.87L336.81,151.04L334.68,149.59L332.78,150.2L332.7,151.04L335.36,157.12L337.46,158L337.87,159.35L339.22,160.7L342.47,162.87L345.04,163.27L348.69,162.73L350.86,163.14L353.7,164.9L355.73,163.54L362.62,162.87L366.55,163.95L368.3,165.44L369.79,165.44L372.5,162.06L376.15,161.11L382.1,160.84L384.67,160.03L386.56,158L389.41,156.51L391.03,156.11L393.19,156.51L392.65,159.08L391.43,160.98L391.84,165.84L389.54,171.66L389.27,176.12L388.46,178.02L384.94,180.18L383.99,181.54L380.75,181.67L378.31,183.83L372.63,184.65L368.57,187.35L362.49,188.7L361.95,190.73L364.11,193.98L364.79,197.63L361.41,197.09L357.35,198.17L352.88,198.44L350.86,198.04L349.77,199.93L348.15,200.34L346.93,201.42L346.66,202.64L342.6,203.31L341.93,204.66L342.06,206.42L343.01,208.05L347.34,211.29L347.34,212.78L344.09,215.35L342.06,218.33L341.52,220.08L340,218.06L337.28,217.99L335.27,216.96L332.23,216.24L331.84,210.47L331.45,209.57L329.92,208.79L329.85,206.33L327.85,205.42L326.81,205.61L326.74,207.49L325.51,208.59L325.25,210.47L319.74,215.92L318.25,222.27L317.28,222.27L313.65,220.58L311.97,218.45L309.57,216.63L309.57,215.33L312.16,212.16L316.57,209.57L317.35,208.34L316.57,205.61L315.14,203.99L314.43,204.12L311,205.35L310.8,206.07L312.16,207.82L312.16,208.92L311.51,209.57L305.62,208.72L302.18,208.79L299.65,207.95L298.03,209.24L297.9,211.25L297.39,211.9L295.38,212.74L295.38,213.58L293.95,215.01L291.1,214.56L286.3,215.53L285.33,216.7L284.49,219.81L284.62,223.37L285.59,225.25L285.4,226.94L284.1,229.2L281.05,229.72L278.4,232.53L268.52,231.66L267.23,232.96L267.2,233.59L265.68,234.73L265.49,235.65L264.46,236.33L263.15,236.28L261.38,235.19L258.42,230.66L257.32,230.28L256.58,230.33L256.18,231.13L249.84,232.96L247.44,232.85L238.81,230.16L238.18,230.51L237.44,229.93L238.78,226.56L238.35,224.36L234.47,220.25L232.64,220.19L232.59,217.91L231.58,216.18L228.24,214.28L225.04,215L222.71,212.05L221.93,211.71L221.15,211.99L220.31,213.5L218.07,214.94L215.16,216.6L212.19,217.22L211.39,218.25L210.13,218.48L207.96,217.4L207.76,216.29L209.99,215.9L212.59,213.11L212.55,211.13L210.1,208.62L209.76,207.45L210.27,205.6L209.93,202.65L208.48,201.64L205.87,201.87L204.34,202.82L202.29,205.27L200.5,204.93L196.3,202.57L192.36,203.14L188.87,201.37L187.33,197.77L188.5,195.73L190.24,194.12L191.04,191.49L190.96,190.54L188.78,187.41L188.34,185.91L189.39,185.03L188.93,183.43L187.1,184.18L185.5,184.06L184.99,181.13L182.36,177.78L182.13,175.38L181.39,175.04L180.36,175.78L180.65,178.18L180.02,178.18L178.65,175.61L176.99,175.32L176.3,176.29L177.05,178.35L176.3,179.38L175.16,178.86L174.83,177.23L175.31,175.92L177.73,173.32L177.57,169.08L178.18,168.69L178.25,165.95L176.88,165.9L175.62,167.27L174,168.02L173.44,169.97L172.48,170.81L169.68,171.78L169.85,172.92L172.19,172.92L173.28,173.95L173.05,177.45L171.87,179.68L172.49,181.8L172.21,182.7L171.21,182.86L170.48,185.2L168.99,184.8L168.88,186.92L167.79,188.29L165.6,189.8L163.14,188.89L161.09,189.75L158.74,189.06L156.57,190.49L156.63,191.8L157.14,191.96L156.81,193.24L157.14,194.77L158.43,196.2L158.17,197.69L156.52,199.34L158.86,202.31L156.4,206.6L155.37,207L153.54,206.14L152.92,202.6L151.03,201.34L148.29,202.54L147.49,205.23L146.29,205.11L145.38,204.2L145.15,200.34L143.78,199.6L143.09,199.54L142.18,200.34L141.57,199.61L138.54,199.31L135.69,201.14L135.34,202.97L133.46,203.66L132.32,203.51L130.32,200.94L128.49,199.91L125.63,199.63L123.58,201.43L120.83,201.11L120.03,199.4L117.75,197.86L115.64,194.72L114.89,194.54L112.49,194.6L111.83,195.09L111.16,197.09L109.98,198.54L109.38,197.71L109.41,194.03L108.09,192.94L108.09,190.96L109.12,188L108.84,181.63L104.1,174.04L101.58,173.46L99.41,174.21L98.46,174.01L98.44,174.55L95.13,175.01L91.13,179.52L88.84,179.86L86.73,178.83L85.76,176.08L81.53,172.89L80.37,172.95L78.71,170.21L77.34,170.67L74.25,168.27L72.66,169.19L71.57,170.67L70.31,170.72L67.51,169.81L65.96,168.47L66.02,164.73L68.48,162.44L68.94,159.47L73.28,159.18L75.45,157.58L78.14,157.01L79.79,155.87L82.48,151.87L84.88,151.01L86.76,148.96L88.93,149.01L90.12,146.73L89.79,144.63L90.24,142.21L91.45,141.16L94.48,139.85L95.87,138.14L96.25,136.82L99.33,134.64L100.28,132.22L101.73,130.76L104.82,129.73L107.33,130.13L107.87,128.54L108.59,128.42L111.79,129.85L113.44,129.45L114.9,127.03L115.01,125.08L113.78,121.51L115.27,116.77L121.5,119.11L123.61,119.05L125.61,118.31L126.36,116.77L130.41,113.88L132.41,113.25L133.15,111.65L137.44,108.63L140.29,108.4L142.88,106.77L143.64,105.89L144.15,102.77L146.36,101.7L151.18,101.99L152.66,102.29L155.52,104.06L159.65,104.35L162.01,102.78L165.75,102.68L168.8,101.3L170.28,101.4L174.91,103.27L177.76,106.13L188.69,108.59L195.48,112.13L198.14,112.92L201.68,115.57L205.42,115.67L206.31,116.76L209.56,115.57L210.74,113.8L211.13,112.13L210.74,108.59L211.13,106.72L213.3,103.27L213.2,101.7L214.28,100.81z" }, { "id":"KG-N", "title":"Naryn", "d":"M449.68,79.38L450.25,80.41L451.5,80.52L452.97,81.43L456.95,79.73L458.15,78.31L458.15,78.31L459.89,80.19L464.31,81.66L465.71,83.29L467.49,83.05L467.65,85.23L469.35,85.54L469.58,86.78L475.63,86L476.48,83.21L477.26,82.9L482.38,83.52L483.07,84.22L482.14,89.49L482.84,89.88L482.53,91.58L482.92,94.3L484.63,98.72L484.39,100.81L488.35,103.37L488.35,106.08L492.61,107.71L493,108.33L493,109.65L491.45,112.83L491.14,114.61L490.44,115.54L489.04,115.62L487.03,119.11L487.11,119.96L490.13,120.73L493.39,119.42L495.87,119.49L497.18,118.02L499.04,118.02L501.12,118.53L505.7,120.77L506.86,120.31L511.28,120.93L511.82,122.17L513.22,123.02L515.93,123.41L517.25,122.56L517.95,122.71L518.96,123.64L521.98,124.65L523.22,126.12L526.79,127.13L527.41,128.53L528.34,128.84L529.81,127.75L530.27,128.06L530.74,129.92L530.35,131.01L528.41,132.25L528.34,134.42L527.79,135.5L526.71,136.12L521.82,136.28L520.04,135.81L519.27,136.28L517.87,139.23L518.49,142.09L518.02,143.65L518.33,145.2L519.73,144.65L525.47,145.51L530.66,144.96L531.52,143.65L533.07,142.71L534.85,143.33L535.93,144.34L536.63,145.66L536.87,147.99L536.24,149.07L534.46,150.24L533.76,151.86L534,152.72L536.4,154.11L536.71,154.96L535.08,159.81L535,161.59L536.4,161.83L538.03,160.28L538.73,160.43L541.05,163.53L547.1,163.61L554.15,162.45L555.16,162.76L556.48,164.23L558.34,164.69L562.14,162.14L571.96,163.38L576.68,162.45L578.86,160.82L580.17,158.34L580.79,158.34L582.19,162.6L580.25,168.18L579.71,169.27L575.68,169.11L576.92,169.5L578,171.21L580.17,179.35L582.81,180.74L584.05,181.05L585.76,180.59L587,181.13L588,182.91L586.61,185.94L586.53,188.5L585.83,189.89L584.13,191.68L582.03,192.92L582.19,194.47L582.89,194.78L590.33,191.21L600.41,189.19L601.73,190.28L604.05,191.06L602.81,192.53L602.81,195.86L605.45,198.27L610.1,197.72L610.95,197.18L615.84,197.88L618.32,197.57L623.75,199.82L626.23,200.28L629.56,198.03L633.13,196.71L633.83,195.86L638.17,195.24L638.63,195.86L639.87,195.94L638.94,198.5L639.41,200.67L640.26,201.99L642.2,203.54L644.05,203.98L644.05,203.98L643.21,207.4L642.3,207.67L639.94,210.2L635.1,210.83L631.9,213.85L630.93,213.85L628.41,211.63L625.27,211.23L622.56,211.57L621.16,211.23L619.5,209.97L618.19,209.97L617.84,210.94L615.56,211.68L615.66,212.19L612.19,213.4L610.81,215.28L608.11,214.81L606.42,215.62L605.45,216.77L601.33,216.54L596.65,217.91L595.05,217.22L590.62,217.74L589.25,217.34L589.38,216.02L585.7,215.62L584.9,214.54L582.11,214.08L575.94,217.22L572.34,215.11L570.34,215.17L567.82,216.42L566.62,216.08L565.48,215.28L563.71,215L562.97,212.83L560.4,211.57L556.57,211.68L556,211.05L554.63,211.11L551.77,214.14L549.93,215.27L548.2,214.98L548.46,215.68L546.12,215.4L545.14,216.88L544.97,219.77L542.57,219.82L542.12,221.19L539.32,222.17L538,226.51L538.35,231.76L536.52,232.73L536.82,234.41L535.78,235.59L535.43,237.19L530.86,240.45L530.98,243.13L532.75,245.7L530.58,250.5L530.9,252.39L529.83,254.1L528.12,254.73L526.98,257.13L525.38,257.87L523.89,260.1L522.35,263.81L522.58,267.01L521.67,268.55L519.78,269.98L519.67,271.01L515.95,273.18L515.32,275.01L512.58,276.21L509.55,276.21L507.96,279.41L506.64,278.32L506.47,274.72L504.53,273.41L501.5,272.89L500.07,273.06L498.05,275.35L494.96,277.52L488.4,276.26L485.48,278.55L484.74,278.21L483.54,276.32L481.65,275.86L480.74,276.44L479.6,279.18L478.4,280.61L478.51,283.18L477.67,283.95L476.11,282.78L472.34,282.83L471.66,281.75L471.26,282.15L470.46,281.29L467.6,283.29L464.75,283.4L462.57,285.03L461.77,284.83L460.92,279.69L459.77,277.69L459.77,276.72L460.74,273.98L460.46,272.89L462.8,270.21L463.54,267.58L460.48,264.78L458.69,264.03L457.81,262.44L456.95,259.07L456.61,252.44L455.87,250.67L453.58,249.53L450.67,250.79L446.5,253.76L441.93,259.07L439.88,260.17L437.64,260.55L436.04,261.7L433.42,264.21L433.02,265.92L431.05,266.35L429.57,268.24L427.17,269.78L423.17,268.75L421.11,268.75L417.57,270.07L415.4,269.84L413.51,268.47L411.06,268.98L409.4,268.58L404.4,264.01L401.6,262.75L402.74,263.27L400.28,262.64L399.18,263.6L396.79,262.58L395.69,262.58L394.33,263.55L388.3,263.03L387.2,261.48L385.25,261.35L384.48,260.77L383.24,261.09L382.08,259.86L381.23,260.31L380.72,260.05L380.26,257.98L381.62,254.74L381.1,253.7L380,252.66L378.71,252.53L376.96,251.24L374.3,250.59L372.36,250.91L370.15,248.26L368.08,248.19L366.52,246.31L364.25,245.54L361.34,239.7L359.72,240.03L358.94,239.57L357.71,236.07L357.26,235.62L355.77,235.62L354.34,234.58L353.95,231.47L351.88,229.01L350.06,228.36L348.05,226.03L346.11,225.77L344.94,222.2L341.9,220.71L341.6,220.08L342.95,216.97L345.25,214.27L347.42,212.78L347.42,211.29L343.09,208.05L342.14,206.42L342.01,204.66L342.68,203.31L346.74,202.64L347.01,201.42L348.23,200.34L349.85,199.93L350.93,198.04L352.96,198.44L357.43,198.17L361.48,197.09L364.87,197.63L364.19,193.98L362.02,190.73L362.57,188.7L368.65,187.35L372.71,184.65L378.39,183.83L380.83,181.67L384.07,181.54L385.02,180.18L388.54,178.02L389.35,176.12L389.62,171.66L391.92,165.84L391.51,160.98L392.73,159.08L393.27,156.51L391.11,156.11L389.48,156.51L386.64,158L384.75,160.03L382.18,160.84L376.23,161.11L372.58,162.06L369.87,165.44L368.38,165.44L366.62,163.95L362.7,162.87L355.8,163.54L353.77,164.9L350.93,163.14L348.77,162.73L345.12,163.27L342.55,162.87L339.3,160.7L337.95,159.35L337.54,158L335.44,157.12L332.78,151.04L332.86,150.2L334.76,149.59L336.89,151.04L340.76,151.87L343.12,153.85L343.65,154.91L342.82,156.66L342.82,158.11L344.34,160.16L345.48,160.08L346.39,157.8L346.01,152.79L345.4,151.34L345.93,147.39L344.95,146.7L340.92,146.7L339.32,145.64L337.49,141.76L337.8,138.64L337.34,137.12L336.13,136.21L333.24,136.21L332.32,135.75L329.66,136.36L327.3,134.16L326.7,134.08L325.48,135.14L324.34,135.07L321.15,133.62L320.39,132.56L324.34,128.45L325.39,126.31L328.34,125.63L329.13,126.31L334.24,126.31L336.06,125.51L337.2,125.74L338.9,124.04L340.04,125.85L342.77,128.35L343.45,129.94L344.92,130.28L348.79,129.6L349.24,130.17L347.54,135.06L349.01,136.76L350.26,135.85L352.08,130.4L353.22,129.38L354.58,128.81L356.97,129.49L358.9,129.15L359.85,123.64L362.58,122.27L363.26,120.57L362.35,117.16L362.92,116.03L364.28,114.89L365.76,114.55L366.67,113.07L367.58,112.73L367.24,111.71L363.94,110.23L362.81,109.21L364.74,100.23L367.81,100.8L370.53,100.57L373.26,99.67L375.65,100.23L378.83,99.44L381.21,99.55L386.17,97.79L389.01,98.24L391.73,96.09L394.12,93.02L395.82,92.22L399.57,91.77L401.39,92.22L402.41,91.43L401.96,88.81L400.6,87L399.8,84.84L397.53,82.23L397.19,80.63L404.8,79.95L405.94,79.38L411.05,80.18L413.32,78.93L414.46,79.27L415.59,80.98L418.43,80.86L421.5,78.7L422.41,79.73L423.77,80.18L426.95,79.38L431.95,81.2L434.68,80.07L437.86,79.95L439,78.48L441.61,80.29L443.2,79.73L445.13,80.07L447.06,79.5L448.31,78.93L448.77,78.13L449.79,78.36z" }, { "id":"KG-O", "title":"Osh", "d":"M399.03,263.6L398.99,264.16L398.47,264.18L398.47,267.9L396.64,269.72L396.76,270.41L401.29,274.46L402.75,276.97L405.03,278.55L404.84,279.92L403.87,280.01L402.04,281.21L400.76,281.03L398.59,279.07L397.82,278.92L390.77,279.07L390.15,279.46L390.36,282.14L387.73,286L386.59,286.36L385.84,285.42L383.9,285.15L382.02,285.55L378.13,291.6L374.7,293.57L372.42,296.89L368.13,300.14L366.74,301.82L364.6,302.71L363.58,302.71L361.58,301.23L360.2,301.87L358.26,299.57L349.69,301.63L348.44,302.26L348.38,302.83L347.01,303.91L345.47,304.37L343.07,302.83L342.44,303L339.71,307.71L335.81,309L335.76,310.03L338.26,311.11L338.5,312.71L334.67,317.4L333.93,319.25L334.73,323.51L333.01,325.05L332.1,324.94L330.1,326.48L328.79,331.96L329.24,334.59L332.5,335.62L333.8,336.96L335.93,342.82L336.84,346.93L336.61,350.24L334.56,350.24L334.1,350.81L333.53,353.47L331.99,354.67L332.5,355.98L331.76,357.64L331.7,360.67L330.16,361.47L321.7,362.73L318.56,362.55L314.85,361.47L313.13,362.44L310.46,362.27L309.03,363.18L306.8,361.87L302.23,361.98L299.72,363.53L296.86,363.92L294.52,365.18L293.95,366.04L294.06,368.27L292.69,370.15L287.61,369.87L286.47,371.35L282.35,372.84L280.24,372.72L277.05,371.29L275.45,371.35L271.51,372.89L268.54,372.21L265.28,373.35L263.34,371.87L262.14,371.92L259.63,373.58L256.94,372.38L253.69,373.64L251.06,371.52L247.12,370.09L241.52,369.29L240.21,370.61L239.58,372.27L238.44,373.01L237.12,373.07L235.98,370.78L233.06,370.61L231.29,371.58L231.41,373.52L231.01,373.87L227.07,373.87L224.38,375.12L221.53,375.35L220.55,376.21L219.56,377.46L218.13,381.52L214.38,388.55L213.39,388.72L212.71,388.15L211.85,384.21L211.16,383.46L209.96,383.35L209.16,381.12L205.11,380.83L203.79,380.26L202.88,379.18L201.51,372.84L200.82,372.15L199.11,372.27L196.6,373.75L195.4,373.75L191.68,376.55L190.26,378.59L184.77,379.23L183.97,379.92L182.48,379.52L180.85,377.77L179.17,374.26L179.69,372.67L182.03,370.49L183.06,368.32L181.07,363.06L179.86,362.41L172.37,364.13L168.83,363.27L168.03,364.18L165.69,363.55L163.92,359.38L163.8,357.9L165.58,354.87L165.67,352.36L165.05,351.08L161.54,348.86L161.54,348.86L162.51,347.52L162.89,344.63L165.59,339.88L166.43,339.32L172.11,338.76L173.32,338.02L175,334.76L179,335.31L179.47,336.9L180.59,337.74L182.26,338.48L185.62,338.95L187.94,340.9L191.11,340.44L193.81,340.81L197.35,343.6L201.17,343.7L202.76,345.38L206.39,343.7L208.07,343.51L211.33,343.79L213.47,345L216.64,344.07L217.57,343.33L221.01,342.49L223.34,339.69L225.76,339.41L226.51,338.48L231.91,336.71L234.33,335.13L234.61,333.17L235.54,332.52L234.89,330L232.66,327.3L231.17,326.28L232.19,325.16L231.17,324.32L230.89,323.39L229.3,322.74L228.47,323.02L227.35,324.42L226.04,324.42L224.46,322.37L222.5,317.43L219.9,315.75L215.98,315.01L215.89,313.7L217.47,309.7L217.38,308.49L216.08,306.62L216.92,303.83L216.54,302.8L215.61,302.15L212.54,301.13L215.52,298.52L215.52,297.22L215.05,295.91L213.93,294.89L209.65,293.21L209,292.46L211.7,290.51L211.7,289.76L210.21,287.9L211.23,283.71L210.86,282.59L209.93,281.85L208.53,281.85L202.1,283.62L198.69,285.25L198.69,285.25L195.25,283.12L194.62,282.43L194.79,281.98L197.67,278.59L198.96,278.32L200.9,275.75L200.5,274.38L202.27,272.44L202.62,270.09L205.87,270.21L205.99,269.29L208.57,267.69L209.04,266.93L208.68,266.04L209.71,265.75L211.08,266.61L213.88,266.61L214.11,269.29L216.05,271.18L217.14,271.69L217.82,271.12L219.14,271.18L221.37,272.89L222.39,274.38L223.36,274.66L223.71,275.46L225.82,274.89L225.31,272.44L225.54,271.29L227.25,269.28L227.31,265.47L226.94,264.35L224.79,263.98L225.08,262.44L225.82,261.7L224.11,257.87L221.82,256.56L222.34,255.58L224.39,255.64L224.85,254.04L225.88,254.38L228.42,257.58L228.99,259.87L230.53,261.18L231.5,260.84L231.61,259.18L232.53,258.78L233.56,260.67L238.58,262.5L240.7,264.15L242.41,264.38L244.3,263.75L245.04,261.18L245.1,256.9L246.07,256.84L246.81,257.81L249.55,257.88L250.75,256.9L250.64,255.58L252.07,250.9L250.52,249.3L250.64,248.56L251.67,247.93L252.75,249.19L253.72,249.07L257.15,247.76L258.46,244.73L263.25,243.47L263.78,242.56L265.78,241.36L268.81,240.33L274.47,239.53L276.24,238.96L277.5,237.82L279.1,234.79L278.32,232.53L280.97,229.72L284.02,229.2L285.32,226.94L285.51,225.25L284.54,223.37L284.41,219.81L285.25,216.7L286.22,215.53L291.02,214.56L293.87,215.01L295.3,213.58L295.3,212.74L297.31,211.9L297.82,211.25L297.95,209.24L299.57,207.95L302.1,208.79L305.54,208.72L311.43,209.57L312.08,208.92L312.08,207.82L310.72,206.07L310.92,205.35L315.06,203.99L317.01,206.39L317.27,208.34L316.49,209.57L312.08,212.16L309.49,215.33L309.49,216.63L311.89,218.45L313.57,220.58L317.2,222.27L318.17,222.27L318.63,221.69L319.08,217.15L320.31,214.88L325.17,210.47L325.43,208.59L326.66,207.49L326.73,205.61L329.06,205.74L329.78,206.33L329.84,208.79L331.37,209.57L331.76,210.47L332.15,216.24L335.19,216.96L337.2,217.99L339.92,218.06L341.74,220.71L344.78,222.2L345.95,225.77L347.9,226.03L349.9,228.36L351.72,229.01L353.79,231.47L354.18,234.58L355.61,235.62L357.1,235.62L357.55,236.07L358.78,239.57L359.56,240.03L361.18,239.7L364.1,245.54L366.37,246.31L367.92,248.19L370,248.26L372.2,250.91L374.14,250.59L379.85,252.66L381.47,254.74L380.11,257.98L380.56,260.05L381.08,260.31L381.92,259.86L383.09,261.09L384.32,260.77L385.1,261.35L387.04,261.48L388.14,263.03L394.17,263.55L395.53,262.58L396.63,262.58z" }, { "id":"KG-T", "title":"Talas", "d":"M193.03,44.24L194.48,44.87L196.14,46.53L201.22,47.67L202.99,49.84L204.76,50.59L208.48,50.87L210.93,49.21L215.73,48.93L223.62,51.3L230.19,54.84L232.24,56.73L234,57.53L234.86,56.84L241.03,56.5L247.37,59.64L249.25,59.81L251.48,61.01L256.11,67.64L259.88,68.27L261.08,68.72L261.59,69.52L263.36,70.04L267.19,70.49L269.78,69.73L271.76,70.32L278.05,69.58L283.19,71.58L289.99,72.32L290.84,73.86L291.33,78.83L294.08,80.15L302.39,81.58L303.31,81.52L305.22,80.28L306.3,80.83L307.09,80.53L307.68,78.86L308.27,75.02L309.65,74.72L310.73,75.81L311.42,77.68L312.5,77.87L313.78,76.79L314.86,77.18L316.04,78.37L316.04,80.24L315.36,82.3L312.6,85.65L312.4,88.8L311.22,90.18L303.84,92.74L299.41,91.26L295.27,91.56L292.62,93.92L288.48,92.84L284.94,94.12L283.46,93.52L282.38,93.72L277.95,97.56L273.62,96.18L272.83,96.87L272.54,101.99L273.91,103.86L277.16,105.04L276.67,107.8L277.16,109.47L274.7,110.55L273.13,109.96L271.75,110.26L270.96,108.78L268.99,110.06L267.42,108.49L266.73,108.68L264.56,111.64L261.81,112.92L260.92,115.87L257.28,116.46L255.9,116.46L249.64,111.64L244.62,109.18L239.89,109.57L235.66,107.31L233.89,107.5L230.94,105.24L227.49,106.22L226.11,105.83L224.24,102.97L221.09,101.5L218.34,101.6L214.2,100.81L213.12,101.7L213.22,103.27L211.05,106.72L210.66,108.59L211.05,112.13L210.66,113.8L209.48,115.57L206.23,116.76L205.34,115.67L201.6,115.57L198.06,112.92L195.4,112.13L188.61,108.59L177.68,106.13L174.83,103.27L170.2,101.4L168.73,101.3L165.67,102.68L161.93,102.78L159.57,104.35L157.31,104.35L155.44,104.06L152.58,102.29L151.1,101.99L146.28,101.7L144.08,102.77L142.27,100.4L140.5,100.11L138.5,98.8L136.73,96.8L133.3,94.74L128.39,94.23L127.36,94.57L125.47,97.03L123.7,97.83L122.33,97.6L120.5,96.4L118.67,97.31L117.59,97.26L117.02,95.09L115.76,94.17L115.25,92.29L117.13,87.43L119.07,87.03L119.14,86.07L120.45,85.49L121.96,83.87L121.59,82.86L120.16,82.01L120.12,80.97L122.79,79.21L123.82,74.98L125.42,74.75L129.19,76.86L130.79,76.69L130.96,74.81L130.5,73.95L128.44,70.98L125.87,68.52L125.42,67.44L125.82,65.95L126.96,64.58L128.33,64.24L133.7,65.21L137.7,64.07L137.81,56.84L140.44,56.24L142.5,54.41L144.15,51.56L144.44,48.64L145.64,48.3L148.55,49.04L150.67,48.64L153.64,45.73L156.55,45.67L157.64,46.24L159.41,46.3L163.69,44.87L166.24,46.83L168.95,47.73L170.01,46.19L172.18,45.27L172.92,43.96L176.98,44.36L184.18,41.73L189.95,42.7z" }, { "id":"KG-Y", "title":"Ysyk-Köl", "d":"M644.05,203.98L642.2,203.54L640.26,201.99L639.41,200.67L638.94,198.5L639.87,195.94L638.63,195.86L638.17,195.24L633.83,195.86L633.13,196.71L629.56,198.03L626.23,200.28L623.75,199.82L618.32,197.57L615.84,197.88L610.95,197.18L610.1,197.72L605.45,198.27L602.81,195.86L602.81,192.53L604.05,191.06L601.73,190.28L600.41,189.19L590.33,191.21L582.89,194.78L582.19,194.47L582.03,192.92L584.13,191.68L585.83,189.89L586.53,188.5L586.61,185.94L588,182.91L587,181.13L585.76,180.59L584.05,181.05L582.81,180.74L580.17,179.35L578,171.21L576.92,169.5L575.68,169.11L579.71,169.27L580.25,168.18L582.19,162.6L580.79,158.34L580.17,158.34L578.86,160.82L576.68,162.45L571.96,163.38L562.14,162.14L558.34,164.69L556.48,164.23L555.16,162.76L554.15,162.45L547.1,163.61L541.05,163.53L538.73,160.43L538.03,160.28L536.4,161.83L535,161.59L535.08,159.81L536.71,154.96L536.4,154.11L534,152.72L533.76,151.86L534.46,150.24L536.24,149.07L536.87,147.99L536.63,145.66L535.93,144.34L534.85,143.33L533.07,142.71L531.52,143.65L530.66,144.96L525.47,145.51L519.73,144.65L518.33,145.2L518.02,143.65L518.49,142.09L517.87,139.23L519.27,136.28L520.04,135.81L521.82,136.28L526.71,136.12L527.79,135.5L528.34,134.42L528.41,132.25L530.35,131.01L530.74,129.92L530.27,128.06L529.81,127.75L528.34,128.84L527.41,128.53L526.79,127.13L523.22,126.12L521.98,124.65L518.96,123.64L517.95,122.71L517.25,122.56L515.93,123.41L513.22,123.02L511.82,122.17L511.28,120.93L506.86,120.31L505.7,120.77L501.12,118.53L499.04,118.02L497.18,118.02L495.87,119.49L493.39,119.42L490.13,120.73L487.11,119.96L487.03,119.11L489.04,115.62L490.44,115.54L491.14,114.61L491.45,112.83L493,109.65L493,108.33L492.61,107.71L488.35,106.08L488.35,103.37L484.39,100.81L484.63,98.72L482.92,94.3L482.53,91.58L482.84,89.88L482.14,89.49L483.07,84.22L482.38,83.52L477.26,82.9L476.48,83.21L475.63,86L469.58,86.78L469.35,85.54L467.65,85.23L467.49,83.05L465.71,83.29L464.31,81.66L459.89,80.19L458.15,78.31L458.15,78.31L461.83,75.64L463.31,72.23L464.22,71.43L465.7,71.43L467.06,70.3L470.58,70.18L470.7,68.14L470.13,65.86L470.7,64.61L472.97,64.96L475.47,66.09L478.08,65.52L481.94,65.64L482.74,64.73L487.28,63.93L488.42,63.02L490.35,62.57L493.65,62.57L495.24,63.25L496.71,62.8L497.74,62.12L498.08,59.5L500.58,58.37L502.39,56.32L508.98,52.12L510.92,50.07L513.42,50.41L515.01,49.62L517.73,49.28L517.85,47L519.78,47.12L520.8,48.03L522.84,47.57L526.37,48.14L528.18,47.35L530.57,47.69L533.18,46.55L538.07,47.23L539.77,47L544.32,44.96L547.27,45.3L547.95,44.5L549.43,44.05L560,42.69L562.72,43.14L563.86,42.57L565.34,37.8L568.52,34.96L571.25,34.28L572.1,32.97L572.95,33.68L577.92,33.68L581.87,34.3L584.09,33.05L589.81,31.68L591.86,32.13L594.83,31.51L596.72,32.02L597.69,33.05L603.35,33.28L609.4,34.36L612.31,33.85L616.83,36.53L618.69,36.36L621.43,37.5L622.57,37.45L624.25,39.56L625.26,39.79L628.57,38.47L632.19,39.85L633.51,40.02L636.08,39.39L638.08,39.79L640.46,38.87L640.85,37.67L644.92,37.85L651.71,39.65L653.37,38.79L654.62,36.79L655.36,36.62L657.26,37.62L663.49,35.73L666.8,38.65L668.56,38.9L669.65,40.27L671.42,40.16L673.37,41.22L675.03,43.56L677.93,43.42L678.79,42.9L680.63,43.67L682.57,43.56L684.05,45.16L686.96,44.56L693.92,47.24L700.36,47.47L702.76,48.67L706.76,46.84L712.24,45.19L713.33,45.3L713.36,46.53L711.88,49.39L712.64,53.41L714.16,56.5L717.63,60.94L720.27,62.21L721.47,64.1L724.29,64.32L724.92,64.84L725.04,66.04L729.69,70.67L730.83,72.89L732.71,74.78L734.71,75.81L735.9,78.04L744.14,78.55L746.88,76.38L760.75,80.09L765.61,79.92L767.49,80.38L768.26,81.12L769.06,85.06L771.29,87.12L772.23,89L776.29,89.86L777.46,91.97L780.03,93.34L780.22,94.99L779.57,96.32L782.37,100.37L782.77,101.91L783.63,102.26L784.86,100.89L785.72,100.77L788,101.4L789.74,102.88L790.54,108.88L789.57,113.22L791.85,116.42L791.54,117.4L789.39,117.4L787.49,116.65L786.4,117L785.58,118L781.97,119.02L773.29,118L770.2,118.4L765.74,118.17L761.86,119.14L759.8,120.45L759.47,124.11L758.13,125.37L756.35,130.64L755.06,131.88L754.09,134.45L752.43,135.93L751.63,138.33L748.21,141.76L743.29,142.96L736.66,142.43L734.3,142.9L733.01,141.69L734.39,141.25L733.98,140.65L734.9,140.24L734.66,139.6L735.44,138.71L734.2,136.95L730.61,136.56L727.64,138.05L725.36,140.9L723.76,141.13L722.45,140.5L721.41,141.02L717.24,145.24L717.08,145.99L716.04,146.39L715.7,147.24L714.39,148.1L711.46,147.82L708.62,148.44L706.05,150.96L701.48,152.56L700.73,154.27L696.56,154.78L694.39,155.98L692.57,158.04L692.62,158.52L691.77,158.73L690.62,160.15L688.97,160.73L687.6,162.44L686.45,162.44L686.51,162.84L684.82,163.7L682.17,163.64L681.94,164.15L679.08,164.44L677.66,165.24L676.74,168.67L675.37,169.29L673.77,172.09L670.17,172.44L667.6,171.69L666.69,172.21L665.49,174.61L663.49,175.98L659.49,177.75L655.55,178.26L654.92,179.81L654.86,182.72L656.23,184.32L656.52,188.26L655.03,189.17L654.63,191.63L651.61,191.97L647.95,195.92L646.46,196.72z" } ] } } };
function TriangleD(n) { let out = '' for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { out += j >= n - i - 1 ? '* ' : ' ' } out += '\n' } return out } TriangleD.title = 'Triangle D' TriangleD.source = ` function TriangleD(n) { let out = '' for (let i = 0; i < n; i++) { for (let j = 0; j < n; j++) { out += j >= n - i ? '* ' : ' ' } out += '\\n' } return out } ` export default TriangleD
//drafts5://x-callback-url/create?text=Hello%20World // https://reference.getdrafts.com/topics/urls var md = "-%20[" + window.getSelection().toString() + "]" + "%0A%0A" + "[" + window.getSelection().toString() + "]: " + document.URL + " \"" +document.title + "\"" +"%0A" ; window.location.href = "drafts5://prepend?uuid=981735F6-1304-4735-A679-4EB05333763F&text=" + md
const db = require('../models'); const router = require('express').Router(); const isAuthenticated = require ('../utils/middleware').isAuthenticated; router.get('/', isAuthenticated, function(req, res) { db.Game.findAll(req.query) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }); router.get('/:id', isAuthenticated, function(req, res) { db.Game.findByPk(req.params.id) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }); router.post('/', isAuthenticated, function(req, res) { db.Game.create(req.body) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }); router.put('/:id', isAuthenticated, function(req, res) { db.Game.update(req.body, { where: { id: req.params.id }}) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); }); router.delete('/:id', isAuthenticated, function(req, res) { db.Game.destroy({ where: { id: req.params.id }}) .then(dbModel => res.json(dbModel)) .catch(err => res.status(422).json(err)); });
(function(vc){ vc.extends({ propTypes: { notifyLoadDataComponentName:vc.propTypes.string }, data:{ addParkingSpaceInfo:{ num:'', typeCd:'', area:'', remark:'', psId:'' } }, _initMethod:function(){ }, _initEvent:function(){ vc.on('addParkingSpace','openAddParkingSpaceModal',function(_parkingSpaceId){ if(_parkingSpaceId != null || _parkingSpaceId != -1){ vc.component.addParkingSpaceInfo.parkingSpaceId = _parkingSpaceId; } $('#addParkingSpaceModel').modal('show'); }); }, methods:{ addParkingSpaceValidate(){ return vc.validate.validate({ addParkingSpaceInfo:vc.component.addParkingSpaceInfo },{ 'addParkingSpaceInfo.num':[ { limit:"required", param:"", errInfo:"车位编号不能为空" }, { limit:"maxLength", param:"12", errInfo:"车位编号长度不能超过12位" }, ], 'addParkingSpaceInfo.typeCd':[ { limit:"required", param:"", errInfo:"车位类型不能为空" } ], 'addParkingSpaceInfo.area':[ { limit:"required", param:"", errInfo:"车位面积不能为空" }, { limit:"money", param:"", errInfo:"车位面积格式错误,如3.09" } ], 'addParkingSpaceInfo.remark':[ { limit:"maxLength", param:"200", errInfo:"备注长度不能超过200位" } ] }); }, saveParkingSpaceInfo:function(){ if(!vc.component.addParkingSpaceValidate()){ vc.message(vc.validate.errInfo); return ; } vc.component.addParkingSpaceInfo.communityId = vc.getCurrentCommunity().communityId; vc.http.post( 'addParkingSpace', 'saveParkingSpace', JSON.stringify(vc.component.addParkingSpaceInfo), { emulateJSON:true }, function(json,res){ //vm.menus = vm.refreshMenuActive(JSON.parse(json),0); if(res.status == 200){ //关闭model $('#addParkingSpaceModel').modal('hide'); vc.component.clearAddParkingSpaceInfo(); vc.emit($props.notifyLoadDataComponentName,'listParkingSpaceData',{}); return ; } vc.message(json); }, function(errInfo,error){ console.log('请求失败处理'); vc.message(errInfo); }); }, clearAddParkingSpaceInfo:function(){ vc.component.addParkingSpaceInfo = { num:'', typeCd:'', area:'', remark:'' }; } } }); })(window.vc);
import moment from "moment"; import momentAm from "../../config/lang-phrases/moment-am"; moment.defineLocale("am", momentAm); export default moment;
var searchData= [ ['mousebutton',['MouseButton',['../class_tri_1_1_input_1_1_mouse.html#a926c664faabb33e4fab8154520289d2d',1,'Tri::Input::Mouse']]] ];
/** * @file 创建 if 指令元素 * @author errorrik(errorrik@gmail.com) */ var each = require('../util/each'); var genStumpHTML = require('./gen-stump-html'); var nodeInit = require('./node-init'); var NodeType = require('./node-type'); var nodeEvalExpr = require('./node-eval-expr'); var rinseCondANode = require('./rinse-cond-anode'); var createNode = require('./create-node'); var createReverseNode = require('./create-reverse-node'); var getNodeStumpParent = require('./get-node-stump-parent'); var elementUpdateChildren = require('./element-update-children'); var nodeOwnSimpleDispose = require('./node-own-simple-dispose'); var nodeOwnGetStumpEl = require('./node-own-get-stump-el'); /** * 创建 if 指令元素 * * @param {Object} options 初始化参数 * @return {Object} */ function createIf(options) { var node = nodeInit(options); node.children = []; node.nodeType = NodeType.IF; node.dispose = nodeOwnSimpleDispose; node._getEl = nodeOwnGetStumpEl; node._attachHTML = ifOwnAttachHTML; node._update = ifOwnUpdate; node.cond = node.aNode.directives.get('if').value; // #[begin] reverse var walker = options.reverseWalker; if (walker) { options.reverseWalker = null; if (nodeEvalExpr(node, node.cond)) { node.elseIndex = -1; node.children[0] = createReverseNode( rinseCondANode(node.aNode), walker, node ); } else { each(node.aNode.elses, function (elseANode, index) { var elif = elseANode.directives.get('elif'); if (!elif || elif && nodeEvalExpr(node, elif.value)) { node.elseIndex = index; node.children[0] = createReverseNode( rinseCondANode(elseANode), walker, node ); return false; } }); } } // #[end] return node; } /** * attach元素的html * * @param {Object} buf html串存储对象 */ function ifOwnAttachHTML(buf) { var me = this; var elseIndex; var child; if (nodeEvalExpr(me, me.cond)) { child = createNode(rinseCondANode(me.aNode), me); elseIndex = -1; } else { each(me.aNode.elses, function (elseANode, index) { var elif = elseANode.directives.get('elif'); if (!elif || elif && nodeEvalExpr(me, elif.value)) { child = createNode(rinseCondANode(elseANode), me); elseIndex = index; return false; } }); } if (child) { me.children[0] = child; child._attachHTML(buf); me.elseIndex = elseIndex; } genStumpHTML(this, buf); } /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ function ifOwnUpdate(changes) { var me = this; var childANode = me.aNode; var elseIndex; if (nodeEvalExpr(this, this.cond)) { elseIndex = -1; } else { each(me.aNode.elses, function (elseANode, index) { var elif = elseANode.directives.get('elif'); if (elif && nodeEvalExpr(me, elif.value) || !elif) { elseIndex = index; childANode = elseANode; return false; } }); } if (elseIndex === me.elseIndex) { elementUpdateChildren(me, changes); } else { var child = me.children[0]; me.children.length = 0; if (child) { child._ondisposed = newChild; child.dispose(); } else { newChild(); } me.elseIndex = elseIndex; } function newChild() { if (typeof elseIndex !== 'undefined') { var child = createNode(rinseCondANode(childANode), me); var parentEl = getNodeStumpParent(me); child.attach(parentEl, me._getEl() || parentEl.firstChild); me.children[0] = child; } } } exports = module.exports = createIf;
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var GalleryAlbum = (function () { function GalleryAlbum(id, title, path, mtime, owner) { this.id = id; this.title = title; this.path = path; this.mtime = mtime; this.owner = owner; } return GalleryAlbum; }()); exports.GalleryAlbum = GalleryAlbum; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2FsbGVyeS5hbGJ1bS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbImdhbGxlcnkuYWxidW0udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQTtJQUNJLHNCQUNXLEVBQVcsRUFDWCxLQUFjLEVBQ2QsSUFBYSxFQUNiLEtBQWMsRUFDZCxLQUFjO1FBSmQsT0FBRSxHQUFGLEVBQUUsQ0FBUztRQUNYLFVBQUssR0FBTCxLQUFLLENBQVM7UUFDZCxTQUFJLEdBQUosSUFBSSxDQUFTO1FBQ2IsVUFBSyxHQUFMLEtBQUssQ0FBUztRQUNkLFVBQUssR0FBTCxLQUFLLENBQVM7SUFDekIsQ0FBQztJQUNMLG1CQUFDO0FBQUQsQ0FBQyxBQVJELElBUUM7QUFSWSxvQ0FBWSIsInNvdXJjZXNDb250ZW50IjpbImV4cG9ydCBjbGFzcyBHYWxsZXJ5QWxidW0ge1xyXG4gICAgY29uc3RydWN0b3IoXHJcbiAgICAgICAgcHVibGljIGlkPzogc3RyaW5nLCBcclxuICAgICAgICBwdWJsaWMgdGl0bGU/OiBzdHJpbmcsIFxyXG4gICAgICAgIHB1YmxpYyBwYXRoPzogc3RyaW5nLCBcclxuICAgICAgICBwdWJsaWMgbXRpbWU/OiBzdHJpbmcsIFxyXG4gICAgICAgIHB1YmxpYyBvd25lcj86IHN0cmluZykge1xyXG4gICAgfVxyXG59Il19
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); //# sourceMappingURL=Theme.js.map
var class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config = [ [ "AllowNull", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a1d17d5f7998e83a052e5180b5d0715bc", null ], [ "Calculate", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#aef7273065605c355701efa14fbb2e7be", null ], [ "Convert", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#aedae12a8c2260b2784f24ca9ebc1d1f6", null ], [ "Critical", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a66e458f5a94ceb1214cd40a252048c09", null ], [ "CustomSortType", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a300a628608f8e33680e7caefd872d398", null ], [ "DateFormat", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a883ceddd854e766fcd4763960e083ddb", null ], [ "DateReadFormat", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a2d2660b5481c3b2cd8bbe1f056ab8e32", null ], [ "DateWriteFormat", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#ac3c3bcc231cf42c1363455ae049909c6", null ], [ "DefaultValue", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a88c815f4e0f3ebb2fd9ca731f81bfcb9", null ], [ "Depends", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a193f52d5e255945788da5a3e49096a01", null ], [ "Fields", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a156ffabcffdddb5c2634a190d11514c4", null ], [ "HtmlEncode", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a50edd177edf6f41bf5c829bef19b49bf", null ], [ "IsComplex", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a7b3535108eb120b1765e50d20f47b7fe", null ], [ "Mapping", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a8c31b312b6d1a89bac7011547c00b79d", null ], [ "MappingFunction", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a315f1595f8074175b88b8dafccf3b9f1", null ], [ "Model", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#aa7f5948710c104a63d08e835543d5f64", null ], [ "ModelName", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a19334ebb31dd84e408b77c3c6dc1afb9", null ], [ "Name", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a6db2901aa326e80e71c962bd9f546f5d", null ], [ "NullConvert", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a1d1bdcd8cf243c2f8be3378f91da5a47", null ], [ "Persist", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a8204a0f982c97fe3eb305a96e89e1bd5", null ], [ "Reference", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a2e620f60cd12aed4efc0d8a5d8b75d4b", null ], [ "ReferenceString", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a45a096b1639b77456caac0e5a75a56af", null ], [ "Serialize", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a312d732a427bfaa36e78ecf428703c50", null ], [ "ServerMapping", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a3d5af54585ae3f6e2d26e963b449f6e6", null ], [ "SortDir", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a9e9b312e2208a75c8b2374cd7500a800", null ], [ "SortType", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#aea4b8d45d57a14f7c9fe3dee2f19bab9", null ], [ "SubmitEmptyValue", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a6a9d4617c7283c2a98c86275d72642e3", null ], [ "Type", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a37278e983d33416dd62dc936d2796e41", null ], [ "Unique", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a08403f2dc74b4d7d1e5d7d57983eaf1f", null ], [ "VersionProperty", "d5/d73/class_ext_1_1_net_1_1_mobile_1_1_model_field_1_1_config.html#a44adce1391f97c294c03658905009ce0", null ] ];
ButtonExpToExcel.prototype.DEF_TITLE = "экспорт в Excel"; ButtonExpToExcel.prototype.DEF_CAPTION="Excel";
'use strict' function isFirstStrInSecondStr(firstStr, secondStr) { return firstStr.search(secondStr) !== - 1; } module.exports = isFirstStrInSecondStr;
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var Observable_1 = require('../Observable'); /** * We need this JSDoc comment for affecting ESDoc. * @extends {Ignored} * @hide true */ var ErrorObservable = (function (_super) { __extends(ErrorObservable, _super); function ErrorObservable(error, scheduler) { _super.call(this); this.error = error; this.scheduler = scheduler; } /** * Creates an Observable that emits no items to the Observer and immediately * emits an error notification. * * <span class="informal">Just emits 'error', and nothing else. * </span> * * <img src="./img/throw.png" width="100%"> * * This static operator is useful for creating a simple Observable that only * emits the error notification. It can be used for composing with other * Observables, such as in a {@link mergeMap}. * * @example <caption>Emit the number 7, then emit an error.</caption> * var result = Rx.Observable.throw(new Error('oops!')).startWith(7); * result.subscribe(x => console.log(x), e => console.error(e)); * * @example <caption>Map and flatten numbers to the sequence 'a', 'b', 'c', but throw an error for 13</caption> * var interval = Rx.Observable.interval(1000); * var result = interval.mergeMap(x => * x === 13 ? * Rx.Observable.throw('Thirteens are bad') : * Rx.Observable.of('a', 'b', 'c') * ); * result.subscribe(x => console.log(x), e => console.error(e)); * * @see {@link create} * @see {@link empty} * @see {@link never} * @see {@link of} * * @param {any} error The particular Error to pass to the error notification. * @param {Scheduler} [scheduler] A {@link IScheduler} to use for scheduling * the emission of the error notification. * @return {Observable} An error Observable: emits only the error notification * using the given error argument. * @static true * @name throw * @owner Observable */ ErrorObservable.create = function (error, scheduler) { return new ErrorObservable(error, scheduler); }; ErrorObservable.dispatch = function (arg) { var error = arg.error, subscriber = arg.subscriber; subscriber.error(error); }; ErrorObservable.prototype._subscribe = function (subscriber) { var error = this.error; var scheduler = this.scheduler; if (scheduler) { return scheduler.schedule(ErrorObservable.dispatch, 0, { error: error, subscriber: subscriber }); } else { subscriber.error(error); } }; return ErrorObservable; }(Observable_1.Observable)); exports.ErrorObservable = ErrorObservable; //# sourceMappingURL=ErrorObservable.js.map
(window.webpackJsonp=window.webpackJsonp||[]).push([[156],{583:function(t,s,a){"use strict";a.r(s);var n=a(25),e=Object(n.a)({},(function(){var t=this,s=t.$createElement,a=t._self._c||s;return a("ContentSlotsDistributor",{attrs:{"slot-key":t.$parent.slotKey}},[a("h1",{attrs:{id:"组件上手"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#组件上手"}},[t._v("#")]),t._v(" "),a("H2Icon"),t._v(" 组件上手")],1),t._v(" "),a("p",[t._v("关于微信小程序组件的相关知识,本文不会做详细的描述,这些知识点需要你去参考微信小程序的"),a("a",{attrs:{href:"https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/",target:"_blank",rel:"noopener noreferrer"}},[t._v("自定义组件"),a("OutboundLink")],1),t._v("来获取,本文的重点是保证每一个使用者都能正确快速的在自己的项目里使用Lin-UI。")]),t._v(" "),a("h2",{attrs:{id:"组件的引入"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#组件的引入"}},[t._v("#")]),t._v(" 组件的引入")]),t._v(" "),a("p",[t._v("引入Lin-UI组件和引入自己写的组件一样,首先需要在 "),a("code",[t._v("json")]),t._v(" 文件中进行自定义组件声明,也就是在"),a("code",[t._v("usingComponents")]),t._v(" 下以键值对的形式去注册,"),a("code",[t._v("l-icon")]),t._v(" 是组件的名称,"),a("code",[t._v("path/to/icon/index")]),t._v(" 是组件的路径。")]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("注意事项")]),t._v(" "),a("p",[t._v("需要注意的是,由于引入lin-ui的方式不同,(npm引入/ 复制源码的dist文件夹),所以这里的"),a("code",[t._v("path/to")]),t._v(" 只是用来表示路径这个含义,并不能直接复制进项目里。需要你根据实际情况来配置正确的路径。")])]),t._v(" "),a("div",{staticClass:"language-json extra-class"},[a("pre",{pre:!0,attrs:{class:"language-json"}},[a("code",[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"usingComponents"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"l-icon"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"path/to/icon/index"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("h2",{attrs:{id:"组件的使用"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#组件的使用"}},[t._v("#")]),t._v(" 组件的使用")]),t._v(" "),a("p",[t._v("当组件的声明已经完成,那么我们在页面的 "),a("code",[t._v("wxml")]),t._v(" 中就可以像使用基础组件一样使用自定义组件。\n"),a("br"),t._v("同时每个组件都有相对应的"),a("code",[t._v("props")]),t._v("(属性), 例如: "),a("code",[t._v("l-icon")]),t._v("标签上的"),a("code",[t._v("name")]),t._v("属性,就是根据传递不同的name值,来显示不同的"),a("code",[t._v("icon")])]),t._v(" "),a("div",{staticClass:"custom-block tip"},[a("p",{staticClass:"custom-block-title"},[t._v("注意事项")]),t._v(" "),a("p",[t._v("因为 WXML 节点标签名只能是小写字母、中划线和下划线的组合,所以自定义组件的标签名也只能包含这些字符。")])]),t._v(" "),a("div",{staticClass:"language-wxml extra-class"},[a("pre",{pre:!0,attrs:{class:"language-text"}},[a("code",[t._v('<l-icon name="add" />\n')])])]),a("h2",{attrs:{id:"组件的事件"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#组件的事件"}},[t._v("#")]),t._v(" 组件的事件")]),t._v(" "),a("p",[t._v("大部分的组件都有对应的事件,详细的内容请参阅每个组件的文档,以及统一的"),a("a",{attrs:{href:"http://doc.mini.talelin.com/start/event.html",target:"_blank",rel:"noopener noreferrer"}},[t._v("事件说明"),a("OutboundLink")],1),t._v("。")]),t._v(" "),a("h2",{attrs:{id:"全局自定义组件"}},[a("a",{staticClass:"header-anchor",attrs:{href:"#全局自定义组件"}},[t._v("#")]),t._v(" 全局自定义组件")]),t._v(" "),a("p",[t._v("我们都知道微信小程序的组件使用需要在页面的json文件里注册,那么这个时候会有一个问题:一些常用的基础组件,如"),a("code",[t._v("toast")]),t._v(","),a("code",[t._v("diolag")]),t._v("等等,每次在一个页面使用都要在"),a("code",[t._v("json")]),t._v("中去声明一次,实在过于繁琐,或则说这一点也不"),a("code",[t._v("前端")]),t._v("。\n"),a("br"),t._v("\n所以,对于这类跨页面,使用频率高的组件,我们可以在"),a("code",[t._v("app.json")]),t._v("里一次性声明,也就是创建"),a("code",[t._v("全局自定义组件")]),t._v(",声明的方法和页面声明一样。")]),t._v(" "),a("div",{staticClass:"language-json extra-class"},[a("pre",{pre:!0,attrs:{class:"language-json"}},[a("code",[a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"pages"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"pages/index/index"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"pages/logs/index"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"window"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"navigationBarTitleText"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"Demo"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"tabBar"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"list"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("[")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"pagePath"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"pages/index/index"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"text"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"首页"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"pagePath"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"pages/logs/logs"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"text"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"日志"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("]")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"usingComponents"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("{")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"l-toast"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"path/to/toast/index"')]),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v(",")]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token property"}},[t._v('"l-message"')]),a("span",{pre:!0,attrs:{class:"token operator"}},[t._v(":")]),t._v(" "),a("span",{pre:!0,attrs:{class:"token string"}},[t._v('"path/to/message/index"')]),t._v("\n "),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n"),a("span",{pre:!0,attrs:{class:"token punctuation"}},[t._v("}")]),t._v("\n")])])]),a("p",[t._v("这样,我们使用Lin-UI开发的效率又会大大提升啦!")]),t._v(" "),a("p",[a("code",[t._v("官方提示")]),t._v(":组件开发体验爽,一直使用一直爽!")]),t._v(" "),a("RightMenu")],1)}),[],!1,null,null,null);s.default=e.exports}}]);
'use strict' const closeIcon = require('@nearform/clinic-common/icons/close') // const d3 = require('./d3-subset.js') // Currently unused but will be used const HtmlContent = require('./html-content.js') const arrayFlatten = require('array-flatten').flatten class Frames extends HtmlContent { constructor (d3Container, contentProperties = {}) { super(d3Container, contentProperties) this.framesByNode = [] this.topmostUI = null this.firstDraw = true this.ui.on('setTopmostUI', (topmostUI) => { this.topmostUI = topmostUI }) } initializeElements () { super.initializeElements() this.d3Element.classed('frames-container', true) this.d3Heading = this.d3ContentWrapper.append('div') .classed('heading', true) this.ui.on('outputFrames', (aggregateNode) => { if (aggregateNode) { this.setData(aggregateNode) } else { this.reset() } }) } reset () { this.node = null this.framesByNode = [] this.parentContent.collapseClose() } setData (aggregateNode) { this.node = aggregateNode this.isRoot = aggregateNode.isRoot this.framesByNode = [] groupFrames(this.node, this.framesByNode) this.parentContent.collapseOpen() } draw () { super.draw() if (this.firstDraw) { this.firstDraw = false this.parentContent.d3ContentWrapper.insert('span', ':first-child') .classed('close', true) .html(closeIcon) .on('click', () => { this.topmostUI.clearFrames() this.parentContent.collapseClose() }) } this.d3ContentWrapper.selectAll('.frame-item').remove() this.d3ContentWrapper.selectAll('.frame-group').remove() if (this.node) { this.drawFrames(this.framesByNode, this.d3ContentWrapper) this.d3Heading.html(`Showing async stack trace from async operation "<strong>${this.node.name}</strong>"`) .on('mouseover', () => { const layoutNode = this.topmostUI.layout.findDataNode(this.node) this.topmostUI.highlightNode(layoutNode, this.node) }) .on('mouseout', () => { this.topmostUI.highlightNode(null) }) } else { this.d3Heading.html(` Click on a grouping in the diagram above to drill down, and find the call stacks showing the exact lines of code these async operations originated from. `) this.d3Heading.on('mouseover', null) this.d3Heading.on('mouseout', null) } } getDelaysText (aggregateNode) { const betweenFigure = this.ui.formatNumber(aggregateNode.getBetweenTime()) const withinFigure = this.ui.formatNumber(aggregateNode.getWithinTime()) return `<span class="figure">${betweenFigure} ms</span> in asynchronous delays, <span class="figure">${withinFigure} ms</span> in synchronous delays.` } drawFrames (frames, d3AppendTo) { if (!frames.length) { const d3Group = d3AppendTo.append('div') .classed('frame-group', true) .on('click', () => { d3Group.classed('collapsed', !d3Group.classed('collapsed')) }) d3Group.append('div') .classed('sub-collapse-control', true) .html('<span class="arrow"></span> Empty frames') const d3EmptyFrameItem = d3Group.append('div') .classed('frame-item', true) if (frames.dataNode && frames.dataNode.isRoot) { d3EmptyFrameItem.text('This is the root node, representing the starting point of your application. No stack frames are available.') } else { d3EmptyFrameItem.text('No frames are available for this async operation. It could be from a native module, or something not integrated with the Async Hooks API.') } } for (const frame of frames) { if (frame.isGroup) { const d3Group = d3AppendTo.append('div') .classed('frame-group', true) const d3SubCollapseControl = d3Group.append('div') .classed('sub-collapse-control', true) let header = '<span class="arrow"></span>' if (frame.dataNode) { const isThisNode = frame.dataNode === this.node d3Group .classed('node-frame-group', true) .classed('collapsed', !isThisNode) .classed('this-node', isThisNode) if (!isThisNode) { d3Group.insert('a', ':first-child') .classed('jump-to-node', true) .text('Select on diagram') .on('mouseover', () => { const layoutNode = this.topmostUI.layout.findDataNode(frame.dataNode) || this.topmostUI.layout.rootLayoutNode this.topmostUI.highlightNode(layoutNode, frame.dataNode) }) .on('mouseout', () => { this.topmostUI.highlightNode(null) }) .on('click', () => { this.topmostUI.queueAnimation('jumpToFrame', (animationQueue) => { const targetUI = this.topmostUI.jumpToNode(frame.dataNode, animationQueue) this.topmostUI.originalUI.emit('navigation', { from: this.ui, to: targetUI }) }) }) } header += `${arrayFlatten(frame).length} frames from ` header += `${isThisNode ? 'this async operation' : `previous async operation "${frame.dataNode.name}"`}` header += `<div class="delays">${this.getDelaysText(frame.dataNode)}</span>` } else if (frame.party) { d3Group.classed(frame.party[0], true) .classed('collapsed', frame.party[0] !== 'user') header += `${frame.length} frame${frame.length === 1 ? '' : 's'} from ${frame.party[1]}` } d3SubCollapseControl.html(header) .on('click', () => { d3Group.classed('collapsed', !d3Group.classed('collapsed')) }) this.drawFrames(frame, d3Group) } else { d3AppendTo.append('pre') .html(frame.formatted) .classed('frame-item', true) } } } } function groupFrames (aggregateNode, framesByNode) { let previousFrame let previousGroup const groupedFrames = [] groupedFrames.dataNode = aggregateNode groupedFrames.isGroup = true for (const frame of aggregateNode.frames) { const party = frame.data.party if (!previousFrame || previousFrame.data.party[1] !== party[1]) { const group = [frame] group.isGroup = true group.party = party groupedFrames.push(group) previousGroup = group } else { previousGroup.push(frame) } previousFrame = frame } framesByNode.push(groupedFrames) // Full async stack trace - recurse through aggregate ancestry to the root aggregate node if (aggregateNode.parentId) groupFrames(aggregateNode.getParentNode(), framesByNode) } module.exports = Frames
var classLabel = [ [ "Label", "classLabel.html#aebb3c4065e132513580a1139c6c4df05", null ], [ "caption", "classLabel.html#ac369d7356d2383945a946a30be9e9d3a", null ], [ "color", "classLabel.html#ad581a5c2bb8cb01e504a2144b33a324e", null ], [ "draw", "classLabel.html#a9451601ed41f80658543b60aff8b37ec", null ], [ "font", "classLabel.html#ac229788cee41a246c99316d1e07d3a04", null ], [ "preferred_size", "classLabel.html#a99fe7144e2c5c6297bd3f0f4b8c6105d", null ], [ "set_caption", "classLabel.html#af9662a8666218adcb82bed5e1c402d3e", null ], [ "set_color", "classLabel.html#a4113f6d0292466622e98580bb27dbe15", null ], [ "set_font", "classLabel.html#a1125eba7c92680b561a5038730414dd3", null ], [ "set_theme", "classLabel.html#a0a45a662a91d3e2805c05a402aabe58a", null ], [ "m_caption", "classLabel.html#a3dcebb09e22ccd332319340340ec6964", null ], [ "m_color", "classLabel.html#ad61b348090ce73487ea2b827d0575c46", null ], [ "m_font", "classLabel.html#ab47f42527753bac3251e04e6735ebbb2", null ] ];
import { expect } from 'chai'; import { spec } from 'modules/komoonaBidAdapter'; describe('Komoona.com Adapter Tests', () => { const bidsRequest = [ { bidder: 'komoona', params: { placementId: '170577', hbid: 'abc12345678', }, placementCode: 'div-gpt-ad-1460505748561-0', transactionId: '9f801c02-bbe8-4683-8ed4-bc816ea186bb', sizes: [ [300, 250] ], bidId: '2faedf1095f815', bidderRequestId: '18065867f8ae39', auctionId: '529e1518-b872-45cf-807c-2d41dfa5bcd3' }, { bidder: 'komoona', params: { placementId: '281277', hbid: 'abc12345678', floorPrice: 0.5 }, placementCode: 'div-gpt-ad-1460505748561-0', transactionId: '9f801c02-bbe8-4683-8ed4-bc816ea186bb', sizes: [ [728, 90] ], bidId: '3c34e2367a3f59', bidderRequestId: '18065867f8ae39', auctionId: '529e1518-b872-45cf-807c-2d41dfa5bcd3' }]; const bidsResponse = { body: { bids: [ { placementid: '170577', uuid: '2faedf1095f815', width: 300, height: 250, cpm: 0.51, creative: '<script type="text/javascript" src="http://creative.com/pathToNiceCreative"></script>', ttl: 360, currency: 'USD', netRevenue: true, creativeId: 'd30b58c2ba' } ] } }; it('Verifies komoonaAdapter bidder code', () => { expect(spec.code).to.equal('komoona'); }); it('Verifies komoonaAdapter bid request validation', () => { expect(spec.isBidRequestValid(bidsRequest[0])).to.equal(true); expect(spec.isBidRequestValid(bidsRequest[1])).to.equal(true); expect(spec.isBidRequestValid({})).to.equal(false); expect(spec.isBidRequestValid({ params: {} })).to.equal(false); expect(spec.isBidRequestValid({ params: { hbid: 12345 } })).to.equal(false); expect(spec.isBidRequestValid({ params: { placementid: 12345 } })).to.equal(false); expect(spec.isBidRequestValid({ params: { hbid: 12345, placementId: 67890 } })).to.equal(true); expect(spec.isBidRequestValid({ params: { hbid: 12345, placementId: 67890, floorPrice: 0.8 } })).to.equal(true); }); it('Verify komoonaAdapter build request', () => { var startTime = new Date().getTime(); const request = spec.buildRequests(bidsRequest); expect(request.url).to.equal('//bidder.komoona.com/v1/GetSBids'); expect(request.method).to.equal('POST'); const requestData = JSON.parse(request.data); // bids object let bids = requestData.bids; expect(bids).to.have.lengthOf(2); // first bid request: no floor price expect(bids[0].uuid).to.equal('2faedf1095f815'); expect(bids[0].floorprice).to.be.undefined; expect(bids[0].placementid).to.equal('170577'); expect(bids[0].hbid).to.equal('abc12345678'); expect(bids[0].trid).to.equal('9f801c02-bbe8-4683-8ed4-bc816ea186bb'); expect(bids[0].sizes).to.have.lengthOf(1); expect(bids[0].sizes[0][0]).to.equal(300); expect(bids[0].sizes[0][1]).to.equal(250); // second bid request: with floor price expect(bids[1].uuid).to.equal('3c34e2367a3f59'); expect(bids[1].floorprice).to.equal(0.5); expect(bids[1].placementid).to.equal('281277'); expect(bids[1].hbid).to.equal('abc12345678'); expect(bids[1].trid).to.equal('9f801c02-bbe8-4683-8ed4-bc816ea186bb'); expect(bids[1]).to.have.property('sizes') .that.is.an('array') .of.length(1) .that.deep.equals([[728, 90]]); // kbConf object let kbConf = requestData.kbConf; expect(kbConf.hdbdid).to.equal(bids[0].hbid); expect(kbConf.hdbdid).to.equal(bids[1].hbid); expect(kbConf.encode_bid).to.be.undefined; // kbConf timezone and cb expect(kbConf.cb).not.to.be.undefined; expect(kbConf.ts_as).to.be.above(startTime - 1); expect(kbConf.tz).to.equal(new Date().getTimezoneOffset()); // kbConf bid ids expect(kbConf.hb_placement_bidids) .to.have.property(bids[0].placementid) .that.equal(bids[0].uuid); expect(kbConf.hb_placement_bidids) .to.have.property(bids[1].placementid) .that.equal(bids[1].uuid); // kbConf floor price expect(kbConf.hb_floors).not.to.have.property(bids[0].placementid) expect(kbConf.hb_floors).to.have.property(bids[1].placementid).that.equal(bids[1].floorprice); // kbConf placement ids expect(kbConf.hb_placements).to.have.lengthOf(2); expect(kbConf.hb_placements[0]).to.equal(bids[0].placementid); expect(kbConf.hb_placements[1]).to.equal(bids[1].placementid); }); it('Verify komoonaAdapter build response', () => { const request = spec.buildRequests(bidsRequest); const bids = spec.interpretResponse(bidsResponse, request); // 'server' return single bid expect(bids).to.have.lengthOf(1); // verify bid object const bid = bids[0]; const responseBids = bidsResponse.body.bids; expect(bid.cpm).to.equal(responseBids[0].cpm); expect(bid.ad).to.equal(responseBids[0].creative); expect(bid.requestId).equal(responseBids[0].uuid); expect(bid.uuid).equal(responseBids[0].uuid); expect(bid.width).to.equal(responseBids[0].width); expect(bid.height).to.equal(responseBids[0].height); expect(bid.ttl).to.equal(responseBids[0].ttl); expect(bid.currency).to.equal('USD'); expect(bid.netRevenue).to.equal(true); expect(bid.creativeId).to.equal(responseBids[0].creativeId); }); it('Verifies komoonaAdapter sync options', () => { // user sync disabled expect(spec.getUserSyncs({})).to.be.undefined; expect(spec.getUserSyncs({ iframeEnabled: false })).to.be.undefined; // user sync enabled const options = spec.getUserSyncs({ iframeEnabled: true }); expect(options).to.not.be.undefined; expect(options).to.have.lengthOf(1); expect(options[0].type).to.equal('iframe'); expect(options[0].url).to.equal('//s.komoona.com/sync/usync.html'); }); });
import config from "./config.js" import server from "./server.js" import { logger } from './util.js' server.listen(config.port) .on('listening', () => logger.info(`server running at ${config.port}!!`))
import { insert } from '../utils' export default { regexp: /\$/, format (value, formatType, roundingFunction, numerify) { const symbols = { before: formatType.match(/^([+|\-|(|\s|$]*)/)[0], after: formatType.match(/([+|\-|)|\s|$]*)$/)[0] } let symbol formatType = formatType.replace(/\s?\$\s?/, '') let output = numerify._numberToFormat(value, formatType, roundingFunction) if (value >= 0) { symbols.before = symbols.before.replace(/[-(]/, '') symbols.after = symbols.after.replace(/[-)]/, '') } else if (value < 0 && (!~symbols.before.indexOf('-') && !~symbols.before.indexOf('('))) { symbols.before = '-' + symbols.before } for (let i = 0; i < symbols.before.length; i++) { symbol = symbols.before[i] switch (symbol) { case '$': output = insert(output, '$', i) break case ' ': output = insert(output, ' ', i) break } } for (let i = symbols.after.length - 1; i >= 0; i--) { symbol = symbols.after[i] switch (symbol) { case '$': output = i === symbols.after.length - 1 ? output + '$' : insert(output, '$', -(symbols.after.length - (1 + i))) break case ' ': output = i === symbols.after.length - 1 ? output + ' ' : insert(output, ' ', -(symbols.after.length - (1 + i))) break } } return output } }
var settings = (function () { var exports = {}; var header_map = { "your-account": i18n.t("Your account"), "display-settings": i18n.t("Display settings"), notifications: i18n.t("Notifications"), "your-bots": i18n.t("Your bots"), "alert-words": i18n.t("Alert words"), "uploaded-files": i18n.t("Uploaded files"), "muted-topics": i18n.t("Muted topics"), "organization-profile": i18n.t("Organization profile"), "organization-settings": i18n.t("Organization settings"), "organization-permissions": i18n.t("Organization permissions"), "emoji-settings": i18n.t("Emoji settings"), "auth-methods": i18n.t("Authorization methods"), "user-list-admin": i18n.t("Active users"), "deactivated-users-admin": i18n.t("Deactivated users"), "bot-list-admin": i18n.t("Bot list"), "default-streams-list": i18n.t("Default streams"), "filter-settings": i18n.t("Linkifiers"), "invites-list-admin": i18n.t("Invitations"), "user-groups-admin": i18n.t("User groups"), "profile-field-settings": i18n.t("Profile field settings"), }; $("body").ready(function () { var $sidebar = $(".form-sidebar"); var $targets = $sidebar.find("[data-target]"); var $title = $sidebar.find(".title h1"); var is_open = false; var close_sidebar = function () { $sidebar.removeClass("show"); $sidebar.find("#edit_bot").empty(); is_open = false; }; exports.trigger_sidebar = function (target) { $targets.hide(); var $target = $(".form-sidebar").find("[data-target='" + target + "']"); $title.text($target.attr("data-title")); $target.show(); $sidebar.addClass("show"); is_open = true; }; $(".form-sidebar .exit").click(function (e) { close_sidebar(); e.stopPropagation(); }); $("body").click(function (e) { if (is_open && !$(e.target).within(".form-sidebar")) { close_sidebar(); } }); $("body").on("click", "[data-sidebar-form]", function (e) { exports.trigger_sidebar($(this).attr("data-sidebar-form")); e.stopPropagation(); }); $("body").on("click", "[data-sidebar-form-close]", close_sidebar); $("#settings_overlay_container").click(function (e) { if (!overlays.is_modal_open()) { return; } if ($(e.target).closest(".modal").length > 0) { return; } e.preventDefault(); e.stopPropagation(); // Whenever opening a modal(over settings overlay) in an event handler // attached to a click event, make sure to stop the propagation of the // event to the parent container otherwise the modal will not open. This // is so because this event handler will get fired on any click in settings // overlay and subsequently close any open modal. overlays.close_active_modal(); }); }); function setup_settings_label() { exports.settings_label = { // settings_notification // stream_notification_settings enable_stream_desktop_notifications: i18n.t("Visual desktop notifications"), enable_stream_sounds: i18n.t("Audible desktop notifications"), enable_stream_push_notifications: i18n.t("Mobile notifications"), enable_stream_email_notifications: i18n.t("Email notifications"), // pm_mention_notification_settings enable_desktop_notifications: i18n.t("Visual desktop notifications"), enable_offline_email_notifications: i18n.t("Email notifications"), enable_offline_push_notifications: i18n.t("Mobile notifications"), enable_online_push_notifications: i18n.t("Send mobile notifications even if I'm online (useful for testing)"), enable_sounds: i18n.t("Audible desktop notifications"), pm_content_in_desktop_notifications: i18n.t("Include content of private messages in desktop notifications"), // other_notification_settings enable_digest_emails: i18n.t("Send digest emails when I'm away"), enable_login_emails: i18n.t("Send email notifications for new logins to my account"), message_content_in_email_notifications: i18n.t("Include message content in missed message emails"), realm_name_in_notifications: i18n.t("Include organization name in subject of missed message emails"), // display settings dense_mode: i18n.t("Dense mode"), high_contrast_mode: i18n.t("High contrast mode"), left_side_userlist: i18n.t("User list on left sidebar in narrow windows"), night_mode: i18n.t("Night mode"), starred_message_counts: i18n.t("Show counts for starred messages"), fluid_layout_width: i18n.t("Use full width on wide screens"), twenty_four_hour_time: i18n.t("24-hour time (17:00 instead of 5:00 PM)"), translate_emoticons: i18n.t("Convert emoticons before sending (<code>:)</code> becomes 😃)"), }; } exports.build_page = function () { setup_settings_label(); var rendered_settings_tab = templates.render('settings_tab', { full_name: people.my_full_name(), page_params: page_params, enable_sound_select: page_params.enable_sounds || page_params.enable_stream_sounds, zuliprc: 'zuliprc', botserverrc: 'botserverrc', timezones: moment.tz.names(), can_create_new_bots: settings_bots.can_create_new_bots(), settings_label: settings.settings_label, demote_inactive_streams_values: settings_display.demote_inactive_streams_values, }); $(".settings-box").html(rendered_settings_tab); }; exports.launch = function (section) { exports.build_page(); admin.build_page(); settings_sections.reset_sections(); overlays.open_settings(); settings_panel_menu.normal_settings.activate_section(section); settings_toggle.highlight_toggle('settings'); }; exports.set_settings_header = function (key) { if (header_map[key]) { $(".settings-header h1 .section").text(" / " + header_map[key]); } else { blueslip.warn("Error: the key '" + key + "' does not exist in the settings" + " header mapping file. Please add it."); } }; return exports; }()); if (typeof module !== 'undefined') { module.exports = settings; } window.settings = settings;
const uuid = require('uuid/v4') const kid = uuid() const jwtHeader = { alg: 'ES384', typ: 'JWT', kid } const jwtPayload = { iss: 'https://sandbox.cds-hooks.org', aud: 'https://trhc-test.apigee.net/medwise/cds-services', exp: Math.round(Date.now() / 1000 + 300), iat: Math.round(Date.now() / 1000), jti: uuid(), tenant: 'jwktest' } module.exports = { jwtHeader, jwtPayload }
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["page-testing-wemos-infra_red"],{"4c26":function(n,t,a){"use strict";a.r(t);var o=function(){var n=this,t=n.$createElement,a=n._self._c||t;return a("div",[n._v("\n infra : "+n._s(n.infra)+"\n "),a("br"),a("br"),a("button",{staticClass:"btn btn-sm btn-primary",attrs:{type:"button"},on:{click:n.coba}},[n._v("coba")])])},e=[],i=a("80f4"),r=a("bc3a"),c=a.n(r),s={data:function(){return{infra:"no"}},beforeMount:function(){var n=this;i["a"].on("new-infra",(function(t){n.infra=t}))},mounted:function(){var n=this;i["a"].emit("last-infra",(function(t){n.infra=t}))},methods:{coba:function(){var n=0,t=setInterval((function(){n++,console.log(n),n>10&&clearInterval(t);var a="motion"+n;c.a.get("/api/wemos/infra/".concat(a)).then((function(n){console.log(n)}))}),1e3)}}},f=s,u=a("2877"),l=Object(u["a"])(f,o,e,!1,null,null,null);t["default"]=l.exports},"80f4":function(n,t,a){"use strict";var o=a("8055"),e=a.n(o),i=(a("7e59"),e()("https://infolayanans.now.sh"));t["a"]=i}}]); //# sourceMappingURL=page-testing-wemos-infra_red.1a2e54e4.js.map
import React from 'react' import PropTypes from 'prop-types' import {getType} from '../lib/types' const Tag = ({type, style}) => { const tag = getType(type) return ( <div className={`tag ${type}`} style={style}> {type} <style jsx>{` .tag { display: flex; margin: 2px; color: ${tag.color}; background-color: ${tag.background}; padding: 2px 4px; border-radius: 2px; justify-content: center; align-items: center; } @media (min-width: 460px) { font-size: 12px; } @media (max-width: 460px) { font-size: x-small; } `}</style> </div> ) } Tag.propTypes = { type: PropTypes.string.isRequired, style: PropTypes.object } Tag.defaultProps = { style: null } export default Tag
const AWS = require("aws-sdk"); const stepFunctions = new AWS.StepFunctions(); exports.handler = async (event, context) => { let jobId; try { jobId = JSON.parse(event.body).jobId } catch(error) { console.log(error) return getResponse(400, 'Invalid Job-Id provided') } const params = { stateMachineArn: process.env.STEP_FUNCTION_ARN, name: jobId, input: JSON.stringify({"jobId": jobId}) }; try { await stepFunctions.startExecution(params).promise() return getResponse(200, 'Successfully started Job-Execution'); } catch (error){ console.log(error) if (error.code == 'ExecutionAlreadyExists') { return getResponse(400, 'Execution already exists'); } else { return getResponse(500, 'Problem while starting Job-Execution'); } } } function getResponse(statusCode, message) { return { statusCode: statusCode, body: JSON.stringify({message: message}) }; }
const winston = require('winston'); const Q = require('q'); const request = require('request'); const keys = require('../config/keys'); module.exports = { addSubscriber(listId, email) { const deferred = Q.defer(); try { const postData = {}; postData.email_address = email; postData.status = 'subscribed'; const url = `https://us10.api.mailchimp.com/3.0/lists/${listId}/members`; request({ url, method: 'POST', headers: { 'Content-Type': 'application/json', }, json: postData, auth: { username: 'cloudboost', password: keys.mailchimpApiKey, }, }, (error, response, body) => { if (error || response.statusCode === 400 || response.statusCode === 500) { deferred.reject(error); } else { deferred.resolve(body); } }); } catch (err) { winston.log('error', { error: String(err), stack: new Error().stack, }); deferred.reject(err); } return deferred.promise; }, };
import React from "react" import Link from "./Link" const LinkToQuestion = props => ( <Link to={`/question/${props.question.id}`}>{props.question.title}</Link> ) export default LinkToQuestion
// knockout-jqAutocomplete 0.4.3 | (c) 2015 Ryan Niemeyer | http://www.opensource.org/licenses/mit-license !function(a){"function"==typeof define&&define.amd?define(["knockout","jquery","jquery-ui/autocomplete"],a):a(window.ko,jQuery)}(function(a,b){var c=function(){var c=this,d=a.utils.unwrapObservable;this.init=function(e,f,g,h,i){var j,k,l=d(f()),m={},n="function"==typeof l.filter?l.filter:c.defaultFilter;a.utils.extend(m,c.options),a.utils.extend(m,l.options),m.source="function"!=typeof l.source||a.isObservable(l.source)?c.processOptions.bind(c,f,n,l.source):function(a,b){var d=function(d){c.processOptions(f,null,d,a,b)};l.source.call(i.$data,a.term,d)},j="function"==typeof m.select&&m.select,k="function"==typeof m.change&&m.change,m.select=function(b,c){c.item&&c.item.actual&&(l.value(c.item.actual),a.isWriteableObservable(l.dataValue)&&l.dataValue(c.item.data)),j&&j.apply(this,arguments)},m.change=function(b,c){c.item&&c.item.actual||(l.value(b.target&&b.target.value),a.isWriteableObservable(l.dataValue)&&l.dataValue(null)),k&&k.apply(this,arguments)};var o=b(e).autocomplete(m).data("ui-autocomplete");l.template&&(o._renderItem=c.renderItem.bind(c,l.template,i)),a.utils.domNodeDisposal.addDisposeCallback(e,function(){o&&"function"==typeof o.destroy&&(o.destroy(),o=null)})},this.update=function(e,f){var g,h,i=d(f()),j=d(i&&i.value);j||0===j||(j=""),h=d(i.source),g=c.getPropertyNames(f),b.isArray(h)&&g.value&&(j=a.utils.arrayFirst(h,function(a){return a[g.value]==j})||j),e.value=g.input&&j&&"object"==typeof j?j[g.input]:j},this.defaultFilter=function(b,c){return c=c&&c.toLowerCase(),(b||0===b)&&a.toJSON(b).toLowerCase().indexOf(c)>-1},this.processOptions=function(a,b,c,e,f){var g,h,i,j=d(c)||[],k=[],l=this.getPropertyNames(a);for(h=0,i=j.length;i>h;h++)g=j[h],(!b||b(g,e.term))&&k.push({label:l.label?g[l.label]:g.toString(),value:l.input?g[l.input]:g.toString(),actual:l.value?g[l.value]:g,data:g});f(k)},this.renderItem=function(c,d,e,f){var g=b("<li></li>").appendTo(e),h=d.createChildContext(f.data);return a.applyBindingsToNode(g[0],{template:c},h),g.one("remove",a.cleanNode.bind(a,g[0])),g},this.getPropertyNames=function(b){var c=a.toJS(b());return{label:c.labelProp||c.valueProp,input:c.inputProp||c.labelProp||c.valueProp,value:c.valueProp}},this.options={autoFocus:!0,delay:50}};a.bindingHandlers.jqAuto=new c});
import React from "react"; import "./style.css" import {Row, Col} from "../Grid" const SavedResult = props => { return (props.savedBooks.length === 0) ? ( <div className="card"> <div className="card-body player"> <div className="article"> <h3>Books that You Saved</h3> </div> </div> </div> ):( <div className="card"> <div className="card-body player"> <div className="article"> <h3>Books that You Saved</h3> {props.savedBooks.map(savedbook => { return ( <li className="saved-list list-group-item"> <Row className="SearchResult" id={savedbook.title + "Card"} key={savedbook._id}> {/* col-3 show image of the book */} <Col size="2" className="bookImage"> <img src={savedbook.image} alt={savedbook.title} /> </Col> <Col size="1" className="emptyCol"/> {/* col-9 show information of the book */} <Col size="9" className="bookInfo"> <Row> <h2 className="bookTitle">{savedbook.title}</h2> </Row> <Row> <h3 className="bookAuthor">{savedbook.authors}</h3> </Row> <Row> <p className="bookDescription">{savedbook.description}</p> </Row> </Col> </Row> <br></br> <Row className="buttonDiv "> <button className="deleteBook btn btn-danger" id={savedbook._id} onClick={() => props.handleDeleteButton(savedbook._id)}> Delete Book </button> <a href={savedbook.link} target="_blank"> <button className="viewBook btn btn-success"> View Book </button> </a> </Row> </li> ); })} </div> </div> </div> ) } export default SavedResult
/* Contracts in this test */ const MyCollectible = artifacts.require("../contracts/MyCollectible.sol"); contract("MyCollectible", (accounts) => { const URI_BASE = 'https://creatures-api.opensea.io'; const CONTRACT_URI = `${URI_BASE}/contract/opensea-erc1155`; let myCollectible; before(async () => { myCollectible = await MyCollectible.deployed(); }); // This is all we test for now // This also tests contractURI() describe('#constructor()', () => { it('should set the contractURI to the supplied value', async () => { assert.equal(await myCollectible.contractURI(), CONTRACT_URI); }); }); });
import { fetchWebhooks, fetchKappWebhookEvents, fetchSpaceWebhookEvents, } from '../../../apis'; import { generateTable } from '../../table/Table'; import { defineFilter } from '../../../helpers'; import { List, Map } from 'immutable'; const clientSide = defineFilter(true) .startsWith('name', 'name') .equals('type', 'type') .equals('event', 'event') .end(); const dataSource = ({ scope, kappSlug }) => ({ fn: fetchWebhooks, clientSide, params: () => [ { include: 'details', scope, kappSlug, }, ], transform: result => ({ data: result.webhooks, }), }); const filterDataSources = ({ kappSlug }) => ({ events: { fn: kappSlug ? fetchKappWebhookEvents : fetchSpaceWebhookEvents, params: [], transform: result => result, }, }); const filters = () => ({ events, values }) => events && [ { name: 'name', label: 'Name', type: 'text' }, { name: 'type', label: 'Type', type: 'select', options: ({ events }) => events ? events .keySeq() .sort() .map(type => Map({ label: type, value: type })) : List(), onChange: ({ values }, { setValue }) => { if (values.get('event')) { setValue('event', ''); } }, }, { name: 'event', label: 'Event', type: 'select', options: ({ values, events }) => values && events ? events .get(values.get('type'), List()) .map(event => Map({ label: event, value: event })) : List(), }, ]; const columns = [ { value: 'createdAt', title: 'Created' }, { value: 'createdBy', title: 'Created By' }, { value: 'event', title: 'Event' }, { value: 'filter', title: 'Filter' }, { value: 'name', title: 'Name' }, { value: 'type', title: 'Type' }, { value: 'updatedAt', title: 'Updated' }, { value: 'updatedBy', title: 'Updated By' }, { value: 'url', title: 'URL' }, ]; export const WebhookTable = generateTable({ tableOptions: ['scope', 'kappSlug'], columns, filters, filterDataSources, dataSource, }); WebhookTable.displayName = 'WebhookTable';
$('document').ready(alert('Now we are anonymous!')); //by the way, you've seen $('document').ready(...) //before. It is very common in jQuery - the function //that is passed to `ready` is run when the HTML document //is ready for javascript to start happening
import {describe, beforeEach, it, expect, iit, ddescribe} from 'test_lib/test_lib'; import {ListWrapper, List} from 'facade/collection'; import {DOM} from 'facade/dom'; import {isPresent, NumberWrapper, StringWrapper} from 'facade/lang'; import {CompilePipeline} from 'core/compiler/pipeline/compile_pipeline'; import {CompileElement} from 'core/compiler/pipeline/compile_element'; import {CompileStep} from 'core/compiler/pipeline/compile_step' import {CompileControl} from 'core/compiler/pipeline/compile_control'; export function main() { describe('compile_pipeline', () => { it('should walk the tree in depth first order including template contents', () => { var element = createElement('<div id="1"><template id="2"><span id="3"></span></template></div>'); var step0Log = []; var results = new CompilePipeline([createLoggerStep(step0Log)]).process(element); expect(step0Log).toEqual(['1', '1<2', '2<3']); expect(resultIdLog(results)).toEqual(['1', '2', '3']); }); describe('control.addParent', () => { it('should report the new parent to the following processor and the result', () => { var element = createElement('<div id="1"><span wrap0="1" id="2"><b id="3"></b></span></div>'); var step0Log = []; var step1Log = []; var pipeline = new CompilePipeline([ createWrapperStep('wrap0', step0Log), createLoggerStep(step1Log) ]); var result = pipeline.process(element); expect(step0Log).toEqual(['1', '1<2', '2<3']); expect(step1Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<2', '2<3']); expect(resultIdLog(result)).toEqual(['1', 'wrap0#0', '2', '3']); }); it('should allow to add a parent by multiple processors to the same element', () => { var element = createElement('<div id="1"><span wrap0="1" wrap1="1" id="2"><b id="3"></b></span></div>'); var step0Log = []; var step1Log = []; var step2Log = []; var pipeline = new CompilePipeline([ createWrapperStep('wrap0', step0Log), createWrapperStep('wrap1', step1Log), createLoggerStep(step2Log) ]); var result = pipeline.process(element); expect(step0Log).toEqual(['1', '1<2', '2<3']); expect(step1Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<2', '2<3']); expect(step2Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<wrap1#0', 'wrap1#0<2', '2<3']); expect(resultIdLog(result)).toEqual(['1', 'wrap0#0', 'wrap1#0', '2', '3']); }); it('should allow to add a parent by multiple processors to different elements', () => { var element = createElement('<div id="1"><span wrap0="1" id="2"><b id="3" wrap1="1"></b></span></div>'); var step0Log = []; var step1Log = []; var step2Log = []; var pipeline = new CompilePipeline([ createWrapperStep('wrap0', step0Log), createWrapperStep('wrap1', step1Log), createLoggerStep(step2Log) ]); var result = pipeline.process(element); expect(step0Log).toEqual(['1', '1<2', '2<3']); expect(step1Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<2', '2<3']); expect(step2Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<2', '2<wrap1#0', 'wrap1#0<3']); expect(resultIdLog(result)).toEqual(['1', 'wrap0#0', '2', 'wrap1#0', '3']); }); it('should allow to add multiple parents by the same processor', () => { var element = createElement('<div id="1"><span wrap0="2" id="2"><b id="3"></b></span></div>'); var step0Log = []; var step1Log = []; var pipeline = new CompilePipeline([ createWrapperStep('wrap0', step0Log), createLoggerStep(step1Log) ]); var result = pipeline.process(element); expect(step0Log).toEqual(['1', '1<2', '2<3']); expect(step1Log).toEqual(['1', '1<wrap0#0', 'wrap0#0<wrap0#1', 'wrap0#1<2', '2<3']); expect(resultIdLog(result)).toEqual(['1', 'wrap0#0', 'wrap0#1', '2', '3']); }); }); describe('control.addChild', () => { it('should report the new child to all processors and the result', () => { var element = createElement('<div id="1"><div id="2"></div></div>'); var resultLog = []; var newChild = new CompileElement(createElement('<div id="3"></div>')); var pipeline = new CompilePipeline([ new MockStep((parent, current, control) => { if (StringWrapper.equals(current.element.id, '1')) { control.addChild(newChild); } }), createLoggerStep(resultLog) ]); var result = pipeline.process(element); expect(result[2]).toBe(newChild); expect(resultLog).toEqual(['1', '1<2', '1<3']); expect(resultIdLog(result)).toEqual(['1', '2', '3']); }); }); }); } class MockStep extends CompileStep { processClosure:Function; constructor(process) { this.processClosure = process; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { this.processClosure(parent, current, control); } } class LoggingStep extends CompileStep { logs:List; constructor(logs) { this.logs = logs; } process(parent:CompileElement, current:CompileElement, control:CompileControl) { ListWrapper.push(this.logs, {'parent':parent, 'current':current}); } } function logEntry(log, parent, current) { var parentId = ''; if (isPresent(parent)) { parentId = parent.element.getAttribute('id')+'<'; } ListWrapper.push(log, parentId+current.element.getAttribute('id')); } function createLoggerStep(log) { return new MockStep((parent, current, control) => { logEntry(log, parent, current); }); } function createWrapperStep(wrapperId, log) { var nextElementId = 0; return new MockStep((parent, current, control) => { var parentCountStr = current.element.getAttribute(wrapperId); if (isPresent(parentCountStr)) { var parentCount = NumberWrapper.parseInt(parentCountStr, 10); while (parentCount > 0) { control.addParent(new CompileElement(createElement(`<a id="${wrapperId}#${nextElementId++}"></a>`))); parentCount--; } } logEntry(log, parent, current); }); } function resultIdLog(result) { var idLog = []; ListWrapper.forEach(result, (current) => { logEntry(idLog, null, current); }); return idLog; } function createElement(html) { return DOM.createTemplate(html).content.firstChild; }
export default "M12,1A9,9 0 0,1 21,10V17A3,3 0 0,1 18,20H15V12H19V10A7,7 0 0,0 12,3A7,7 0 0,0 5,10V12H9V20H6A3,3 0 0,1 3,17V10A9,9 0 0,1 12,1M15,24V22H17V24H15M11,24V22H13V24H11M7,24V22H9V24H7Z"
/* eslint-disable no-unused-vars */ // required express const express = require('express'); // init express const app = express(); // set port const port = 3001; // node redis import const redis = require('redis'); // client creation from redis const client = redis.createClient(); // Utility for Promises working with redis const { promisify } = require('util'); const getAsync = promisify(client.get).bind(client); app.get('/jobs', async (req, res) => { const jobs = await getAsync('github'); }); app.listen(port, () => console.log(`Example app listening on port ${port}!`));
function printDeckOfCards(arr) { function makeCard(face, suit) { const validCardFaces = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']; const validCardSuits = ['S', 'H', 'D', 'C']; function checkFace(currentFace) { if (!validCardFaces.some(c => c === currentFace)) { throw new Error(`Invalid card: ${face}${suit}`); } } function checkSuit(currentSuit) { if (!validCardSuits.some(c => c === currentSuit)) { throw new Error(`Invalid card: ${face}${suit}`); } } checkFace(face); checkSuit(suit); let cardFace = face; let cardSuit = suit; return { getFace: () => cardFace, getSuit: () => cardSuit, toString: function () { const result = `${this.getFace()}`; switch (cardSuit) { case 'C': return `${result}\u2663`; case 'D': return `${result}\u2666`; case 'H': return `${result}\u2665`; case 'S': return `${result}\u2660`; } }, }; } const deck = []; for (const cardString of arr) { const currentCardFace = cardString.slice(0, cardString.length - 1); const currentCardSuit = cardString.slice(cardString.length - 1); try { const currentCard = makeCard(currentCardFace, currentCardSuit) deck.push(currentCard); } catch (ex) { console.log(ex.message); return } } console.log(deck.join(' ')); } printDeckOfCards(['5S', '3D', 'QD', '1C']);
import {StyleSheet} from 'react-native' import * as colors from '@/assets/colors' export default StyleSheet.create({ container: { borderBottomWidth: 1, borderColor: colors.gray.lighter }, header: { display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center', padding: 15 }, title: { fontSize: 12, fontWeight: '600', color: colors.gray.mediumDark }, button: { fontSize: 12, color: colors.blue.medium } })
import i18n from "i18next"; import Backend from "i18next-http-backend"; import LanguageDetector from "i18next-browser-languagedetector"; import { initReactI18next } from "react-i18next"; const defaultLanguage = ["en"]; const availableLanguages = ["en", "ru"]; const options = { // order and from where user language should be detected order: ["navigator", "localStorage", "cookie"], // keys or params to lookup language from lookupCookie: "_app-language", lookupLocalStorage: "_app-language", // cache user language on caches: ["localStorage", "cookie"], excludeCacheFor: ["cimode"], // languages to not persist (cookie, localStorage) // optional expire and domain for set cookie cookieMinutes: 10, cookieDomain: "myDomain", // optional set cookie options, reference:[MDN Set-Cookie docs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie) cookieOptions: { path: "/", sameSite: "strict" }, }; i18n // Подключение бэкенда i18next .use(Backend) // Автоматическое определение языка .use(LanguageDetector) // модуль инициализации .use(initReactI18next) .init({ // Стандартный язык fallbackLng: defaultLanguage, debug: false, whitelist: availableLanguages, // Распознавание и кэширование языковых кук detection: options, interpolation: { escapeValue: false, }, }); export default i18n;
const path = require('path'); const fsPromises = require('fs/promises'); //пути для копирования const sourceFolderPath = path.join(__dirname, 'files'); const destinationFolderPath = path.join(__dirname, 'files-copy'); //промисы нужны для того, чтобы не было "конкуренции" //(когда файл копируется и асинхронно его пытаются удалить) async function copyAll() { try { //создаём папку await fsPromises.mkdir(destinationFolderPath, {recursive: true}); const destinationFiles = await fsPromises.readdir(destinationFolderPath); //удаляем файлы из папки, если они есть for (const destinationFile of destinationFiles) { let curPath = path.join(destinationFolderPath, destinationFile); await fsPromises.unlink(curPath); } //читаем папку сырцов const sourceFiles = await fsPromises.readdir(sourceFolderPath, {withFileTypes: true}); //копируем файлы for (const sourceFile of sourceFiles) { let sourceFilePath = path.join(sourceFolderPath, sourceFile.name); let destinationFilePath = path.join(destinationFolderPath, sourceFile.name); await fsPromises.copyFile(sourceFilePath, destinationFilePath); } } catch (err) { console.error(err); } } copyAll().then(() => console.log('Files copy successfully'));
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[10],{ /***/ "./node_modules/monaco-editor/esm/vs/basic-languages/coffee/coffee.js": /*!****************************************************************************!*\ !*** ./node_modules/monaco-editor/esm/vs/basic-languages/coffee/coffee.js ***! \****************************************************************************/ /*! exports provided: conf, language */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; __webpack_require__.r(__webpack_exports__); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "conf", function() { return conf; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "language", function() { return language; }); /*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var conf = { wordPattern: /(-?\d*\.\d\w*)|([^\`\~\!\@\#%\^\&\*\(\)\=\$\-\+\[\{\]\}\\\|\;\:\'\"\,\.\<\>\/\?\s]+)/g, comments: { blockComment: ['###', '###'], lineComment: '#' }, brackets: [ ['{', '}'], ['[', ']'], ['(', ')'] ], autoClosingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: '\'', close: '\'' }, ], surroundingPairs: [ { open: '{', close: '}' }, { open: '[', close: ']' }, { open: '(', close: ')' }, { open: '"', close: '"' }, { open: '\'', close: '\'' }, ], folding: { markers: { start: new RegExp("^\\s*#region\\b"), end: new RegExp("^\\s*#endregion\\b") } } }; var language = { defaultToken: '', ignoreCase: true, tokenPostfix: '.coffee', brackets: [ { open: '{', close: '}', token: 'delimiter.curly' }, { open: '[', close: ']', token: 'delimiter.square' }, { open: '(', close: ')', token: 'delimiter.parenthesis' } ], regEx: /\/(?!\/\/)(?:[^\/\\]|\\.)*\/[igm]*/, keywords: [ 'and', 'or', 'is', 'isnt', 'not', 'on', 'yes', '@', 'no', 'off', 'true', 'false', 'null', 'this', 'new', 'delete', 'typeof', 'in', 'instanceof', 'return', 'throw', 'break', 'continue', 'debugger', 'if', 'else', 'switch', 'for', 'while', 'do', 'try', 'catch', 'finally', 'class', 'extends', 'super', 'undefined', 'then', 'unless', 'until', 'loop', 'of', 'by', 'when' ], // we include these common regular expressions symbols: /[=><!~?&%|+\-*\/\^\.,\:]+/, escapes: /\\(?:[abfnrtv\\"'$]|x[0-9A-Fa-f]{1,4}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})/, // The main tokenizer for our languages tokenizer: { root: [ // identifiers and keywords [/\@[a-zA-Z_]\w*/, 'variable.predefined'], [/[a-zA-Z_]\w*/, { cases: { 'this': 'variable.predefined', '@keywords': { token: 'keyword.$0' }, '@default': '' } }], // whitespace [/[ \t\r\n]+/, ''], // Comments [/###/, 'comment', '@comment'], [/#.*$/, 'comment'], // regular expressions ['///', { token: 'regexp', next: '@hereregexp' }], [/^(\s*)(@regEx)/, ['', 'regexp']], [/(\()(\s*)(@regEx)/, ['@brackets', '', 'regexp']], [/(\,)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\=)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\:)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\[)(\s*)(@regEx)/, ['@brackets', '', 'regexp']], [/(\!)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\&)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\|)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\?)(\s*)(@regEx)/, ['delimiter', '', 'regexp']], [/(\{)(\s*)(@regEx)/, ['@brackets', '', 'regexp']], [/(\;)(\s*)(@regEx)/, ['', '', 'regexp']], // delimiters [/}/, { cases: { '$S2==interpolatedstring': { token: 'string', next: '@pop' }, '@default': '@brackets' } }], [/[{}()\[\]]/, '@brackets'], [/@symbols/, 'delimiter'], // numbers [/\d+[eE]([\-+]?\d+)?/, 'number.float'], [/\d+\.\d+([eE][\-+]?\d+)?/, 'number.float'], [/0[xX][0-9a-fA-F]+/, 'number.hex'], [/0[0-7]+(?!\d)/, 'number.octal'], [/\d+/, 'number'], // delimiter: after number because of .\d floats [/[,.]/, 'delimiter'], // strings: [/"""/, 'string', '@herestring."""'], [/'''/, 'string', '@herestring.\'\'\''], [/"/, { cases: { '@eos': 'string', '@default': { token: 'string', next: '@string."' } } }], [/'/, { cases: { '@eos': 'string', '@default': { token: 'string', next: '@string.\'' } } }], ], string: [ [/[^"'\#\\]+/, 'string'], [/@escapes/, 'string.escape'], [/\./, 'string.escape.invalid'], [/\./, 'string.escape.invalid'], [/#{/, { cases: { '$S2=="': { token: 'string', next: 'root.interpolatedstring' }, '@default': 'string' } }], [/["']/, { cases: { '$#==$S2': { token: 'string', next: '@pop' }, '@default': 'string' } }], [/#/, 'string'] ], herestring: [ [/("""|''')/, { cases: { '$1==$S2': { token: 'string', next: '@pop' }, '@default': 'string' } }], [/[^#\\'"]+/, 'string'], [/['"]+/, 'string'], [/@escapes/, 'string.escape'], [/\./, 'string.escape.invalid'], [/#{/, { token: 'string.quote', next: 'root.interpolatedstring' }], [/#/, 'string'] ], comment: [ [/[^#]+/, 'comment',], [/###/, 'comment', '@pop'], [/#/, 'comment'], ], hereregexp: [ [/[^\\\/#]+/, 'regexp'], [/\\./, 'regexp'], [/#.*$/, 'comment'], ['///[igm]*', { token: 'regexp', next: '@pop' }], [/\//, 'regexp'], ], }, }; /***/ }) }]); //# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly8vLi9ub2RlX21vZHVsZXMvbW9uYWNvLWVkaXRvci9lc20vdnMvYmFzaWMtbGFuZ3VhZ2VzL2NvZmZlZS9jb2ZmZWUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7OztBQUFBO0FBQUE7QUFBQTtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ2E7QUFDTjtBQUNQLHFFQUFxRSxJQUFJLE1BQU07QUFDL0U7QUFDQTtBQUNBO0FBQ0EsS0FBSztBQUNMO0FBQ0EsV0FBVyxLQUFLO0FBQ2hCO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsU0FBUyxTQUFTLFlBQVksR0FBRztBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLDBCQUEwQjtBQUNuQztBQUNBO0FBQ0EsU0FBUyxTQUFTLFlBQVksR0FBRztBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLHdCQUF3QjtBQUNqQyxTQUFTLDBCQUEwQjtBQUNuQztBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ087QUFDUDtBQUNBO0FBQ0E7QUFDQTtBQUNBLFNBQVMsU0FBUyxZQUFZLDZCQUE2QjtBQUMzRCxTQUFTLG1EQUFtRDtBQUM1RCxTQUFTO0FBQ1Q7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSwrQ0FBK0MsSUFBSSxjQUFjLEVBQUUsY0FBYyxFQUFFO0FBQ25GO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSxzQ0FBc0Msc0JBQXNCO0FBQzVEO0FBQ0E7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EscUJBQXFCLHVDQUF1QztBQUM1RDtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQixpQkFBaUI7QUFDakI7QUFDQSxlQUFlO0FBQ2Y7QUFDQSxvREFBb0QsZ0NBQWdDO0FBQ3BGO0FBQ0E7QUFDQSxpQkFBaUI7QUFDakIsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLHFDQUFxQztBQUNyQztBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0E7QUFDQSxxQ0FBcUM7QUFDckM7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsZ0JBQWdCO0FBQ2hCO0FBQ0EsbUNBQW1DLG1EQUFtRDtBQUN0RjtBQUNBO0FBQ0EsaUJBQWlCO0FBQ2pCO0FBQ0E7QUFDQSxvQ0FBb0MsZ0NBQWdDO0FBQ3BFO0FBQ0E7QUFDQSxpQkFBaUI7QUFDakI7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBLG9DQUFvQyxnQ0FBZ0M7QUFDcEU7QUFDQTtBQUNBLGlCQUFpQjtBQUNqQjtBQUNBO0FBQ0E7QUFDQTtBQUNBLGdCQUFnQixJQUFJLHlEQUF5RDtBQUM3RTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0EsMkJBQTJCLGdDQUFnQztBQUMzRDtBQUNBO0FBQ0EsS0FBSztBQUNMIiwiZmlsZSI6IjEwLmpzIiwic291cmNlc0NvbnRlbnQiOlsiLyotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS1cbiAqICBDb3B5cmlnaHQgKGMpIE1pY3Jvc29mdCBDb3Jwb3JhdGlvbi4gQWxsIHJpZ2h0cyByZXNlcnZlZC5cbiAqICBMaWNlbnNlZCB1bmRlciB0aGUgTUlUIExpY2Vuc2UuIFNlZSBMaWNlbnNlLnR4dCBpbiB0aGUgcHJvamVjdCByb290IGZvciBsaWNlbnNlIGluZm9ybWF0aW9uLlxuICotLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLSovXG4ndXNlIHN0cmljdCc7XG5leHBvcnQgdmFyIGNvbmYgPSB7XG4gICAgd29yZFBhdHRlcm46IC8oLT9cXGQqXFwuXFxkXFx3Kil8KFteXFxgXFx+XFwhXFxAXFwjJVxcXlxcJlxcKlxcKFxcKVxcPVxcJFxcLVxcK1xcW1xce1xcXVxcfVxcXFxcXHxcXDtcXDpcXCdcXFwiXFwsXFwuXFw8XFw+XFwvXFw/XFxzXSspL2csXG4gICAgY29tbWVudHM6IHtcbiAgICAgICAgYmxvY2tDb21tZW50OiBbJyMjIycsICcjIyMnXSxcbiAgICAgICAgbGluZUNvbW1lbnQ6ICcjJ1xuICAgIH0sXG4gICAgYnJhY2tldHM6IFtcbiAgICAgICAgWyd7JywgJ30nXSxcbiAgICAgICAgWydbJywgJ10nXSxcbiAgICAgICAgWycoJywgJyknXVxuICAgIF0sXG4gICAgYXV0b0Nsb3NpbmdQYWlyczogW1xuICAgICAgICB7IG9wZW46ICd7JywgY2xvc2U6ICd9JyB9LFxuICAgICAgICB7IG9wZW46ICdbJywgY2xvc2U6ICddJyB9LFxuICAgICAgICB7IG9wZW46ICcoJywgY2xvc2U6ICcpJyB9LFxuICAgICAgICB7IG9wZW46ICdcIicsIGNsb3NlOiAnXCInIH0sXG4gICAgICAgIHsgb3BlbjogJ1xcJycsIGNsb3NlOiAnXFwnJyB9LFxuICAgIF0sXG4gICAgc3Vycm91bmRpbmdQYWlyczogW1xuICAgICAgICB7IG9wZW46ICd7JywgY2xvc2U6ICd9JyB9LFxuICAgICAgICB7IG9wZW46ICdbJywgY2xvc2U6ICddJyB9LFxuICAgICAgICB7IG9wZW46ICcoJywgY2xvc2U6ICcpJyB9LFxuICAgICAgICB7IG9wZW46ICdcIicsIGNsb3NlOiAnXCInIH0sXG4gICAgICAgIHsgb3BlbjogJ1xcJycsIGNsb3NlOiAnXFwnJyB9LFxuICAgIF0sXG4gICAgZm9sZGluZzoge1xuICAgICAgICBtYXJrZXJzOiB7XG4gICAgICAgICAgICBzdGFydDogbmV3IFJlZ0V4cChcIl5cXFxccyojcmVnaW9uXFxcXGJcIiksXG4gICAgICAgICAgICBlbmQ6IG5ldyBSZWdFeHAoXCJeXFxcXHMqI2VuZHJlZ2lvblxcXFxiXCIpXG4gICAgICAgIH1cbiAgICB9XG59O1xuZXhwb3J0IHZhciBsYW5ndWFnZSA9IHtcbiAgICBkZWZhdWx0VG9rZW46ICcnLFxuICAgIGlnbm9yZUNhc2U6IHRydWUsXG4gICAgdG9rZW5Qb3N0Zml4OiAnLmNvZmZlZScsXG4gICAgYnJhY2tldHM6IFtcbiAgICAgICAgeyBvcGVuOiAneycsIGNsb3NlOiAnfScsIHRva2VuOiAnZGVsaW1pdGVyLmN1cmx5JyB9LFxuICAgICAgICB7IG9wZW46ICdbJywgY2xvc2U6ICddJywgdG9rZW46ICdkZWxpbWl0ZXIuc3F1YXJlJyB9LFxuICAgICAgICB7IG9wZW46ICcoJywgY2xvc2U6ICcpJywgdG9rZW46ICdkZWxpbWl0ZXIucGFyZW50aGVzaXMnIH1cbiAgICBdLFxuICAgIHJlZ0V4OiAvXFwvKD8hXFwvXFwvKSg/OlteXFwvXFxcXF18XFxcXC4pKlxcL1tpZ21dKi8sXG4gICAga2V5d29yZHM6IFtcbiAgICAgICAgJ2FuZCcsICdvcicsICdpcycsICdpc250JywgJ25vdCcsICdvbicsICd5ZXMnLCAnQCcsICdubycsICdvZmYnLFxuICAgICAgICAndHJ1ZScsICdmYWxzZScsICdudWxsJywgJ3RoaXMnLFxuICAgICAgICAnbmV3JywgJ2RlbGV0ZScsICd0eXBlb2YnLCAnaW4nLCAnaW5zdGFuY2VvZicsXG4gICAgICAgICdyZXR1cm4nLCAndGhyb3cnLCAnYnJlYWsnLCAnY29udGludWUnLCAnZGVidWdnZXInLFxuICAgICAgICAnaWYnLCAnZWxzZScsICdzd2l0Y2gnLCAnZm9yJywgJ3doaWxlJywgJ2RvJywgJ3RyeScsICdjYXRjaCcsICdmaW5hbGx5JyxcbiAgICAgICAgJ2NsYXNzJywgJ2V4dGVuZHMnLCAnc3VwZXInLFxuICAgICAgICAndW5kZWZpbmVkJywgJ3RoZW4nLCAndW5sZXNzJywgJ3VudGlsJywgJ2xvb3AnLCAnb2YnLCAnYnknLCAnd2hlbidcbiAgICBdLFxuICAgIC8vIHdlIGluY2x1ZGUgdGhlc2UgY29tbW9uIHJlZ3VsYXIgZXhwcmVzc2lvbnNcbiAgICBzeW1ib2xzOiAvWz0+PCF+PyYlfCtcXC0qXFwvXFxeXFwuLFxcOl0rLyxcbiAgICBlc2NhcGVzOiAvXFxcXCg/OlthYmZucnR2XFxcXFwiJyRdfHhbMC05QS1GYS1mXXsxLDR9fHVbMC05QS1GYS1mXXs0fXxVWzAtOUEtRmEtZl17OH0pLyxcbiAgICAvLyBUaGUgbWFpbiB0b2tlbml6ZXIgZm9yIG91ciBsYW5ndWFnZXNcbiAgICB0b2tlbml6ZXI6IHtcbiAgICAgICAgcm9vdDogW1xuICAgICAgICAgICAgLy8gaWRlbnRpZmllcnMgYW5kIGtleXdvcmRzXG4gICAgICAgICAgICBbL1xcQFthLXpBLVpfXVxcdyovLCAndmFyaWFibGUucHJlZGVmaW5lZCddLFxuICAgICAgICAgICAgWy9bYS16QS1aX11cXHcqLywge1xuICAgICAgICAgICAgICAgICAgICBjYXNlczoge1xuICAgICAgICAgICAgICAgICAgICAgICAgJ3RoaXMnOiAndmFyaWFibGUucHJlZGVmaW5lZCcsXG4gICAgICAgICAgICAgICAgICAgICAgICAnQGtleXdvcmRzJzogeyB0b2tlbjogJ2tleXdvcmQuJDAnIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAnQGRlZmF1bHQnOiAnJ1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgICAgICAvLyB3aGl0ZXNwYWNlXG4gICAgICAgICAgICBbL1sgXFx0XFxyXFxuXSsvLCAnJ10sXG4gICAgICAgICAgICAvLyBDb21tZW50c1xuICAgICAgICAgICAgWy8jIyMvLCAnY29tbWVudCcsICdAY29tbWVudCddLFxuICAgICAgICAgICAgWy8jLiokLywgJ2NvbW1lbnQnXSxcbiAgICAgICAgICAgIC8vIHJlZ3VsYXIgZXhwcmVzc2lvbnNcbiAgICAgICAgICAgIFsnLy8vJywgeyB0b2tlbjogJ3JlZ2V4cCcsIG5leHQ6ICdAaGVyZXJlZ2V4cCcgfV0sXG4gICAgICAgICAgICBbL14oXFxzKikoQHJlZ0V4KS8sIFsnJywgJ3JlZ2V4cCddXSxcbiAgICAgICAgICAgIFsvKFxcKCkoXFxzKikoQHJlZ0V4KS8sIFsnQGJyYWNrZXRzJywgJycsICdyZWdleHAnXV0sXG4gICAgICAgICAgICBbLyhcXCwpKFxccyopKEByZWdFeCkvLCBbJ2RlbGltaXRlcicsICcnLCAncmVnZXhwJ11dLFxuICAgICAgICAgICAgWy8oXFw9KShcXHMqKShAcmVnRXgpLywgWydkZWxpbWl0ZXInLCAnJywgJ3JlZ2V4cCddXSxcbiAgICAgICAgICAgIFsvKFxcOikoXFxzKikoQHJlZ0V4KS8sIFsnZGVsaW1pdGVyJywgJycsICdyZWdleHAnXV0sXG4gICAgICAgICAgICBbLyhcXFspKFxccyopKEByZWdFeCkvLCBbJ0BicmFja2V0cycsICcnLCAncmVnZXhwJ11dLFxuICAgICAgICAgICAgWy8oXFwhKShcXHMqKShAcmVnRXgpLywgWydkZWxpbWl0ZXInLCAnJywgJ3JlZ2V4cCddXSxcbiAgICAgICAgICAgIFsvKFxcJikoXFxzKikoQHJlZ0V4KS8sIFsnZGVsaW1pdGVyJywgJycsICdyZWdleHAnXV0sXG4gICAgICAgICAgICBbLyhcXHwpKFxccyopKEByZWdFeCkvLCBbJ2RlbGltaXRlcicsICcnLCAncmVnZXhwJ11dLFxuICAgICAgICAgICAgWy8oXFw/KShcXHMqKShAcmVnRXgpLywgWydkZWxpbWl0ZXInLCAnJywgJ3JlZ2V4cCddXSxcbiAgICAgICAgICAgIFsvKFxceykoXFxzKikoQHJlZ0V4KS8sIFsnQGJyYWNrZXRzJywgJycsICdyZWdleHAnXV0sXG4gICAgICAgICAgICBbLyhcXDspKFxccyopKEByZWdFeCkvLCBbJycsICcnLCAncmVnZXhwJ11dLFxuICAgICAgICAgICAgLy8gZGVsaW1pdGVyc1xuICAgICAgICAgICAgWy99Lywge1xuICAgICAgICAgICAgICAgICAgICBjYXNlczoge1xuICAgICAgICAgICAgICAgICAgICAgICAgJyRTMj09aW50ZXJwb2xhdGVkc3RyaW5nJzogeyB0b2tlbjogJ3N0cmluZycsIG5leHQ6ICdAcG9wJyB9LFxuICAgICAgICAgICAgICAgICAgICAgICAgJ0BkZWZhdWx0JzogJ0BicmFja2V0cydcbiAgICAgICAgICAgICAgICAgICAgfVxuICAgICAgICAgICAgICAgIH1dLFxuICAgICAgICAgICAgWy9be30oKVxcW1xcXV0vLCAnQGJyYWNrZXRzJ10sXG4gICAgICAgICAgICBbL0BzeW1ib2xzLywgJ2RlbGltaXRlciddLFxuICAgICAgICAgICAgLy8gbnVtYmVyc1xuICAgICAgICAgICAgWy9cXGQrW2VFXShbXFwtK10/XFxkKyk/LywgJ251bWJlci5mbG9hdCddLFxuICAgICAgICAgICAgWy9cXGQrXFwuXFxkKyhbZUVdW1xcLStdP1xcZCspPy8sICdudW1iZXIuZmxvYXQnXSxcbiAgICAgICAgICAgIFsvMFt4WF1bMC05YS1mQS1GXSsvLCAnbnVtYmVyLmhleCddLFxuICAgICAgICAgICAgWy8wWzAtN10rKD8hXFxkKS8sICdudW1iZXIub2N0YWwnXSxcbiAgICAgICAgICAgIFsvXFxkKy8sICdudW1iZXInXSxcbiAgICAgICAgICAgIC8vIGRlbGltaXRlcjogYWZ0ZXIgbnVtYmVyIGJlY2F1c2Ugb2YgLlxcZCBmbG9hdHNcbiAgICAgICAgICAgIFsvWywuXS8sICdkZWxpbWl0ZXInXSxcbiAgICAgICAgICAgIC8vIHN0cmluZ3M6XG4gICAgICAgICAgICBbL1wiXCJcIi8sICdzdHJpbmcnLCAnQGhlcmVzdHJpbmcuXCJcIlwiJ10sXG4gICAgICAgICAgICBbLycnJy8sICdzdHJpbmcnLCAnQGhlcmVzdHJpbmcuXFwnXFwnXFwnJ10sXG4gICAgICAgICAgICBbL1wiLywge1xuICAgICAgICAgICAgICAgICAgICBjYXNlczoge1xuICAgICAgICAgICAgICAgICAgICAgICAgJ0Blb3MnOiAnc3RyaW5nJyxcbiAgICAgICAgICAgICAgICAgICAgICAgICdAZGVmYXVsdCc6IHsgdG9rZW46ICdzdHJpbmcnLCBuZXh0OiAnQHN0cmluZy5cIicgfVxuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgICAgICBbLycvLCB7XG4gICAgICAgICAgICAgICAgICAgIGNhc2VzOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICAnQGVvcyc6ICdzdHJpbmcnLFxuICAgICAgICAgICAgICAgICAgICAgICAgJ0BkZWZhdWx0JzogeyB0b2tlbjogJ3N0cmluZycsIG5leHQ6ICdAc3RyaW5nLlxcJycgfVxuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgIF0sXG4gICAgICAgIHN0cmluZzogW1xuICAgICAgICAgICAgWy9bXlwiJ1xcI1xcXFxdKy8sICdzdHJpbmcnXSxcbiAgICAgICAgICAgIFsvQGVzY2FwZXMvLCAnc3RyaW5nLmVzY2FwZSddLFxuICAgICAgICAgICAgWy9cXC4vLCAnc3RyaW5nLmVzY2FwZS5pbnZhbGlkJ10sXG4gICAgICAgICAgICBbL1xcLi8sICdzdHJpbmcuZXNjYXBlLmludmFsaWQnXSxcbiAgICAgICAgICAgIFsvI3svLCB7XG4gICAgICAgICAgICAgICAgICAgIGNhc2VzOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICAnJFMyPT1cIic6IHsgdG9rZW46ICdzdHJpbmcnLCBuZXh0OiAncm9vdC5pbnRlcnBvbGF0ZWRzdHJpbmcnIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAnQGRlZmF1bHQnOiAnc3RyaW5nJ1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgICAgICBbL1tcIiddLywge1xuICAgICAgICAgICAgICAgICAgICBjYXNlczoge1xuICAgICAgICAgICAgICAgICAgICAgICAgJyQjPT0kUzInOiB7IHRva2VuOiAnc3RyaW5nJywgbmV4dDogJ0Bwb3AnIH0sXG4gICAgICAgICAgICAgICAgICAgICAgICAnQGRlZmF1bHQnOiAnc3RyaW5nJ1xuICAgICAgICAgICAgICAgICAgICB9XG4gICAgICAgICAgICAgICAgfV0sXG4gICAgICAgICAgICBbLyMvLCAnc3RyaW5nJ11cbiAgICAgICAgXSxcbiAgICAgICAgaGVyZXN0cmluZzogW1xuICAgICAgICAgICAgWy8oXCJcIlwifCcnJykvLCB7XG4gICAgICAgICAgICAgICAgICAgIGNhc2VzOiB7XG4gICAgICAgICAgICAgICAgICAgICAgICAnJDE9PSRTMic6IHsgdG9rZW46ICdzdHJpbmcnLCBuZXh0OiAnQHBvcCcgfSxcbiAgICAgICAgICAgICAgICAgICAgICAgICdAZGVmYXVsdCc6ICdzdHJpbmcnXG4gICAgICAgICAgICAgICAgICAgIH1cbiAgICAgICAgICAgICAgICB9XSxcbiAgICAgICAgICAgIFsvW14jXFxcXCdcIl0rLywgJ3N0cmluZyddLFxuICAgICAgICAgICAgWy9bJ1wiXSsvLCAnc3RyaW5nJ10sXG4gICAgICAgICAgICBbL0Blc2NhcGVzLywgJ3N0cmluZy5lc2NhcGUnXSxcbiAgICAgICAgICAgIFsvXFwuLywgJ3N0cmluZy5lc2NhcGUuaW52YWxpZCddLFxuICAgICAgICAgICAgWy8jey8sIHsgdG9rZW46ICdzdHJpbmcucXVvdGUnLCBuZXh0OiAncm9vdC5pbnRlcnBvbGF0ZWRzdHJpbmcnIH1dLFxuICAgICAgICAgICAgWy8jLywgJ3N0cmluZyddXG4gICAgICAgIF0sXG4gICAgICAgIGNvbW1lbnQ6IFtcbiAgICAgICAgICAgIFsvW14jXSsvLCAnY29tbWVudCcsXSxcbiAgICAgICAgICAgIFsvIyMjLywgJ2NvbW1lbnQnLCAnQHBvcCddLFxuICAgICAgICAgICAgWy8jLywgJ2NvbW1lbnQnXSxcbiAgICAgICAgXSxcbiAgICAgICAgaGVyZXJlZ2V4cDogW1xuICAgICAgICAgICAgWy9bXlxcXFxcXC8jXSsvLCAncmVnZXhwJ10sXG4gICAgICAgICAgICBbL1xcXFwuLywgJ3JlZ2V4cCddLFxuICAgICAgICAgICAgWy8jLiokLywgJ2NvbW1lbnQnXSxcbiAgICAgICAgICAgIFsnLy8vW2lnbV0qJywgeyB0b2tlbjogJ3JlZ2V4cCcsIG5leHQ6ICdAcG9wJyB9XSxcbiAgICAgICAgICAgIFsvXFwvLywgJ3JlZ2V4cCddLFxuICAgICAgICBdLFxuICAgIH0sXG59O1xuIl0sInNvdXJjZVJvb3QiOiIifQ==
import React, { Fragment } from 'react' import Helmet from 'react-helmet' import { stringify } from 'qs' import { serialize } from 'dom-form-serializer' // import Recaptcha from 'react-google-invisible-recaptcha' import './Form.css' class Form extends React.Component { static defaultProps = { name: 'Simple Form Ajax', subject: '', // optional subject of the notification email action: '', successMessage: 'Thanks for your enquiry, we will get back to you soon', errorMessage: 'There is a problem, your message has not been sent, please try contacting us via email' } state = { alert: '', disabled: false } handleSubmit = e => { e.preventDefault() if (this.state.disabled) return const form = e.target const data = serialize(form) // eslint-disable-next-line // data["g-recaptcha-response"] = this.recaptcha.getResponse() this.setState({ disabled: true }) fetch(form.action + '?' + stringify(data), { method: 'POST' }) .then(res => { if (res.ok) { return res } else { throw new Error('Network error') } }) .then(() => { form.reset() this.setState({ alert: this.props.successMessage, disabled: false }) }) .catch(err => { console.error(err) this.setState({ disabled: false, alert: this.props.errorMessage }) }) } render() { const { name, subject, action } = this.props return ( <Fragment> <Helmet> {/* <script src="https://www.google.com/recaptcha/api.js" /> */} </Helmet> <form className="Form" name={name} action={action} // onSubmit={(e) => {e.preventDefault(); this.recaptcha.execute()}} onSubmit={this.handleSubmit} data-netlify="true" netlify-honeypot="name" // data-netlify-recaptcha="true" > {this.state.alert && ( <div className="Form--Alert">{this.state.alert}</div> )} <div className="Form--Group"> <label className="Form--Label"> <input className="Form--Input Form--InputText" type="text" placeholder="Firstname" name="firstname" required /> <span>First name</span> </label> <label className="Form--Label"> <input className="Form--Input Form--InputText" type="text" placeholder="Lastname" name="lastname" required /> <span>Last name</span> </label> </div> <label className="Form--Label"> <input className="Form--Input Form--InputText" type="email" placeholder="Email" name="emailAddress" required /> <span>Email address</span> </label> <label className="Form--Label has-arrow"> <select className="Form--Input Form--Select" name="type" defaultValue="Type of Enquiry" required > <option disabled hidden> Type of Enquiry </option> <option>Schedule a private event</option> <option>Found an issue with the website</option> <option>Something else</option> </select> </label> <label className="Form--Label"> <textarea className="Form--Input Form--Textarea Form--InputText" placeholder="Message" name="message" rows="10" required /> <span>Message</span> </label> <label className="Form--Label Form-Checkbox"> <input className="Form--Input Form--Textarea Form--CheckboxInput" name="newsletter" type="checkbox" /> <span>Get news updates</span> </label> <label className="Form--NotHuman"> Don’t fill this out if you’re human: <input name="name" /> </label> {/* <Recaptcha data-netlify-recaptcha="true" ref={ ref => this.recaptcha = ref } sitekey="6LezB6kaAAAAAMp8VpZ4JYyKEpeQJjkwDEu5k0iU" onResolved={ this.handleSubmit } /> */} {!!subject && <input type="hidden" name="subject" value={subject} />} <input type="hidden" name="form-name" value={name} /> <input className="Button Form--SubmitButton" type="submit" value="Enquire" disabled={this.state.disabled} /> </form> </Fragment> ) } } export default Form
/* eslint-disable react/prop-types */ import React from 'react'; import Typography from '@material-ui/core/Typography'; import Job from './Job'; export default function Jobs() { return ( <div className="Jobs"> <Typography variant="h1">Entry Level Software Jobs</Typography> {jobs.map(job => ( <Job key={job.company} job={job} /> ))} </div> ); }
const mysqlDb = require ( 'mysql'); // Define the database pool, this needs to be in the global object let pool = undefined; const mysqlDB = () => { // Setup the database connection details const DB_HOST = process.env.DB_HOST; const DB_USER = process.env.DB_USER; const DB_PASSWORD = process.env.DB_PASSWORD; const DB_DATABASE = process.env.DB_DATABASE; const DB_PORT = process.env.DB_PORT; // // checkConnected // // Check the database is connected too. // // // function checkConnected () { return new Promise (function (resolve, reject) { // Get a connection from the mysql connection pool pool.getConnection(function(err, connection) { if (err) return reject({error: err}); return resolve ( { msg: 'Connected.' }); }); }); } // // Function : connectToDB // // Create a connection to the MySQL database and create a connection pool // // ReturnValues : None // async function connectToDB () { try { if ( pool === undefined ){ pool = await mysqlDb.createPool({ connectionLimit : 10, host : DB_HOST, user : DB_USER, password : DB_PASSWORD, database : DB_DATABASE, port : DB_PORT }); await checkConnected (); } } catch (err) { console.error(err.message); process.exit(1); } } // // Function : disconnectDB // // Disconnect from the database and terminate the connection pool // // ReturnValues : None // async function disconnectDB () { await pool.end(); } // // Function: convertSqlValue // // This function takes a variable and prepares it to be inserted into the database // // ReturnValue : Returns a value that can be inserted into the database. ie a string needs to quoted // function convertSqlValue ( value ) { let val; switch (typeof(value)) { case 'string': val = `'${value}'`; break; case 'number': val = value.toString(); break; case 'boolean': val = value; break; case 'undefined': val = 'null'; break; default: if ( value === null ) val = 'null' break; } return val; } // // Function : createInsertSql // // This function takes a table name and an object to be insert, it turns this into an insert statement // // ReturnValues : Returns the insert sql. function createInsertSql ( tableName, insertObj ) { let cols = ""; let values = ""; for ( let key in insertObj ){ let val = convertSqlValue (insertObj[key]); if (cols.length === 0) { cols = key; values = val; } else { cols = cols + ', ' + key; values = `${values}, ${val}`; } } return `INSERT INTO ${tableName} ( ${cols} ) VALUES ( ${values})`; } // // Function : createUpdateSql // // This function takes a table name and an object, it turns this into an update statement // // ReturnValues : Returns the update sql without the where clause // function createUpdateSql ( tableName, dataObj ) { let setStatement = ""; // Calculate set statement for ( let key in dataObj ){ let val = convertSqlValue (dataObj[key]); if (setStatement.length === 0) { setStatement = `SET ${key} = ${val}`; } else { setStatement = `${setStatement}, ${key} = ${val}`; } } return `UPDATE ${tableName} ${setStatement} `; } // // Function : createWhereClause // // This function takes an object and constructs a where clause // // Returns the where clause // function createWhereClause ( whereObj ) { let whereStatement = ""; // Calculate where statement for ( let key in whereObj ){ let val = convertSqlValue (whereObj[key]); if (whereStatement.length === 0) { whereStatement = `WHERE ${key} = ${val}`; } else { whereStatement = `${whereStatement} AND ${key} = ${val}`; } } return whereStatement; } // // Function : executeData // // Description: This function executes the sql we pass to it. It is returned via a promise to allow syncronous running. // // ReturnValues : // error This lists the errors found // results This returns the data and the status of the execution // fields This returns the type of fields returned // function executeSQL (query) { return new Promise (function (resolve, reject) { // Get a connection from the mysql connection pool pool.getConnection(function(err, connection) { if (err) return reject({error: err}); // Use the connection try { connection.query(query, function (error, results, fields) { // When done with the connection, release it. connection.release(); if (error === null){ return resolve ( { error, results, fields }); } else { return reject(error); } }); } catch (error) { console.error (error); return reject(error); } }); }); } // // Function : selectData // // Description: This function is called with a select statement. It executes the select statement and returns the results. // // ReturnValues : // Success // error True if error occurred // rows This contains the number of records found // data This contains the data found // // Failure // error True if error occurred // errNo The MySQL error numner // errMsg The MySQL error message // sqlState The Mysql sqlState // async function selectData (sql, whereObj) { try { if ( whereObj !== undefined) { sql += db.createWhereClause (whereObj); } const res = await executeSQL(sql); const returnDets = { error : (res.error?true:false), rows : res.results.length, data : [] }; res.results.forEach( ( obj ) => { returnDets.data.push ( obj ); }); return (returnDets); }catch (err) { console.error (err); const userDets = { error : true, errNo : err.errno, errMsg : err.sqlMessage, sqlState : err.sqlState }; return (userDets); } } // // Function : saveData // // Description: This function is called with an insert / update statement. It executes the statement and returns the status. // // ReturnValues : // Success // error True if error occurred // errNo The MySQL error number // insertId The record number if the table is auto incremented // affectedRows The number of rows affected // changedRows The number of rows affected // // Failure // error True if error occurred // errNo The MySQL error numner // errMsg The MySQL error message // sqlState The Mysql sqlState // async function saveData (sql, whereObj) { const returnStatus = { }; try { if ( whereObj !== undefined) { sql += db.createWhereClause (whereObj); } const res = await executeSQL(sql); if ( !res.error ){ returnStatus.error = false; returnStatus.errNo = 0; returnStatus.insertId = res.results.insertId; returnStatus.affectedRows = res.results.affectedRows; returnStatus.changedRows = res.results.changedRows; } }catch (err) { returnStatus.error = true; returnStatus.errNo = err.errno; returnStatus.errMsg = err.sqlMessage; returnStatus.sqlState = err.sqlState; } return (returnStatus); } // // Function : insertProcedure // // Description: This function is called as a wrapper to insert data into a table. The stored procedurfe it calls // will select data to be returned and this wrapper will pass that back. // // ReturnValues : // Success // error False is no error occured // errNo 0 is no error occurred. // insertId The record number if the table is auto incremented // affectedRows The number of rows affected // changedRows The number of rows affected // // Failure // error True if error occurred // errNo The MySQL error numner // errMsg The MySQL error message // sqlState The Mysql sqlState // async function insertProcedure (sql) { const returnStatus = { }; try { const res = await executeSQL(sql); if ( !res.error ){ let insertedId = ( res.results === undefined? undefined: res.results[0][0].inserted_id) let affectedRows = ( res.results === undefined? 0: res.results[0][0].affectedRows) let changedRows = ( res.results === undefined? 0: res.results[0][0].changedRows) returnStatus.error = false; returnStatus.errNo = 0; returnStatus.insertId = insertedId; returnStatus.affectedRows = affectedRows; returnStatus.changedRows = changedRows; } }catch (err) { returnStatus.error = true; returnStatus.errNo = err.errno; returnStatus.errMsg = err.sqlMessage; returnStatus.sqlState = err.sqlState; } return (returnStatus); } // // These are the functions we are exposing from the database closure // return { connectToDB, disconnectDB, createInsertSql, createUpdateSql, createWhereClause, selectData, saveData, insertProcedure }; } module.exports.mysqlDB = mysqlDB;
import {getAssetsByToken} from "../formatter/selectors"; import {toBig} from "LoopringJS/common/formatter"; export default { namespace: 'convert', state: { amount: toBig(0), isMax: false, gasPrice: 10, gasLimit: 200000, outBalance: false, loading:false, }, reducers: { reset(state, {payload}) { return { ...state, amount: toBig(0), isMax: false, outBalance: false, loading:false, } }, setOutBalance(state, {payload}) { const {outBalance} = payload; return { ...state, outBalance } }, setAmount(state, {payload}) { const {amount} = payload; return { ...state, amount } }, setIsMax(state, {payload}) { const {isMax} = payload; return { ...state, isMax } }, setGasPrice(state, {payload}) { const {gasPrice} = payload; return { ...state, gasPrice } }, setToken(state, {payload}) { const {token} = payload; return { ...state, token } }, setLoading(state,{payload}){ const {loading} = payload; return { ...state, loading } } }, effects: { * amountChange({payload}, {put}) { const {amount} = payload; yield put({type: "setAmount", payload: {amount:toBig(amount)}}); }, * gasPriceChange({payload}, {select, put}) { const {gasPrice,token,gasLimit,balance} = payload; const {isMax} = yield select((state) => state.convert); if (isMax && token.toLowerCase() === 'eth') { const gas = toBig(gasPrice).times(gasLimit).div(1e9); const amount = balance.minus(gas).minus(0.1).gt(0) ? balance.minus(gas).minus(0.1) : toBig(0); yield put({type: 'amountChange', payload: {amount}}) } yield put({type: 'setGasPrice', payload: {gasPrice}}) }, * tokenChange({payload}, {put}) { yield put({type: 'reset', payload}); yield put({type: 'setToken', payload}); }, * setMax({payload}, {put}) { const {amount} = payload; yield put({type:"setIsMax",payload:{isMax:true}}); yield put({type:"setAmount",payload:{amount:toBig(amount)}}) } } };
"use strict"; var Api = require("../lib/Api"); var ArgumentParser = require("argparse").ArgumentParser; var parser = new ArgumentParser({ addHelp: true, description: "Get the key phrases and concepts in a piece of text" }); parser.addArgument(["--key"], {help: "Rosette API key", required: true}); parser.addArgument(["--url"], {help: "Rosette API alt-url", required: false}); var args = parser.parseArgs(); var api = new Api(args.key, args.url); var endpoint = "topics"; var topics_data = "Lily Collins is in talks to join Nicholas Hoult in Chernin Entertainment and Fox Searchlight's J.R.R. Tolkien biopic Tolkien. Anthony Boyle, known for playing Scorpius Malfoy in the British play Harry Potter and the Cursed Child, also has signed on for the film centered on the famed author. In Tolkien, Hoult will play the author of the Hobbit and Lord of the Rings book series that were later adapted into two Hollywood trilogies from Peter Jackson. Dome Karukoski is directing the project." var content = topics_data; api.parameters.content = content; api.rosette(endpoint, function(err, res){ if(err){ console.log(err); } else { console.log(JSON.stringify(res, null, 2)); } });
(function () { var Grid = (function () { function Grid(scale) { this.scale = scale; } Grid.prototype.calculateDistanceFromOrigin = function (point) { var xDist = (point.x - Grid.origin.x); var yDist = (point.y - Grid.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; }; return Grid; }()); Grid.origin = { x: 0, y: 0 }; var grid1 = new Grid(1.0); // 1x scale var grid2 = new Grid(5.0); // 5x scale console.log('grid1 distance: ' + grid1.calculateDistanceFromOrigin({ x: 10, y: 10 })); console.log('grid2 distance: ' + grid2.calculateDistanceFromOrigin({ x: 10, y: 10 })); var instance_origin = grid1.origin; console.log('instance_origin from grid1 (static origin): ' + instance_origin); })(); (function () { var Grid = (function () { function Grid(scale) { this.scale = scale; this.origin = { x: 0, y: 0 }; } Grid.prototype.calculateDistanceFromOrigin = function (point) { var xDist = (point.x - this.origin.x); var yDist = (point.y - this.origin.y); return Math.sqrt(xDist * xDist + yDist * yDist) / this.scale; }; return Grid; }()); var grid3 = new Grid(1.0); // 1x scale var grid4 = new Grid(5.0); // 5x scale console.log('grid3 distance: ' + grid3.calculateDistanceFromOrigin({ x: 10, y: 10 })); console.log('grid4 distance: ' + grid4.calculateDistanceFromOrigin({ x: 10, y: 10 })); var instance_origin = grid3.origin; console.log('instance_origin from grid3 (public origin): ' + instance_origin.x + ', ' + instance_origin.y); })();
const weave = require("./index"); const Queue = require("./queue"); test("queues have a peek function", () => { const q = new Queue(); expect(typeof q.peek).toEqual("function"); }); test("peek returns the first value without removing it", () => { const q = new Queue(); q.add("a"); q.add("b"); expect(q.peek()).toEqual("a"); expect(q.remove()).toEqual("a"); expect(q.peek()).toEqual("b"); expect(q.remove()).toEqual("b"); }); test("weave is a function", () => { expect(typeof weave).toEqual("function"); }); test("weave can combine two queues", () => { const first = new Queue(); first.add(12); first.add(23); first.add(34); first.add(45); const second = new Queue(); second.add("onetwo"); second.add("twothree"); second.add("threefour"); second.add("fourfive"); const result = weave(first, second); expect(result.remove()).toEqual(12); expect(result.remove()).toEqual("onetwo"); expect(result.remove()).toEqual(23); expect(result.remove()).toEqual("twothree"); expect(result.remove()).toEqual(34); expect(result.remove()).toEqual("threefour"); expect(result.remove()).toEqual(45); expect(result.remove()).toEqual("fourfive"); expect(result.remove()).toBeUndefined(); });
import Vue from 'vue'; import Vuex from 'vuex'; import state from 'ee_else_ce/boards/stores/state'; import actions from 'ee_else_ce/boards/stores/actions'; import mutations from 'ee_else_ce/boards/stores/mutations'; Vue.use(Vuex); export default () => new Vuex.Store({ state, actions, mutations, });
import Link from '@/components/Link' export default function Pagination({ totalPages, currentPage }) { const prevPage = parseInt(currentPage) - 1 > 0 const nextPage = parseInt(currentPage) + 1 <= parseInt(totalPages) return ( <div className="pt-6 pb-8 space-y-2 md:space-y-5"> <nav className="flex justify-between"> {!prevPage && ( <button rel="previous" className="cursor-auto disabled:opacity-50" disabled={!prevPage}> Previous </button> )} {prevPage && ( <Link href={currentPage - 1 === 1 ? `/posts/` : `/posts/page/${currentPage - 1}`}> <button rel="previous">Previous</button> </Link> )} <span> {currentPage} of {totalPages} </span> {!nextPage && ( <button rel="next" className="cursor-auto disabled:opacity-50" disabled={!nextPage}> Next </button> )} {nextPage && ( <Link href={`/posts/page/${currentPage + 1}`}> <button rel="next">Next</button> </Link> )} </nav> </div> ) }
/** * Finnhub API * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. * */ import ApiClient from '../ApiClient'; /** * The FinancialStatements model module. * @module model/FinancialStatements * @version 1.2.7 */ class FinancialStatements { /** * Constructs a new <code>FinancialStatements</code>. * @alias module:model/FinancialStatements */ constructor() { FinancialStatements.initialize(this); } /** * Initializes the fields of this object. * This method is used by the constructors of any subclasses, in order to implement multiple inheritance (mix-ins). * Only for internal use. */ static initialize(obj) { } /** * Constructs a <code>FinancialStatements</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/FinancialStatements} obj Optional instance to populate. * @return {module:model/FinancialStatements} The populated <code>FinancialStatements</code> instance. */ static constructFromObject(data, obj) { if (data) { obj = obj || new FinancialStatements(); if (data.hasOwnProperty('symbol')) { obj['symbol'] = ApiClient.convertToType(data['symbol'], 'String'); } if (data.hasOwnProperty('financials')) { obj['financials'] = ApiClient.convertToType(data['financials'], [Object]); } } return obj; } } /** * Symbol of the company. * @member {String} symbol */ FinancialStatements.prototype['symbol'] = undefined; /** * An array of map of key, value pairs containing the data for each period. * @member {Array.<Object>} financials */ FinancialStatements.prototype['financials'] = undefined; export default FinancialStatements;
"use strict"; // Copyright 2020 Google LLC // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. Object.defineProperty(exports, "__esModule", { value: true }); exports.osconfig_v1 = void 0; /* eslint-disable @typescript-eslint/no-explicit-any */ /* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ const googleapis_common_1 = require("googleapis-common"); var osconfig_v1; (function (osconfig_v1) { /** * OS Config API * * OS management tools that can be used for patch management, patch compliance, and configuration management on VM instances. * * @example * const {google} = require('googleapis'); * const osconfig = google.osconfig('v1'); * * @namespace osconfig * @type {Function} * @version v1 * @variation v1 * @param {object=} options Options for Osconfig */ class Osconfig { constructor(options, google) { this.context = { _options: options || {}, google, }; this.projects = new Resource$Projects(this.context); } } osconfig_v1.Osconfig = Osconfig; class Resource$Projects { constructor(context) { this.context = context; this.patchDeployments = new Resource$Projects$Patchdeployments(this.context); this.patchJobs = new Resource$Projects$Patchjobs(this.context); } } osconfig_v1.Resource$Projects = Resource$Projects; class Resource$Projects$Patchdeployments { constructor(context) { this.context = context; } create(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+parent}/patchDeployments').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } delete(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } get(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } list(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+parent}/patchDeployments').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } } osconfig_v1.Resource$Projects$Patchdeployments = Resource$Projects$Patchdeployments; class Resource$Projects$Patchjobs { constructor(context) { this.context = context; this.instanceDetails = new Resource$Projects$Patchjobs$Instancedetails(this.context); } cancel(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+name}:cancel').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } execute(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+parent}/patchJobs:execute').replace(/([^:]\/)\/+/g, '$1'), method: 'POST', }, options), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } get(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } list(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+parent}/patchJobs').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } } osconfig_v1.Resource$Projects$Patchjobs = Resource$Projects$Patchjobs; class Resource$Projects$Patchjobs$Instancedetails { constructor(context) { this.context = context; } list(paramsOrCallback, optionsOrCallback, callback) { let params = (paramsOrCallback || {}); let options = (optionsOrCallback || {}); if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {}; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://osconfig.googleapis.com/'; const parameters = { options: Object.assign({ url: (rootUrl + '/v1/{+parent}/instanceDetails').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { googleapis_common_1.createAPIRequest(parameters, callback); } else { return googleapis_common_1.createAPIRequest(parameters); } } } osconfig_v1.Resource$Projects$Patchjobs$Instancedetails = Resource$Projects$Patchjobs$Instancedetails; })(osconfig_v1 = exports.osconfig_v1 || (exports.osconfig_v1 = {})); //# sourceMappingURL=v1.js.map