code
stringlengths
2
1.05M
search_result['449']=["topic_00000000000000DE.html","StringExtension Class",""];
"use strict"; var CleanCss = require("clean-css"); var _cleanCssOptions = { // 例如 top: 7px; 与 top: 5px\9; 同时存在后者会被优化掉 noAdvanced : true }; var CssCompressor = { __name__ : "CssCompressor", "__proto__" : null, /** * @brief 压缩代码 * * @param {string} code 代码文本 * @param {function} next 回调函数 * @return void * * @details 压缩代码文本 */ compress : function (code, next) { next(null, new CleanCss(_cleanCssOptions).minify(code)); } }; module.exports = CssCompressor;
import { FETCH_USER, FETCH_USER_ARTISTS, FETCH_USER_EVENTS, FETCH_ARTIST_EVENTS, HIDE_ARTIST_EVENTS, SHOW_ARTIST_EVENTS, fetchUser, fetchUserArtists, fetchArtistEvents, hideArtistEvents, showArtistEvents } from '../../src/actions'; describe('(Actions)', () => { describe('fetchUser', function() { it('has the correct type', function() { expect(fetchUser().type).to.eql(FETCH_USER); }); }); describe('fetchUserArtists', function() { it('has the correct type', function() { expect(fetchUserArtists().type).to.eql(FETCH_USER_ARTISTS); }); }); describe('fetchArtistEvents', function() { it('has the correct type', function() { expect(fetchArtistEvents().type).to.eql(FETCH_ARTIST_EVENTS); }); }); describe('hideArtistEvents', function() { it('has the correct type', function() { expect(hideArtistEvents().type).to.eql(HIDE_ARTIST_EVENTS); }); }); describe('showArtistEvents', function() { it('has the correct type', function() { expect(showArtistEvents().type).to.eql(SHOW_ARTIST_EVENTS); }); }); });
requirejs.config({ paths: { 'jquery': '../lib/jquery/dist/jquery' } }); define(['app', 'jquery'], function(App, $) { var app = new App($('body')); app.render(); });
import React from 'react'; import ReactDOM from 'react-dom'; import Routes from './routes'; import { Provider } from 'react-redux'; import { Store } from './Redux'; import './index.css'; ReactDOM.render( <Provider store={Store}><Routes /></Provider>, document.getElementById('root') );
c['3399']=[['3400',"RoomSid Property","topic_000000000000007A.html",0],['3401',"Token Property","topic_0000000000000079.html",0]];
'use strict'; module.exports = { port: 443, db: process.env.MONGOHQ_URL || process.env.MONGOLAB_URI || 'mongodb://localhost/myapp4', assets: { lib: { css: [ 'public/lib/bootstrap/dist/css/bootstrap.min.css', 'public/lib/bootstrap/dist/css/bootstrap-theme.min.css', ], js: [ 'public/lib/angular/angular.min.js', 'public/lib/angular-resource/angular-resource.min.js', 'public/lib/angular-animate/angular-animate.min.js', 'public/lib/angular-ui-router/release/angular-ui-router.min.js', 'public/lib/angular-ui-utils/ui-utils.min.js', 'public/lib/angular-bootstrap/ui-bootstrap-tpls.min.js' ] }, css: 'public/dist/application.min.css', js: 'public/dist/application.min.js' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: 'https://localhost:443/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: 'https://localhost:443/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
export{B as Behavior,X as CONTEXT,a8 as CUSTOM_UNITS,a6 as FLEX_GAP_SUPPORTED,P as NuAction,O as NuBase,M as Nude,a9 as ROOT_CONTEXT,a7 as STATES_MAP,a1 as assign,Y as behaviors,a5 as color,U as contrast,c as deepQuery,d as deepQueryAll,M as default,a0 as define,Q as elements,_ as helpers,a3 as hue,D as icons,i as isEqual,V as reduceMotion,Z as requestIdleCallback,j as routing,T as scheme,$ as styles,S as svg,a4 as themes,a2 as units}from"./index-78d32569.js";
// Copyright (c) 2011-2013 Turbulenz Limited /*global Backbone*/ /*global TurbulenzStore*/ /*global TurbulenzGameNotifications*/ /*global TurbulenzBridge*/ /*global LocalMessageView*/ /*global LocalPlayView*/ /*global CarouselView*/ /*global LocalMetricsView*/ /*global LocalListView*/ /*global LocalUserdataView*/ /*global LocalDeployView*/ /*global LocalEditView*/ /*jshint nomen: false*/ /*global _*/ /*global $*/ /*jshint nomen: true*/ /*exported LocalApplicationController*/ var LocalApplicationController = Backbone.Controller.extend({ routes: { '' : 'home', 'add-game' : 'create', ':slug/?' : 'game', '/play/:slug/?' : 'play_versions', '/play/:slug/:version' : 'play', '/edit/:slug/?' : 'edit', '/metrics/:slug/?' : 'metrics', '/list/:type/:slug/?' : 'list', '/list/:type/:slug/*directory' : 'list', '/userdata/:slug' : 'userdata', '/userdata/:slug/*directory' : 'userdata' }, initialize: function initializeFn(options) { this.pluginInfo = options.pluginInfo; this.sdkUrl = options.sdkUrl; this.router = options.router; this.viewerEnabled = options.viewer_enabled; /*jshint nomen: false*/ _.bindAll(this, 'home', 'game', 'play'); /*jshint nomen: false*/ this.messageView = new LocalMessageView({ engine: this.pluginInfo, sdk: this.sdkUrl }); this.playView = new LocalPlayView({ app: this, engine: this.pluginInfo }); this.carousel = new CarouselView({app: this}); this.metrics = new LocalMetricsView({app: this}); this.list = new LocalListView({app: this}); this.userdata = new LocalUserdataView({app: this}); this.deploy = new LocalDeployView({app: this}); this.editView = new LocalEditView({app: this}); this.messageView.render(); this.deploy.render(); this.turbulenzBridge = TurbulenzBridge.create(this); this.store = TurbulenzStore.create(this); this.gameNotifications = TurbulenzGameNotifications.create(this); this.playingGameSlug = null; var that = this; this.bind('game:play', function (slug /*, version */) { that.playingGameSlug = slug; }); this.bind('game:stop', function () { that.playingGameSlug = null; }); return this; }, route: function routeFn(route, name, callback) { if (!Backbone.history) { Backbone.history = new Backbone.History(); } /*jshint nomen: false*/ if (!_.isRegExp(route)) { route = this._routeToRegExp(route); } Backbone.history.route(route, _.bind(function (fragment) { if (!this.preLeave()) { return; } this.currentView = null; var args = this._extractParameters(route, fragment); callback.apply(this, args); this.trigger.apply(this, ['route:' + name].concat(args)); }, this)); /*jshint nomen: true*/ }, home: function homeFn() { this.trigger('carousel:refresh'); this.trigger('carousel:collapse'); this.trigger('game:stop'); }, create: function createFn() { this.carousel.addGame('add-game'); }, game: function gameFn(slug, quick) { this.trigger('game:stop'); if (!quick) { this.trigger('carousel:refresh'); } if ($('#carousel').find('#' + slug).length === 0) { //game does not exist this.trigger('carousel:collapse'); } else { $('#actionspacer').empty(); this.carousel.expand('#' + slug); $('#details').empty(); } }, preLeave: function preLeavefn(/* args */) { if (this.currentView && this.currentView.preLeave && !this.currentView.preLeave()) { if (window.location.hash !== this.currentHash) { window.location.hash = this.currentHash; } return false; } return true; }, prepareAction: function prepareActionFn(slug, action) { var $game = $('#' + slug); //no game selected for the action and not creating a new game if (!$game.hasClass('selected') && !$game.hasClass('Temporary')) { this.trigger('carousel:collapse'); } //if carousel empty if ($('#carousel').length === 0) { this.trigger('carousel:refresh'); } var actBtn = $('#' + action + '-button'); if (!actBtn.hasClass('selected')) { actBtn .addClass('selected') .parent().siblings().children().removeClass('selected'); } this.currentView = null; }, setCurrentView: function (view) { this.currentView = view; this.currentHash = window.location.hash; }, play_versions: function (slug) { this.game(slug, true); this.prepareAction(slug, 'play'); this.trigger('game:versions', slug); }, play: function playFn(slug, version) { this.trigger('game:play', slug, version); this.currentView = undefined; }, edit: function editFn(slug) { this.game(slug, true); this.prepareAction(slug, 'edit'); this.trigger('game:edit', slug); }, metrics: function metricsFn(slug) { this.game(slug, true); this.prepareAction(slug, 'metrics'); this.trigger('game:metrics', slug); }, list: function listFn(type, slug, directory) { this.game(slug, true); this.prepareAction(slug, 'list'); this.trigger('assets:list', type, slug, directory); }, userdata: function userdataFn(slug, directory) { this.game(slug, true); this.prepareAction(slug, 'userdata'); this.trigger('game:userdata', slug, directory); } });
/** * Created by nbenes on 11/16/13. */ var $window = $(window) var $body = $(document.body) var navHeight = $('.navbar').outerHeight(true) + 10 $body.scrollspy({ target: '.crc-sidebar', offset: navHeight }) $window.on('load', function () { $body.scrollspy('refresh') }) $('.crc-container [href=#]').click(function (e) { e.preventDefault() }) // back to top setTimeout(function () { var $sideBar = $('.crc-sidebar') $sideBar.affix({ offset: { top: function () { var offsetTop = $sideBar.offset().top var sideBarMargin = parseInt($sideBar.children(0).css('margin-top'), 10) var navOuterHeight = $('.crc-nav').height() return (this.top = offsetTop - navOuterHeight - sideBarMargin) } , bottom: function () { return (this.bottom = $('.crc-footer').outerHeight(true)) } } }) }, 100) setTimeout(function () { $('.crc-top').affix() }, 100)
/** * Swiper 6.2.0 * Most modern mobile touch slider and framework with hardware accelerated transitions * http://swiperjs.com * * Copyright 2014-2020 Vladimir Kharlampidi * * Released under the MIT License * * Released on: September 4, 2020 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Swiper = _interopDefault(require('./cjs/components/core/core-class')); var Virtual = _interopDefault(require('./cjs/components/virtual/virtual')); var Keyboard = _interopDefault(require('./cjs/components/keyboard/keyboard')); var Mousewheel = _interopDefault(require('./cjs/components/mousewheel/mousewheel')); var Navigation = _interopDefault(require('./cjs/components/navigation/navigation')); var Pagination = _interopDefault(require('./cjs/components/pagination/pagination')); var Scrollbar = _interopDefault(require('./cjs/components/scrollbar/scrollbar')); var Parallax = _interopDefault(require('./cjs/components/parallax/parallax')); var Zoom = _interopDefault(require('./cjs/components/zoom/zoom')); var Lazy = _interopDefault(require('./cjs/components/lazy/lazy')); var Controller = _interopDefault(require('./cjs/components/controller/controller')); var A11y = _interopDefault(require('./cjs/components/a11y/a11y')); var History = _interopDefault(require('./cjs/components/history/history')); var HashNavigation = _interopDefault(require('./cjs/components/hash-navigation/hash-navigation')); var Autoplay = _interopDefault(require('./cjs/components/autoplay/autoplay')); var EffectFade = _interopDefault(require('./cjs/components/effect-fade/effect-fade')); var EffectCube = _interopDefault(require('./cjs/components/effect-cube/effect-cube')); var EffectFlip = _interopDefault(require('./cjs/components/effect-flip/effect-flip')); var EffectCoverflow = _interopDefault(require('./cjs/components/effect-coverflow/effect-coverflow')); var Thumbs = _interopDefault(require('./cjs/components/thumbs/thumbs')); // Swiper Class var components = [Virtual, Keyboard, Mousewheel, Navigation, Pagination, Scrollbar, Parallax, Zoom, Lazy, Controller, A11y, History, HashNavigation, Autoplay, EffectFade, EffectCube, EffectFlip, EffectCoverflow, Thumbs]; Swiper.use(components); exports.Swiper = Swiper; exports.default = Swiper;
import React from 'react' const DRAG_PIXELS_TO_NORMALIZED_VALUE = 0.008; const clampUnit = (v) => { if (v < 0) { return 0; } else if (v > 1) { return 1; } else if (isNaN(v)) { return 0; } else { return v; } } export default class Knob extends React.Component { constructor(props) { super(props); this.state = { inputFocused: false, editingText: null, canvasFocused: false, }; this.mouseCaptured = false; this.lastMousePosition; this.activeCanvasTouches = {}; // maps from identifier to object this.accumulatedValue = 0; this.handleInputFocus = this.handleInputFocus.bind(this); this.handleInputBlur = this.handleInputBlur.bind(this); this.handleInputChange = this.handleInputChange.bind(this); this.handleInputKeyDown = this.handleInputKeyDown.bind(this); this.defaultFormatInternalValue = this.defaultFormatInternalValue.bind(this); this.defaultInternalValueToNormalized = this.defaultInternalValueToNormalized.bind(this); this.defaultNormalizedValueToInternal = this.defaultNormalizedValueToInternal.bind(this); this.handleCanvasMouseDown = this.handleCanvasMouseDown.bind(this); this.handleCanvasMouseMove = this.handleCanvasMouseMove.bind(this); this.handleCanvasMouseUp = this.handleCanvasMouseUp.bind(this); this.handleCanvasTouchStart = this.handleCanvasTouchStart.bind(this); this.handleCanvasTouchEndOrCancel = this.handleCanvasTouchEndOrCancel.bind(this); this.handleCanvasTouchMove = this.handleCanvasTouchMove.bind(this); this.handleCanvasFocus = this.handleCanvasFocus.bind(this); this.handleCanvasBlur = this.handleCanvasBlur.bind(this); this.handleCanvasKeyDown = this.handleCanvasKeyDown.bind(this); this.captureMouse = this.captureMouse.bind(this); this.releaseMouse = this.releaseMouse.bind(this); } // Utility method that can also be used by other components that use this one static formatWithMinimumDigits(v, minDigits) { for (let i = 0; ; i++) { const s = v.toFixed(i); const len = (s.match(/[0-9]/g)||[]).length; if (len >= minDigits) { return s; } } } defaultFormatInternalValue(v) { return this.props.integral ? v.toFixed() : Knob.formatWithMinimumDigits(v, 3); } formatInternalValue(v) { const impl = this.props.formatInternalValue || this.defaultFormatInternalValue; return impl(v); } defaultInternalValueToNormalized(v) { const curve = this.props.curve; const min = this.props.min; const max = this.props.max; let nv; if (curve === 'linear') { nv = (v - min)/(max - min); } else if (curve === 'log') { nv = Math.log(v/min)/Math.log(max/min); } else { throw new Error('Unrecognized value for curve', curve); } return nv; } // This _may_ result in a value outside [0,1], or even NaN internalValueToNormalized(v) { const impl = this.props.internalValueToNormalized || this.defaultInternalValueToNormalized; return impl(v); } defaultNormalizedValueToInternal(nv) { const curve = this.props.curve; const min = this.props.min; const max = this.props.max; let v; if (curve === 'linear') { v = min + nv*(max - min); } else if (curve === 'log') { v = min * Math.exp(nv * Math.log(max/min)); } else { throw new Error('Unrecognized value for curve', curve); } return v; } // This expects a value within [0,1] normalizedValueToInternal(nv) { if ((nv < 0) || (nv > 1)) { console.warn('normalizedValueToInternal: input out of range'); } const impl = this.props.normalizedValueToInternal || this.defaultNormalizedValueToInternal; return impl(nv); } parseToInternalValue(s) { return this.props.integral ? parseInt(s) : parseFloat(s); } componentDidMount() { this.updateCanvas(); } componentDidUpdate() { this.updateCanvas(); } componentWillUnmount() { if (this.mouseCaptured) { this.releaseMouse(); } } handleInputFocus() { this.setState({ inputFocused: true, editingText: '', }); } commitEditText() { const v = this.parseToInternalValue(this.inputElem.value); if (isNaN(v)) { // Ignore the edit } else { this.props.onChange(v); } } handleInputBlur() { this.commitEditText(); this.setState({ inputFocused: false, editingText: null, }); } handleInputChange(e) { if (this.state.inputFocused) { this.setState({ editingText: e.target.value, }); } else { // NOTE: I'm not sure if this code can be reached, but if it can, I think this is the right behavior this.commitEditText(); } } handleInputKeyDown(e) { switch (e.key) { case 'Enter': this.inputElem.blur(); break; case 'Escape': this.inputElem.value = ''; // NOTE: This is a hacky way to cause the edit to be cancelled, but seems to work this.inputElem.blur(); break; } } captureMouse() { document.addEventListener('mousemove', this.handleCanvasMouseMove); document.addEventListener('mouseup', this.handleCanvasMouseUp); this.mouseCaptured = true; } releaseMouse() { document.removeEventListener('mousemove', this.handleCanvasMouseMove); document.removeEventListener('mouseup', this.handleCanvasMouseUp); this.mouseCaptured = false; } handleCanvasMouseDown(e) { this.captureMouse(); this.lastMousePosition = {x: e.nativeEvent.pageX, y: e.nativeEvent.pageY}; this.canvasElem.focus(); // Since we preventDefault, need to do this manually e.preventDefault(); } adjustValueByPixels(deltaPixels) { const deltaNormalizedValue = deltaPixels*DRAG_PIXELS_TO_NORMALIZED_VALUE; let newValue = this.normalizedValueToInternal(clampUnit(this.internalValueToNormalized(this.props.value + this.accumulatedValue) + deltaNormalizedValue)); if (this.props.integral) { const roundedNewValue = Math.round(newValue); this.accumulatedValue = (newValue - roundedNewValue); newValue = roundedNewValue; } if (newValue !== this.props.value) { this.props.onChange(newValue); } } // dir should be -1 or 1 bumpValue(dir) { if (this.props.integral) { let newValue = this.props.value + dir; if (newValue < this.props.min) { newValue = this.props.min; } else if (newValue > this.props.max) { newValue = this.props.max; } this.props.onChange(newValue); } else { this.adjustValueByPixels(dir); } } handleCanvasMouseMove(e) { const dx = e.pageX - this.lastMousePosition.x; const dy = e.pageY - this.lastMousePosition.y; this.lastMousePosition = {x: e.pageX, y: e.pageY}; this.adjustValueByPixels(-dy); } handleCanvasMouseUp(e) { this.releaseMouse(); this.lastMousePosition = undefined; } handleCanvasTouchStart(e) { e.preventDefault(); for (let i = 0; i < e.changedTouches.length; i++) { const t = e.changedTouches.item(i); this.activeCanvasTouches[t.identifier] = { screenX: t.screenX, screenY: t.screenY, }; } } handleCanvasTouchEndOrCancel(e) { e.preventDefault(); for (let i = 0; i < e.changedTouches.length; i++) { const t = e.changedTouches.item(i); delete this.activeCanvasTouches[t.identifier]; } } handleCanvasTouchMove(e) { e.preventDefault(); for (let i = 0; i < e.changedTouches.length; i++) { const t = e.changedTouches.item(i); const at = this.activeCanvasTouches[t.identifier]; const dy = t.screenY - at.screenY; at.screenX = t.screenX; at.screenY = t.screenY; this.adjustValueByPixels(-dy); } } handleCanvasTouchCancel(e) { e.preventDefault(); } handleCanvasFocus() { this.setState({ canvasFocused: true, }); } handleCanvasBlur() { this.setState({ canvasFocused: false, }); } handleCanvasKeyDown(e) { switch (e.key) { case 'ArrowUp': this.bumpValue(1); break; case 'ArrowDown': this.bumpValue(-1); break; } } updateCanvas() { const canvasWidth = this.canvasElem.width; const canvasHeight = this.canvasElem.height; const ctx = this.canvasElem.getContext('2d'); ctx.clearRect(0, 0, canvasWidth, canvasHeight); const knobCenterX = 0.5*canvasWidth; const knobCenterY = 0.5*canvasHeight; const knobRadius = 0.3*canvasWidth; const arcRadius = 0.45*canvasWidth; const bottomHalfAngle = Math.PI/6; const beginAngle = 0.5*Math.PI+bottomHalfAngle; const endAngle = 2.5*Math.PI-bottomHalfAngle; const nv = this.internalValueToNormalized(this.props.value); let currentAngle; let validAngle; if ((nv < 0) || (nv > 1) || isNaN(nv)) { validAngle = false; } else { currentAngle = beginAngle + this.internalValueToNormalized(this.props.value)*(endAngle - beginAngle); validAngle = true; } const activeArcStyle = 'rgb(102, 153, 255)'; const inactiveArcStyle = 'rgb(150, 150, 150)'; const knobFaceStyle = 'rgb(200, 200, 200)'; const notchStyle = 'rgb(64, 64, 64)'; ctx.lineWidth = 2; if (validAngle) { ctx.strokeStyle = activeArcStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, arcRadius, beginAngle, currentAngle); ctx.stroke(); ctx.strokeStyle = inactiveArcStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, arcRadius, currentAngle, endAngle); ctx.stroke(); } else { ctx.strokeStyle = inactiveArcStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, arcRadius, beginAngle, endAngle); ctx.stroke(); } ctx.shadowOffsetX = 0; ctx.shadowOffsetY = 2; ctx.shadowColor = 'rgba(0, 0, 0, 0.5)'; ctx.shadowBlur = 20; ctx.fillStyle = knobFaceStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, knobRadius, 0, 2*Math.PI); ctx.fill(); ctx.shadowColor = 'rgba(0, 0, 0, 0.75)'; ctx.shadowBlur = 10; ctx.fill(); ctx.shadowColor = 'rgba(0, 0, 0, 0)'; if (validAngle) { ctx.lineWidth = 2; ctx.strokeStyle = notchStyle; ctx.translate(knobCenterX, knobCenterY); ctx.rotate(currentAngle); ctx.translate(-knobCenterX, -knobCenterY); ctx.beginPath(); ctx.moveTo(knobCenterX+knobRadius, knobCenterY); ctx.lineTo(knobCenterX+0.25*knobRadius, knobCenterY); ctx.stroke(); ctx.setTransform(1, 0, 0, 1, 0, 0); } if (this.state.canvasFocused) { const FOCUS_CIRCLE_RADIUS = 2; ctx.lineWidth = 1; ctx.strokeStyle = inactiveArcStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, 0.65*canvasWidth, 0, 2*Math.PI); ctx.stroke(); } } render() { const {value, label, width} = this.props; const canvasWidth = width; const canvasHeight = width; const WIDE_WIDTH = 200; // For centering text in absolutely positioned elements const inputText = this.state.inputFocused ? this.state.editingText : this.formatInternalValue(value); const inputExtraAttrs = this.state.inputFocused ? { onKeyDown: this.handleInputKeyDown } : {}; return ( <div style={{position: 'relative'}}> <label style={{display: 'block', position: 'absolute', top: -(0.5*canvasHeight + 15), width: WIDE_WIDTH, left: -0.5*WIDE_WIDTH, textAlign: 'center', whiteSpace: 'nowrap'}}>{label}</label> <canvas ref={canvas => { this.canvasElem = canvas; }} width={canvasWidth} height={canvasHeight} onMouseDown={this.handleCanvasMouseDown} onTouchStart={this.handleCanvasTouchStart} onTouchEnd={this.handleCanvasTouchEndOrCancel} onTouchMove={this.handleCanvasTouchMove} onTouchCancel={this.handleCanvasTouchEndOrCancel} onFocus={this.handleCanvasFocus} onBlur={this.handleCanvasBlur} onKeyDown={this.handleCanvasKeyDown} style={{position: 'absolute', width: canvasWidth, height: canvasHeight, left: -0.5*canvasWidth, top: -0.5*canvasHeight, outline: 'none'}} tabIndex="0" /> <input ref={(elem) => { this.inputElem = elem; }} type="text" style={{position: 'absolute', top: 0.5*canvasHeight - 5, width: 1.2*width, left: -0.6*width, textAlign: 'center', background: 'none', border: 0, fontSize: 'inherit', fontFamily: 'inherit'}} value={inputText} onFocus={this.handleInputFocus} onBlur={this.handleInputBlur} onChange={this.handleInputChange} {...inputExtraAttrs} /> </div> ); } } Knob.defaultProps = { curve: 'linear', min: 0, max: 1, integral: false, };
export default function(n) { return n < 10 ? '0' + n : n; }
describe("clone", function() { "use strict"; var link; beforeEach(function() { jasmine.sandbox.set("<a id='link'><input id='input'></a>"); link = DOM.find("#link"); }); it("allows to clone all clildren", function() { var clone = link.clone(true), child = clone.child(0); jasmine.sandbox.set(clone); expect(clone).not.toBe(link); expect(clone).toHaveTag("a"); expect(clone).toHaveId("link"); expect(child).not.toBe(link.child(0)); expect(child).toHaveTag("input"); expect(child).toHaveId("input"); }); it("should allow to do a shallow copy", function() { var clone = link.clone(false); expect(clone).not.toBe(link); expect(clone).toHaveTag("a"); expect(clone).toHaveId("link"); expect(clone.children().length).toBe(0); }); it("should work on empty elements", function() { var emptyEl = DOM.find("xxx"); expect(emptyEl.clone(false)).toBeTruthy(); }); it("should throw error if argument is invalud", function() { expect(function() { link.clone() }).toThrow(); expect(function() { link.clone(1) }).toThrow(); expect(function() { link.clone({}) }).toThrow(); expect(function() { link.clone(function() {}) }).toThrow(); expect(function() { link.clone(null) }).toThrow(); expect(function() { link.clone("abc") }).toThrow(); }); });
import React from "react"; import TextWithLineBreaks from "../components/TextWithLineBreaks"; const RecipeNotes = ({ note, updateInput, editing }) => ( <section className="section"> <p className="section__title">Notes supplémentaires :</p> {editing ? ( <textarea className="add-form-textfield" name="note" value={note} onChange={updateInput} /> ) : ( <TextWithLineBreaks className="recipe-notes" text={note} /> )} </section> ); export default RecipeNotes;
define("Navigo.amd", [], () => /******/ (() => { // webpackBootstrap /******/ "use strict"; /******/ var __webpack_modules__ = ({ /***/ "./src/Q.ts": /*!******************!*\ !*** ./src/Q.ts ***! \******************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => /* binding */ Q /* harmony export */ }); function Q(funcs, c) { var context = c || {}; var idx = 0; (function next() { if (!funcs[idx]) return; if (Array.isArray(funcs[idx])) { funcs.splice.apply(funcs, [idx, 1].concat(funcs[idx][0](context) ? funcs[idx][1] : funcs[idx][2])); next(); } else { // console.log(funcs[idx].name + " " + JSON.stringify(context)); funcs[idx](context, function (moveForward) { if (typeof moveForward === "undefined" || moveForward === true) { idx += 1; next(); } }); } })(); } Q.if = function (condition, one, two) { if (!Array.isArray(one)) one = [one]; if (!Array.isArray(two)) two = [two]; return [condition, one, two]; }; /***/ }), /***/ "./src/constants.ts": /*!**************************!*\ !*** ./src/constants.ts ***! \**************************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "PARAMETER_REGEXP": () => /* binding */ PARAMETER_REGEXP, /* harmony export */ "WILDCARD_REGEXP": () => /* binding */ WILDCARD_REGEXP, /* harmony export */ "REPLACE_VARIABLE_REGEXP": () => /* binding */ REPLACE_VARIABLE_REGEXP, /* harmony export */ "REPLACE_WILDCARD": () => /* binding */ REPLACE_WILDCARD, /* harmony export */ "START_BY_SLASH_REGEXP": () => /* binding */ START_BY_SLASH_REGEXP, /* harmony export */ "MATCH_REGEXP_FLAGS": () => /* binding */ MATCH_REGEXP_FLAGS /* harmony export */ }); var PARAMETER_REGEXP = /([:*])(\w+)/g; var WILDCARD_REGEXP = /\*/g; var REPLACE_VARIABLE_REGEXP = "([^/]+)"; var REPLACE_WILDCARD = "(?:.*)"; var START_BY_SLASH_REGEXP = "(?:/^|^)"; var MATCH_REGEXP_FLAGS = ""; /***/ }), /***/ "./src/index.ts": /*!**********************!*\ !*** ./src/index.ts ***! \**********************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "default": () => /* binding */ Navigo /* harmony export */ }); /* harmony import */ var _utils__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./utils */ "./src/utils.ts"); /* harmony import */ var _Q__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./Q */ "./src/Q.ts"); function Navigo(r) { var root = "/"; var current = null; var routes = []; var notFoundRoute; var destroyed = false; var genericHooks; var self = this; var isPushStateAvailable = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.pushStateAvailable)(); var isWindowAvailable = typeof window !== "undefined"; var lifecycle = [_checkForAlreadyHook, _checkForLeaveHook, _checkForBeforeHook, _callHandler, _checkForAfterHook]; var notFoundLifeCycle = [_checkForNotFoundHandler, _Q__WEBPACK_IMPORTED_MODULE_1__.default.if(function (_ref) { var notFoundHandled = _ref.notFoundHandled; return notFoundHandled; }, lifecycle, _errorOut)]; if (!r) { console.warn('Navigo requires a root path in its constructor. If not provided will use "/" as default.'); } else { root = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(r); } // functions that are part of Q (queue) processing function _required(obj, fields) { for (var i = 0; i < fields.length; i++) { if (typeof obj[fields[i]] === "undefined") { throw new Error("Navigo internal error. Required field \"" + fields[i] + "\" is missing in a queue context."); } } } function _checkForLeaveHook(context, done) { if (current && current.route.hooks && current.route.hooks.leave) { current.route.hooks.leave(function (moveForward) { if (typeof moveForward === "undefined" || moveForward === true) { done(); } }, current); return; } done(); } function _checkForBeforeHook(context, done) { _required(context, ["route", "match"]); if (context.route.hooks && context.route.hooks.before) { context.route.hooks.before(function (moveForward) { if (typeof moveForward === "undefined" || moveForward === true) { done(); } }, context.match); } else { done(); } } function _callHandler(context, done) { _required(context, ["route", "match", "options"]); if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.options, "updateState")) { current = context.match; } if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.options, "callHandler")) { context.route.handler(context.match); } updatePageLinks(); done(); } function _checkForAfterHook(context, done) { _required(context, ["route", "match"]); if (context.route.hooks && context.route.hooks.after) { context.route.hooks.after(context.match); } done(); } function _checkForAlreadyHook(context, done) { _required(context, ["route", "match"]); if (current && current.route === context.route && current.url === context.match.url && current.queryString === context.match.queryString) { if (current.route.hooks && current.route.hooks.already) { current.route.hooks.already(context.match); } done(false); return; } done(); } function _checkForNotFoundHandler(context, done) { _required(context, ["currentLocationPath"]); if (notFoundRoute) { context.notFoundHandled = true; var _extractGETParameters = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters)(context.currentLocationPath), url = _extractGETParameters[0], queryString = _extractGETParameters[1]; notFoundRoute.path = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(url); context.match = { url: notFoundRoute.path, queryString: queryString, data: null, route: notFoundRoute, params: queryString !== "" ? (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseQuery)(queryString) : null }; context.route = notFoundRoute; } done(); } function _errorOut(context, done) { _required(context, ["currentLocationPath"]); console.warn("Navigo: \"" + context.currentLocationPath + "\" didn't match any of the registered routes."); done(false); } function _setLocationPath(context, done) { if (typeof context.currentLocationPath === "undefined") { context.currentLocationPath = getCurrentEnvURL(); } done(); } function _findAMatch(context, done) { _required(context, ["currentLocationPath"]); for (var i = 0; i < routes.length; i++) { var route = routes[i]; var match = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.matchRoute)(context.currentLocationPath, route); if (match) { context.match = match; context.route = route; done(); return; } } done(); } function _checkForDeprecationMethods(context, done) { if (context.options) { if (typeof context.options["shouldResolve"] !== "undefined") { console.warn("\"shouldResolve\" is deprecated. Please check the documentation."); } if (typeof context.options["silent"] !== "undefined") { console.warn("\"silent\" is deprecated. Please check the documentation."); } } done(); } function _checkForForceOp(context, done) { _required(context, ["options"]); if (context.options.force === true) { self.current = current = pathToMatchObject(context.to); done(false); } else { done(); } } function _updateBrowserURL(context, done) { _required(context, ["to", "options"]); context.to = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(root) + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(context.to); if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.undefinedOrTrue)(context.options, "updateBrowserURL")) { if (isPushStateAvailable) { history[context.options.historyAPIMethod || "pushState"](context.options.stateObj || {}, context.options.title || "", ("/" + context.to).replace(/\/\//g, "/") // making sure that we don't have two slashes ); } else if (isWindowAvailable) { window.location.href = context.to; } } done(); } // public APIs function createRoute(path, handler, hooks, name) { path = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(path) ? (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(root + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path)) : path; return { name: name || String(path), path: path, handler: handler, hooks: hooks }; } function getCurrentEnvURL() { if (isWindowAvailable) { return location.pathname + location.search + location.hash; } return root; } function on(path, handler, hooks) { var _this = this; if (typeof path === "object" && !(path instanceof RegExp)) { Object.keys(path).forEach(function (p) { if (typeof path[p] === "function") { _this.on(p, path[p]); } else { var _path$p = path[p], _handler = _path$p.uses, name = _path$p.as, _hooks = _path$p.hooks; routes.push(createRoute(p, _handler, _hooks || genericHooks, name)); } }); return this; } else if (typeof path === "function") { hooks = handler; handler = path; path = root; } routes.push(createRoute(path, handler, hooks || genericHooks)); return this; } function resolve(currentLocationPath) { var context = { currentLocationPath: currentLocationPath, options: {} }; (0,_Q__WEBPACK_IMPORTED_MODULE_1__.default)([_setLocationPath, _findAMatch, _Q__WEBPACK_IMPORTED_MODULE_1__.default.if(function (_ref2) { var match = _ref2.match; return match; }, lifecycle, notFoundLifeCycle)], context); return context.match ? context.match : false; } function navigate(to, options) { if (options === void 0) { options = {}; } var context = { to: to, options: options, currentLocationPath: to }; (0,_Q__WEBPACK_IMPORTED_MODULE_1__.default)([_checkForDeprecationMethods, _checkForForceOp, _findAMatch, _Q__WEBPACK_IMPORTED_MODULE_1__.default.if(function (_ref3) { var match = _ref3.match; return match; }, lifecycle, notFoundLifeCycle), _updateBrowserURL], context); } function off(what) { this.routes = routes = routes.filter(function (r) { if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.isString)(what)) { return (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(r.path) !== (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(what); } else if ((0,_utils__WEBPACK_IMPORTED_MODULE_0__.isFunction)(what)) { return what !== r.handler; } return String(r.path) !== String(what); }); return this; } function listen() { if (isPushStateAvailable) { this.__popstateListener = function () { resolve(); }; window.addEventListener("popstate", this.__popstateListener); } } function destroy() { this.routes = routes = []; if (isPushStateAvailable) { window.removeEventListener("popstate", this.__popstateListener); } this.destroyed = destroyed = true; } function notFound(handler, hooks) { notFoundRoute = createRoute("/", handler, hooks || genericHooks, "__NOT_FOUND__"); return this; } function updatePageLinks() { if (!isWindowAvailable) return; findLinks().forEach(function (link) { if (!link.hasListenerAttached) { link.addEventListener("click", function (e) { if ((e.ctrlKey || e.metaKey) && e.target.tagName.toLowerCase() === "a") { return false; } var location = link.getAttribute("href"); var options = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseNavigateToOptions)(link.getAttribute("data-navigo-options")); if (!destroyed) { e.preventDefault(); self.navigate((0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(location), options); } }); link.hasListenerAttached = true; } }); return this; } function findLinks() { if (isWindowAvailable) { return [].slice.call(document.querySelectorAll("[data-navigo]")); } return []; } function link(path) { return "/" + root + "/" + (0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path); } function setGenericHooks(hooks) { genericHooks = hooks; return this; } function lastResolved() { return current; } function generate(name, data) { var result = routes.reduce(function (result, route) { var key; if (route.name === name) { result = route.path; for (key in data) { result = result.replace(":" + key, data[key]); } } return result; }, ""); return !result.match(/^\//) ? "/" + result : result; } function getLinkPath(link) { return link.getAttribute("href"); } function pathToMatchObject(path) { var _extractGETParameters2 = (0,_utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters)((0,_utils__WEBPACK_IMPORTED_MODULE_0__.clean)(path)), url = _extractGETParameters2[0], queryString = _extractGETParameters2[1]; var params = queryString === "" ? null : (0,_utils__WEBPACK_IMPORTED_MODULE_0__.parseQuery)(queryString); var route = createRoute(url, function () {}, genericHooks, url); return { url: url, queryString: queryString, route: route, data: null, params: params }; } this.root = root; this.routes = routes; this.destroyed = destroyed; this.current = current; this.on = on; this.off = off; this.resolve = resolve; this.navigate = navigate; this.destroy = destroy; this.notFound = notFound; this.updatePageLinks = updatePageLinks; this.link = link; this.hooks = setGenericHooks; this.extractGETParameters = _utils__WEBPACK_IMPORTED_MODULE_0__.extractGETParameters; this.lastResolved = lastResolved; this.generate = generate; this.getLinkPath = getLinkPath; this._pathToMatchObject = pathToMatchObject; this._matchRoute = _utils__WEBPACK_IMPORTED_MODULE_0__.matchRoute; this._clean = _utils__WEBPACK_IMPORTED_MODULE_0__.clean; listen.call(this); updatePageLinks.call(this); } /***/ }), /***/ "./src/utils.ts": /*!**********************!*\ !*** ./src/utils.ts ***! \**********************/ /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { __webpack_require__.r(__webpack_exports__); /* harmony export */ __webpack_require__.d(__webpack_exports__, { /* harmony export */ "clean": () => /* binding */ clean, /* harmony export */ "isString": () => /* binding */ isString, /* harmony export */ "isFunction": () => /* binding */ isFunction, /* harmony export */ "regExpResultToParams": () => /* binding */ regExpResultToParams, /* harmony export */ "extractGETParameters": () => /* binding */ extractGETParameters, /* harmony export */ "parseQuery": () => /* binding */ parseQuery, /* harmony export */ "matchRoute": () => /* binding */ matchRoute, /* harmony export */ "pushStateAvailable": () => /* binding */ pushStateAvailable, /* harmony export */ "undefinedOrTrue": () => /* binding */ undefinedOrTrue, /* harmony export */ "parseNavigateToOptions": () => /* binding */ parseNavigateToOptions /* harmony export */ }); /* harmony import */ var _constants__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./constants */ "./src/constants.ts"); function clean(s) { return s.split("#")[0].replace(/\/+$/, "").replace(/^\/+/, ""); } function isString(s) { return typeof s === "string"; } function isFunction(s) { return typeof s === "function"; } function regExpResultToParams(match, names) { if (names.length === 0) return null; if (!match) return null; return match.slice(1, match.length).reduce(function (params, value, index) { if (params === null) params = {}; params[names[index]] = decodeURIComponent(value); return params; }, null); } function extractGETParameters(url) { var tmp = clean(url).split(/\?(.*)?$/); return [clean(tmp[0]), tmp.slice(1).join("")]; } function parseQuery(queryString) { var query = {}; var pairs = queryString.split("&"); for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split("="); if (pair[0] !== "") { var key = decodeURIComponent(pair[0]); if (!query[key]) { query[key] = decodeURIComponent(pair[1] || ""); } else { if (!Array.isArray(query[key])) query[key] = [query[key]]; query[key].push(decodeURIComponent(pair[1] || "")); } } } return query; } function matchRoute(currentPath, route) { var _extractGETParameters = extractGETParameters(clean(currentPath)), current = _extractGETParameters[0], GETParams = _extractGETParameters[1]; var params = GETParams === "" ? null : parseQuery(GETParams); var paramNames = []; var pattern; if (isString(route.path)) { pattern = _constants__WEBPACK_IMPORTED_MODULE_0__.START_BY_SLASH_REGEXP + clean(route.path).replace(_constants__WEBPACK_IMPORTED_MODULE_0__.PARAMETER_REGEXP, function (full, dots, name) { paramNames.push(name); return _constants__WEBPACK_IMPORTED_MODULE_0__.REPLACE_VARIABLE_REGEXP; }).replace(_constants__WEBPACK_IMPORTED_MODULE_0__.WILDCARD_REGEXP, _constants__WEBPACK_IMPORTED_MODULE_0__.REPLACE_WILDCARD) + "$"; if (clean(route.path) === "") { if (clean(current) === "") { return { url: current, queryString: GETParams, route: route, data: null, params: params }; } } } else { pattern = route.path; } var regexp = new RegExp(pattern, _constants__WEBPACK_IMPORTED_MODULE_0__.MATCH_REGEXP_FLAGS); var match = current.match(regexp); if (match) { var data = isString(route.path) ? regExpResultToParams(match, paramNames) : match.slice(1); return { url: current, queryString: GETParams, route: route, data: data, params: params }; } return false; } function pushStateAvailable() { return !!(typeof window !== "undefined" && window.history && window.history.pushState); } function undefinedOrTrue(obj, key) { return typeof obj[key] === "undefined" || obj[key] === true; } function parseNavigateToOptions(source) { if (!source) return {}; var pairs = source.split(","); var options = {}; pairs.forEach(function (str) { var temp = str.split(":").map(function (v) { return v.replace(/(^ +| +$)/g, ""); }); switch (temp[0]) { case "historyAPIMethod": options.historyAPIMethod = temp[1]; break; case "updateBrowserURL": case "callHandler": case "updateState": case "force": options[temp[0]] = temp[1] === "true"; break; } }); return options; } /***/ }) /******/ }); /************************************************************************/ /******/ // The module cache /******/ var __webpack_module_cache__ = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(__webpack_module_cache__[moduleId]) { /******/ return __webpack_module_cache__[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__); /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /************************************************************************/ /******/ /* webpack/runtime/define property getters */ /******/ (() => { /******/ // define getter functions for harmony exports /******/ __webpack_require__.d = (exports, definition) => { /******/ for(var key in definition) { /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) { /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); /******/ } /******/ } /******/ }; /******/ })(); /******/ /******/ /* webpack/runtime/hasOwnProperty shorthand */ /******/ (() => { /******/ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop) /******/ })(); /******/ /******/ /* webpack/runtime/make namespace object */ /******/ (() => { /******/ // define __esModule on exports /******/ __webpack_require__.r = (exports) => { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ })(); /******/ /************************************************************************/ /******/ // module exports must be returned from runtime so entry inlining is disabled /******/ // startup /******/ // Load entry module and return exports /******/ return __webpack_require__("./src/index.ts"); /******/ })() .default);; //# sourceMappingURL=Navigo.amd.js.map
'use strict'; module.exports = function(app, passport, express) { let homeController = require('../controllers/home-controller')(); let homeRouter = new express.Router(); homeRouter .get('/', homeController.home) .post('/api/contact', homeController.sendEmail); app.use(homeRouter); };
/** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file San 主文件 */ (function (root) { // 人工调整打包代码顺序,通过注释手工写一些依赖 // // require('./util/guid'); // // require('./util/empty'); // // require('./util/extend'); // // require('./util/inherits'); // // require('./util/each'); // // require('./util/contains'); // // require('./util/bind'); // // require('./browser/on'); // // require('./browser/un'); // // require('./browser/svg-tags'); // // require('./browser/create-el'); // // require('./browser/remove-el'); // // require('./util/next-tick'); // // require('./browser/ie'); // // require('./browser/ie-old-than-9'); // // require('./browser/input-event-compatible'); // // require('./browser/auto-close-tags'); // // require('./util/data-types.js'); // // require('./util/create-data-types-checker.js'); // // require('./parser/walker'); // // require('./parser/parse-template'); // // require('./runtime/change-expr-compare'); // // require('./runtime/data-change-type'); // // require('./runtime/default-filters'); // // require('./view/life-cycle'); // // require('./view/node-type'); // // require('./view/get-prop-handler'); // // require('./view/is-data-change-by-element'); // // require('./view/get-event-listener'); // // require('./view/create-node'); /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 唯一id */ /** * 获取唯一id * * @type {number} 唯一id */ var guid = 1; // exports = module.exports = guid; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 空函数 */ /** * 啥都不干 */ function empty() {} // exports = module.exports = empty; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 属性拷贝 */ /** * 对象属性拷贝 * * @param {Object} target 目标对象 * @param {Object} source 源对象 * @return {Object} 返回目标对象 */ function extend(target, source) { for (var key in source) { /* istanbul ignore else */ if (source.hasOwnProperty(key)) { var value = source[key]; if (typeof value !== 'undefined') { target[key] = value; } } } return target; } // exports = module.exports = extend; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 构建类之间的继承关系 */ // var extend = require('./extend'); /** * 构建类之间的继承关系 * * @param {Function} subClass 子类函数 * @param {Function} superClass 父类函数 */ function inherits(subClass, superClass) { /* jshint -W054 */ var subClassProto = subClass.prototype; var F = new Function(); F.prototype = superClass.prototype; subClass.prototype = new F(); subClass.prototype.constructor = subClass; extend(subClass.prototype, subClassProto); /* jshint +W054 */ } // exports = module.exports = inherits; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 遍历数组 */ /** * 遍历数组集合 * * @param {Array} array 数组源 * @param {function(Any,number):boolean} iterator 遍历函数 */ function each(array, iterator) { if (array && array.length > 0) { for (var i = 0, l = array.length; i < l; i++) { if (iterator(array[i], i) === false) { break; } } } } // exports = module.exports = each; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 判断数组中是否包含某项 */ // var each = require('./each'); /** * 判断数组中是否包含某项 * * @param {Array} array 数组 * @param {*} value 包含的项 * @return {boolean} */ function contains(array, value) { var result = false; each(array, function (item) { result = item === value; return !result; }); return result; } // exports = module.exports = contains; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file bind函数 */ /** * Function.prototype.bind 方法的兼容性封装 * * @param {Function} func 要bind的函数 * @param {Object} thisArg this指向对象 * @param {...*} args 预设的初始参数 * @return {Function} */ function bind(func, thisArg) { var nativeBind = Function.prototype.bind; var slice = Array.prototype.slice; // #[begin] allua if (nativeBind && func.bind === nativeBind) { // #[end] return nativeBind.apply(func, slice.call(arguments, 1)); // #[begin] allua } /* istanbul ignore next */ var args = slice.call(arguments, 2); /* istanbul ignore next */ return function () { return func.apply(thisArg, args.concat(slice.call(arguments))); }; // #[end] } // exports = module.exports = bind; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file DOM 事件挂载 */ /** * DOM 事件挂载 * * @inner * @param {HTMLElement} el DOM元素 * @param {string} eventName 事件名 * @param {Function} listener 监听函数 * @param {boolean} capture 是否是捕获阶段 */ function on(el, eventName, listener, capture) { // #[begin] allua /* istanbul ignore else */ if (el.addEventListener) { // #[end] el.addEventListener(eventName, listener, capture); // #[begin] allua } else { el.attachEvent('on' + eventName, listener); } // #[end] } // exports = module.exports = on; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file DOM 事件卸载 */ /** * DOM 事件卸载 * * @inner * @param {HTMLElement} el DOM元素 * @param {string} eventName 事件名 * @param {Function} listener 监听函数 * @param {boolean} capture 是否是捕获阶段 */ function un(el, eventName, listener, capture) { // #[begin] allua /* istanbul ignore else */ if (el.addEventListener) { // #[end] el.removeEventListener(eventName, listener, capture); // #[begin] allua } else { el.detachEvent('on' + eventName, listener); } // #[end] } // exports = module.exports = un; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 将字符串逗号切分返回对象 */ // var each = require('../util/each'); /** * 将字符串逗号切分返回对象 * * @param {string} source 源字符串 * @return {Object} */ function splitStr2Obj(source) { var result = {}; each( source.split(','), function (key) { result[key] = key; } ); return result; } // exports = module.exports = splitStr2Obj; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file SVG标签表 */ // var splitStr2Obj = require('../util/split-str-2-obj'); /** * svgTags * * @see https://www.w3.org/TR/SVG/svgdtd.html 只取常用 * @type {Object} */ var svgTags = splitStr2Obj('' // Animation elements + 'animate,animateMotion,animateTransform,' // Basic shapes + 'circle,ellipse,line,polygon,polyline,rect,' // Container elements + 'defs,g,marker,mask,missing-glyph,pattern,svg,symbol,' // Descriptive elements + 'desc,metadata,' // Font elements + 'font,font-face,' // Gradient elements + 'linearGradient,radialGradient,stop,' // Graphics elements + 'image,path,use,' // Text elements + 'glyph,textPath,text,tref,tspan,' // Others + 'clipPath,cursor,filter,foreignObject,view' ); // exports = module.exports = svgTags; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file DOM创建 */ // var svgTags = require('./svg-tags'); /** * 创建 DOM 元素 * * @param {string} tagName tagName * @return {HTMLElement} */ function createEl(tagName) { if (svgTags[tagName] && document.createElementNS) { return document.createElementNS('http://www.w3.org/2000/svg', tagName); } return document.createElement(tagName); } // exports = module.exports = createEl; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 移除DOM */ /** * 将 DOM 从页面中移除 * * @param {HTMLElement} el DOM元素 */ function removeEl(el) { if (el && el.parentNode) { el.parentNode.removeChild(el); } } // exports = module.exports = removeEl; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 在下一个时间周期运行任务 */ // 该方法参照了vue2.5.0的实现,感谢vue团队 // SEE: https://github.com/vuejs/vue/blob/0948d999f2fddf9f90991956493f976273c5da1f/src/core/util/env.js#L68 // var bind = require('./bind'); /** * 下一个周期要执行的任务列表 * * @inner * @type {Array} */ var nextTasks = []; /** * 执行下一个周期任务的函数 * * @inner * @type {Function} */ var nextHandler; /** * 浏览器是否支持原生Promise * 对Promise做判断,是为了禁用一些不严谨的Promise的polyfill * * @inner * @type {boolean} */ var isNativePromise = typeof Promise === 'function' && /native code/.test(Promise); /** * 浏览器是否支持原生setImmediate * * @inner * @type {boolean} */ var isNativeSetImmediate = typeof setImmediate === 'function' && /native code/.test(setImmediate); /** * 在下一个时间周期运行任务 * * @inner * @param {Function} fn 要运行的任务函数 * @param {Object=} thisArg this指向对象 */ function nextTick(fn, thisArg) { if (thisArg) { fn = bind(fn, thisArg); } nextTasks.push(fn); if (nextHandler) { return; } nextHandler = function () { var tasks = nextTasks.slice(0); nextTasks = []; nextHandler = null; for (var i = 0, l = tasks.length; i < l; i++) { tasks[i](); } }; // 非标准方法,但是此方法非常吻合要求。 /* istanbul ignore next */ if (isNativeSetImmediate) { setImmediate(nextHandler); } // 用MessageChannel去做setImmediate的polyfill // 原理是将新的message事件加入到原有的dom events之后 else if (typeof MessageChannel === 'function') { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = nextHandler; port.postMessage(1); } // for native app else if (isNativePromise) { Promise.resolve().then(nextHandler); } else { setTimeout(nextHandler, 0); } } // exports = module.exports = nextTick; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file ie版本号 */ // #[begin] allua /** * 从userAgent中ie版本号的匹配信息 * * @type {Array} */ var ieVersionMatch = typeof navigator !== 'undefined' && navigator.userAgent.match(/(msie|trident)(\s*|\/)([0-9]+)/i); /** * ie版本号,非ie时为0 * * @type {number} */ var ie = ieVersionMatch ? /* istanbul ignore next */ ieVersionMatch[3] - 0 : 0; if (ie && !/msie/i.test(ieVersionMatch[1])) { ie += 4; } // #[end] // exports = module.exports = ie; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 是否 IE 并且小于 9 */ // var ie = require('./ie'); // HACK: // 1. IE8下,设置innerHTML时如果以html comment开头,comment会被自动滤掉 // 为了保证stump存在,需要设置完html后,createComment并appendChild/insertBefore // 2. IE8下,innerHTML还不支持custom element,所以需要用div替代,不用createElement // 3. 虽然IE8已经优化了字符串+连接,碎片化连接性能不再退化 // 但是由于上面多个兼容场景都用 < 9 判断,所以字符串连接也沿用 // 所以结果是IE8下字符串连接用的是数组join的方式 // #[begin] allua /** * 是否 IE 并且小于 9 */ var ieOldThan9 = ie && /* istanbul ignore next */ ie < 9; // #[end] // exports = module.exports = ieOldThan9; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 触发元素事件 */ /** * 触发元素事件 * * @inner * @param {HTMLElement} el DOM元素 * @param {string} eventName 事件名 */ function trigger(el, eventName) { var event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, true); el.dispatchEvent(event); } // exports = module.exports = trigger; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解决 IE9 在表单元素中删除字符时不触发事件的问题 */ // var ie = require('./ie'); // var on = require('./on'); // var trigger = require('./trigger'); // #[begin] allua /* istanbul ignore if */ if (ie === 9) { on(document, 'selectionchange', function () { var el = document.activeElement; if (el.tagName === 'TEXTAREA' || el.tagName === 'INPUT') { trigger(el, 'input'); } }); } // #[end] /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 自闭合标签表 */ // var splitStr2Obj = require('../util/split-str-2-obj'); /** * 自闭合标签列表 * * @type {Object} */ var autoCloseTags = splitStr2Obj('area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr'); // exports = module.exports = autoCloseTags; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file data types */ // var bind = require('./bind'); // var empty = require('./empty'); // var extend = require('./extend'); // #[begin] error var ANONYMOUS_CLASS_NAME = '<<anonymous>>'; /** * 获取精确的类型 * * @NOTE 如果 obj 是一个 DOMElement,我们会返回 `element`; * * @param {*} obj 目标 * @return {string} */ function getDataType(obj) { // 不支持element了。data应该是纯数据 // if (obj && obj.nodeType === 1) { // return 'element'; // } return Object.prototype.toString .call(obj) .slice(8, -1) .toLowerCase(); } // #[end] /** * 创建链式的数据类型校验器 * * @param {Function} validate 真正的校验器 * @return {Function} */ function createChainableChecker(validate) { /* istanbul ignore next */ var chainedChecker = function () {}; chainedChecker.isRequired = empty; // 只在 error 功能启用时才有实际上的 dataTypes 检测 // #[begin] error validate = validate || empty; var checkType = function (isRequired, data, dataName, componentName, fullDataName) { var dataValue = data[dataName]; var dataType = getDataType(dataValue); /* istanbul ignore next */ componentName = componentName || ANONYMOUS_CLASS_NAME; // 如果是 null 或 undefined,那么要提前返回啦 if (dataValue == null) { // 是 required 就报错 if (isRequired) { throw new Error('[SAN ERROR] ' + 'The `' + dataName + '` ' + 'is marked as required in `' + componentName + '`, ' + 'but its value is ' + dataType ); } // 不是 required,那就是 ok 的 return; } validate(data, dataName, componentName, fullDataName); }; chainedChecker = bind(checkType, null, false); chainedChecker.isRequired = bind(checkType, null, true); // #[end] return chainedChecker; } // #[begin] error /** * 生成主要类型数据校验器 * * @param {string} type 主类型 * @return {Function} */ function createPrimaryTypeChecker(type) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { var dataValue = data[dataName]; var dataType = getDataType(dataValue); if (dataType !== type) { throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type' + '(' + dataType + ' supplied to ' + componentName + ', ' + 'expected ' + type + ')' ); } }); } /** * 生成 arrayOf 校验器 * * @param {Function} arrayItemChecker 数组中每项数据的校验器 * @return {Function} */ function createArrayOfChecker(arrayItemChecker) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { if (typeof arrayItemChecker !== 'function') { throw new Error('[SAN ERROR] ' + 'Data `' + dataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `arrayOf`, expected `function`' ); } var dataValue = data[dataName]; var dataType = getDataType(dataValue); if (dataType !== 'array') { throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type' + '(' + dataType + ' supplied to ' + componentName + ', ' + 'expected array)' ); } for (var i = 0, len = dataValue.length; i < len; i++) { arrayItemChecker(dataValue, i, componentName, fullDataName + '[' + i + ']'); } }); } /** * 生成 instanceOf 检测器 * * @param {Function|Class} expectedClass 期待的类 * @return {Function} */ function createInstanceOfChecker(expectedClass) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { var dataValue = data[dataName]; if (dataValue instanceof expectedClass) { return; } var dataValueClassName = dataValue.constructor && dataValue.constructor.name ? dataValue.constructor.name : /* istanbul ignore next */ ANONYMOUS_CLASS_NAME; /* istanbul ignore next */ var expectedClassName = expectedClass.name || ANONYMOUS_CLASS_NAME; throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type' + '(' + dataValueClassName + ' supplied to ' + componentName + ', ' + 'expected instance of ' + expectedClassName + ')' ); }); } /** * 生成 shape 校验器 * * @param {Object} shapeTypes shape 校验规则 * @return {Function} */ function createShapeChecker(shapeTypes) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { if (getDataType(shapeTypes) !== 'object') { throw new Error('[SAN ERROR] ' + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `shape`, expected `object`' ); } var dataValue = data[dataName]; var dataType = getDataType(dataValue); if (dataType !== 'object') { throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + fullDataName + '` of type' + '(' + dataType + ' supplied to ' + componentName + ', ' + 'expected object)' ); } for (var shapeKeyName in shapeTypes) { /* istanbul ignore else */ if (shapeTypes.hasOwnProperty(shapeKeyName)) { var checker = shapeTypes[shapeKeyName]; if (typeof checker === 'function') { checker(dataValue, shapeKeyName, componentName, fullDataName + '.' + shapeKeyName); } } } }); } /** * 生成 oneOf 校验器 * * @param {Array} expectedEnumValues 期待的枚举值 * @return {Function} */ function createOneOfChecker(expectedEnumValues) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { if (getDataType(expectedEnumValues) !== 'array') { throw new Error('[SAN ERROR] ' + 'Data `' + fullDataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `oneOf`, array is expected.' ); } var dataValue = data[dataName]; for (var i = 0, len = expectedEnumValues.length; i < len; i++) { if (dataValue === expectedEnumValues[i]) { return; } } throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + fullDataName + '` of value' + '(`' + dataValue + '` supplied to ' + componentName + ', ' + 'expected one of ' + expectedEnumValues.join(',') + ')' ); }); } /** * 生成 oneOfType 校验器 * * @param {Array<Function>} expectedEnumOfTypeValues 期待的枚举类型 * @return {Function} */ function createOneOfTypeChecker(expectedEnumOfTypeValues) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { if (getDataType(expectedEnumOfTypeValues) !== 'array') { throw new Error('[SAN ERROR] ' + 'Data `' + dataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `oneOf`, array is expected.' ); } var dataValue = data[dataName]; for (var i = 0, len = expectedEnumOfTypeValues.length; i < len; i++) { var checker = expectedEnumOfTypeValues[i]; if (typeof checker !== 'function') { continue; } try { checker(data, dataName, componentName, fullDataName); // 如果 checker 完成校验没报错,那就返回了 return; } catch (e) { // 如果有错误,那么应该把错误吞掉 } } // 所有的可接受 type 都失败了,才丢一个异常 throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + dataName + '` of value' + '(`' + dataValue + '` supplied to ' + componentName + ')' ); }); } /** * 生成 objectOf 校验器 * * @param {Function} typeChecker 对象属性值校验器 * @return {Function} */ function createObjectOfChecker(typeChecker) { return createChainableChecker(function (data, dataName, componentName, fullDataName) { if (typeof typeChecker !== 'function') { throw new Error('[SAN ERROR] ' + 'Data `' + dataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `objectOf`, expected function' ); } var dataValue = data[dataName]; var dataType = getDataType(dataValue); if (dataType !== 'object') { throw new Error('[SAN ERROR] ' + 'Invalid ' + componentName + ' data `' + dataName + '` of type' + '(' + dataType + ' supplied to ' + componentName + ', ' + 'expected object)' ); } for (var dataKeyName in dataValue) { /* istanbul ignore else */ if (dataValue.hasOwnProperty(dataKeyName)) { typeChecker( dataValue, dataKeyName, componentName, fullDataName + '.' + dataKeyName ); } } }); } /** * 生成 exact 校验器 * * @param {Object} shapeTypes object 形态定义 * @return {Function} */ function createExactChecker(shapeTypes) { return createChainableChecker(function (data, dataName, componentName, fullDataName, secret) { if (getDataType(shapeTypes) !== 'object') { throw new Error('[SAN ERROR] ' + 'Data `' + dataName + '` of `' + componentName + '` has invalid ' + 'DataType notation inside `exact`' ); } var dataValue = data[dataName]; var dataValueType = getDataType(dataValue); if (dataValueType !== 'object') { throw new Error('[SAN ERROR] ' + 'Invalid data `' + fullDataName + '` of type `' + dataValueType + '`' + '(supplied to ' + componentName + ', expected `object`)' ); } var allKeys = {}; // 先合入 shapeTypes extend(allKeys, shapeTypes); // 再合入 dataValue extend(allKeys, dataValue); // 保证 allKeys 的类型正确 for (var key in allKeys) { /* istanbul ignore else */ if (allKeys.hasOwnProperty(key)) { var checker = shapeTypes[key]; // dataValue 中有一个多余的数据项 if (!checker) { throw new Error('[SAN ERROR] ' + 'Invalid data `' + fullDataName + '` key `' + key + '` ' + 'supplied to `' + componentName + '`. ' + '(`' + key + '` is not defined in `DataTypes.exact`)' ); } if (!(key in dataValue)) { throw new Error('[SAN ERROR] ' + 'Invalid data `' + fullDataName + '` key `' + key + '` ' + 'supplied to `' + componentName + '`. ' + '(`' + key + '` is marked `required` in `DataTypes.exact`)' ); } checker( dataValue, key, componentName, fullDataName + '.' + key, secret ); } } }); } // #[end] /* eslint-disable fecs-valid-var-jsdoc */ var DataTypes = { array: createChainableChecker(), object: createChainableChecker(), func: createChainableChecker(), string: createChainableChecker(), number: createChainableChecker(), bool: createChainableChecker(), symbol: createChainableChecker(), any: createChainableChecker, arrayOf: createChainableChecker, instanceOf: createChainableChecker, shape: createChainableChecker, oneOf: createChainableChecker, oneOfType: createChainableChecker, objectOf: createChainableChecker, exact: createChainableChecker }; // #[begin] error DataTypes = { any: createChainableChecker(), // 类型检测 array: createPrimaryTypeChecker('array'), object: createPrimaryTypeChecker('object'), func: createPrimaryTypeChecker('function'), string: createPrimaryTypeChecker('string'), number: createPrimaryTypeChecker('number'), bool: createPrimaryTypeChecker('boolean'), symbol: createPrimaryTypeChecker('symbol'), // 复合类型检测 arrayOf: createArrayOfChecker, instanceOf: createInstanceOfChecker, shape: createShapeChecker, oneOf: createOneOfChecker, oneOfType: createOneOfTypeChecker, objectOf: createObjectOfChecker, exact: createExactChecker }; /* eslint-enable fecs-valid-var-jsdoc */ // #[end] // module.exports = DataTypes; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 创建数据检测函数 */ // #[begin] error /** * 创建数据检测函数 * * @param {Object} dataTypes 数据格式 * @param {string} componentName 组件名 * @return {Function} */ function createDataTypesChecker(dataTypes, componentName) { /** * 校验 data 是否满足 data types 的格式 * * @param {*} data 数据 */ return function (data) { for (var dataTypeName in dataTypes) { /* istanbul ignore else */ if (dataTypes.hasOwnProperty(dataTypeName)) { var dataTypeChecker = dataTypes[dataTypeName]; if (typeof dataTypeChecker !== 'function') { throw new Error('[SAN ERROR] ' + componentName + ':' + dataTypeName + ' is invalid; ' + 'it must be a function, usually from san.DataTypes' ); } dataTypeChecker( data, dataTypeName, componentName, dataTypeName ); } } }; } // #[end] // module.exports = createDataTypesChecker; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 字符串源码读取类 */ /** * 字符串源码读取类,用于模板字符串解析过程 * * @class * @param {string} source 要读取的字符串 */ function Walker(source) { this.source = source; this.len = this.source.length; this.index = 0; } /** * 读取下一个字符,返回下一个字符的 code * * @return {number} */ Walker.prototype.nextCode = function () { this.index++; return this.source.charCodeAt(this.index); }; /** * 向前读取字符,直到遇到指定字符再停止 * 未指定字符时,当遇到第一个非空格、制表符的字符停止 * * @param {number=} charCode 指定字符的code * @return {boolean} 当指定字符时,返回是否碰到指定的字符 */ Walker.prototype.goUntil = function (charCode) { var code; while (this.index < this.len && (code = this.source.charCodeAt(this.index))) { switch (code) { case 32: // 空格 space case 9: // 制表符 tab case 13: // \r case 10: // \n this.index++; break; default: if (code === charCode) { this.index++; return 1; } return; } } }; /** * 向前读取符合规则的字符片段,并返回规则匹配结果 * * @param {RegExp} reg 字符片段的正则表达式 * @param {boolean} isMatchStart 是否必须匹配当前位置 * @return {Array?} */ Walker.prototype.match = function (reg, isMatchStart) { reg.lastIndex = this.index; var match = reg.exec(this.source); if (match && (!isMatchStart || this.index === match.index)) { this.index = reg.lastIndex; return match; } }; // exports = module.exports = Walker; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 表达式类型 */ /** * 表达式类型 * * @const * @type {Object} */ var ExprType = { STRING: 1, NUMBER: 2, BOOL: 3, ACCESSOR: 4, INTERP: 5, CALL: 6, TEXT: 7, BINARY: 8, UNARY: 9, TERTIARY: 10, OBJECT: 11, ARRAY: 12, NULL: 13 }; // exports = module.exports = ExprType; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 把 kebab case 字符串转换成 camel case */ /** * 把 kebab case 字符串转换成 camel case * * @param {string} source 源字符串 * @return {string} */ function kebab2camel(source) { return source.replace(/-+(.)/ig, function (match, alpha) { return alpha.toUpperCase(); }); } // exports = module.exports = kebab2camel; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file bool属性表 */ // var splitStr2Obj = require('../util/split-str-2-obj'); /** * bool属性表 * * @type {Object} */ var boolAttrs = splitStr2Obj( 'allowpaymentrequest,async,autofocus,autoplay,' + 'checked,controls,default,defer,disabled,formnovalidate,' + 'hidden,ismap,itemscope,loop,multiple,muted,nomodule,novalidate,' + 'open,readonly,required,reversed,selected,typemustmatch' ); // exports = module.exports = boolAttrs; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取字符串 */ // var ExprType = require('./expr-type'); /** * 读取字符串 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readString(walker) { var startCode = walker.source.charCodeAt(walker.index); var value = ""; var charCode; walkLoop: while ((charCode = walker.nextCode())) { switch (charCode) { case 92: // \ charCode = walker.nextCode(); switch (charCode) { case 117: // \u value += String.fromCharCode(parseInt( walker.source.slice(walker.index + 1, walker.index + 5), 16 )); walker.index += 4; break; case 120: // \x value += String.fromCharCode(parseInt( walker.source.slice(walker.index + 1, walker.index + 3), 16 )); walker.index += 2; break; case 98: value += '\b'; break; case 102: value += '\f'; break; case 110: value += '\n'; break; case 114: value += '\r'; break; case 116: value += '\t'; break; case 118: value += '\v'; break; default: value += String.fromCharCode(charCode); } break; case startCode: walker.index++; break walkLoop; default: value += String.fromCharCode(charCode); } } return { type: 1, // 处理字符转义 value: value }; } // exports = module.exports = readString; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取ident */ /** * 读取ident * 这里的 ident 指标识符(identifier),也就是通常意义上的变量名 * 这里默认的变量名规则为:由美元符号($)、数字、字母或者下划线(_)构成的字符串 * * @inner * @param {Walker} walker 源码读取对象 * @return {string} */ function readIdent(walker) { var match = walker.match(/\s*([\$0-9a-z_]+)/ig, 1); // #[begin] error if (!match) { throw new Error('[SAN FATAL] expect an ident: ' + walker.source.slice(walker.index)); } // #[end] return match[1]; } // exports = module.exports = readIdent; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取三元表达式 */ // var ExprType = require('./expr-type'); // var readLogicalORExpr = require('./read-logical-or-expr'); /** * 读取三元表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readTertiaryExpr(walker) { var conditional = readLogicalORExpr(walker); walker.goUntil(); if (walker.source.charCodeAt(walker.index) === 63) { // ? walker.index++; var yesExpr = readTertiaryExpr(walker); walker.goUntil(); if (walker.source.charCodeAt(walker.index) === 58) { // : walker.index++; return { type: 10, segs: [ conditional, yesExpr, readTertiaryExpr(walker) ] }; } } return conditional; } // exports = module.exports = readTertiaryExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取访问表达式 */ // var ExprType = require('./expr-type'); // var readIdent = require('./read-ident'); // var readTertiaryExpr = require('./read-tertiary-expr'); /** * 读取访问表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readAccessor(walker) { var firstSeg = readIdent(walker); switch (firstSeg) { case 'true': case 'false': return { type: 3, value: firstSeg === 'true' }; case 'null': return { type: 13 }; } var result = { type: 4, paths: [ {type: 1, value: firstSeg} ] }; /* eslint-disable no-constant-condition */ accessorLoop: while (1) { /* eslint-enable no-constant-condition */ switch (walker.source.charCodeAt(walker.index)) { case 46: // . walker.index++; // ident as string result.paths.push({ type: 1, value: readIdent(walker) }); break; case 91: // [ walker.index++; result.paths.push(readTertiaryExpr(walker)); walker.goUntil(93); // ] break; default: break accessorLoop; } } return result; } // exports = module.exports = readAccessor; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取调用 */ // var ExprType = require('./expr-type'); // var readAccessor = require('./read-accessor'); // var readTertiaryExpr = require('./read-tertiary-expr'); /** * 读取调用 * * @param {Walker} walker 源码读取对象 * @param {Array=} defaultArgs 默认参数 * @return {Object} */ function readCall(walker, defaultArgs) { walker.goUntil(); var result = readAccessor(walker); var args; if (walker.goUntil(40)) { // ( args = []; while (!walker.goUntil(41)) { // ) args.push(readTertiaryExpr(walker)); walker.goUntil(44); // , } } else if (defaultArgs) { args = defaultArgs; } if (args) { result = { type: 6, name: result, args: args }; } return result; } // exports = module.exports = readCall; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取括号表达式 */ // var readTertiaryExpr = require('./read-tertiary-expr'); /** * 读取括号表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readParenthesizedExpr(walker) { walker.index++; var expr = readTertiaryExpr(walker); walker.goUntil(41); // ) expr.parenthesized = true; return expr; } // exports = module.exports = readParenthesizedExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取一元表达式 */ // var ExprType = require('./expr-type'); // var readString = require('./read-string'); // var readCall = require('./read-call'); // var readParenthesizedExpr = require('./read-parenthesized-expr'); // var readTertiaryExpr = require('./read-tertiary-expr'); function postUnaryExpr(expr, operator) { switch (operator) { case 33: var value; switch (expr.type) { case 2: case 1: case 3: value = !expr.value; break; case 12: case 11: value = false; break; case 13: value = true; break; } if (value != null) { return { type: 3, value: value }; } break; case 43: switch (expr.type) { case 2: case 1: case 3: return { type: 2, value: +expr.value }; } break; case 45: switch (expr.type) { case 2: case 1: case 3: return { type: 2, value: -expr.value }; } break; } return { type: 9, expr: expr, operator: operator }; } /** * 读取一元表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readUnaryExpr(walker) { walker.goUntil(); var currentCode = walker.source.charCodeAt(walker.index); switch (currentCode) { case 33: // ! case 43: // + case 45: // - walker.index++; return postUnaryExpr(readUnaryExpr(walker), currentCode); case 34: // " case 39: // ' return readString(walker); case 48: // number case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return { type: 2, value: +(walker.match(/[0-9]+(\.[0-9]+)?/g, 1)[0]) }; case 40: // ( return readParenthesizedExpr(walker); // array literal case 91: // [ walker.index++; var arrItems = []; while (!walker.goUntil(93)) { // ] var item = {}; arrItems.push(item); if (walker.source.charCodeAt(walker.index) === 46 && walker.match(/\.\.\.\s*/g)) { item.spread = true; } item.expr = readTertiaryExpr(walker); walker.goUntil(44); // , } return { type: 12, items: arrItems }; // object literal case 123: // { walker.index++; var objItems = []; while (!walker.goUntil(125)) { // } var item = {}; objItems.push(item); if (walker.source.charCodeAt(walker.index) === 46 && walker.match(/\.\.\.\s*/g)) { item.spread = true; item.expr = readTertiaryExpr(walker); } else { // #[begin] error var walkerIndexBeforeName = walker.index; // #[end] item.name = readUnaryExpr(walker); // #[begin] error if (item.name.type > 4) { throw new Error( '[SAN FATAL] unexpect object name: ' + walker.source.slice(walkerIndexBeforeName, walker.index) ); } // #[end] if (walker.goUntil(58)) { // : item.expr = readTertiaryExpr(walker); } else { item.expr = item.name; } if (item.name.type === 4) { item.name = item.name.paths[0]; } } walker.goUntil(44); // , } return { type: 11, items: objItems }; } return readCall(walker); } // exports = module.exports = readUnaryExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取乘法表达式 */ // var ExprType = require('./expr-type'); // var readUnaryExpr = require('./read-unary-expr'); /** * 读取乘法表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readMultiplicativeExpr(walker) { var expr = readUnaryExpr(walker); while (1) { walker.goUntil(); var code = walker.source.charCodeAt(walker.index); switch (code) { case 37: // % case 42: // * case 47: // / walker.index++; expr = { type: 8, operator: code, segs: [expr, readUnaryExpr(walker)] }; continue; } break; } return expr; } // exports = module.exports = readMultiplicativeExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取加法表达式 */ // var ExprType = require('./expr-type'); // var readMultiplicativeExpr = require('./read-multiplicative-expr'); /** * 读取加法表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readAdditiveExpr(walker) { var expr = readMultiplicativeExpr(walker); while (1) { walker.goUntil(); var code = walker.source.charCodeAt(walker.index); switch (code) { case 43: // + case 45: // - walker.index++; expr = { type: 8, operator: code, segs: [expr, readMultiplicativeExpr(walker)] }; continue; } break; } return expr; } // exports = module.exports = readAdditiveExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取关系判断表达式 */ // var ExprType = require('./expr-type'); // var readAdditiveExpr = require('./read-additive-expr'); /** * 读取关系判断表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readRelationalExpr(walker) { var expr = readAdditiveExpr(walker); walker.goUntil(); var code = walker.source.charCodeAt(walker.index); switch (code) { case 60: // < case 62: // > if (walker.nextCode() === 61) { code += 61; walker.index++; } return { type: 8, operator: code, segs: [expr, readAdditiveExpr(walker)] }; } return expr; } // exports = module.exports = readRelationalExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取相等比对表达式 */ // var ExprType = require('./expr-type'); // var readRelationalExpr = require('./read-relational-expr'); /** * 读取相等比对表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readEqualityExpr(walker) { var expr = readRelationalExpr(walker); walker.goUntil(); var code = walker.source.charCodeAt(walker.index); switch (code) { case 61: // = case 33: // ! if (walker.nextCode() === 61) { code += 61; if (walker.nextCode() === 61) { code += 61; walker.index++; } return { type: 8, operator: code, segs: [expr, readRelationalExpr(walker)] }; } walker.index--; } return expr; } // exports = module.exports = readEqualityExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取逻辑与表达式 */ // var ExprType = require('./expr-type'); // var readEqualityExpr = require('./read-equality-expr'); /** * 读取逻辑与表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readLogicalANDExpr(walker) { var expr = readEqualityExpr(walker); walker.goUntil(); if (walker.source.charCodeAt(walker.index) === 38) { // & if (walker.nextCode() === 38) { walker.index++; return { type: 8, operator: 76, segs: [expr, readLogicalANDExpr(walker)] }; } walker.index--; } return expr; } // exports = module.exports = readLogicalANDExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 读取逻辑或表达式 */ // var ExprType = require('./expr-type'); // var readLogicalANDExpr = require('./read-logical-and-expr'); /** * 读取逻辑或表达式 * * @param {Walker} walker 源码读取对象 * @return {Object} */ function readLogicalORExpr(walker) { var expr = readLogicalANDExpr(walker); walker.goUntil(); if (walker.source.charCodeAt(walker.index) === 124) { // | if (walker.nextCode() === 124) { walker.index++; return { type: 8, operator: 248, segs: [expr, readLogicalORExpr(walker)] }; } walker.index--; } return expr; } // exports = module.exports = readLogicalORExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析表达式 */ // var Walker = require('./walker'); // var readTertiaryExpr = require('./read-tertiary-expr'); /** * 解析表达式 * * @param {string} source 源码 * @return {Object} */ function parseExpr(source) { if (!source) { return; } if (typeof source === 'object' && source.type) { return source; } return readTertiaryExpr(new Walker(source)); } // exports = module.exports = parseExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析调用 */ // var Walker = require('./walker'); // var ExprType = require('./expr-type'); // var readCall = require('./read-call'); /** * 解析调用 * * @param {string} source 源码 * @param {Array=} defaultArgs 默认参数 * @return {Object} */ function parseCall(source, defaultArgs) { var expr = readCall(new Walker(source), defaultArgs); if (expr.type !== 6) { expr = { type: 6, name: expr, args: defaultArgs || [] }; } return expr; } // exports = module.exports = parseCall; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解码 HTML 字符实体 */ var ENTITY_DECODE_MAP = { lt: '<', gt: '>', nbsp: '\u00a0', quot: '\"', emsp: '\u2003', ensp: '\u2002', thinsp: '\u2009', copy: '\xa9', reg: '\xae', zwnj: '\u200c', zwj: '\u200d', amp: '&' }; /** * 解码 HTML 字符实体 * * @param {string} source 要解码的字符串 * @return {string} */ function decodeHTMLEntity(source) { return source .replace(/&#(x[0-9a-f]+|[0-9]+);/g, function (match, code) { if (code.charCodeAt(0) === 120) { // x return String.fromCharCode(parseInt(code.slice(1), 16)); } return String.fromCharCode(+code); }) .replace(/&([a-z]+);/ig, function (match, code) { return ENTITY_DECODE_MAP[code] || match; }); } // exports = module.exports = decodeHTMLEntity; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析文本 */ // var Walker = require('./walker'); // var readTertiaryExpr = require('./read-tertiary-expr'); // var ExprType = require('./expr-type'); // var readCall = require('./read-call'); // var decodeHTMLEntity = require('../util/decode-html-entity'); /** * 解析文本 * * @param {string} source 源码 * @param {Array?} delimiters 分隔符。默认为 ['{{', '}}'] * @return {Object} */ function parseText(source, delimiters) { delimiters = delimiters || ['{{', '}}']; var walker = new Walker(source); var beforeIndex = 0; var segs = []; var segIndex = -1; var original; function pushString(value) { var current = segs[segIndex]; if (!current || current.type !== 1) { segs[++segIndex] = { type: 1, value: value }; } else { current.value = current.value + value; } } var delimStart = delimiters[0]; var delimStartLen = delimStart.length; var delimEnd = delimiters[1]; var delimEndLen = delimEnd.length; while (1) { var delimStartIndex = walker.source.indexOf(delimStart, walker.index); var delimEndIndex = walker.source.indexOf(delimEnd, walker.index); if (delimStartIndex === -1 || delimEndIndex < delimStartIndex) { break; } // pushStringToSeg var strValue = walker.source.slice( beforeIndex, delimStartIndex ); strValue && pushString(decodeHTMLEntity(strValue)); // pushInterpToSeg if (walker.source.indexOf(delimEnd, delimEndIndex + 1) === delimEndIndex + 1) { delimEndIndex++; } var interpWalker = new Walker(walker.source.slice(delimStartIndex + delimStartLen, delimEndIndex)); if (!interpWalker.goUntil(125) && interpWalker.index < interpWalker.len) { var interp = { type: 5, expr: readTertiaryExpr(interpWalker), filters: [] }; while (interpWalker.goUntil(124)) { // | var callExpr = readCall(interpWalker, []); switch (callExpr.name.paths[0].value) { case 'html': break; case 'raw': interp.original = 1; break; default: interp.filters.push(callExpr); } } original = original || interp.original; segs[++segIndex] = interp; } else { pushString(delimStart + interpWalker.source + delimEnd); } beforeIndex = walker.index = delimEndIndex + delimEndLen; } // pushStringToSeg var strValue = walker.source.slice(beforeIndex); strValue && pushString(decodeHTMLEntity(strValue)); switch (segs.length) { case 0: return { type: 1, value: '' }; case 1: if (segs[0].type === 5 && segs[0].filters.length === 0 && !segs[0].original) { return segs[0].expr; } return segs[0]; } return original ? { type: 7, segs: segs, original: 1 } : { type: 7, segs: segs }; } // exports = module.exports = parseText; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析指令 */ // var Walker = require('./walker'); // var parseExpr = require('./parse-expr'); // var parseCall = require('./parse-call'); // var parseText = require('./parse-text'); // var readAccessor = require('./read-accessor'); // var readUnaryExpr = require('./read-unary-expr'); /** * 解析指令 * * @param {string} name 指令名称 * @param {string} value 指令值 * @param {Object} options 解析参数 * @param {Array?} options.delimiters 插值分隔符列表 */ function parseDirective(name, value, options) { switch (name) { case 'is': case 'show': case 'html': case 'bind': case 'if': case 'elif': return { value: parseExpr(value.replace(/(^\{\{|\}\}$)/g, '')) }; case 'else': return { value: {} }; case 'transition': return { value: parseCall(value) }; case 'ref': return { value: parseText(value, options.delimiters) }; case 'for': var walker = new Walker(value); var match = walker.match(/^\s*([$0-9a-z_]+)(\s*,\s*([$0-9a-z_]+))?\s+in\s+/ig, 1); if (match) { var directive = { item: match[1], value: readUnaryExpr(walker) }; if (match[3]) { directive.index = match[3]; } if (walker.match(/\s*trackby\s+/ig, 1)) { var start = walker.index; directive.trackBy = readAccessor(walker); directive.trackByRaw = walker.source.slice(start, walker.index); } return directive; } // #[begin] error throw new Error('[SAN FATAL] for syntax error: ' + value); // #[end] } } // exports = module.exports = parseDirective; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析抽象节点属性 */ // var each = require('../util/each'); // var kebab2camel = require('../util/kebab2camel'); // var boolAttrs = require('../browser/bool-attrs'); // var ExprType = require('./expr-type'); // var parseExpr = require('./parse-expr'); // var parseCall = require('./parse-call'); // var parseText = require('./parse-text'); // var parseDirective = require('./parse-directive'); /** * 解析抽象节点属性 * * @param {ANode} aNode 抽象节点 * @param {string} name 属性名称 * @param {string} value 属性值 * @param {Object} options 解析参数 * @param {Array?} options.delimiters 插值分隔符列表 */ function integrateAttr(aNode, name, value, options) { var prefixIndex = name.indexOf('-'); var realName; var prefix; if (prefixIndex > 0) { prefix = name.slice(0, prefixIndex); realName = name.slice(prefixIndex + 1); } switch (prefix) { case 'on': var event = { name: realName, modifier: {} }; aNode.events.push(event); var colonIndex; while ((colonIndex = value.indexOf(':')) > 0) { var modifier = value.slice(0, colonIndex); // eventHandler("dd:aa") 这种情况不能算modifier,需要辨识 if (!/^[a-z]+$/i.test(modifier)) { break; } event.modifier[modifier] = true; value = value.slice(colonIndex + 1); } event.expr = parseCall(value, [ { type: 4, paths: [ {type: 1, value: '$event'} ] } ]); break; case 'san': case 's': if (realName === 'else-if') { realName = 'elif'; } var directiveValue = parseDirective(realName, value, options); directiveValue && (aNode.directives[realName] = directiveValue); break; case 'var': if (!aNode.vars) { aNode.vars = []; } realName = kebab2camel(realName); aNode.vars.push({ name: realName, expr: parseExpr(value.replace(/(^\{\{|\}\}$)/g, '')) }); break; default: if (prefix === 'prop') { name = realName; } // parse two way binding, e.g. value="{=ident=}" if (value && value.indexOf('{=') === 0 && value.slice(-2) === '=}') { aNode.props.push({ name: name, expr: parseExpr(value.slice(2, -2)), x: 1 }); return; } var expr = parseText(value || '', options.delimiters); if (expr.value === '') { if (boolAttrs[name]) { expr = { type: 3, value: true }; } } else { switch (name) { case 'class': case 'style': switch (expr.type) { case 7: for (var i = 0, l = expr.segs.length; i < l; i++) { if (expr.segs[i].type === 5) { expr.segs[i].filters.push({ type: 6, name: { type: 4, paths: [ {type: 1, value: '_' + name} ] }, args: [] }); } } break; case 5: expr.filters.push({ type: 6, name: { type: 4, paths: [ {type: 1, value: '_' + name} ] }, args: [] }); break; default: if (expr.type !== 1) { expr = { type: 5, expr: expr, filters: [{ type: 6, name: { type: 4, paths: [ {type: 1, value: '_' + name} ] }, args: [] }] } } } } } aNode.props.push( value != null ? {name: name, expr: expr} : {name: name, expr: expr, noValue: 1} ); } } // exports = module.exports = integrateAttr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析模板 */ // var Walker = require('./walker'); // var ExprType = require('./expr-type'); // var integrateAttr = require('./integrate-attr'); // var parseText = require('./parse-text'); // var svgTags = require('../browser/svg-tags'); // var autoCloseTags = require('../browser/auto-close-tags'); // #[begin] error function getXPath(stack, currentTagName) { var path = ['ROOT']; for (var i = 1, len = stack.length; i < len; i++) { path.push(stack[i].tagName); } if (currentTagName) { path.push(currentTagName); } return path.join('>'); } // #[end] /* eslint-disable fecs-max-statements */ /** * 解析 template * * @param {string} source template源码 * @param {Object?} options 解析参数 * @param {string?} options.trimWhitespace 空白文本的处理策略。none|blank|all * @param {Array?} options.delimiters 插值分隔符列表 * @return {ANode} */ function parseTemplate(source, options) { options = options || {}; options.trimWhitespace = options.trimWhitespace || 'none'; var rootNode = { directives: {}, props: [], events: [], children: [] }; if (typeof source !== 'string') { return rootNode; } source = source.replace(/<!--([\s\S]*?)-->/mg, ''); var walker = new Walker(source); walker.goUntil(); var tagReg = /<(\/)?([a-z][a-z0-9-]*)\s*/ig; var attrReg = /([-:0-9a-z\[\]_]+)(\s*=\s*(([^'"<>\s]+)|"([^"]*?)"|'([^']*?)'))?\s*/ig; var tagMatch; var currentNode = rootNode; var stack = [rootNode]; var stackIndex = 0; var beforeLastIndex = walker.index; while ((tagMatch = walker.match(tagReg)) != null) { var tagMatchStart = walker.index - tagMatch[0].length; var tagEnd = tagMatch[1]; var tagName = tagMatch[2]; // 62: > // 47: / // 处理 </xxxx > if (tagEnd) { if (walker.source.charCodeAt(walker.index) === 62) { // 满足关闭标签的条件时,关闭标签 // 向上查找到对应标签,找不到时忽略关闭 var closeIndex = stackIndex; // #[begin] error // 如果正在闭合一个自闭合的标签,例如 </input>,报错 if (autoCloseTags[tagName]) { throw new Error('' + '[SAN ERROR] ' + getXPath(stack, tagName) + ' is a `auto closed` tag, ' + 'so it cannot be closed with </' + tagName + '>' ); } // 如果关闭的 tag 和当前打开的不一致,报错 if ( stack[closeIndex].tagName !== tagName // 这里要把 table 自动添加 tbody 的情况给去掉 && !(tagName === 'table' && stack[closeIndex].tagName === 'tbody') ) { throw new Error('[SAN ERROR] ' + getXPath(stack) + ' is closed with ' + tagName); } // #[end] pushTextNode(source.slice(beforeLastIndex, tagMatchStart)); while (closeIndex > 0 && stack[closeIndex].tagName !== tagName) { closeIndex--; } if (closeIndex > 0) { stackIndex = closeIndex - 1; currentNode = stack[stackIndex]; } walker.index++; } // #[begin] error else { // 处理 </xxx 非正常闭合标签 // 如果闭合标签时,匹配后的下一个字符是 <,即下一个标签的开始,那么当前闭合标签未闭合 if (walker.source.charCodeAt(walker.index) === 60) { throw new Error('' + '[SAN ERROR] ' + getXPath(stack) + '\'s close tag not closed' ); } // 闭合标签有属性 throw new Error('' + '[SAN ERROR] ' + getXPath(stack) + '\'s close tag has attributes' ); } // #[end] } else { var aElement = { directives: {}, props: [], events: [], children: [], tagName: tagName }; var tagClose = autoCloseTags[tagName]; // 解析 attributes /* eslint-disable no-constant-condition */ while (1) { /* eslint-enable no-constant-condition */ var nextCharCode = walker.source.charCodeAt(walker.index); // 标签结束时跳出 attributes 读取 // 标签可能直接结束或闭合结束 if (nextCharCode === 62) { walker.index++; break; } // 遇到 /> 按闭合处理 if (nextCharCode === 47 && walker.source.charCodeAt(walker.index + 1) === 62 ) { walker.index += 2; tagClose = 1; break; } // template 串结束了 // 这时候,说明这个读取周期的所有内容,都是text if (!nextCharCode) { pushTextNode(walker.source.slice(beforeLastIndex)); aElement = null; break; } // #[begin] error // 在处理一个 open 标签时,如果遇到了 <, 即下一个标签的开始,则当前标签未能正常闭合,报错 if (nextCharCode === 60) { throw new Error('[SAN ERROR] ' + getXPath(stack, tagName) + ' is not closed'); } // #[end] // 读取 attribute var attrMatch = walker.match(attrReg, 1); if (attrMatch) { integrateAttr( aElement, attrMatch[1], attrMatch[2] ? (attrMatch[5] || attrMatch[6] || attrMatch[4] || '') : void(0), options ); } else { pushTextNode(walker.source.slice(beforeLastIndex, walker.index)); aElement = null; break; } } if (aElement) { pushTextNode(source.slice(beforeLastIndex, tagMatchStart)); // handle show directive, append expr to style prop if (aElement.directives.show) { // find style prop var styleProp = null; var propsLen = aElement.props.length; while (propsLen--) { if (aElement.props[propsLen].name === 'style') { styleProp = aElement.props[propsLen]; break; } } var showStyleExpr = { type: 10, segs: [ aElement.directives.show.value, {type: 1, value: ''}, {type: 1, value: ';display:none;'} ] }; if (styleProp) { if (styleProp.expr.type === 7) { styleProp.expr.segs.push(showStyleExpr); } else { aElement.props[propsLen].expr = { type: 7, segs: [ styleProp.expr, showStyleExpr ] }; } } else { aElement.props.push({ name: 'style', expr: showStyleExpr }); } } // match if directive for else/elif directive var elseDirective = aElement.directives['else'] // eslint-disable-line dot-notation || aElement.directives.elif; if (elseDirective) { var parentChildrenLen = currentNode.children.length; var ifANode = null; while (parentChildrenLen--) { var parentChild = currentNode.children[parentChildrenLen]; if (parentChild.textExpr) { currentNode.children.splice(parentChildrenLen, 1); continue; } ifANode = parentChild; break; } // #[begin] error if (!ifANode || !parentChild.directives['if']) { // eslint-disable-line dot-notation throw new Error('[SAN FATEL] else not match if.'); } // #[end] if (ifANode) { ifANode.elses = ifANode.elses || []; ifANode.elses.push(aElement); } } else { if (aElement.tagName === 'tr' && currentNode.tagName === 'table') { var tbodyNode = { directives: {}, props: [], events: [], children: [], tagName: 'tbody' }; currentNode.children.push(tbodyNode); currentNode = tbodyNode; stack[++stackIndex] = tbodyNode; } currentNode.children.push(aElement); } if (!tagClose) { currentNode = aElement; stack[++stackIndex] = aElement; } } } beforeLastIndex = walker.index; } pushTextNode(walker.source.slice(beforeLastIndex).replace(/^\s+$/, '')); return rootNode; /** * 在读取栈中添加文本节点 * * @inner * @param {string} text 文本内容 */ function pushTextNode(text) { switch (options.trimWhitespace) { case 'blank': if (/^\s+$/.test(text)) { text = null; } break; case 'all': text = text.replace(/(^\s+|\s+$)/g, ''); break; } if (text) { var expr = parseText(text, options.delimiters); var lastChild = currentNode.children[currentNode.children.length - 1]; var textExpr = lastChild && lastChild.textExpr; if (textExpr) { if (textExpr.segs) { textExpr.segs = textExpr.segs.concat(expr.segs || expr); } else if (textExpr.value != null && expr.value != null) { textExpr.value = textExpr.value + expr.value; } else { lastChild.textExpr = { type: 7, segs: [textExpr].concat(expr.segs || expr) }; } } else { currentNode.children.push({ textExpr: expr }); } } } } /* eslint-enable fecs-max-statements */ // exports = module.exports = parseTemplate; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 处理组件异常 */ function handleError(e, component, info) { var current = component; while (current) { if (typeof current.error === 'function') { current.error(e, component, info); return; } current = current.parentComponent } throw e; } // exports = module.exports = handleError; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 默认filter */ /* eslint-disable fecs-camelcase */ function defaultStyleFilter(source) { if (typeof source === 'object') { var result = ''; for (var key in source) { /* istanbul ignore else */ if (source.hasOwnProperty(key)) { result += key + ':' + source[key] + ';'; } } return result; } return source; } /** * 默认filter * * @const * @type {Object} */ var DEFAULT_FILTERS = { /** * URL编码filter * * @param {string} source 源串 * @return {string} 替换结果串 */ url: encodeURIComponent, _class: function (source) { if (source instanceof Array) { return source.join(' '); } return source; }, _style: defaultStyleFilter, _xclass: function (outer, inner) { if (outer instanceof Array) { outer = outer.join(' '); } if (outer) { if (inner) { return inner + ' ' + outer; } return outer; } return inner; }, _xstyle: function (outer, inner) { outer = outer && defaultStyleFilter(outer); if (outer) { if (inner) { return inner + ';' + outer; } return outer; } return inner; } }; /* eslint-enable fecs-camelcase */ // exports = module.exports = DEFAULT_FILTERS; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 表达式计算 */ // var ExprType = require('../parser/expr-type'); // var extend = require('../util/extend'); // var handleError = require('../util/handle-error'); // var DEFAULT_FILTERS = require('./default-filters'); // var evalArgs = require('./eval-args'); /** * 计算表达式的值 * * @param {Object} expr 表达式对象 * @param {Data} data 数据容器对象 * @param {Component=} owner 所属组件环境 * @return {*} */ function evalExpr(expr, data, owner) { if (expr.value != null) { return expr.value; } var value; switch (expr.type) { case 13: return null; case 9: value = evalExpr(expr.expr, data, owner); switch (expr.operator) { case 33: value = !value; break; case 43: value = +value; break; case 45: value = 0 - value; break; } return value; case 8: value = evalExpr(expr.segs[0], data, owner); var rightValue = evalExpr(expr.segs[1], data, owner); /* eslint-disable eqeqeq */ switch (expr.operator) { case 37: value = value % rightValue; break; case 43: value = value + rightValue; break; case 45: value = value - rightValue; break; case 42: value = value * rightValue; break; case 47: value = value / rightValue; break; case 60: value = value < rightValue; break; case 62: value = value > rightValue; break; case 76: value = value && rightValue; break; case 94: value = value != rightValue; break; case 121: value = value <= rightValue; break; case 122: value = value == rightValue; break; case 123: value = value >= rightValue; break; case 155: value = value !== rightValue; break; case 183: value = value === rightValue; break; case 248: value = value || rightValue; break; } /* eslint-enable eqeqeq */ return value; case 10: return evalExpr( expr.segs[evalExpr(expr.segs[0], data, owner) ? 1 : 2], data, owner ); case 12: value = []; for (var i = 0, l = expr.items.length; i < l; i++) { var item = expr.items[i]; var itemValue = evalExpr(item.expr, data, owner); if (item.spread) { itemValue && (value = value.concat(itemValue)); } else { value.push(itemValue); } } return value; case 11: value = {}; for (var i = 0, l = expr.items.length; i < l; i++) { var item = expr.items[i]; var itemValue = evalExpr(item.expr, data, owner); if (item.spread) { itemValue && extend(value, itemValue); } else { value[evalExpr(item.name, data, owner)] = itemValue; } } return value; case 4: return data.get(expr); case 5: value = evalExpr(expr.expr, data, owner); if (owner) { for (var i = 0, l = expr.filters.length; i < l; i++) { var filter = expr.filters[i]; var filterName = filter.name.paths[0].value; switch (filterName) { case 'url': case '_class': case '_style': value = DEFAULT_FILTERS[filterName](value); break; case '_xclass': case '_xstyle': value = DEFAULT_FILTERS[filterName](value, evalExpr(filter.args[0], data, owner)); break; default: try { value = owner.filters[filterName] && owner.filters[filterName].apply( owner, [value].concat(evalArgs(filter.args, data, owner)) ); } catch (e) { handleError(e, owner, 'filter:' + filterName); } } } } if (value == null) { value = ''; } return value; case 6: if (owner && expr.name.type === 4) { var method = owner; var pathsLen = expr.name.paths.length; for (var i = 0; method && i < pathsLen; i++) { method = method[evalExpr(expr.name.paths[i], data, owner)]; } if (method) { value = method.apply(owner, evalArgs(expr.args, data, owner)); } } break; /* eslint-disable no-redeclare */ case 7: var buf = ''; for (var i = 0, l = expr.segs.length; i < l; i++) { var seg = expr.segs[i]; buf += seg.value || evalExpr(seg, data, owner); } return buf; } return value; } // exports = module.exports = evalExpr; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 为函数调用计算参数数组的值 */ // var evalExpr = require('./eval-expr'); /** * 为函数调用计算参数数组的值 * * @param {Array} args 参数表达式列表 * @param {Data} data 数据环境 * @param {Component} owner 组件环境 * @return {Array} */ function evalArgs(args, data, owner) { var result = []; for (var i = 0; i < args.length; i++) { result.push(evalExpr(args[i], data, owner)); } return result; } // exports = module.exports = evalArgs; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 比较变更表达式与目标表达式之间的关系 */ // var ExprType = require('../parser/expr-type'); // var evalExpr = require('./eval-expr'); /** * 判断变更表达式与多个表达式之间的关系,0为完全没关系,1为有关系 * * @inner * @param {Object} changeExpr 目标表达式 * @param {Array} exprs 多个源表达式 * @param {Data} data 表达式所属数据环境 * @return {number} */ function changeExprCompareExprs(changeExpr, exprs, data) { for (var i = 0, l = exprs.length; i < l; i++) { if (changeExprCompare(changeExpr, exprs[i], data)) { return 1; } } return 0; } /** * 比较变更表达式与目标表达式之间的关系,用于视图更新判断 * 视图更新需要根据其关系,做出相应的更新行为 * * 0: 完全没关系 * 1: 变更表达式是目标表达式的母项(如a与a.b) 或 表示需要完全变化 * 2: 变更表达式是目标表达式相等 * >2: 变更表达式是目标表达式的子项,如a.b.c与a.b * * @param {Object} changeExpr 变更表达式 * @param {Object} expr 要比较的目标表达式 * @param {Data} data 表达式所属数据环境 * @return {number} */ function changeExprCompare(changeExpr, expr, data) { // if (!expr.dynamic) { // return 0; // } switch (expr.type) { case 4: var paths = expr.paths; var pathsLen = paths.length; var changePaths = changeExpr.paths; var changeLen = changePaths.length; var result = 1; for (var i = 0; i < pathsLen; i++) { var pathExpr = paths[i]; var pathExprValue = pathExpr.value; if (pathExprValue == null && changeExprCompare(changeExpr, pathExpr, data)) { result = 1; break; } if (result && i < changeLen /* eslint-disable eqeqeq */ && (pathExprValue || evalExpr(pathExpr, data)) != changePaths[i].value /* eslint-enable eqeqeq */ ) { result = 0; } } if (result) { result = Math.max(1, changeLen - pathsLen + 2); } return result; case 9: return changeExprCompare(changeExpr, expr.expr, data) ? 1 : 0; case 7: case 8: case 10: return changeExprCompareExprs(changeExpr, expr.segs, data); case 12: case 11: for (var i = 0; i < expr.items.length; i++) { if (changeExprCompare(changeExpr, expr.items[i].expr, data)) { return 1; } } break; case 5: if (changeExprCompare(changeExpr, expr.expr, data)) { return 1 } else { for (var i = 0; i < expr.filters.length; i++) { if (changeExprCompareExprs(changeExpr, expr.filters[i].args, data)) { return 1; } } } break; case 6: if (changeExprCompareExprs(changeExpr, expr.name.paths, data) || changeExprCompareExprs(changeExpr, expr.args, data) ) { return 1 } break; } return 0; } // exports = module.exports = changeExprCompare; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 数据变更类型枚举 */ /** * 数据变更类型枚举 * * @const * @type {Object} */ var DataChangeType = { SET: 1, SPLICE: 2 }; // exports = module.exports = DataChangeType; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 生命周期类 */ function lifeCycleOwnIs(name) { return this[name]; } /* eslint-disable fecs-valid-var-jsdoc */ /** * 节点生命周期信息 * * @inner * @type {Object} */ var LifeCycle = { start: { is: lifeCycleOwnIs }, compiled: { is: lifeCycleOwnIs, compiled: true }, inited: { is: lifeCycleOwnIs, compiled: true, inited: true }, created: { is: lifeCycleOwnIs, compiled: true, inited: true, created: true }, attached: { is: lifeCycleOwnIs, compiled: true, inited: true, created: true, attached: true }, leaving: { is: lifeCycleOwnIs, compiled: true, inited: true, created: true, attached: true, leaving: true }, detached: { is: lifeCycleOwnIs, compiled: true, inited: true, created: true, detached: true }, disposed: { is: lifeCycleOwnIs, disposed: true } }; /* eslint-enable fecs-valid-var-jsdoc */ // exports = module.exports = LifeCycle; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 节点类型 */ /** * 节点类型 * * @const * @type {Object} */ var NodeType = { TEXT: 1, IF: 2, FOR: 3, ELEM: 4, CMPT: 5, SLOT: 6, TPL: 7, LOADER: 8, IS: 9 }; // exports = module.exports = NodeType; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取 ANode props 数组中相应 name 的项 */ /** * 获取 ANode props 数组中相应 name 的项 * * @param {Object} aNode ANode对象 * @param {string} name name属性匹配串 * @return {Object} */ function getANodeProp(aNode, name) { var index = aNode._pi[name]; if (index != null) { return aNode.props[index]; } } // exports = module.exports = getANodeProp; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取属性处理对象 */ // var contains = require('../util/contains'); // var empty = require('../util/empty'); // var nextTick = require('../util/next-tick'); // var svgTags = require('../browser/svg-tags'); // var ie = require('../browser/ie'); // var evalExpr = require('../runtime/eval-expr'); // var getANodeProp = require('./get-a-node-prop'); // var NodeType = require('./node-type'); /** * HTML 属性和 DOM 操作属性的对照表 * * @inner * @const * @type {Object} */ var HTML_ATTR_PROP_MAP = { 'readonly': 'readOnly', 'cellpadding': 'cellPadding', 'cellspacing': 'cellSpacing', 'colspan': 'colSpan', 'rowspan': 'rowSpan', 'valign': 'vAlign', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'for': 'htmlFor' }; /** * 默认的元素的属性设置的变换方法 * * @inner * @type {Object} */ function defaultElementPropHandler(el, value, name) { var propName = HTML_ATTR_PROP_MAP[name] || name; var valueNotNull = value != null; // input 的 type 是个特殊属性,其实也应该用 setAttribute // 但是 type 不应该运行时动态改变,否则会有兼容性问题 // 所以这里直接就不管了 if (propName in el) { el[propName] = valueNotNull ? value : ''; } else if (valueNotNull) { el.setAttribute(name, value); } if (!valueNotNull) { el.removeAttribute(name); } } function svgPropHandler(el, value, name) { el.setAttribute(name, value); } function boolPropHandler(el, value, name) { var propName = HTML_ATTR_PROP_MAP[name] || name; el[propName] = !!value; } // #[begin] allua // see https://github.com/baidu/san/issues/495 function placeholderHandler(el, value, name, element) { /* istanbul ignore if */ if (ie > 9 && !el.value && value) { element.__bkph = true; nextTick(function () { element.__bkph = false; }); } defaultElementPropHandler(el, value, name); } // #[end] /* eslint-disable fecs-properties-quote */ /** * 默认的属性设置变换方法 * * @inner * @type {Object} */ var defaultElementPropHandlers = { id: function (el, value) { if (value != null) { el.id = value; } else if (el.id) { el.removeAttribute('id'); } }, style: function (el, value) { el.style.cssText = value; }, 'class': function (el, value) { // eslint-disable-line if ( // #[begin] allua ie || // #[end] el.className !== value ) { el.className = value; } }, slot: empty, draggable: boolPropHandler }; /* eslint-enable fecs-properties-quote */ var analInputChecker = { checkbox: contains, radio: function (a, b) { return a === b; } }; function analInputCheckedState(element, value) { var bindValue = getANodeProp(element.aNode, 'value'); var bindType = getANodeProp(element.aNode, 'type'); if (bindValue && bindType) { var type = evalExpr(bindType.expr, element.scope, element.owner); if (analInputChecker[type]) { var bindChecked = getANodeProp(element.aNode, 'checked'); if (bindChecked != null && !bindChecked.hintExpr) { bindChecked.hintExpr = bindValue.expr; } return !!analInputChecker[type]( value, element.data ? evalExpr(bindValue.expr, element.data, element) : evalExpr(bindValue.expr, element.scope, element.owner) ); } } } var elementPropHandlers = { input: { multiple: boolPropHandler, checked: function (el, value, name, element) { var state = analInputCheckedState(element, value); boolPropHandler( el, state != null ? state : value, 'checked', element ); // #[begin] allua // 代码不用抽出来防重复,allua内的代码在现代浏览器版本会被编译时干掉,gzip也会处理重复问题 // see: #378 /* istanbul ignore if */ if (ie && ie < 8 && !element.lifeCycle.attached) { boolPropHandler( el, state != null ? state : value, 'defaultChecked', element ); } // #[end] }, // #[begin] allua placeholder: placeholderHandler, // #[end] readonly: boolPropHandler, disabled: boolPropHandler, autofocus: boolPropHandler, required: boolPropHandler }, option: { value: function (el, value, name, element) { defaultElementPropHandler(el, value, name, element); if (isOptionSelected(element, value)) { el.selected = true; } } }, select: { readonly: boolPropHandler, disabled: boolPropHandler, autofocus: boolPropHandler, required: boolPropHandler }, textarea: { // #[begin] allua placeholder: placeholderHandler, // #[end] readonly: boolPropHandler, disabled: boolPropHandler, autofocus: boolPropHandler, required: boolPropHandler }, button: { disabled: boolPropHandler, autofocus: boolPropHandler, type: function (el, value) { if (value != null) { el.setAttribute('type', value); } else { el.removeAttribute('type'); } } } }; function isOptionSelected(element, value) { var parentSelect = element.parent; while (parentSelect) { if (parentSelect.tagName === 'select') { break; } parentSelect = parentSelect.parent; } if (parentSelect) { var selectValue = null; var prop; var expr; if ((prop = getANodeProp(parentSelect.aNode, 'value')) && (expr = prop.expr) ) { selectValue = parentSelect.nodeType === 5 ? evalExpr(expr, parentSelect.data, parentSelect) : evalExpr(expr, parentSelect.scope, parentSelect.owner) || ''; } if (selectValue === value) { return 1; } } } /** * 获取属性处理对象 * * @param {string} tagName 元素tag * @param {string} attrName 属性名 * @return {Object} */ function getPropHandler(tagName, attrName) { if (svgTags[tagName]) { return svgPropHandler; } var tagPropHandlers = elementPropHandlers[tagName]; if (!tagPropHandlers) { tagPropHandlers = elementPropHandlers[tagName] = {}; } var propHandler = tagPropHandlers[attrName]; if (!propHandler) { propHandler = defaultElementPropHandlers[attrName] || defaultElementPropHandler; tagPropHandlers[attrName] = propHandler; } return propHandler; } // exports = module.exports = getPropHandler; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 判断变更是否来源于元素 */ /** * 判断变更是否来源于元素,来源于元素时,视图更新需要阻断 * * @param {Object} change 变更对象 * @param {Element} element 元素 * @param {string?} propName 属性名,可选。需要精确判断是否来源于此属性时传入 * @return {boolean} */ function isDataChangeByElement(change, element, propName) { var changeTarget = change.option.target; return changeTarget && changeTarget.node === element && (!propName || changeTarget.prop === propName); } // exports = module.exports = isDataChangeByElement; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 在对象上使用accessor表达式查找方法 */ // var evalExpr = require('../runtime/eval-expr'); /** * 在对象上使用accessor表达式查找方法 * * @param {Object} source 源对象 * @param {Object} nameExpr 表达式 * @param {Data} data 所属数据环境 * @return {Function} */ function findMethod(source, nameExpr, data) { var method = source; for (var i = 0; method != null && i < nameExpr.paths.length; i++) { method = method[evalExpr(nameExpr.paths[i], data)]; } return method; } // exports = module.exports = findMethod; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 数据类 */ // var ExprType = require('../parser/expr-type'); // var evalExpr = require('./eval-expr'); // var DataChangeType = require('./data-change-type'); // var parseExpr = require('../parser/parse-expr'); /** * 数据类 * * @class * @param {Object?} data 初始数据 * @param {Model?} parent 父级数据容器 */ function Data(data, parent) { this.parent = parent; this.raw = data || {}; this.listeners = []; } // #[begin] error // 以下两个函数只在开发模式下可用,在生产模式下不存在 /** * DataTypes 检测 */ Data.prototype.checkDataTypes = function () { if (this.typeChecker) { this.typeChecker(this.raw); } }; /** * 设置 type checker * * @param {Function} typeChecker 类型校验器 */ Data.prototype.setTypeChecker = function (typeChecker) { this.typeChecker = typeChecker; }; // #[end] /** * 添加数据变更的事件监听器 * * @param {Function} listener 监听函数 */ Data.prototype.listen = function (listener) { if (typeof listener === 'function') { this.listeners.push(listener); } }; /** * 移除数据变更的事件监听器 * * @param {Function} listener 监听函数 */ Data.prototype.unlisten = function (listener) { var len = this.listeners.length; while (len--) { if (!listener || this.listeners[len] === listener) { this.listeners.splice(len, 1); } } }; /** * 触发数据变更 * * @param {Object} change 变更信息对象 */ Data.prototype.fire = function (change) { if (change.option.silent || change.option.silence || change.option.quiet) { return; } for (var i = 0; i < this.listeners.length; i++) { this.listeners[i].call(this, change); } }; /** * 获取数据项 * * @param {string|Object?} expr 数据项路径 * @param {Data?} callee 当前数据获取的调用环境 * @return {*} */ Data.prototype.get = function (expr, callee) { var value = this.raw; if (!expr) { return value; } if (typeof expr !== 'object') { expr = parseExpr(expr); } var paths = expr.paths; callee = callee || this; value = value[paths[0].value]; if (typeof value == 'undefined' && this.parent) { value = this.parent.get(expr, callee); } else { for (var i = 1, l = paths.length; value != null && i < l; i++) { value = value[paths[i].value || evalExpr(paths[i], callee)]; } } return value; }; /** * 数据对象变更操作 * * @inner * @param {Object|Array} source 要变更的源数据 * @param {Array} exprPaths 属性路径 * @param {number} pathsStart 当前处理的属性路径指针位置 * @param {number} pathsLen 属性路径长度 * @param {*} value 变更属性值 * @param {Data} data 对应的Data对象 * @return {*} 变更后的新数据 */ function immutableSet(source, exprPaths, pathsStart, pathsLen, value, data) { if (pathsStart >= pathsLen) { return value; } if (source == null) { source = {}; } var pathExpr = exprPaths[pathsStart]; var prop = evalExpr(pathExpr, data); var result = source; if (source instanceof Array) { var index = +prop; prop = isNaN(index) ? prop : index; result = source.slice(0); result[prop] = immutableSet(source[prop], exprPaths, pathsStart + 1, pathsLen, value, data); } else if (typeof source === 'object') { result = {}; var needAssigned = true; for (var key in source) { /* istanbul ignore else */ if (source.hasOwnProperty(key)) { if (key === prop) { needAssigned = false; result[prop] = immutableSet(source[prop], exprPaths, pathsStart + 1, pathsLen, value, data); } else { result[key] = source[key]; } } } // 如果set的是一个不存在的属性,会走到该逻辑 if (needAssigned) { result[prop] = immutableSet(source[prop], exprPaths, pathsStart + 1, pathsLen, value, data); } } if (pathExpr.value == null) { exprPaths[pathsStart] = { type: typeof prop === 'string' ? 1 : 2, value: prop }; } return result; } /** * 设置数据项 * * @param {string|Object} expr 数据项路径 * @param {*} value 数据值 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.set = function (expr, value, option) { option = option || {}; // #[begin] error var exprRaw = expr; // #[end] expr = parseExpr(expr); // #[begin] error if (expr.type !== 4) { throw new Error('[SAN ERROR] Invalid Expression in Data set: ' + exprRaw); } // #[end] if (this.get(expr) === value && !option.force) { return; } expr = { type: 4, paths: expr.paths.slice(0) }; var prop = expr.paths[0].value; this.raw[prop] = immutableSet(this.raw[prop], expr.paths, 1, expr.paths.length, value, this); this.fire({ type: 1, expr: expr, value: value, option: option }); // #[begin] error this.checkDataTypes(); // #[end] }; /** * 批量设置数据 * * @param {Object} source 待设置的数据集 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.assign = function (source, option) { option = option || {}; for (var key in source) { // eslint-disable-line this.set( { type: 4, paths: [ {type: 1, value: key} ] }, source[key], option ); } }; /** * 合并更新数据项 * * @param {string|Object} expr 数据项路径 * @param {Object} source 待合并的数据 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.merge = function (expr, source, option) { option = option || {}; // #[begin] error var exprRaw = expr; // #[end] expr = parseExpr(expr); // #[begin] error if (expr.type !== 4) { throw new Error('[SAN ERROR] Invalid Expression in Data merge: ' + exprRaw); } if (typeof this.get(expr) !== 'object') { throw new Error('[SAN ERROR] Merge Expects a Target of Type \'object\'; got ' + typeof oldValue); } if (typeof source !== 'object') { throw new Error('[SAN ERROR] Merge Expects a Source of Type \'object\'; got ' + typeof source); } // #[end] for (var key in source) { // eslint-disable-line this.set( { type: 4, paths: expr.paths.concat( [ { type: 1, value: key } ] ) }, source[key], option ); } }; /** * 基于更新函数更新数据项 * * @param {string|Object} expr 数据项路径 * @param {Function} fn 数据处理函数 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.apply = function (expr, fn, option) { // #[begin] error var exprRaw = expr; // #[end] expr = parseExpr(expr); // #[begin] error if (expr.type !== 4) { throw new Error('[SAN ERROR] Invalid Expression in Data apply: ' + exprRaw); } // #[end] var oldValue = this.get(expr); // #[begin] error if (typeof fn !== 'function') { throw new Error( '[SAN ERROR] Invalid Argument\'s Type in Data apply: ' + 'Expected Function but got ' + typeof fn ); } // #[end] this.set(expr, fn(oldValue), option); }; /** * 数组数据项splice操作 * * @param {string|Object} expr 数据项路径 * @param {Array} args splice 接受的参数列表,数组项与Array.prototype.splice的参数一致 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 * @return {Array} 新数组 */ Data.prototype.splice = function (expr, args, option) { option = option || {}; // #[begin] error var exprRaw = expr; // #[end] expr = parseExpr(expr); // #[begin] error if (expr.type !== 4) { throw new Error('[SAN ERROR] Invalid Expression in Data splice: ' + exprRaw); } // #[end] expr = { type: 4, paths: expr.paths.slice(0) }; var target = this.get(expr); var returnValue = []; if (target instanceof Array) { var index = args[0]; var len = target.length; if (index > len) { index = len; } else if (index < 0) { index = len + index; if (index < 0) { index = 0; } } var newArray = target.slice(0); returnValue = newArray.splice.apply(newArray, args); this.raw = immutableSet(this.raw, expr.paths, 0, expr.paths.length, newArray, this); this.fire({ expr: expr, type: 2, index: index, deleteCount: returnValue.length, value: returnValue, insertions: args.slice(2), option: option }); } // #[begin] error this.checkDataTypes(); // #[end] return returnValue; }; /** * 数组数据项push操作 * * @param {string|Object} expr 数据项路径 * @param {*} item 要push的值 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 * @return {number} 新数组的length属性 */ Data.prototype.push = function (expr, item, option) { var target = this.get(expr); if (target instanceof Array) { this.splice(expr, [target.length, 0, item], option); return target.length + 1; } }; /** * 数组数据项pop操作 * * @param {string|Object} expr 数据项路径 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 * @return {*} */ Data.prototype.pop = function (expr, option) { var target = this.get(expr); if (target instanceof Array) { var len = target.length; if (len) { return this.splice(expr, [len - 1, 1], option)[0]; } } }; /** * 数组数据项shift操作 * * @param {string|Object} expr 数据项路径 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 * @return {*} */ Data.prototype.shift = function (expr, option) { return this.splice(expr, [0, 1], option)[0]; }; /** * 数组数据项unshift操作 * * @param {string|Object} expr 数据项路径 * @param {*} item 要unshift的值 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 * @return {number} 新数组的length属性 */ Data.prototype.unshift = function (expr, item, option) { var target = this.get(expr); if (target instanceof Array) { this.splice(expr, [0, 0, item], option); return target.length + 1; } }; /** * 数组数据项移除操作 * * @param {string|Object} expr 数据项路径 * @param {number} index 要移除项的索引 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.removeAt = function (expr, index, option) { this.splice(expr, [index, 1], option); }; /** * 数组数据项移除操作 * * @param {string|Object} expr 数据项路径 * @param {*} value 要移除的项 * @param {Object=} option 设置参数 * @param {boolean} option.silent 静默设置,不触发变更事件 */ Data.prototype.remove = function (expr, value, option) { var target = this.get(expr); if (target instanceof Array) { var len = target.length; while (len--) { if (target[len] === value) { this.splice(expr, [len, 1], option); break; } } } }; // exports = module.exports = Data; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取声明式事件的监听函数 */ // var evalArgs = require('../runtime/eval-args'); // var findMethod = require('../runtime/find-method'); // var Data = require('../runtime/data'); /** * 获取声明式事件的监听函数 * * @param {Object} eventBind 绑定信息对象 * @param {Component} owner 所属组件环境 * @param {Data} data 数据环境 * @param {boolean} isComponentEvent 是否组件自定义事件 * @return {Function} */ function getEventListener(eventBind, owner, data, isComponentEvent) { var args = eventBind.expr.args; return function (e) { e = isComponentEvent ? e : e || window.event; var method = findMethod(owner, eventBind.expr.name, data); if (typeof method === 'function') { method.apply( owner, args.length ? evalArgs(args, new Data({ $event: e }, data), owner) : [] ); } if (eventBind.modifier.prevent) { e.preventDefault && e.preventDefault(); return false; } if (eventBind.modifier.stop) { if (e.stopPropagation) { e.stopPropagation(); } else { e.cancelBubble = true; } } }; } // exports = module.exports = getEventListener; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 判断变更数组是否影响到数据引用摘要 */ /** * 判断变更数组是否影响到数据引用摘要 * * @param {Array} changes 变更数组 * @param {Object} dataRef 数据引用摘要 * @return {boolean} */ function changesIsInDataRef(changes, dataRef) { if (dataRef) { for (var i = 0; i < changes.length; i++) { var change = changes[i]; if (!change.overview) { var paths = change.expr.paths; change.overview = paths[0].value; if (paths.length > 1) { change.extOverview = paths[0].value + '.' + paths[1].value; change.wildOverview = paths[0].value + '.*'; } } if (dataRef[change.overview] || change.wildOverview && dataRef[change.wildOverview] || change.extOverview && dataRef[change.extOverview] ) { return true; } } } } // exports = module.exports = changesIsInDataRef; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file insertBefore 方法的兼容性封装 */ /** * insertBefore 方法的兼容性封装 * * @param {HTMLNode} targetEl 要插入的节点 * @param {HTMLElement} parentEl 父元素 * @param {HTMLElement?} beforeEl 在此元素之前插入 */ function insertBefore(targetEl, parentEl, beforeEl) { if (parentEl) { if (beforeEl) { parentEl.insertBefore(targetEl, beforeEl); } else { parentEl.appendChild(targetEl); } } } // exports = module.exports = insertBefore; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 样式的基本属性 */ // var splitStr2Obj = require('../util/split-str-2-obj'); /** * 元素的基本属性 * * @type {Object} */ var styleProps = splitStr2Obj('class,style'); // exports = module.exports = styleProps; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 元素子节点遍历操作类 */ // var removeEl = require('../browser/remove-el'); // #[begin] reverse // /** // * 元素子节点遍历操作类 // * // * @inner // * @class // * @param {HTMLElement} el 要遍历的元素 // */ // function DOMChildrenWalker(el) { // this.children = []; // this.index = 0; // this.target = el; // // var child = el.firstChild; // var next; // while (child) { // next = child.nextSibling; // // switch (child.nodeType) { // case 3: // if (/^\s*$/.test(child.data || child.textContent)) { // removeEl(child); // } // else { // this.children.push(child); // } // break; // // case 1: // case 8: // this.children.push(child); // } // // child = next; // } // // this.current = this.children[this.index]; // this.next = this.children[this.index + 1]; // } // // /** // * 往下走一个元素 // */ // DOMChildrenWalker.prototype.goNext = function () { // this.current = this.children[++this.index]; // this.next = this.children[this.index + 1]; // }; // #[end] // exports = module.exports = DOMChildrenWalker; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 元素节点类 */ // var changeExprCompare = require('../runtime/change-expr-compare'); // var changesIsInDataRef = require('../runtime/changes-is-in-data-ref'); // var evalExpr = require('../runtime/eval-expr'); // var insertBefore = require('../browser/insert-before'); // var LifeCycle = require('./life-cycle'); // var NodeType = require('./node-type'); // var styleProps = require('./style-props'); // var reverseElementChildren = require('./reverse-element-children'); // var isDataChangeByElement = require('./is-data-change-by-element'); // var getPropHandler = require('./get-prop-handler'); // var createNode = require('./create-node'); // var preheatEl = require('./preheat-el'); // var elementOwnDetach = require('./element-own-detach'); // var elementOwnDispose = require('./element-own-dispose'); // var elementOwnOnEl = require('./element-own-on-el'); // var elementOwnAttached = require('./element-own-attached'); // var nodeSBindInit = require('./node-s-bind-init'); // var nodeSBindUpdate = require('./node-s-bind-update'); // var warnSetHTML = require('./warn-set-html'); // var getNodePath = require('./get-node-path'); /** * 元素节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {string} tagName 元素标签名 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function Element(aNode, parent, scope, owner, tagName, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; this.lifeCycle = LifeCycle.start; this.children = []; this._elFns = []; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.tagName = tagName || aNode.tagName; // #[begin] allua // ie8- 不支持innerHTML输出自定义标签 /* istanbul ignore if */ if (ieOldThan9 && this.tagName.indexOf('-') > 0) { this.tagName = 'div'; } // #[end] aNode._i++; this._sbindData = nodeSBindInit(aNode.directives.bind, this.scope, this.owner); this.lifeCycle = LifeCycle.inited; // #[begin] reverse // if (reverseWalker) { // var currentNode = reverseWalker.current; // // /* istanbul ignore if */ // if (!currentNode) { // throw new Error('[SAN REVERSE ERROR] Element not found. \nPaths: ' // + getNodePath(this).join(' > ')); // } // // /* istanbul ignore if */ // if (currentNode.nodeType !== 1) { // throw new Error('[SAN REVERSE ERROR] Element type not match, expect 1 but ' // + currentNode.nodeType + '.\nPaths: ' // + getNodePath(this).join(' > ')); // } // // /* istanbul ignore if */ // if (currentNode.tagName.toLowerCase() !== this.tagName) { // throw new Error('[SAN REVERSE ERROR] Element tagName not match, expect ' // + this.tagName + ' but meet ' + currentNode.tagName.toLowerCase() + '.\nPaths: ' // + getNodePath(this).join(' > ')); // } // // this.el = currentNode; // reverseWalker.goNext(); // // reverseElementChildren(this, this.scope, this.owner); // // this.lifeCycle = LifeCycle.created; // this._attached(); // this.lifeCycle = LifeCycle.attached; // } // #[end] } Element.prototype.nodeType = 4; /** * 将元素attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ Element.prototype.attach = function (parentEl, beforeEl) { if (!this.lifeCycle.attached) { var aNode = this.aNode; if (!this.el) { var props; if (aNode._ce && aNode._i > 2) { props = aNode._dp; this.el = (aNode._el || preheatEl(aNode)).cloneNode(false); } else { props = aNode.props; this.el = createEl(this.tagName); } if (this._sbindData) { for (var key in this._sbindData) { if (this._sbindData.hasOwnProperty(key)) { getPropHandler(this.tagName, key)( this.el, this._sbindData[key], key, this ); } } } for (var i = 0, l = props.length; i < l; i++) { var prop = props[i]; var value = evalExpr(prop.expr, this.scope, this.owner); if (value || !styleProps[prop.name]) { prop.handler(this.el, value, prop.name, this); } } this.lifeCycle = LifeCycle.created; } insertBefore(this.el, parentEl, beforeEl); if (!this._contentReady) { var htmlDirective = aNode.directives.html; if (htmlDirective) { // #[begin] error warnSetHTML(this.el); // #[end] this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner); } else { for (var i = 0, l = aNode.children.length; i < l; i++) { var childANode = aNode.children[i]; var child = childANode.Clazz ? new childANode.Clazz(childANode, this, this.scope, this.owner) : createNode(childANode, this, this.scope, this.owner); this.children.push(child); child.attach(this.el); } } this._contentReady = 1; } this._attached(); this.lifeCycle = LifeCycle.attached; } }; Element.prototype.detach = elementOwnDetach; Element.prototype.dispose = elementOwnDispose; Element.prototype._onEl = elementOwnOnEl; Element.prototype._leave = function () { if (this.leaveDispose) { if (!this.lifeCycle.disposed) { var len = this.children.length; while (len--) { this.children[len].dispose(1, 1); } len = this._elFns.length; while (len--) { var fn = this._elFns[len]; un(this.el, fn[0], fn[1], fn[2]); } this._elFns = null; // #[begin] allua /* istanbul ignore if */ if (this._inputTimer) { clearInterval(this._inputTimer); this._inputTimer = null; } // #[end] // 如果没有parent,说明是一个root component,一定要从dom树中remove if (!this.disposeNoDetach || !this.parent) { removeEl(this.el); } this.lifeCycle = LifeCycle.detached; this.el = null; this.owner = null; this.scope = null; this.children = null; this.lifeCycle = LifeCycle.disposed; if (this._ondisposed) { this._ondisposed(); } } } }; /** * 视图更新 * * @param {Array} changes 数据变化信息 */ Element.prototype._update = function (changes) { var dataHotspot = this.aNode._d; if (dataHotspot && changesIsInDataRef(changes, dataHotspot)) { // update s-bind var me = this; this._sbindData = nodeSBindUpdate( this.aNode.directives.bind, this._sbindData, this.scope, this.owner, changes, function (name, value) { if (name in me.aNode._pi) { return; } getPropHandler(me.tagName, name)(me.el, value, name, me); } ); // update prop var dynamicProps = this.aNode._dp; for (var i = 0, l = dynamicProps.length; i < l; i++) { var prop = dynamicProps[i]; var propName = prop.name; for (var j = 0, changeLen = changes.length; j < changeLen; j++) { var change = changes[j]; if (!isDataChangeByElement(change, this, propName) && ( changeExprCompare(change.expr, prop.expr, this.scope) || prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.scope) ) ) { prop.handler(this.el, evalExpr(prop.expr, this.scope, this.owner), propName, this); break; } } } // update content var htmlDirective = this.aNode.directives.html; if (htmlDirective) { var len = changes.length; while (len--) { if (changeExprCompare(changes[len].expr, htmlDirective.value, this.scope)) { // #[begin] error warnSetHTML(this.el); // #[end] this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner); break; } } } else { for (var i = 0, l = this.children.length; i < l; i++) { this.children[i]._update(changes); } } } }; /** * 执行完成attached状态的行为 */ Element.prototype._attached = elementOwnAttached; // exports = module.exports = Element; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 通过组件反解创建节点的工厂方法 */ // var Element = require('./element'); // var TemplateNode = require('./template-node'); // var AsyncComponent = require('./async-component'); // #[begin] reverse // /** // * 通过组件反解创建节点 // * // * @param {ANode} aNode 抽象节点 // * @param {Node} parent 父亲节点 // * @param {Model} scope 所属数据环境 // * @param {Component} owner 所属组件环境 // * @param {DOMChildrenWalker} reverseWalker 子元素遍历对象 // * @return {Node} // */ // function createReverseNode(aNode, parent, scope, owner, reverseWalker, componentName) { // if (aNode.elem) { // return new Element(aNode, parent, scope, owner, componentName, reverseWalker); // } // // if (aNode.Clazz) { // return new aNode.Clazz(aNode, parent, scope, owner, reverseWalker); // } // // var ComponentOrLoader = owner.components[componentName || aNode.tagName]; // // if (ComponentOrLoader) { // return typeof ComponentOrLoader === 'function' // ? new ComponentOrLoader({ // source: aNode, // owner: owner, // scope: scope, // parent: parent, // reverseWalker: reverseWalker // }) // : new AsyncComponent({ // source: aNode, // owner: owner, // scope: scope, // parent: parent, // reverseWalker: reverseWalker // }, ComponentOrLoader); // } // // if (aNode.directives.is) { // switch (componentName) { // case 'fragment': // case 'template': // return new TemplateNode(aNode, parent, scope, owner, reverseWalker); // } // } // else { // aNode.elem = true; // } // return new Element(aNode, parent, scope, owner, componentName, reverseWalker); // } // #[end] // exports = module.exports = createReverseNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 销毁释放元素的子元素 */ /** * 销毁释放元素的子元素 * * @param {Array=} children 子元素数组 * @param {boolean=} noDetach 是否不要把节点从dom移除 * @param {boolean=} noTransition 是否不显示过渡动画效果 */ function elementDisposeChildren(children, noDetach, noTransition) { var len = children && children.length; while (len--) { children[len].dispose(noDetach, noTransition); } } // exports = module.exports = elementDisposeChildren; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 创建节点的工厂方法 */ // var Element = require('./element'); // var TemplateNode = require('./template-node'); // var AsyncComponent = require('./async-component'); /** * 创建节点 * * @param {ANode} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @return {Node} */ function createNode(aNode, parent, scope, owner, componentName) { if (aNode.elem) { return new Element(aNode, parent, scope, owner, componentName); } if (aNode.Clazz) { return new aNode.Clazz(aNode, parent, scope, owner); } var ComponentOrLoader = owner.components[componentName || aNode.tagName]; if (ComponentOrLoader) { return typeof ComponentOrLoader === 'function' ? new ComponentOrLoader({ source: aNode, owner: owner, scope: scope, parent: parent }) : new AsyncComponent({ source: aNode, owner: owner, scope: scope, parent: parent }, ComponentOrLoader); } if (aNode.directives.is) { switch (componentName) { case 'fragment': case 'template': return new TemplateNode(aNode, parent, scope, owner); } } else { aNode.elem = true; } return new Element(aNode, parent, scope, owner, componentName); } // exports = module.exports = createNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 将没有 root 只有 children 的元素 attach 到页面 */ // var insertBefore = require('../browser/insert-before'); // var LifeCycle = require('./life-cycle'); // var createNode = require('./create-node'); /** * 将没有 root 只有 children 的元素 attach 到页面 * 主要用于 slot 和 template * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ function nodeOwnOnlyChildrenAttach(parentEl, beforeEl) { this.sel = document.createComment(this.id); insertBefore(this.sel, parentEl, beforeEl); for (var i = 0; i < this.aNode.children.length; i++) { var child = createNode( this.aNode.children[i], this, this.childScope || this.scope, this.childOwner || this.owner ); this.children.push(child); child.attach(parentEl, beforeEl); } this.el = document.createComment(this.id); insertBefore(this.el, parentEl, beforeEl); this.lifeCycle = LifeCycle.attached; } // exports = module.exports = nodeOwnOnlyChildrenAttach; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file template 节点类 */ // var guid = require('../util/guid'); // var insertBefore = require('../browser/insert-before'); // var removeEl = require('../browser/remove-el'); // var NodeType = require('./node-type'); // var LifeCycle = require('./life-cycle'); // var createReverseNode = require('./create-reverse-node'); // var elementDisposeChildren = require('./element-dispose-children'); // var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach'); /** * template 节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function TemplateNode(aNode, parent, scope, owner, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.id = guid++; this.lifeCycle = LifeCycle.start; this.children = []; // #[begin] reverse // if (reverseWalker) { // var hasFlagComment; // // // start flag // if (reverseWalker.current && reverseWalker.current.nodeType === 8) { // this.sel = reverseWalker.current; // hasFlagComment = 1; // reverseWalker.goNext(); // } // else { // this.sel = document.createComment(this.id); // insertBefore(this.sel, reverseWalker.target, reverseWalker.current); // } // // // content // var aNodeChildren = this.aNode.children; // for (var i = 0, l = aNodeChildren.length; i < l; i++) { // this.children.push( // createReverseNode(aNodeChildren[i], this, this.scope, this.owner, reverseWalker) // ); // } // // // end flag // if (hasFlagComment) { // this.el = reverseWalker.current; // reverseWalker.goNext(); // } // else { // this.el = document.createComment(this.id); // insertBefore(this.el, reverseWalker.target, reverseWalker.current); // } // // this.lifeCycle = LifeCycle.attached; // } // #[end] } TemplateNode.prototype.nodeType = 7; TemplateNode.prototype.attach = nodeOwnOnlyChildrenAttach; /** * 销毁释放 * * @param {boolean=} noDetach 是否不要把节点从dom移除 * @param {boolean=} noTransition 是否不显示过渡动画效果 */ TemplateNode.prototype.dispose = function (noDetach, noTransition) { elementDisposeChildren(this.children, noDetach, noTransition); if (!noDetach) { removeEl(this.el); removeEl(this.sel); } this.sel = null; this.el = null; this.owner = null; this.scope = null; this.children = null; this.lifeCycle = LifeCycle.disposed; if (this._ondisposed) { this._ondisposed(); } }; /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ TemplateNode.prototype._update = function (changes) { for (var i = 0; i < this.children.length; i++) { this.children[i]._update(changes); } }; TemplateNode.prototype._getElAsRootNode = function () { return this.sel; }; // exports = module.exports = TemplateNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 创建节点对应的 stump comment 元素 */ /** * 创建节点对应的 stump comment 主元素 */ function nodeOwnCreateStump() { this.el = this.el || document.createComment(this.id); } // exports = module.exports = nodeOwnCreateStump; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 简单执行销毁节点的行为 */ // var removeEl = require('../browser/remove-el'); // var LifeCycle = require('./life-cycle'); // var elementDisposeChildren = require('./element-dispose-children'); /** * 简单执行销毁节点的行为 * * @param {boolean=} noDetach 是否不要把节点从dom移除 */ function nodeOwnSimpleDispose(noDetach) { elementDisposeChildren(this.children, noDetach, 1); if (!noDetach) { removeEl(this.el); } this.el = null; this.owner = null; this.scope = null; this.children = null; this.lifeCycle = LifeCycle.disposed; if (this._ondisposed) { this._ondisposed(); } } // exports = module.exports = nodeOwnSimpleDispose; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 异步组件类 */ // var guid = require('../util/guid'); // var each = require('../util/each'); // var insertBefore = require('../browser/insert-before'); // var nodeOwnCreateStump = require('./node-own-create-stump'); // var nodeOwnSimpleDispose = require('./node-own-simple-dispose'); /** * 异步组件类 * * @class * @param {Object} options 初始化参数 * @param {Object} loader 组件加载器 */ function AsyncComponent(options, loader) { this.options = options; this.loader = loader; this.id = guid++; this.children = []; // #[begin] reverse // var reverseWalker = options.reverseWalker; // if (reverseWalker) { // var PlaceholderComponent = this.loader.placeholder; // if (PlaceholderComponent) { // this.children[0] = new PlaceholderComponent(options); // } // // this._create(); // insertBefore(this.el, reverseWalker.target, reverseWalker.current); // // var me = this; // this.loader.start(function (ComponentClass) { // me.onload(ComponentClass); // }); // } // options.reverseWalker = null; // #[end] } AsyncComponent.prototype._create = nodeOwnCreateStump; AsyncComponent.prototype.dispose = nodeOwnSimpleDispose; /** * attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ AsyncComponent.prototype.attach = function (parentEl, beforeEl) { var PlaceholderComponent = this.loader.placeholder; if (PlaceholderComponent) { var component = new PlaceholderComponent(this.options); this.children[0] = component; component.attach(parentEl, beforeEl); } this._create(); insertBefore(this.el, parentEl, beforeEl); var me = this; this.loader.start(function (ComponentClass) { me.onload(ComponentClass); }); }; AsyncComponent.prototype._getElAsRootNode = function () { var child = this.children[0]; return child && child.el; }; /** * loader加载完成,渲染组件 * * @param {Function=} ComponentClass 组件类 */ AsyncComponent.prototype.onload = function (ComponentClass) { if (this.el && ComponentClass) { var component = new ComponentClass(this.options); component.attach(this.el.parentNode, this.el); var parent = this.options.parent; if (parent._rootNode === this) { // 如果异步组件为 root 节点,直接更新 parent._rootNode = component; component._getElAsRootNode && (parent.el = component._getElAsRootNode()); } else { // 在 children 中查找 var parentChildren = parent.children; // children 中存在多个 AsyncComponent 时,只循环一遍,为所有 AsyncComponent 的 parentIndex 赋值 if (this.parentIndex == null || parentChildren[this.parentIndex] !== this) { each(parentChildren, function (child, index) { if (child instanceof AsyncComponent) { child.parentIndex = index; } }); } parentChildren[this.parentIndex] = component; } } this.dispose(); }; /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ AsyncComponent.prototype._update = function (changes) { this.children[0] && this.children[0]._update(changes); }; // exports = module.exports = AsyncComponent; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 对元素的子节点进行反解 */ // var each = require('../util/each'); // var DOMChildrenWalker = require('./dom-children-walker'); // var createReverseNode = require('./create-reverse-node'); // #[begin] reverse // // /** // * 对元素的子节点进行反解 // * // * @param {Object} element 元素 // */ // function reverseElementChildren(element, scope, owner) { // var htmlDirective = element.aNode.directives.html; // // if (!htmlDirective) { // var reverseWalker = new DOMChildrenWalker(element.el); // var aNodeChildren = element.aNode.children; // // for (var i = 0, l = aNodeChildren.length; i < l; i++) { // element.children.push( // createReverseNode(aNodeChildren[i], element, scope, owner, reverseWalker) // ); // } // } // } // #[end] // exports = module.exports = reverseElementChildren; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file ANode预热 */ /** * ANode预热HTML元素,用于循环创建时clone * * @param {Object} aNode 要预热的ANode * @return {HTMLElement} */ function preheatEl(aNode) { var el = createEl(aNode.tagName); aNode._el = el; for (var i = 0, l = aNode.props.length; i < l; i++) { var prop = aNode.props[i]; if (prop.expr.value != null) { prop.handler(el, prop.expr.value, prop.name, aNode); } } return el; } // exports = module.exports = preheatEl; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取 element 的 transition 控制对象 */ // var evalArgs = require('../runtime/eval-args'); // var findMethod = require('../runtime/find-method'); // var handleError = require('../util/handle-error'); // var NodeType = require('./node-type'); /** * 获取 element 的 transition 控制对象 * * @param {Object} element 元素 * @return {Object?} */ function elementGetTransition(element) { var directive = element.aNode.directives.transition; var owner = element.owner; if (element.nodeType === 5) { var cmptGivenTransition = element.source && element.source.directives.transition; if (cmptGivenTransition) { directive = cmptGivenTransition; } else { owner = element; } } var transition; if (directive && owner) { transition = findMethod(owner, directive.value.name); if (typeof transition === 'function') { try { transition = transition.apply( owner, evalArgs(directive.value.args, element.scope, owner) ); } catch (e) { handleError(e, owner, 'transitionCreate') } } } return transition || element.transition; } // exports = module.exports = elementGetTransition; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 将元素从页面上移除 */ // var NodeType = require('./node-type'); // var handleError = require('../util/handle-error'); // var elementGetTransition = require('./element-get-transition'); /** * 将元素从页面上移除 */ function elementOwnDetach() { var lifeCycle = this.lifeCycle; if (lifeCycle.leaving) { return; } if (!this.disposeNoTransition) { var transition = elementGetTransition(this); if (transition && transition.leave) { if (this._toPhase) { this._toPhase('leaving'); } else { this.lifeCycle = LifeCycle.leaving; } var me = this; try { transition.leave(this.el, function () { me._leave(); }); return; } catch (e) { handleError( e, this.nodeType === 5 ? this.parentComponent : this.owner, 'transitionLeave' ); } } } this._leave(); } // exports = module.exports = elementOwnDetach; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 销毁释放元素 */ /** * 销毁释放元素 * * @param {boolean=} noDetach 是否不要把节点从dom移除 * @param {boolean=} noTransition 是否不显示过渡动画效果 */ function elementOwnDispose(noDetach, noTransition) { this.leaveDispose = 1; this.disposeNoDetach = noDetach; this.disposeNoTransition = noTransition; this.detach(); } // exports = module.exports = elementOwnDispose; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 为元素的 el 绑定事件 */ // var on = require('../browser/on'); /** * 为元素的 el 绑定事件 * * @param {string} name 事件名 * @param {Function} listener 监听器 * @param {boolean} capture 是否是捕获阶段触发 */ function elementOwnOnEl(name, listener, capture) { capture = !!capture; this._elFns.push([name, listener, capture]); on(this.el, name, listener, capture); } // exports = module.exports = elementOwnOnEl; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 是否浏览器环境 */ var isBrowser = typeof window !== 'undefined'; // exports = module.exports = isBrowser; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 开发时的警告提示 */ // #[begin] error /** * 开发时的警告提示 * * @param {string} message 警告信息 */ function warn(message) { message = '[SAN WARNING] ' + message; /* eslint-disable no-console */ /* istanbul ignore next */ if (typeof console === 'object' && console.warn) { console.warn(message); } else { // 防止警告中断调用堆栈 setTimeout(function () { throw new Error(message); }, 0); } /* eslint-enable no-console */ } // #[end] // exports = module.exports = warn; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 事件绑定不存在的 warning */ // var each = require('../util/each'); // var warn = require('../util/warn'); // #[begin] error /** * 事件绑定不存在的 warning * * @param {Object} eventBind 事件绑定对象 * @param {Component} owner 所属的组件对象 */ function warnEventListenMethod(eventBind, owner) { var valid = true; var method = owner; each(eventBind.expr.name.paths, function (path) { method = method[path.value]; valid = !!method; return valid; }); if (!valid) { var paths = []; each(eventBind.expr.name.paths, function (path) { paths.push(path.value); }); warn(eventBind.name + ' listen fail,"' + paths.join('.') + '" not exist'); } } // #[end] // exports = module.exports = warnEventListenMethod; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 完成元素 attached 后的行为 */ // var empty = require('../util/empty'); // var isBrowser = require('../browser/is-browser'); // var trigger = require('../browser/trigger'); // var NodeType = require('./node-type'); // var elementGetTransition = require('./element-get-transition'); // var getEventListener = require('./get-event-listener'); // var warnEventListenMethod = require('./warn-event-listen-method'); // var handleError = require('../util/handle-error'); /** * 双绑输入框CompositionEnd事件监听函数 * * @inner */ function inputOnCompositionEnd() { if (!this.composing) { return; } this.composing = 0; trigger(this, 'input'); } /** * 双绑输入框CompositionStart事件监听函数 * * @inner */ function inputOnCompositionStart() { this.composing = 1; } function getXPropOutputer(element, xProp, data) { return function () { xPropOutput(element, xProp, data); }; } function getInputXPropOutputer(element, xProp, data) { return function () { // #[begin] allua /* istanbul ignore if */ if (element.__bkph) { element.__bkph = false; return; } // #[end] if (!this.composing) { xPropOutput(element, xProp, data); } }; } // #[begin] allua /* istanbul ignore next */ function getInputFocusXPropHandler(element, xProp, data) { return function () { element._inputTimer = setInterval(function () { xPropOutput(element, xProp, data); }, 16); }; } /* istanbul ignore next */ function getInputBlurXPropHandler(element) { return function () { clearInterval(element._inputTimer); element._inputTimer = null; }; } // #[end] function xPropOutput(element, bindInfo, data) { /* istanbul ignore if */ if (!element.lifeCycle.created) { return; } var el = element.el; if (element.tagName === 'input' && bindInfo.name === 'checked') { var bindValue = getANodeProp(element.aNode, 'value'); var bindType = getANodeProp(element.aNode, 'type'); if (bindValue && bindType) { switch (el.type) { case 'checkbox': data[el.checked ? 'push' : 'remove'](bindInfo.expr, evalExpr(bindValue.expr, data)); return; case 'radio': el.checked && data.set(bindInfo.expr, evalExpr(bindValue.expr, data), { target: { node: element, prop: bindInfo.name } }); return; } } } data.set(bindInfo.expr, el[bindInfo.name], { target: { node: element, prop: bindInfo.name } }); } /** * 完成元素 attached 后的行为 * * @param {Object} element 元素节点 */ function elementOwnAttached() { if (this._rootNode) { return; } var isComponent = this.nodeType === 5; var data = isComponent ? this.data : this.scope; /* eslint-disable no-redeclare */ // 处理自身变化时双向绑定的逻辑 var xProps = this.aNode._xp; for (var i = 0, l = xProps.length; i < l; i++) { var xProp = xProps[i]; switch (xProp.name) { case 'value': switch (this.tagName) { case 'input': case 'textarea': if (isBrowser && window.CompositionEvent) { this._onEl('change', inputOnCompositionEnd); this._onEl('compositionstart', inputOnCompositionStart); this._onEl('compositionend', inputOnCompositionEnd); } // #[begin] allua /* istanbul ignore else */ if ('oninput' in this.el) { // #[end] this._onEl('input', getInputXPropOutputer(this, xProp, data)); // #[begin] allua } else { this._onEl('focusin', getInputFocusXPropHandler(this, xProp, data)); this._onEl('focusout', getInputBlurXPropHandler(this)); } // #[end] break; case 'select': this._onEl('change', getXPropOutputer(this, xProp, data)); break; } break; case 'checked': switch (this.tagName) { case 'input': switch (this.el.type) { case 'checkbox': case 'radio': this._onEl('click', getXPropOutputer(this, xProp, data)); } } break; } } var owner = isComponent ? this : this.owner; for (var i = 0, l = this.aNode.events.length; i < l; i++) { var eventBind = this.aNode.events[i]; // #[begin] error warnEventListenMethod(eventBind, owner); // #[end] this._onEl( eventBind.name, getEventListener(eventBind, owner, data, eventBind.modifier), eventBind.modifier.capture ); } if (isComponent) { for (var i = 0, l = this.nativeEvents.length; i < l; i++) { var eventBind = this.nativeEvents[i]; // #[begin] error warnEventListenMethod(eventBind, this.owner); // #[end] this._onEl( eventBind.name, getEventListener(eventBind, this.owner, this.scope), eventBind.modifier.capture ); } } var transition = elementGetTransition(this); if (transition && transition.enter) { try { transition.enter(this.el, empty); } catch (e) { handleError(e, isComponent ? owner.parentComponent : owner, 'transitionEnter'); } } } // exports = module.exports = elementOwnAttached; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 初始化节点的 s-bind 数据 */ // var evalExpr = require('../runtime/eval-expr'); /** * 初始化节点的 s-bind 数据 * * @param {Object} sBind bind指令对象 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @return {boolean} */ function nodeSBindInit(sBind, scope, owner) { if (sBind && scope) { return evalExpr(sBind.value, scope, owner); } } // exports = module.exports = nodeSBindInit; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 计算两个对象 key 的并集 */ /** * 计算两个对象 key 的并集 * * @param {Object} obj1 目标对象 * @param {Object} obj2 源对象 * @return {Array} */ function unionKeys(obj1, obj2) { var result = []; var key; for (key in obj1) { /* istanbul ignore else */ if (obj1.hasOwnProperty(key)) { result.push(key); } } for (key in obj2) { /* istanbul ignore else */ if (obj2.hasOwnProperty(key)) { !obj1[key] && result.push(key); } } return result; } // exports = module.exports = unionKeys; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 更新节点的 s-bind 数据 */ // var unionKeys = require('../util/union-keys'); // var evalExpr = require('../runtime/eval-expr'); // var changeExprCompare = require('../runtime/change-expr-compare'); /** * 更新节点的 s-bind 数据 * * @param {Object} sBind bind指令对象 * @param {Object} oldBindData 当前s-bind数据 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {Array} changes 变更数组 * @param {Function} updater 绑定对象子项变更的更新函数 */ function nodeSBindUpdate(sBind, oldBindData, scope, owner, changes, updater) { if (sBind) { var len = changes.length; while (len--) { if (changeExprCompare(changes[len].expr, sBind.value, scope)) { var newBindData = evalExpr(sBind.value, scope, owner); var keys = unionKeys(newBindData, oldBindData); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; var value = newBindData[key]; if (value !== oldBindData[key]) { updater(key, value); } } return newBindData; } } return oldBindData; } } // exports = module.exports = nodeSBindUpdate; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 判断元素是否不允许设置HTML */ // some html elements cannot set innerHTML in old ie // see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx /** * 判断元素是否不允许设置HTML * * @param {HTMLElement} el 要判断的元素 * @return {boolean} */ function noSetHTML(el) { return /^(col|colgroup|frameset|style|table|tbody|tfoot|thead|tr|select)$/i.test(el.tagName); } // exports = module.exports = noSetHTML; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取节点 stump 的 comment */ // var noSetHTML = require('../browser/no-set-html'); // var warn = require('../util/warn'); // #[begin] error /** * 获取节点 stump 的 comment * * @param {HTMLElement} el HTML元素 */ function warnSetHTML(el) { // dont warn if not in browser runtime /* istanbul ignore if */ if (!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document)) { return; } // some html elements cannot set innerHTML in old ie // see: https://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx if (noSetHTML(el)) { warn('set html for element "' + el.tagName + '" may cause an error in old IE'); } } // #[end] // exports = module.exports = warnSetHTML; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 获取节点在组件树中的路径 */ // var NodeType = require('./node-type'); // #[begin] reverse // /** // * 获取节点在组件树中的路径 // * // * @param {Node} node 节点对象 // * @return {Array} // */ // /* istanbul ignore next */ // function getNodePath(node) { // var nodePaths = []; // var nodeParent = node; // while (nodeParent) { // switch (nodeParent.nodeType) { // case 4: // nodePaths.unshift(nodeParent.tagName); // break; // // case 2: // nodePaths.unshift('if'); // break; // // case 3: // nodePaths.unshift('for[' + nodeParent.aNode.directives['for'].item + ']'); // eslint-disable-line dot-notation // break; // // case 6: // nodePaths.unshift('slot[' + (nodeParent.name || 'default') + ']'); // break; // // case 7: // nodePaths.unshift('template'); // break; // // case 5: // nodePaths.unshift('component[' + (nodeParent.source ? nodeParent.source.tagName : 'root') + ']'); // break; // // case 1: // nodePaths.unshift('text'); // break; // } // // nodeParent = nodeParent.parent; // } // // return nodePaths; // } // #[end] // exports = module.exports = getNodePath; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解压缩 ANode */ // var ExprType = require('./expr-type'); /** * 解压缩 ANode * * @param {Array} packed ANode压缩数据 * @return {Object} */ function unpackANode(packed) { var root; var nodeStack = []; var typeStack = []; var stateStack = []; var targetStack = []; var stackIndex = -1; for (var i = 0, l = packed.length; i < l; i++) { var current = nodeStack[stackIndex]; var currentType = typeStack[stackIndex]; var currentState = stateStack[stackIndex]; var currentTarget = targetStack[stackIndex]; while (current) { if (currentState === -3) { currentState = stateStack[stackIndex] = packed[i++] || -1; } if (currentState === -1) { current = nodeStack[--stackIndex]; currentType = typeStack[stackIndex]; currentState = stateStack[stackIndex]; currentTarget = targetStack[stackIndex]; } else { break; } } var type = packed[i]; var node; var state = -1; var target = false; switch (type) { // Node: Tag case 1: node = { directives: {}, props: [], events: [], children: [] }; var tagName = packed[++i]; tagName && (node.tagName = tagName); state = packed[++i] || -1; break; case 3: node = { type: 1, value: packed[++i] }; break; case 4: node = { type: 2, value: packed[++i] }; break; case 5: node = { type: 3, value: !!packed[++i] }; break; case 19: node = { type: 13 }; break; case 6: target = []; node = { type: 4, paths: target }; state = packed[++i] || -1; break; case 7: target = []; node = { type: 5, filters: target }; packed[++i] && (node.original = 1); state = -2; break; case 8: target = []; node = { type: 6, args: target }; state = -2; break; case 9: target = []; node = { type: 7, segs: target }; packed[++i] && (node.original = 1); state = packed[++i] || -1; break; case 10: target = []; node = { type: 8, operator: packed[++i], segs: target }; state = 2; break; case 11: node = { type: 9, operator: packed[++i] }; state = -2; break; case 12: target = []; node = { type: 10, segs: target }; state = 3; break; case 13: target = []; node = { type: 11, items: target }; state = packed[++i] || -1; break; case 14: node = {}; state = -2; break; case 15: node = {spread: true}; state = -2; break; case 16: target = []; node = { type: 12, items: target }; state = packed[++i] || -1; break; case 17: case 18: node = type === 18 ? {spread: true} : {}; state = -2; break; case 2: case 33: case 34: node = { name: packed[++i] }; (type === 33) && (node.noValue = 1); (type === 34) && (node.x = 1); state = -2; break; case 35: node = { name: packed[++i], modifier: {} }; state = -2; break; case 36: node = { name: packed[++i] }; state = -2; break; case 37: node = { item: packed[++i] }; var forIndex = packed[++i]; forIndex && (node.index = forIndex); var trackBy = packed[++i]; if (trackBy) { node.trackByRaw = trackBy; node.trackBy = parseExpr(trackBy); } state = -2; break; case 38: case 39: case 41: case 42: case 43: case 44: case 45: node = {}; state = -2; break; // else case 40: node = {value: {}}; break; // Node: Text // Event modifier default: if (!type) { node = {}; state = -2; } } if (!root) { root = node; } if (current) { switch (currentType) { // Node: Tag case 1: if (currentTarget) { current.elses = current.elses || []; current.elses.push(node); if (!(--stateStack[stackIndex])) { stackIndex--; } } else { switch (type) { case 2: case 33: case 34: current.props.push(node); break; case 35: current.events.push(node); break; case 36: current.vars = current.vars || []; current.vars.push(node); break; case 37: current.directives['for'] = node; break; case 38: current.directives['if'] = node; break; case 39: current.directives.elif = node; break; case 40: current.directives['else'] = node; break; case 41: current.directives.ref = node; break; case 42: current.directives.bind = node; break; case 43: current.directives.html = node; break; case 44: current.directives.transition = node; break; case 45: current.directives.is = node; break; case 1: default: current.children.push(node); } if (!(--stateStack[stackIndex])) { if (current.directives['if']) { targetStack[stackIndex] = 'elses'; stateStack[stackIndex] = -3; } else { stackIndex--; } } } break; // Expr: Interp case 7: if (currentState === -2) { stateStack[stackIndex] = -3; current.expr = node; } else { currentTarget.push(node); if (!(--stateStack[stackIndex])) { stackIndex--; } } break; // Expr: CALL case 8: if (currentState === -2) { stateStack[stackIndex] = -3; current.name = node; } else { currentTarget.push(node); if (!(--stateStack[stackIndex])) { stackIndex--; } } break; // Expr: ACCESSOR, TEXT, BINARY, TERTIARY, OBJECT, ARRAY case 6: case 9: case 10: case 12: case 13: case 16: currentTarget.push(node); if (!(--stateStack[stackIndex])) { stackIndex--; } break; // Expr: UNARY // Prop // var // Object Spread Item, Array Item case 11: case 2: case 33: case 34: case 36: case 15: case 17: case 18: current.expr = node; stackIndex--; break; // Expr: Object Item case 14: if (currentState === -2) { stateStack[stackIndex] = -4; current.name = node; } else { current.expr = node; stackIndex--; } break; // Event case 35: if (currentState === -2) { stateStack[stackIndex] = -3; current.expr = node; } else { current.modifier[type] = true; if (!(--stateStack[stackIndex])) { stackIndex--; } } break; // Directive: for, if, elif, ref, bind, html, transition, is case 37: case 38: case 39: case 41: case 42: case 43: case 44: case 45: current.value = node; stackIndex--; break; // Node: Text default: current.textExpr = node; stackIndex--; } } if (state !== -1) { nodeStack[++stackIndex] = node; typeStack[stackIndex] = type; stateStack[stackIndex] = state; targetStack[stackIndex] = target; } } return root; } // exports = module.exports = unpackANode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 给 devtool 发通知消息 */ // var isBrowser = require('../browser/is-browser'); // #[begin] devtool var san4devtool; /** * 给 devtool 发通知消息 * * @param {string} name 消息名称 * @param {*} arg 消息参数 */ function emitDevtool(name, arg) { /* istanbul ignore if */ if (isBrowser && san4devtool && san4devtool.debug && window.__san_devtool__) { window.__san_devtool__.emit(name, arg); } } emitDevtool.start = function (main) { san4devtool = main; emitDevtool('san', main); }; // #[end] // exports = module.exports = emitDevtool; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 组件类 */ // var bind = require('../util/bind'); // var each = require('../util/each'); // var guid = require('../util/guid'); // var extend = require('../util/extend'); // var nextTick = require('../util/next-tick'); // var emitDevtool = require('../util/emit-devtool'); // var ExprType = require('../parser/expr-type'); // var parseExpr = require('../parser/parse-expr'); // var parseTemplate = require('../parser/parse-template'); // var unpackANode = require('../parser/unpack-anode'); // var removeEl = require('../browser/remove-el'); // var Data = require('../runtime/data'); // var evalExpr = require('../runtime/eval-expr'); // var changeExprCompare = require('../runtime/change-expr-compare'); // var DataChangeType = require('../runtime/data-change-type'); // var insertBefore = require('../browser/insert-before'); // var un = require('../browser/un'); // var defineComponent = require('./define-component'); // var ComponentLoader = require('./component-loader'); // var createNode = require('./create-node'); // var preheatEl = require('./preheat-el'); // var parseComponentTemplate = require('./parse-component-template'); // var preheatANode = require('./preheat-a-node'); // var LifeCycle = require('./life-cycle'); // var getANodeProp = require('./get-a-node-prop'); // var isDataChangeByElement = require('./is-data-change-by-element'); // var getEventListener = require('./get-event-listener'); // var reverseElementChildren = require('./reverse-element-children'); // var NodeType = require('./node-type'); // var styleProps = require('./style-props'); // var nodeSBindInit = require('./node-s-bind-init'); // var nodeSBindUpdate = require('./node-s-bind-update'); // var elementOwnAttached = require('./element-own-attached'); // var elementOwnOnEl = require('./element-own-on-el'); // var elementOwnDetach = require('./element-own-detach'); // var elementOwnDispose = require('./element-own-dispose'); // var warnEventListenMethod = require('./warn-event-listen-method'); // var elementDisposeChildren = require('./element-dispose-children'); // var createDataTypesChecker = require('../util/create-data-types-checker'); // var warn = require('../util/warn'); // var handleError = require('../util/handle-error'); /** * 组件类 * * @class * @param {Object} options 初始化参数 */ function Component(options) { // eslint-disable-line // #[begin] error for (var key in Component.prototype) { if (this[key] !== Component.prototype[key]) { /* eslint-disable max-len */ warn('\`' + key + '\` is a reserved key of san components. Overriding this property may cause unknown exceptions.'); /* eslint-enable max-len */ } } // #[end] options = options || {}; this.lifeCycle = LifeCycle.start; this.id = guid++; if (typeof this.construct === 'function') { this.construct(options); } this.children = []; this._elFns = []; this.listeners = {}; this.slotChildren = []; this.implicitChildren = []; var clazz = this.constructor; this.filters = this.filters || clazz.filters || {}; this.computed = this.computed || clazz.computed || {}; this.messages = this.messages || clazz.messages || {}; if (options.transition) { this.transition = options.transition; } this.owner = options.owner; this.scope = options.scope; this.el = options.el; var parent = options.parent; if (parent) { this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent && parent.parentComponent; } else if (this.owner) { this.parentComponent = this.owner; this.scope = this.owner.data; } this.sourceSlotNameProps = []; this.sourceSlots = { named: {} }; // #[begin] devtool this._toPhase('beforeCompile'); // #[end] var proto = clazz.prototype; // pre define components class /* istanbul ignore else */ if (!proto.hasOwnProperty('_cmptReady')) { proto.components = clazz.components || proto.components || {}; var components = proto.components; for (var key in components) { // eslint-disable-line var cmptClass = components[key]; if (typeof cmptClass === 'object' && !(cmptClass instanceof ComponentLoader)) { components[key] = defineComponent(cmptClass); } else if (cmptClass === 'self') { components[key] = clazz; } } proto._cmptReady = 1; } // compile if (!proto.hasOwnProperty('aNode')) { var aPack = clazz.aPack || proto.hasOwnProperty('aPack') && proto.aPack; if (aPack) { proto.aNode = unpackANode(aPack); clazz.aPack = proto.aPack = null; } else { proto.aNode = parseComponentTemplate(clazz); } } preheatANode(proto.aNode, this); this.tagName = proto.aNode.tagName; this.source = typeof options.source === 'string' ? parseTemplate(options.source).children[0] : options.source; preheatANode(this.source); proto.aNode._i++; // #[begin] reverse // // 组件反解,读取注入的组件数据 // if (this.el) { // var firstCommentNode = this.el.firstChild; // if (firstCommentNode && firstCommentNode.nodeType === 3) { // firstCommentNode = firstCommentNode.nextSibling; // } // // if (firstCommentNode && firstCommentNode.nodeType === 8) { // var stumpMatch = firstCommentNode.data.match(/^\s*s-data:([\s\S]+)?$/); // if (stumpMatch) { // var stumpText = stumpMatch[1]; // // // fill component data // options.data = (new Function('return ' // + stumpText // .replace(/^[\s\n]*/, '') // .replace( // /"(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.\d+Z"/g, // function (match, y, mon, d, h, m, s) { // return 'new Date(' + (+y) + ',' + (+mon) + ',' + (+d) // + ',' + (+h) + ',' + (+m) + ',' + (+s) + ')'; // } // ) // ))(); // // if (firstCommentNode.previousSibling) { // removeEl(firstCommentNode.previousSibling); // } // removeEl(firstCommentNode); // } // } // } // #[end] // native事件数组 this.nativeEvents = []; if (this.source) { // 组件运行时传入的结构,做slot解析 this._initSourceSlots(1); for (var i = 0, l = this.source.events.length; i < l; i++) { var eventBind = this.source.events[i]; // 保存当前实例的native事件,下面创建aNode时候做合并 if (eventBind.modifier.native) { this.nativeEvents.push(eventBind); } else { // #[begin] error warnEventListenMethod(eventBind, options.owner); // #[end] this.on( eventBind.name, getEventListener(eventBind, options.owner, this.scope, 1), eventBind ); } } this.tagName = this.tagName || this.source.tagName; this.binds = this.source._b; // init s-bind data this._srcSbindData = nodeSBindInit(this.source.directives.bind, this.scope, this.owner); } this._toPhase('compiled'); // #[begin] devtool this._toPhase('beforeInit'); // #[end] // init data var initData; try { initData = typeof this.initData === 'function' && this.initData(); } catch (e) { handleError(e, this, 'initData'); } initData = extend(initData || {}, options.data || this._srcSbindData); if (this.binds && this.scope) { for (var i = 0, l = this.binds.length; i < l; i++) { var bindInfo = this.binds[i]; var value = evalExpr(bindInfo.expr, this.scope, this.owner); if (typeof value !== 'undefined') { // See: https://github.com/ecomfe/san/issues/191 initData[bindInfo.name] = value; } } } this.data = new Data(initData); this.tagName = this.tagName || 'div'; // #[begin] allua // ie8- 不支持innerHTML输出自定义标签 /* istanbul ignore if */ if (ieOldThan9 && this.tagName.indexOf('-') > 0) { this.tagName = 'div'; } // #[end] // #[begin] error // 在初始化 + 数据绑定后,开始数据校验 // NOTE: 只在开发版本中进行属性校验 var dataTypes = this.dataTypes || clazz.dataTypes; if (dataTypes) { var dataTypeChecker = createDataTypesChecker( dataTypes, this.name || clazz.name ); this.data.setTypeChecker(dataTypeChecker); this.data.checkDataTypes(); } // #[end] this.computedDeps = {}; for (var expr in this.computed) { if (this.computed.hasOwnProperty(expr) && !this.computedDeps[expr]) { this._calcComputed(expr); } } this._initDataChanger(); this._sbindData = nodeSBindInit(this.aNode.directives.bind, this.data, this); this._toPhase('inited'); // #[begin] reverse // var reverseWalker = options.reverseWalker; // if (this.el || reverseWalker) { // var RootComponentType = this.components[this.aNode.tagName]; // // if (reverseWalker && (this.aNode.hasRootNode || RootComponentType)) { // this._rootNode = createReverseNode(this.aNode, this, this.data, this, reverseWalker); // this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode()); // } // else if (this.el && RootComponentType) { // this._rootNode = new RootComponentType({ // source: this.aNode, // owner: this, // scope: this.data, // parent: this, // el: this.el // }); // } // else { // if (reverseWalker) { // var currentNode = reverseWalker.current; // if (currentNode && currentNode.nodeType === 1) { // this.el = currentNode; // reverseWalker.goNext(); // } // } // // reverseElementChildren(this, this.data, this); // } // // this._toPhase('created'); // this._attached(); // this._toPhase('attached'); // } // #[end] } /** * 初始化创建组件外部传入的插槽对象 * * @protected * @param {boolean} isFirstTime 是否初次对sourceSlots进行计算 */ Component.prototype._initSourceSlots = function (isFirstTime) { this.sourceSlots.named = {}; // 组件运行时传入的结构,做slot解析 if (this.source && this.scope) { var sourceChildren = this.source.children; for (var i = 0, l = sourceChildren.length; i < l; i++) { var child = sourceChildren[i]; var target; var slotBind = !child.textExpr && getANodeProp(child, 'slot'); if (slotBind) { isFirstTime && this.sourceSlotNameProps.push(slotBind); var slotName = evalExpr(slotBind.expr, this.scope, this.owner); target = this.sourceSlots.named[slotName]; if (!target) { target = this.sourceSlots.named[slotName] = []; } target.push(child); } else if (isFirstTime) { target = this.sourceSlots.noname; if (!target) { target = this.sourceSlots.noname = []; } target.push(child); } } } }; /** * 类型标识 * * @type {string} */ Component.prototype.nodeType = 5; /** * 在下一个更新周期运行函数 * * @param {Function} fn 要运行的函数 */ Component.prototype.nextTick = nextTick; Component.prototype._ctx = (new Date()).getTime().toString(16); /* eslint-disable operator-linebreak */ /** * 使节点到达相应的生命周期 * * @protected * @param {string} name 生命周期名称 */ Component.prototype._toPhase = function (name) { if (!this.lifeCycle[name]) { this.lifeCycle = LifeCycle[name] || this.lifeCycle; if (typeof this[name] === 'function') { try { this[name](); } catch (e) { handleError(e, this, 'hook:' + name); } } this._afterLife = this.lifeCycle; // 通知devtool // #[begin] devtool emitDevtool('comp-' + name, this); // #[end] } }; /* eslint-enable operator-linebreak */ /** * 添加事件监听器 * * @param {string} name 事件名 * @param {Function} listener 监听器 * @param {string?} declaration 声明式 */ Component.prototype.on = function (name, listener, declaration) { if (typeof listener === 'function') { if (!this.listeners[name]) { this.listeners[name] = []; } this.listeners[name].push({fn: listener, declaration: declaration}); } }; /** * 移除事件监听器 * * @param {string} name 事件名 * @param {Function=} listener 监听器 */ Component.prototype.un = function (name, listener) { var nameListeners = this.listeners[name]; var len = nameListeners && nameListeners.length; while (len--) { if (!listener || listener === nameListeners[len].fn) { nameListeners.splice(len, 1); } } }; /** * 派发事件 * * @param {string} name 事件名 * @param {Object} event 事件对象 */ Component.prototype.fire = function (name, event) { var me = this; // #[begin] devtool emitDevtool('comp-event', { name: name, event: event, target: this }); // #[end] each(this.listeners[name], function (listener) { try { listener.fn.call(me, event); } catch (e) { handleError(e, me, 'event:' + name); } }); }; /** * 计算 computed 属性的值 * * @private * @param {string} computedExpr computed表达式串 */ Component.prototype._calcComputed = function (computedExpr) { var computedDeps = this.computedDeps[computedExpr]; if (!computedDeps) { computedDeps = this.computedDeps[computedExpr] = {}; } var me = this; try { var result = this.computed[computedExpr].call({ data: { get: function (expr) { // #[begin] error if (!expr) { throw new Error('[SAN ERROR] call get method in computed need argument'); } // #[end] if (!computedDeps[expr]) { computedDeps[expr] = 1; if (me.computed[expr] && !me.computedDeps[expr]) { me._calcComputed(expr); } me.watch(expr, function () { me._calcComputed(computedExpr); }); } return me.data.get(expr); } } }); this.data.set(computedExpr, result); } catch (e) { handleError(e, this, 'computed:' + computedExpr); } }; /** * 派发消息 * 组件可以派发消息,消息将沿着组件树向上传递,直到遇上第一个处理消息的组件 * * @param {string} name 消息名称 * @param {*?} value 消息值 */ Component.prototype.dispatch = function (name, value) { var parentComponent = this.parentComponent; while (parentComponent) { var handler = parentComponent.messages[name] || parentComponent.messages['*']; if (typeof handler === 'function') { // #[begin] devtool emitDevtool('comp-message', { target: this, value: value, name: name, receiver: parentComponent }); // #[end] try { handler.call( parentComponent, {target: this, value: value, name: name} ); } catch (e) { handleError(e, parentComponent, 'message:' + (name || '*')); } return; } parentComponent = parentComponent.parentComponent; } // #[begin] devtool emitDevtool('comp-message', {target: this, value: value, name: name}); // #[end] }; /** * 获取组件内部的 slot * * @param {string=} name slot名称,空为default slot * @return {Array} */ Component.prototype.slot = function (name) { var result = []; var me = this; function childrenTraversal(children) { each(children, function (child) { if (child.nodeType === 6 && child.owner === me) { if (child.isNamed && child.name === name || !child.isNamed && !name ) { result.push(child); } } else { childrenTraversal(child.children); } }); } childrenTraversal(this.children); return result; }; /** * 获取带有 san-ref 指令的子组件引用 * * @param {string} name 子组件的引用名 * @return {Component} */ Component.prototype.ref = function (name) { var refTarget; var owner = this; function childrenTraversal(children) { if (children) { for (var i = 0, l = children.length; i < l; i++) { elementTraversal(children[i]); if (refTarget) { return; } } } } function elementTraversal(element) { var nodeType = element.nodeType; if (nodeType === 1) { return; } if (element.owner === owner) { var ref; switch (element.nodeType) { case 4: ref = element.aNode.directives.ref; if (ref && evalExpr(ref.value, element.scope, owner) === name) { refTarget = element.el; } break; case 5: ref = element.source.directives.ref; if (ref && evalExpr(ref.value, element.scope, owner) === name) { refTarget = element; } } if (refTarget) { return; } childrenTraversal(element.slotChildren); } if (refTarget) { return; } childrenTraversal(element.children); } this._rootNode ? elementTraversal(this._rootNode) : childrenTraversal(this.children); return refTarget; }; /** * 视图更新函数 * * @param {Array?} changes 数据变化信息 */ Component.prototype._update = function (changes) { if (this.lifeCycle.disposed) { return; } var me = this; var needReloadForSlot = false; this._notifyNeedReload = function () { needReloadForSlot = true; }; if (changes) { if (this.source) { this._srcSbindData = nodeSBindUpdate( this.source.directives.bind, this._srcSbindData, this.scope, this.owner, changes, function (name, value) { if (name in me.source._pi) { return; } me.data.set(name, value, { target: { node: me.owner } }); } ); } each(changes, function (change) { var changeExpr = change.expr; each(me.binds, function (bindItem) { var relation; var setExpr = bindItem.name; var updateExpr = bindItem.expr; if (!isDataChangeByElement(change, me, setExpr) && (relation = changeExprCompare(changeExpr, updateExpr, me.scope)) ) { if (relation > 2) { setExpr = { type: 4, paths: [ { type: 1, value: setExpr } ].concat(changeExpr.paths.slice(updateExpr.paths.length)) }; updateExpr = changeExpr; } if (relation >= 2 && change.type === 2) { me.data.splice(setExpr, [change.index, change.deleteCount].concat(change.insertions), { target: { node: me.owner } }); } else { me.data.set(setExpr, evalExpr(updateExpr, me.scope, me.owner), { target: { node: me.owner } }); } } }); each(me.sourceSlotNameProps, function (bindItem) { needReloadForSlot = needReloadForSlot || changeExprCompare(changeExpr, bindItem.expr, me.scope); return !needReloadForSlot; }); }); if (needReloadForSlot) { this._initSourceSlots(); this._repaintChildren(); } else { var slotChildrenLen = this.slotChildren.length; while (slotChildrenLen--) { var slotChild = this.slotChildren[slotChildrenLen]; if (slotChild.lifeCycle.disposed) { this.slotChildren.splice(slotChildrenLen, 1); } else if (slotChild.isInserted) { slotChild._update(changes, 1); } } } } var dataChanges = this._dataChanges; if (dataChanges) { // #[begin] devtool this._toPhase('beforeUpdate'); // #[end] this._dataChanges = null; this._sbindData = nodeSBindUpdate( this.aNode.directives.bind, this._sbindData, this.data, this, dataChanges, function (name, value) { if (me._rootNode || (name in me.aNode._pi)) { return; } getPropHandler(me.tagName, name)(me.el, value, name, me); } ); var htmlDirective = this.aNode.directives.html; if (this._rootNode) { this._rootNode._update(dataChanges); this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode()); } else if (htmlDirective) { var len = dataChanges.length; while (len--) { if (changeExprCompare(dataChanges[len].expr, htmlDirective.value, this.data)) { // #[begin] error warnSetHTML(this.el); // #[end] this.el.innerHTML = evalExpr(htmlDirective.value, this.data, this); break; } } } else { var dynamicProps = this.aNode._dp; for (var i = 0; i < dynamicProps.length; i++) { var prop = dynamicProps[i]; for (var j = 0; j < dataChanges.length; j++) { var change = dataChanges[j]; if (changeExprCompare(change.expr, prop.expr, this.data) || prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.data) ) { prop.handler(this.el, evalExpr(prop.expr, this.data, this), prop.name, this); break; } } } for (var i = 0; i < this.children.length; i++) { this.children[i]._update(dataChanges); } } if (needReloadForSlot) { this._initSourceSlots(); this._repaintChildren(); } for (var i = 0; i < this.implicitChildren.length; i++) { this.implicitChildren[i]._update(dataChanges); } if (typeof this.updated === 'function') { this.updated(); } if (this.owner && this._updateBindxOwner(dataChanges)) { this.owner._update(); } } this._notifyNeedReload = null; }; Component.prototype._updateBindxOwner = function (dataChanges) { var me = this; var xbindUped; each(dataChanges, function (change) { each(me.binds, function (bindItem) { var changeExpr = change.expr; if (bindItem.x && !isDataChangeByElement(change, me.owner) && changeExprCompare(changeExpr, parseExpr(bindItem.name), me.data) ) { var updateScopeExpr = bindItem.expr; if (changeExpr.paths.length > 1) { updateScopeExpr = { type: 4, paths: bindItem.expr.paths.concat(changeExpr.paths.slice(1)) }; } xbindUped = 1; me.scope.set( updateScopeExpr, evalExpr(changeExpr, me.data, me), { target: { node: me, prop: bindItem.name } } ); } }); }); return xbindUped; }; /** * 重新绘制组件的内容 * 当 dynamic slot name 发生变更或 slot 匹配发生变化时,重新绘制 * 在组件级别重绘有点粗暴,但是能保证视图结果正确性 */ Component.prototype._repaintChildren = function () { // TODO: repaint once? if (this._rootNode) { var parentEl = this._rootNode.el.parentNode; var beforeEl = this._rootNode.el.nextSibling; this._rootNode.dispose(0, 1); this.slotChildren = []; this._rootNode = createNode(this.aNode, this, this.data, this); this._rootNode.attach(parentEl, beforeEl); this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode()); } else { elementDisposeChildren(this.children, 0, 1); this.children = []; this.slotChildren = []; for (var i = 0, l = this.aNode.children.length; i < l; i++) { var child = createNode(this.aNode.children[i], this, this.data, this); this.children.push(child); child.attach(this.el); } } }; /** * 初始化组件内部监听数据变化 * * @private * @param {Object} change 数据变化信息 */ Component.prototype._initDataChanger = function (change) { var me = this; this._dataChanger = function (change) { if (me._afterLife.created) { if (!me._dataChanges) { nextTick(me._update, me); me._dataChanges = []; } me._dataChanges.push(change); } else if (me.lifeCycle.inited && me.owner) { me._updateBindxOwner([change]); } }; this.data.listen(this._dataChanger); }; /** * 监听组件的数据变化 * * @param {string} dataName 变化的数据项 * @param {Function} listener 监听函数 */ Component.prototype.watch = function (dataName, listener) { var dataExpr = parseExpr(dataName); var value = evalExpr(dataExpr, this.data, this); var me = this; this.data.listen(function (change) { if (changeExprCompare(change.expr, dataExpr, me.data)) { var newValue = evalExpr(dataExpr, me.data, me); if (newValue !== value) { var oldValue = value; value = newValue; try { listener.call( me, newValue, { oldValue: oldValue, newValue: newValue, change: change } ); } catch (e) { handleError(e, me, 'watch:' + dataName); } } } }); }; Component.prototype._getElAsRootNode = function () { return this.el; }; /** * 将组件attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ Component.prototype.attach = function (parentEl, beforeEl) { if (!this.lifeCycle.attached) { // #[begin] devtool this._toPhase('beforeAttach'); // #[end] var aNode = this.aNode; if (aNode.hasRootNode || this.components[aNode.tagName]) { // #[begin] devtool this._toPhase('beforeCreate'); // #[end] this._rootNode = this._rootNode || createNode(aNode, this, this.data, this); this._rootNode.attach(parentEl, beforeEl); this._rootNode._getElAsRootNode && (this.el = this._rootNode._getElAsRootNode()); this._toPhase('created'); } else { if (!this.el) { // #[begin] devtool this._toPhase('beforeCreate'); // #[end] var props; if (aNode._ce && aNode._i > 2) { props = aNode._dp; this.el = (aNode._el || preheatEl(aNode)).cloneNode(false); } else { props = aNode.props; this.el = createEl(this.tagName); } if (this._sbindData) { for (var key in this._sbindData) { if (this._sbindData.hasOwnProperty(key)) { getPropHandler(this.tagName, key)( this.el, this._sbindData[key], key, this ); } } } for (var i = 0, l = props.length; i < l; i++) { var prop = props[i]; var value = evalExpr(prop.expr, this.data, this); if (value || !styleProps[prop.name]) { prop.handler(this.el, value, prop.name, this); } } this._toPhase('created'); } insertBefore(this.el, parentEl, beforeEl); if (!this._contentReady) { var htmlDirective = aNode.directives.html; if (htmlDirective) { // #[begin] error warnSetHTML(this.el); // #[end] this.el.innerHTML = evalExpr(htmlDirective.value, this.data, this); } else { for (var i = 0, l = aNode.children.length; i < l; i++) { var childANode = aNode.children[i]; var child = childANode.Clazz ? new childANode.Clazz(childANode, this, this.data, this) : createNode(childANode, this, this.data, this); this.children.push(child); child.attach(this.el); } } this._contentReady = 1; } this._attached(); } this._toPhase('attached'); // element 都是内部创建的,只有动态创建的 component 才会进入这个分支 if (this.owner && !this.parent) { this.owner.implicitChildren.push(this); } } }; Component.prototype.detach = elementOwnDetach; Component.prototype.dispose = elementOwnDispose; Component.prototype._onEl = elementOwnOnEl; Component.prototype._attached = elementOwnAttached; Component.prototype._leave = function () { if (this.leaveDispose) { if (!this.lifeCycle.disposed) { // #[begin] devtool this._toPhase('beforeDetach'); // #[end] this.data.unlisten(); this.dataChanger = null; this._dataChanges = null; var len = this.implicitChildren.length; while (len--) { this.implicitChildren[len].dispose(0, 1); } this.implicitChildren = null; this.source = null; this.sourceSlots = null; this.sourceSlotNameProps = null; // 这里不用挨个调用 dispose 了,因为 children 释放链会调用的 this.slotChildren = null; if (this._rootNode) { // 如果没有parent,说明是一个root component,一定要从dom树中remove this._rootNode.dispose(this.disposeNoDetach && this.parent); } else { var len = this.children.length; while (len--) { this.children[len].dispose(1, 1); } len = this._elFns.length; while (len--) { var fn = this._elFns[len]; un(this.el, fn[0], fn[1], fn[2]); } this._elFns = null; // #[begin] allua /* istanbul ignore if */ if (this._inputTimer) { clearInterval(this._inputTimer); this._inputTimer = null; } // #[end] // 如果没有parent,说明是一个root component,一定要从dom树中remove if (!this.disposeNoDetach || !this.parent) { removeEl(this.el); } } this._toPhase('detached'); // #[begin] devtool this._toPhase('beforeDispose'); // #[end] this._rootNode = null; this.el = null; this.owner = null; this.scope = null; this.children = null; this._toPhase('disposed'); if (this._ondisposed) { this._ondisposed(); } } } else if (this.lifeCycle.attached) { // #[begin] devtool this._toPhase('beforeDetach'); // #[end] if (this._rootNode) { if (this._rootNode.detach) { this._rootNode.detach(); } else { this._rootNode.dispose(); this._rootNode = null; } } else { removeEl(this.el); } this._toPhase('detached'); } }; // exports = module.exports = Component; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 创建组件类 */ // var Component = require('./component'); // var inherits = require('../util/inherits'); /** * 创建组件类 * * @param {Object} proto 组件类的方法表 * @param {Function=} SuperComponent 父组件类 * @return {Function} */ function defineComponent(proto, SuperComponent) { // 如果传入一个不是 san component 的 constructor,直接返回不是组件构造函数 // 这种场景导致的错误 san 不予考虑 if (typeof proto === 'function') { return proto; } // #[begin] error if (typeof proto !== 'object') { throw new Error('[SAN FATAL] defineComponent need a plain object.'); } // #[end] SuperComponent = SuperComponent || Component; function ComponentClass(option) { // eslint-disable-line SuperComponent.call(this, option); } ComponentClass.prototype = proto; inherits(ComponentClass, SuperComponent); return ComponentClass; } // exports = module.exports = defineComponent; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 组件Loader类 */ // var nextTick = require('../util/next-tick'); // var each = require('../util/each'); /** * 组件Loader类 * * @class * * @param {Function} load load方法 * @param {Function=} placeholder loading过程中渲染的组件 * @param {Function=} fallback load失败时渲染的组件 */ function ComponentLoader(load, placeholder, fallback) { this.load = load; this.placeholder = placeholder; this.fallback = fallback; this.listeners = []; } /** * 开始加载组件 * * @param {Function} onload 组件加载完成监听函数 */ ComponentLoader.prototype.start = function (onload) { var me = this; switch (this.state) { case 2: nextTick(function () { onload(me.Component); }); break; case 1: this.listeners.push(onload); break; default: this.listeners.push(onload); this.state = 1; var startLoad = this.load(); var done = function (RealComponent) { me.done(RealComponent); }; if (startLoad && typeof startLoad.then === 'function') { startLoad.then(done, done); } } }; /** * 完成组件加载 * * @param {Function=} ComponentClass 组件类 */ ComponentLoader.prototype.done = function (ComponentClass) { this.state = 2; ComponentClass = ComponentClass || this.fallback; this.Component = ComponentClass; each(this.listeners, function (listener) { listener(ComponentClass); }); }; // exports = module.exports = ComponentLoader; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 解析组件的模板 */ // var warn = require('../util/warn'); // var parseTemplate = require('../parser/parse-template'); // var ExprType = require('../parser/expr-type'); /** * 解析组件的模板 * * @param {Function} ComponentClass 组件类 * @return {ANode} */ function parseComponentTemplate(ComponentClass) { var proto = ComponentClass.prototype; var tplANode = parseTemplate(ComponentClass.template || proto.template, { trimWhitespace: proto.trimWhitespace || ComponentClass.trimWhitespace, delimiters: proto.delimiters || ComponentClass.delimiters }); var aNode = tplANode.children[0]; if (aNode && aNode.textExpr) { aNode = null; } // #[begin] error if (tplANode.children.length !== 1 || !aNode) { warn('Component template must have a root element.'); } // #[end] aNode = aNode || { directives: {}, props: [], events: [], children: [] }; if (aNode.tagName === 'template') { delete aNode.tagName; } if (proto.autoFillStyleAndId !== false && ComponentClass.autoFillStyleAndId !== false) { var extraPropExists = {}; var len = aNode.props.length; while (len--) { var prop = aNode.props[len]; switch (prop.name) { case 'class': case 'style': extraPropExists[prop.name] = true; prop.expr = { type: 5, expr: { type: 4, paths: [ {type: 1, value: prop.name} ] }, filters: [{ type: 6, args: [prop.expr], name: { type: 4, paths: [ {type: 1, value: '_x' + prop.name} ] } }] } break; case 'id': extraPropExists[prop.name] = true; } } if (!extraPropExists['class']) { aNode.props.push({ name: 'class', expr: { type: 5, expr: { type: 4, paths: [ {type: 1, value: 'class'} ] }, filters: [{ type: 6, args: [], name: { type: 4, paths: [ {type: 1, value: '_class'} ] } }] } }); } if (!extraPropExists.style) { aNode.props.push({ name: 'style', expr: { type: 5, expr: { type: 4, paths: [ {type: 1, value: 'style'} ] }, filters: [{ type: 6, args: [], name: { type: 4, paths: [ {type: 1, value: '_style'} ] } }] } }); } if (!extraPropExists.id) { aNode.props.push({ name: 'id', expr: { type: 4, paths: [ {type: 1, value: 'id'} ] } }); } } return aNode; } // exports = module.exports = parseComponentTemplate; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 常用标签表,用于 element 创建优化 */ // var splitStr2Obj = require('../util/split-str-2-obj'); /** * 常用标签表 * * @type {Object} */ var hotTags = splitStr2Obj( 'div,span,img,ul,ol,li,dl,dt,dd,a,b,u,hr,' + 'form,input,textarea,button,label,select,option,' + 'table,tbody,th,tr,td,thead,main,aside,header,footer,nav' ); // exports = module.exports = hotTags; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 判断是否结束桩 */ // #[begin] reverse // /** // * 判断是否结束桩 // * // * @param {HTMLElement|HTMLComment} target 要判断的元素 // * @param {string} type 桩类型 // * @return {boolean} // */ // function isEndStump(target, type) { // return target.nodeType === 8 && target.data === '/s-' + type; // } // #[end] // exports = module.exports = isEndStump; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file text 节点类 */ // var guid = require('../util/guid'); // var isBrowser = require('../browser/is-browser'); // var removeEl = require('../browser/remove-el'); // var insertBefore = require('../browser/insert-before'); // var changeExprCompare = require('../runtime/change-expr-compare'); // var evalExpr = require('../runtime/eval-expr'); // var NodeType = require('./node-type'); // var warnSetHTML = require('./warn-set-html'); // var isEndStump = require('./is-end-stump'); // var getNodePath = require('./get-node-path'); /** * text 节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function TextNode(aNode, parent, scope, owner, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; // #[begin] reverse // if (reverseWalker) { // var currentNode = reverseWalker.current; // if (currentNode) { // switch (currentNode.nodeType) { // case 8: // if (currentNode.data === 's-text') { // this.id = this.id || guid++; // this.sel = currentNode; // currentNode.data = this.id; // reverseWalker.goNext(); // // while (1) { // eslint-disable-line // currentNode = reverseWalker.current; // /* istanbul ignore if */ // if (!currentNode) { // throw new Error('[SAN REVERSE ERROR] Text end flag not found. \nPaths: ' // + getNodePath(this).join(' > ')); // } // // if (isEndStump(currentNode, 'text')) { // this.el = currentNode; // reverseWalker.goNext(); // currentNode.data = this.id; // break; // } // // reverseWalker.goNext(); // } // } // break; // // case 3: // reverseWalker.goNext(); // if (!this.aNode.textExpr.original) { // this.el = currentNode; // } // break; // } // } // else { // this.el = document.createTextNode(''); // insertBefore(this.el, reverseWalker.target, reverseWalker.current); // } // } // #[end] } TextNode.prototype.nodeType = 1; /** * 将text attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ TextNode.prototype.attach = function (parentEl, beforeEl) { this.content = evalExpr(this.aNode.textExpr, this.scope, this.owner); if (this.content == null) { this.content = ''; } if (this.aNode.textExpr.original) { this.id = this.id || guid++; this.sel = document.createComment(this.id); insertBefore(this.sel, parentEl, beforeEl); this.el = document.createComment(this.id); insertBefore(this.el, parentEl, beforeEl); var tempFlag = document.createElement('script'); parentEl.insertBefore(tempFlag, this.el); tempFlag.insertAdjacentHTML('beforebegin', this.content); parentEl.removeChild(tempFlag); } else { this.el = document.createTextNode(this.content); insertBefore(this.el, parentEl, beforeEl); } }; /** * 销毁 text 节点 * * @param {boolean=} noDetach 是否不要把节点从dom移除 */ TextNode.prototype.dispose = function (noDetach) { if (!noDetach) { removeEl(this.el); removeEl(this.sel); } this.el = null; this.sel = null; }; var textUpdateProp = isBrowser && (typeof document.createTextNode('').textContent === 'string' ? 'textContent' : 'data'); /** * 更新 text 节点的视图 * * @param {Array} changes 数据变化信息 */ TextNode.prototype._update = function (changes) { if (this.aNode.textExpr.value) { return; } var len = changes.length; while (len--) { if (changeExprCompare(changes[len].expr, this.aNode.textExpr, this.scope)) { var text = evalExpr(this.aNode.textExpr, this.scope, this.owner); if (text == null) { text = ''; } if (text !== this.content) { this.content = text; if (this.aNode.textExpr.original) { var startRemoveEl = this.sel.nextSibling; var parentEl = this.el.parentNode; while (startRemoveEl !== this.el) { var removeTarget = startRemoveEl; startRemoveEl = startRemoveEl.nextSibling; removeEl(removeTarget); } // #[begin] error warnSetHTML(parentEl); // #[end] var tempFlag = document.createElement('script'); parentEl.insertBefore(tempFlag, this.el); tempFlag.insertAdjacentHTML('beforebegin', text); parentEl.removeChild(tempFlag); } else { this.el[textUpdateProp] = text; } } return; } } }; // exports = module.exports = TextNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file slot 节点类 */ // var each = require('../util/each'); // var guid = require('../util/guid'); // var extend = require('../util/extend'); // var ExprType = require('../parser/expr-type'); // var evalExpr = require('../runtime/eval-expr'); // var Data = require('../runtime/data'); // var DataChangeType = require('../runtime/data-change-type'); // var changeExprCompare = require('../runtime/change-expr-compare'); // var removeEl = require('../browser/remove-el'); // var NodeType = require('./node-type'); // var LifeCycle = require('./life-cycle'); // var getANodeProp = require('./get-a-node-prop'); // var nodeSBindInit = require('./node-s-bind-init'); // var nodeSBindUpdate = require('./node-s-bind-update'); // var createReverseNode = require('./create-reverse-node'); // var elementDisposeChildren = require('./element-dispose-children'); // var nodeOwnOnlyChildrenAttach = require('./node-own-only-children-attach'); /** * slot 节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function SlotNode(aNode, parent, scope, owner, reverseWalker) { this.owner = owner; this.scope = scope; this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.id = guid++; this.lifeCycle = LifeCycle.start; this.children = []; // calc slot name this.nameBind = getANodeProp(aNode, 'name'); if (this.nameBind) { this.isNamed = true; this.name = evalExpr(this.nameBind.expr, this.scope, this.owner); } // calc aNode children var sourceSlots = owner.sourceSlots; var matchedSlots; if (sourceSlots) { matchedSlots = this.isNamed ? sourceSlots.named[this.name] : sourceSlots.noname; } if (matchedSlots) { this.isInserted = true; } this.aNode = { directives: aNode.directives, props: [], events: [], children: matchedSlots || aNode.children.slice(0), vars: aNode.vars }; this._sbindData = nodeSBindInit(aNode.directives.bind, this.scope, this.owner); // calc scoped slot vars var initData; if (this._sbindData) { initData = extend({}, this._sbindData); } if (aNode.vars) { initData = initData || {}; each(aNode.vars, function (varItem) { initData[varItem.name] = evalExpr(varItem.expr, scope, owner); }); } // child owner & child scope if (this.isInserted) { this.childOwner = owner.owner; this.childScope = owner.scope; } if (initData) { this.isScoped = true; this.childScope = new Data(initData, this.childScope || this.scope); } owner.slotChildren.push(this); // #[begin] reverse // if (reverseWalker) { // var currentNode = reverseWalker.current; // var hasFlagComment; // // // start flag // if (currentNode && currentNode.nodeType === 8 && currentNode.data === 's-slot') { // this.sel = reverseWalker.current; // hasFlagComment = 1; // reverseWalker.goNext(); // } // else { // this.sel = document.createComment(this.id); // reverseWalker.current // ? reverseWalker.target.insertBefore(this.sel, reverseWalker.current) // : reverseWalker.target.appendChild(this.sel); // } // // var aNodeChildren = this.aNode.children; // for (var i = 0, l = aNodeChildren.length; i < l; i++) { // this.children.push(createReverseNode( // aNodeChildren[i], // this, // this.childScope || this.scope, // this.childOwner || this.owner, // reverseWalker // )); // } // // // end flag // if (hasFlagComment) { // this.el = reverseWalker.current; // reverseWalker.goNext(); // } // else { // this.el = document.createComment(this.id); // reverseWalker.current // ? reverseWalker.target.insertBefore(this.el, reverseWalker.current) // : reverseWalker.target.appendChild(this.el); // } // // this.lifeCycle = LifeCycle.attached; // } // #[end] } SlotNode.prototype.nodeType = 6; /** * 销毁释放 slot * * @param {boolean=} noDetach 是否不要把节点从dom移除 * @param {boolean=} noTransition 是否不显示过渡动画效果 */ SlotNode.prototype.dispose = function (noDetach, noTransition) { this.childOwner = null; this.childScope = null; elementDisposeChildren(this.children, noDetach, noTransition); if (!noDetach) { removeEl(this.el); removeEl(this.sel); } this.sel = null; this.el = null; this.owner = null; this.scope = null; this.children = null; this.lifeCycle = LifeCycle.disposed; if (this._ondisposed) { this._ondisposed(); } }; SlotNode.prototype.attach = nodeOwnOnlyChildrenAttach; /** * 视图更新函数 * * @param {Array} changes 数据变化信息 * @param {boolean=} isFromOuter 变化信息是否来源于父组件之外的组件 * @return {boolean} */ SlotNode.prototype._update = function (changes, isFromOuter) { var me = this; if (this.nameBind && evalExpr(this.nameBind.expr, this.scope, this.owner) !== this.name) { this.owner._notifyNeedReload(); return false; } if (isFromOuter) { if (this.isInserted) { for (var i = 0; i < this.children.length; i++) { this.children[i]._update(changes); } } } else { if (this.isScoped) { var varKeys = {}; each(this.aNode.vars, function (varItem) { varKeys[varItem.name] = 1; me.childScope.set(varItem.name, evalExpr(varItem.expr, me.scope, me.owner)); }); var scopedChanges = []; this._sbindData = nodeSBindUpdate( this.aNode.directives.bind, this._sbindData, this.scope, this.owner, changes, function (name, value) { if (varKeys[name]) { return; } me.childScope.set(name, value); scopedChanges.push({ type: 1, expr: { type: 4, paths: [ {type: 1, value: name} ] }, value: value, option: {} }); } ); each(changes, function (change) { if (!me.isInserted) { scopedChanges.push(change); } each(me.aNode.vars, function (varItem) { var name = varItem.name; var relation = changeExprCompare(change.expr, varItem.expr, me.scope); if (relation < 1) { return; } if (change.type !== 2) { scopedChanges.push({ type: 1, expr: { type: 4, paths: [ {type: 1, value: name} ] }, value: me.childScope.get(name), option: change.option }); } else if (relation === 2) { scopedChanges.push({ expr: { type: 4, paths: [ {type: 1, value: name} ] }, type: 2, index: change.index, deleteCount: change.deleteCount, value: change.value, insertions: change.insertions, option: change.option }); } }); }); for (var i = 0; i < this.children.length; i++) { this.children[i]._update(scopedChanges); } } else if (!this.isInserted) { for (var i = 0; i < this.children.length; i++) { this.children[i]._update(changes); } } } }; // exports = module.exports = SlotNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file for 指令节点类 */ // var inherits = require('../util/inherits'); // var each = require('../util/each'); // var guid = require('../util/guid'); // var ExprType = require('../parser/expr-type'); // var parseExpr = require('../parser/parse-expr'); // var Data = require('../runtime/data'); // var DataChangeType = require('../runtime/data-change-type'); // var changeExprCompare = require('../runtime/change-expr-compare'); // var evalExpr = require('../runtime/eval-expr'); // var changesIsInDataRef = require('../runtime/changes-is-in-data-ref'); // var insertBefore = require('../browser/insert-before'); // var NodeType = require('./node-type'); // var createNode = require('./create-node'); // var createReverseNode = require('./create-reverse-node'); // var nodeOwnSimpleDispose = require('./node-own-simple-dispose'); // var nodeOwnCreateStump = require('./node-own-create-stump'); /** * 循环项的数据容器类 * * @inner * @class * @param {Object} forElement for元素对象 * @param {*} item 当前项的数据 * @param {number} index 当前项的索引 */ function ForItemData(forElement, item, index) { this.parent = forElement.scope; this.raw = {}; this.listeners = []; this.directive = forElement.aNode.directives['for']; // eslint-disable-line dot-notation this.indexName = this.directive.index || '$index'; this.raw[this.directive.item] = item; this.raw[this.indexName] = index; } /** * 将数据操作的表达式,转换成为对parent数据操作的表达式 * 主要是对item和index进行处理 * * @param {Object} expr 表达式 * @return {Object} */ ForItemData.prototype.exprResolve = function (expr) { var directive = this.directive; if (expr.type === 4 && expr.paths[0].value === directive.item) { expr = { type: 4, paths: directive.value.paths.concat( { type: 2, value: this.raw[this.indexName] }, expr.paths.slice(1) ) }; } var resolvedPaths = []; for (var i = 0, l = expr.paths.length; i < l; i++) { var pathSeg = expr.paths[i]; if (pathSeg.type === 4) { switch (pathSeg.paths[0].value) { case directive.item: pathSeg = { type: 4, paths: directive.value.paths.concat( { type: 2, value: this.raw[this.indexName] }, pathSeg.paths.slice(1) ) }; break; case this.indexName: pathSeg = { type: 2, value: this.raw[this.indexName] }; break; } } resolvedPaths.push(pathSeg); } return { type: 4, paths: resolvedPaths }; }; // 代理数据操作方法 inherits(ForItemData, Data); each( ['set', 'remove', 'unshift', 'shift', 'push', 'pop', 'splice'], function (method) { ForItemData.prototype['_' + method] = Data.prototype[method]; ForItemData.prototype[method] = function (expr) { expr = this.exprResolve(parseExpr(expr)); this.parent[method].apply( this.parent, [expr].concat(Array.prototype.slice.call(arguments, 1)) ); }; } ); /** * for 指令节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function ForNode(aNode, parent, scope, owner, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.id = guid++; this.children = []; this.param = aNode.directives['for']; // eslint-disable-line dot-notation this.itemPaths = [ { type: 1, value: this.param.item } ]; this.itemExpr = { type: 4, paths: this.itemPaths, raw: this.param.item }; if (this.param.index) { this.indexExpr = { type: 4, paths: [{ type: 1, value: '' + this.param.index }] }; } // #[begin] reverse // if (reverseWalker) { // this.listData = evalExpr(this.param.value, this.scope, this.owner); // if (this.listData instanceof Array) { // for (var i = 0; i < this.listData.length; i++) { // this.children.push(createReverseNode( // this.aNode.forRinsed, // this, // new ForItemData(this, this.listData[i], i), // this.owner, // reverseWalker // )); // } // } // else if (this.listData && typeof this.listData === 'object') { // for (var i in this.listData) { // if (this.listData.hasOwnProperty(i) && this.listData[i] != null) { // this.children.push(createReverseNode( // this.aNode.forRinsed, // this, // new ForItemData(this, this.listData[i], i), // this.owner, // reverseWalker // )); // } // } // } // // this._create(); // insertBefore(this.el, reverseWalker.target, reverseWalker.current); // } // #[end] } ForNode.prototype.nodeType = 3; ForNode.prototype._create = nodeOwnCreateStump; ForNode.prototype.dispose = nodeOwnSimpleDispose; /** * 将元素attach到页面的行为 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ ForNode.prototype.attach = function (parentEl, beforeEl) { this._create(); insertBefore(this.el, parentEl, beforeEl); this.listData = evalExpr(this.param.value, this.scope, this.owner); this._createChildren(); }; /** * 创建子元素 */ ForNode.prototype._createChildren = function () { var parentEl = this.el.parentNode; var listData = this.listData; if (listData instanceof Array) { for (var i = 0; i < listData.length; i++) { var childANode = this.aNode.forRinsed; var child = childANode.Clazz ? new childANode.Clazz(childANode, this, new ForItemData(this, listData[i], i), this.owner) : createNode(childANode, this, new ForItemData(this, listData[i], i), this.owner); this.children.push(child); child.attach(parentEl, this.el); } } else if (listData && typeof listData === 'object') { for (var i in listData) { if (listData.hasOwnProperty(i) && listData[i] != null) { var childANode = this.aNode.forRinsed; var child = childANode.Clazz ? new childANode.Clazz(childANode, this, new ForItemData(this, listData[i], i), this.owner) : createNode(childANode, this, new ForItemData(this, listData[i], i), this.owner); this.children.push(child); child.attach(parentEl, this.el); } } } }; /* eslint-disable fecs-max-statements */ /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ ForNode.prototype._update = function (changes) { var listData = evalExpr(this.param.value, this.scope, this.owner); var oldIsArr = this.listData instanceof Array; var newIsArr = listData instanceof Array; if (this.children.length) { if (!listData || newIsArr && listData.length === 0) { this._disposeChildren(); this.listData = listData; } else if (oldIsArr !== newIsArr || !newIsArr) { // 就是这么暴力 // 不推荐使用for遍历object,用的话自己负责 this.listData = listData; var isListChanged; for (var cIndex = 0; !isListChanged && cIndex < changes.length; cIndex++) { isListChanged = changeExprCompare(changes[cIndex].expr, this.param.value, this.scope); } var dataHotspot = this.aNode._d; if (isListChanged || dataHotspot && changesIsInDataRef(changes, dataHotspot)) { var me = this; this._disposeChildren(null, function () { me._createChildren(); }); } } else { this._updateArray(changes, listData); this.listData = listData; } } else { this.listData = listData; this._createChildren(); } }; /** * 销毁释放子元素 * * @param {Array?} children 要销毁的子元素,默认为自身的children * @param {Function} callback 释放完成的回调函数 */ ForNode.prototype._disposeChildren = function (children, callback) { var parentEl = this.el.parentNode; var parentFirstChild = parentEl.firstChild; var parentLastChild = parentEl.lastChild; var len = this.children.length; var violentClear = !this.aNode.directives.transition && !children // 是否 parent 的唯一 child && len && parentFirstChild === this.children[0].el && parentLastChild === this.el ; if (!children) { children = this.children; this.children = []; } var disposedChildCount = 0; len = children.length; // 调用入口处已保证此处必有需要被删除的 child for (var i = 0; i < len; i++) { var disposeChild = children[i]; if (violentClear) { disposeChild && disposeChild.dispose(violentClear, violentClear); } else if (disposeChild) { disposeChild._ondisposed = childDisposed; disposeChild.dispose(); } else { childDisposed(); } } if (violentClear) { // #[begin] allua /* istanbul ignore next */ if (ie) { parentEl.innerHTML = ''; } else { // #[end] parentEl.textContent = ''; // #[begin] allua } // #[end] this.el = document.createComment(this.id); parentEl.appendChild(this.el); callback && callback(); } function childDisposed() { disposedChildCount++; if (disposedChildCount >= len) { callback && callback(); } } }; ForNode.prototype.opti = typeof navigator !== 'undefined' && /chrome\/[0-9]+/i.test(navigator.userAgent); /** * 数组类型的视图更新 * * @param {Array} changes 数据变化信息 * @param {Array} newList 新数组数据 */ ForNode.prototype._updateArray = function (changes, newList) { var oldChildrenLen = this.children.length; var childrenChanges = new Array(oldChildrenLen); var childIsElem = this.children[0].nodeType === 4; function pushToChildrenChanges(change) { for (var i = 0, l = childrenChanges.length; i < l; i++) { (childrenChanges[i] = childrenChanges[i] || []).push(change); } childrenNeedUpdate = null; isOnlyDispose = false; } var disposeChildren = []; // 控制列表是否整体更新的变量 var isChildrenRebuild; // var isOnlyDispose = true; var childrenNeedUpdate = {}; var newLen = newList.length; var getItemKey = this.aNode._gfk; /* eslint-disable no-redeclare */ for (var cIndex = 0; cIndex < changes.length; cIndex++) { var change = changes[cIndex]; var relation = changeExprCompare(change.expr, this.param.value, this.scope); if (!relation) { // 无关时,直接传递给子元素更新,列表本身不需要动 pushToChildrenChanges(change); } else { if (relation > 2) { // 变更表达式是list绑定表达式的子项 // 只需要对相应的子项进行更新 var changePaths = change.expr.paths; var forLen = this.param.value.paths.length; var changeIndex = +evalExpr(changePaths[forLen], this.scope, this.owner); if (isNaN(changeIndex)) { pushToChildrenChanges(change); } else if (!isChildrenRebuild) { isOnlyDispose = false; childrenNeedUpdate && (childrenNeedUpdate[changeIndex] = 1); childrenChanges[changeIndex] = childrenChanges[changeIndex] || []; if (this.param.index) { childrenChanges[changeIndex].push(change); } change = change.type === 1 ? { type: change.type, expr: { type: 4, paths: this.itemPaths.concat(changePaths.slice(forLen + 1)) }, value: change.value, option: change.option } : { index: change.index, deleteCount: change.deleteCount, insertions: change.insertions, type: change.type, expr: { type: 4, paths: this.itemPaths.concat(changePaths.slice(forLen + 1)) }, value: change.value, option: change.option }; childrenChanges[changeIndex].push(change); if (change.type === 1) { if (this.children[changeIndex]) { this.children[changeIndex].scope._set( change.expr, change.value, { silent: 1 } ); } else { // 设置数组项的索引可能超出数组长度,此时需要新增 // 比如当前数组只有2项,但是set list[4] this.children[changeIndex] = 0; } } else if (this.children[changeIndex]) { this.children[changeIndex].scope._splice( change.expr, [].concat(change.index, change.deleteCount, change.insertions), { silent: 1 } ); } } } else if (isChildrenRebuild) { continue; } else if (relation === 2 && change.type === 2 && (this.owner.updateMode !== 'optimized' || !this.opti || this.aNode.directives.transition) ) { childrenNeedUpdate = null; // 变更表达式是list绑定表达式本身数组的splice操作 // 此时需要删除部分项,创建部分项 var changeStart = change.index; var deleteCount = change.deleteCount; var insertionsLen = change.insertions.length; var newCount = insertionsLen - deleteCount; if (newCount) { var indexChange = this.param.index ? { type: 1, option: change.option, expr: this.indexExpr } : null; for (var i = changeStart + deleteCount; i < this.children.length; i++) { if (indexChange) { isOnlyDispose = false; (childrenChanges[i] = childrenChanges[i] || []).push(indexChange); } var child = this.children[i]; if (child) { child.scope.raw[child.scope.indexName] = i - deleteCount + insertionsLen; } } } var deleteLen = deleteCount; while (deleteLen--) { if (deleteLen < insertionsLen) { isOnlyDispose = false; var i = changeStart + deleteLen; // update (childrenChanges[i] = childrenChanges[i] || []).push({ type: 1, option: change.option, expr: this.itemExpr, value: change.insertions[deleteLen] }); if (this.children[i]) { this.children[i].scope.raw[this.param.item] = change.insertions[deleteLen]; } } } if (newCount < 0) { disposeChildren = disposeChildren.concat( this.children.splice(changeStart + insertionsLen, -newCount) ); childrenChanges.splice(changeStart + insertionsLen, -newCount); } else if (newCount > 0) { isOnlyDispose = false; var spliceArgs = [changeStart + deleteCount, 0].concat(new Array(newCount)); this.children.splice.apply(this.children, spliceArgs); childrenChanges.splice.apply(childrenChanges, spliceArgs); } } else { childrenNeedUpdate = null; isOnlyDispose = false; isChildrenRebuild = 1; // 变更表达式是list绑定表达式本身或母项的重新设值 // 此时需要更新整个列表 if (getItemKey && newLen && oldChildrenLen) { // 如果设置了trackBy,用lis更新。开始 ==== var newListKeys = []; var oldListKeys = []; var newListKeysMap = {}; var oldListInNew = []; var oldListKeyIndex = {}; for (var i = 0; i < newList.length; i++) { var itemKey = getItemKey(newList[i]); newListKeys.push(itemKey); newListKeysMap[itemKey] = i; }; for (var i = 0; i < this.listData.length; i++) { var itemKey = getItemKey(this.listData[i]); oldListKeys.push(itemKey); oldListKeyIndex[itemKey] = i; if (newListKeysMap[itemKey] != null) { oldListInNew[i] = newListKeysMap[itemKey]; } else { oldListInNew[i] = -1; disposeChildren.push(this.children[i]); } }; var newIndexStart = 0; var newIndexEnd = newLen; var oldIndexStart = 0; var oldIndexEnd = oldChildrenLen; // 优化:从头开始比对新旧 list 项是否相同 while (newIndexStart < newLen && oldIndexStart < oldChildrenLen && newListKeys[newIndexStart] === oldListKeys[oldIndexStart] ) { if (this.listData[oldIndexStart] !== newList[newIndexStart]) { this.children[oldIndexStart].scope.raw[this.param.item] = newList[newIndexStart]; (childrenChanges[oldIndexStart] = childrenChanges[oldIndexStart] || []).push({ type: 1, option: change.option, expr: this.itemExpr, value: newList[newIndexStart] }); } // 对list更上级数据的直接设置 if (relation < 2) { (childrenChanges[oldIndexStart] = childrenChanges[oldIndexStart] || []).push(change); } newIndexStart++; oldIndexStart++; } var indexChange = this.param.index ? { type: 1, option: change.option, expr: this.indexExpr } : null; // 优化:从尾开始比对新旧 list 项是否相同 while (newIndexEnd > newIndexStart && oldIndexEnd > oldIndexStart && newListKeys[newIndexEnd - 1] === oldListKeys[oldIndexEnd - 1] ) { newIndexEnd--; oldIndexEnd--; if (this.listData[oldIndexEnd] !== newList[newIndexEnd]) { // refresh item this.children[oldIndexEnd].scope.raw[this.param.item] = newList[newIndexEnd]; (childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push({ type: 1, option: change.option, expr: this.itemExpr, value: newList[newIndexEnd] }); } // refresh index if (newIndexEnd !== oldIndexEnd) { this.children[oldIndexEnd].scope.raw[this.children[oldIndexEnd].scope.indexName] = newIndexEnd; if (indexChange) { (childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push(indexChange); } } // 对list更上级数据的直接设置 if (relation < 2) { (childrenChanges[oldIndexEnd] = childrenChanges[oldIndexEnd] || []).push(change); } } var oldListLIS = []; var lisIdx = []; var lisPos = -1; var lisSource = oldListInNew.slice(oldIndexStart, oldIndexEnd); var len = oldIndexEnd - oldIndexStart; var preIdx = new Array(len); for (var i = 0; i < len; i++) { var oldItemInNew = lisSource[i]; if (oldItemInNew === -1) { continue; } var rePos = -1; var rePosEnd = oldListLIS.length; if (rePosEnd > 0 && oldListLIS[rePosEnd - 1] <= oldItemInNew) { rePos = rePosEnd - 1; } else { while (rePosEnd - rePos > 1) { var mid = Math.floor((rePos + rePosEnd) / 2); if (oldListLIS[mid] > oldItemInNew) { rePosEnd = mid; } else { rePos = mid; } } } if (rePos !== -1) { preIdx[i] = lisIdx[rePos]; } if (rePos === lisPos) { lisPos++; oldListLIS[lisPos] = oldItemInNew; lisIdx[lisPos] = i; } else if (oldItemInNew < oldListLIS[rePos + 1]) { oldListLIS[rePos + 1] = oldItemInNew; lisIdx[rePos + 1] = i; } } for (var i = lisIdx[lisPos]; lisPos >= 0; i = preIdx[i], lisPos--) { oldListLIS[lisPos] = i; } var oldListLISPos = oldListLIS.length; var staticPos = oldListLISPos ? oldListInNew[oldListLIS[--oldListLISPos] + oldIndexStart] : -1; var newChildren = []; var newChildrenChanges = []; var beforeEl = this.el; var parentEl = childIsElem && beforeEl.parentNode; for (var i = newLen - 1; i >= 0; i--) { if (i >= newIndexEnd) { newChildren[i] = this.children[oldChildrenLen - newLen + i]; newChildrenChanges[i] = childrenChanges[oldChildrenLen - newLen + i]; if (childIsElem) { beforeEl = newChildren[i].el; } } else if (i < newIndexStart) { newChildren[i] = this.children[i]; newChildrenChanges[i] = childrenChanges[i]; } else { var oldListIndex = oldListKeyIndex[newListKeys[i]]; var oldListNode = this.children[oldListIndex]; if (oldListNode && (childIsElem || i === staticPos)) { var oldScope = oldListNode.scope; // 如果数据本身引用发生变化,设置变更 if (this.listData[oldListIndex] !== newList[i]) { oldScope.raw[this.param.item] = newList[i]; (childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push({ type: 1, option: change.option, expr: this.itemExpr, value: newList[i] }); } // refresh index if (indexChange && i !== oldListIndex) { oldScope.raw[oldScope.indexName] = i; if (indexChange) { (childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push(indexChange); } } // 对list更上级数据的直接设置 if (relation < 2) { (childrenChanges[oldListIndex] = childrenChanges[oldListIndex] || []).push(change); } newChildren[i] = oldListNode; newChildrenChanges[i] = childrenChanges[oldListIndex]; if (i === staticPos) { staticPos = oldListLISPos ? oldListInNew[oldListLIS[--oldListLISPos] + oldIndexStart] : -1; } else { parentEl.insertBefore(oldListNode.el, beforeEl); } if (childIsElem) { beforeEl = oldListNode.el; } } else { oldListNode && disposeChildren.push(oldListNode); newChildren[i] = 0; newChildrenChanges[i] = 0; } } } this.children = newChildren; childrenChanges = newChildrenChanges; // 如果设置了trackBy,用lis更新。结束 ==== } else { // 老的比新的多的部分,标记需要dispose if (oldChildrenLen > newLen) { disposeChildren = disposeChildren.concat(this.children.slice(newLen)); childrenChanges = childrenChanges.slice(0, newLen); this.children = this.children.slice(0, newLen); } // 剩下的部分整项变更 for (var i = 0; i < newLen; i++) { // 对list更上级数据的直接设置 if (relation < 2) { (childrenChanges[i] = childrenChanges[i] || []).push(change); } if (this.children[i]) { if (this.children[i].scope.raw[this.param.item] !== newList[i]) { this.children[i].scope.raw[this.param.item] = newList[i]; (childrenChanges[i] = childrenChanges[i] || []).push({ type: 1, option: change.option, expr: this.itemExpr, value: newList[i] }); } } else { this.children[i] = 0; } } } } } } // 标记 length 是否发生变化 if (newLen !== oldChildrenLen && this.param.value.paths) { var lengthChange = { type: 1, option: {}, expr: { type: 4, paths: this.param.value.paths.concat({ type: 1, value: 'length' }) } }; if (changesIsInDataRef([lengthChange], this.aNode._d)) { pushToChildrenChanges(lengthChange); } } // 执行视图更新,先删再刷新 this._doCreateAndUpdate = doCreateAndUpdate; var me = this; if (disposeChildren.length === 0) { doCreateAndUpdate(); } else { this._disposeChildren(disposeChildren, function () { if (doCreateAndUpdate === me._doCreateAndUpdate) { doCreateAndUpdate(); } }); } function doCreateAndUpdate() { me._doCreateAndUpdate = null; if (isOnlyDispose) { return; } var beforeEl = me.el; var parentEl = beforeEl.parentNode; // 对相应的项进行更新 // 如果不attached则直接创建,如果存在则调用更新函数 var j = -1; for (var i = 0; i < newLen; i++) { var child = me.children[i]; if (child) { if (childrenChanges[i] && (!childrenNeedUpdate || childrenNeedUpdate[i])) { child._update(childrenChanges[i]); } } else { if (j < i) { j = i + 1; beforeEl = null; while (j < newLen) { var nextChild = me.children[j]; if (nextChild) { beforeEl = nextChild.sel || nextChild.el; break; } j++; } } me.children[i] = createNode(me.aNode.forRinsed, me, new ForItemData(me, newList[i], i), me.owner); me.children[i].attach(parentEl, beforeEl || me.el); } } } }; // exports = module.exports = ForNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file if 指令节点类 */ // var each = require('../util/each'); // var guid = require('../util/guid'); // var insertBefore = require('../browser/insert-before'); // var evalExpr = require('../runtime/eval-expr'); // var NodeType = require('./node-type'); // var createNode = require('./create-node'); // var createReverseNode = require('./create-reverse-node'); // var nodeOwnCreateStump = require('./node-own-create-stump'); // var nodeOwnSimpleDispose = require('./node-own-simple-dispose'); /** * if 指令节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function IfNode(aNode, parent, scope, owner, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.id = guid++; this.children = []; // #[begin] reverse // if (reverseWalker) { // if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation // this.elseIndex = -1; // this.children[0] = createReverseNode( // this.aNode.ifRinsed, // this, // this.scope, // this.owner, // reverseWalker // ); // } // else { // var me = this; // each(aNode.elses, function (elseANode, index) { // var elif = elseANode.directives.elif; // // if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) { // me.elseIndex = index; // me.children[0] = createReverseNode( // elseANode, // me, // me.scope, // me.owner, // reverseWalker // ); // return false; // } // }); // } // // this._create(); // insertBefore(this.el, reverseWalker.target, reverseWalker.current); // } // #[end] } IfNode.prototype.nodeType = 2; IfNode.prototype._create = nodeOwnCreateStump; IfNode.prototype.dispose = nodeOwnSimpleDispose; /** * attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ IfNode.prototype.attach = function (parentEl, beforeEl) { var me = this; var elseIndex; var child; if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation child = createNode(this.aNode.ifRinsed, this, this.scope, this.owner); elseIndex = -1; } else { each(this.aNode.elses, function (elseANode, index) { var elif = elseANode.directives.elif; if (!elif || elif && evalExpr(elif.value, me.scope, me.owner)) { child = createNode(elseANode, me, me.scope, me.owner); elseIndex = index; return false; } }); } if (child) { this.children[0] = child; child.attach(parentEl, beforeEl); this.elseIndex = elseIndex; } this._create(); insertBefore(this.el, parentEl, beforeEl); }; /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ IfNode.prototype._update = function (changes) { var me = this; var childANode = this.aNode.ifRinsed; var elseIndex; if (evalExpr(this.aNode.directives['if'].value, this.scope, this.owner)) { // eslint-disable-line dot-notation elseIndex = -1; } else { each(this.aNode.elses, function (elseANode, index) { var elif = elseANode.directives.elif; if (elif && evalExpr(elif.value, me.scope, me.owner) || !elif) { elseIndex = index; childANode = elseANode; return false; } }); } var child = this.children[0]; if (elseIndex === this.elseIndex) { child && child._update(changes); } else { this.children = []; if (child) { child._ondisposed = newChild; child.dispose(); } else { newChild(); } this.elseIndex = elseIndex; } function newChild() { if (typeof elseIndex !== 'undefined') { (me.children[0] = createNode(childANode, me, me.scope, me.owner)) .attach(me.el.parentNode, me.el); } } }; IfNode.prototype._getElAsRootNode = function () { var child = this.children[0]; return child && child.el || this.el; }; // exports = module.exports = IfNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file is 指令节点类 */ // var guid = require('../util/guid'); // var evalExpr = require('../runtime/eval-expr'); // var NodeType = require('./node-type'); // var createNode = require('./create-node'); // var createReverseNode = require('./create-reverse-node'); // var nodeOwnSimpleDispose = require('./node-own-simple-dispose'); // var TemplateNode = require('./template-node'); /** * is 指令节点类 * * @class * @param {Object} aNode 抽象节点 * @param {Node} parent 父亲节点 * @param {Model} scope 所属数据环境 * @param {Component} owner 所属组件环境 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象 */ function IsNode(aNode, parent, scope, owner, reverseWalker) { this.aNode = aNode; this.owner = owner; this.scope = scope; this.parent = parent; this.parentComponent = parent.nodeType === 5 ? parent : parent.parentComponent; this.id = guid++; this.children = []; this.tagName = this.aNode.tagName; // #[begin] reverse // if (reverseWalker) { // this.cmpt = evalExpr(this.aNode.directives.is.value, this.scope) || this.tagName; // this.children[0] = createReverseNode( // this.aNode.isRinsed, // this, // this.scope, // this.owner, // reverseWalker, // this.cmpt // ); // } // #[end] } IsNode.prototype.nodeType = 9; IsNode.prototype.dispose = nodeOwnSimpleDispose; /** * attach到页面 * * @param {HTMLElement} parentEl 要添加到的父元素 * @param {HTMLElement=} beforeEl 要添加到哪个元素之前 */ IsNode.prototype.attach = function (parentEl, beforeEl) { this.cmpt = evalExpr(this.aNode.directives.is.value, this.scope) || this.tagName; var child = createNode(this.aNode.isRinsed, this, this.scope, this.owner, this.cmpt); this.children[0] = child; child.attach(parentEl, beforeEl); }; /** * 视图更新函数 * * @param {Array} changes 数据变化信息 */ IsNode.prototype._update = function (changes) { var child = this.children[0]; var cmpt = evalExpr(this.aNode.directives.is.value, this.scope) || this.tagName; if (cmpt === this.cmpt) { child._update(changes); } else { this.cmpt = cmpt; var newChild = createNode(this.aNode.isRinsed, this, this.scope, this.owner, this.cmpt); var el = child.el; newChild.attach(el.parentNode, el); child.dispose(); this.children[0] = newChild; } }; IsNode.prototype._getElAsRootNode = function () { return this.children[0].el; }; // exports = module.exports = IsNode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file ANode预热 */ // var ExprType = require('../parser/expr-type'); // var each = require('../util/each'); // var kebab2camel = require('../util/kebab2camel'); // var hotTags = require('../browser/hot-tags'); // var createEl = require('../browser/create-el'); // var getPropHandler = require('./get-prop-handler'); // var getANodeProp = require('./get-a-node-prop'); // var isBrowser = require('../browser/is-browser'); // var TextNode = require('./text-node'); // var SlotNode = require('./slot-node'); // var ForNode = require('./for-node'); // var IfNode = require('./if-node'); // var IsNode = require('./is-node'); // var TemplateNode = require('./template-node'); // var Element = require('./element'); /** * ANode预热,分析的数据引用等信息 * * @param {Object} aNode 要预热的ANode */ function preheatANode(aNode, componentInstance) { var stack = []; function recordHotspotData(expr, notContentData) { var refs = analyseExprDataHotspot(expr); var refsLen = refs.length; if (refsLen) { for (var i = 0, len = stack.length; i < len; i++) { if (!notContentData || i !== len - 1) { var data = stack[i]._d; // hotspot: data if (!data) { data = stack[i]._d = {}; } for (var j = 0; j < refsLen; j++) { data[refs[j]] = 1; } } } } } function analyseANodeHotspot(aNode) { if (!aNode._ht) { stack.push(aNode); if (aNode.textExpr) { aNode._ht = true; aNode.Clazz = TextNode; recordHotspotData(aNode.textExpr); } else { aNode._ht = true; aNode._i = 0; // hotspot: instance count aNode._dp = []; // hotspot: dynamic props aNode._xp = []; // hotspot: x props aNode._pi = {}; // hotspot: props index aNode._b = []; // hotspot: binds aNode._ce = !aNode.directives.is // cache element && aNode.tagName && aNode.tagName.indexOf('-') < 0 && !/^(template|select|input|option|button|video|audio|canvas|img|embed|object|iframe)$/i.test(aNode.tagName); // === analyse hotspot data: start each(aNode.vars, function (varItem) { recordHotspotData(varItem.expr); }); var props = aNode.props; var propsLen = props.length; for (var i = 0; i < propsLen; i++) { var prop = props[i]; aNode._b.push({ name: kebab2camel(prop.name), expr: prop.noValue != null ? {type: 3, value: true} : prop.expr, x: prop.x, noValue: prop.noValue }); recordHotspotData(prop.expr); } for (var key in aNode.directives) { /* istanbul ignore else */ if (aNode.directives.hasOwnProperty(key)) { var directive = aNode.directives[key]; recordHotspotData( directive.value, !/^(html|bind)$/.test(key) ); // init trackBy getKey function if (key === 'for') { var trackBy = directive.trackBy; if (trackBy && trackBy.type === 4 && trackBy.paths[0].value === directive.item ) { aNode._gfk = new Function( // hotspot: getForKey directive.item, 'return ' + directive.trackByRaw ); } } } } each(aNode.elses, function (child) { analyseANodeHotspot(child); }); for (var i = 0, l = aNode.children.length; i < l; i++) { analyseANodeHotspot(aNode.children[i]); } // === analyse hotspot data: end // === analyse hotspot props: start for (var i = 0; i < propsLen; i++) { var prop = props[i]; aNode._pi[prop.name] = i; prop.handler = getPropHandler(aNode.tagName, prop.name); if (prop.expr.value == null) { if (prop.x) { aNode._xp.push(prop); } aNode._dp.push(prop); } } // ie 下,如果 option 没有 value 属性,select.value = xx 操作不会选中 option // 所以没有设置 value 时,默认把 option 的内容作为 value if (aNode.tagName === 'option' && !getANodeProp(aNode, 'value') && aNode.children[0] ) { var valueProp = { name: 'value', expr: aNode.children[0].textExpr, handler: getPropHandler(aNode.tagName, 'value') }; aNode.props.push(valueProp); aNode._dp.push(valueProp); aNode._pi.value = props.length - 1; } if (aNode.directives['if']) { // eslint-disable-line dot-notation aNode.ifRinsed = { children: aNode.children, props: props, events: aNode.events, tagName: aNode.tagName, vars: aNode.vars, directives: aNode.directives, _ht: true, _i: 0, _d: aNode._d, _dp: aNode._dp, _xp: aNode._xp, _pi: aNode._pi, _b: aNode._b, _ce: aNode._ce }; aNode.hasRootNode = true; aNode.Clazz = IfNode; aNode = aNode.ifRinsed; } if (aNode.directives['for']) { // eslint-disable-line dot-notation aNode.forRinsed = { children: aNode.children, props: props, events: aNode.events, tagName: aNode.tagName, vars: aNode.vars, directives: aNode.directives, _ht: true, _i: 0, _d: aNode._d, _dp: aNode._dp, _xp: aNode._xp, _pi: aNode._pi, _b: aNode._b, _ce: aNode._ce }; aNode.hasRootNode = true; aNode.Clazz = ForNode; aNode = aNode.forRinsed; } if (aNode.directives.is) { aNode.isRinsed = { children: aNode.children, props: props, events: aNode.events, tagName: aNode.tagName, vars: aNode.vars, directives: aNode.directives, _ht: true, _i: 0, _d: aNode._d, _dp: aNode._dp, _xp: aNode._xp, _pi: aNode._pi, _b: aNode._b, _ce: aNode._ce }; aNode.hasRootNode = true; aNode.Clazz = IsNode; aNode = aNode.isRinsed; } switch (aNode.tagName) { case 'slot': aNode.Clazz = SlotNode; break; case 'template': case 'fragment': aNode.hasRootNode = true; aNode.Clazz = TemplateNode; break; default: if (!aNode.directives.is && hotTags[aNode.tagName]) { if (!componentInstance || !componentInstance.components[aNode.tagName]) { aNode.elem = true; } // #[begin] error if (componentInstance && componentInstance.components[aNode.tagName]) { warn('\`' + aNode.tagName + '\` as sub-component tag is a bad practice.'); } // #[end] } } // === analyse hotspot props: end } stack.pop(); } } if (aNode) { analyseANodeHotspot(aNode); } } /** * 分析表达式的数据引用 * * @param {Object} expr 要分析的表达式 * @return {Array} */ function analyseExprDataHotspot(expr, accessorMeanDynamic) { var refs = []; var isDynamic; function analyseExprs(exprs, accessorMeanDynamic) { for (var i = 0, l = exprs.length; i < l; i++) { refs = refs.concat(analyseExprDataHotspot(exprs[i], accessorMeanDynamic)); isDynamic = isDynamic || exprs[i].dynamic; } } switch (expr.type) { case 4: isDynamic = accessorMeanDynamic; var paths = expr.paths; refs.push(paths[0].value); if (paths.length > 1) { refs.push(paths[0].value + '.' + (paths[1].value || '*')); } analyseExprs(paths.slice(1), 1); break; case 9: refs = analyseExprDataHotspot(expr.expr, accessorMeanDynamic); isDynamic = expr.expr.dynamic; break; case 7: case 8: case 10: analyseExprs(expr.segs, accessorMeanDynamic); break; case 5: refs = analyseExprDataHotspot(expr.expr); isDynamic = expr.expr.dynamic; each(expr.filters, function (filter) { analyseExprs(filter.name.paths); analyseExprs(filter.args); }); break; case 6: analyseExprs(expr.name.paths); analyseExprs(expr.args); break; case 12: case 11: for (var i = 0; i < expr.items.length; i++) { refs = refs.concat(analyseExprDataHotspot(expr.items[i].expr)); isDynamic = isDynamic || expr.items[i].expr.dynamic; } break; } isDynamic && (expr.dynamic = true); return refs; } // exports = module.exports = preheatANode; /** * Copyright (c) Baidu Inc. All rights reserved. * * This source code is licensed under the MIT license. * See LICENSE file in the project root for license information. * * @file 创建组件Loader */ // var ComponentLoader = require('./component-loader'); /** * 创建组件Loader * * @param {Object|Function} options 创建组件Loader的参数。为Object时参考下方描述,为Function时代表load方法。 * @param {Function} options.load load方法 * @param {Function=} options.placeholder loading过程中渲染的占位组件 * @param {Function=} options.fallback load失败时渲染的组件 * @return {ComponentLoader} */ function createComponentLoader(options) { var placeholder = options.placeholder; var fallback = options.fallback; var load = typeof options === 'function' ? options : options.load; return new ComponentLoader(load, placeholder, fallback); } // exports = module.exports = createComponentLoader; /* eslint-disable no-unused-vars */ // var nextTick = require('./util/next-tick'); // var inherits = require('./util/inherits'); // var parseTemplate = require('./parser/parse-template'); // var parseExpr = require('./parser/parse-expr'); // var ExprType = require('./parser/expr-type'); // var unpackANode = require('./parser/unpack-anode'); // var LifeCycle = require('./view/life-cycle'); // var NodeType = require('./view/node-type'); // var Component = require('./view/component'); // var parseComponentTemplate = require('./view/parse-component-template'); // var defineComponent = require('./view/define-component'); // var createComponentLoader = require('./view/create-component-loader'); // var emitDevtool = require('./util/emit-devtool'); // var Data = require('./runtime/data'); // var evalExpr = require('./runtime/eval-expr'); // var DataTypes = require('./util/data-types'); var san = { /** * san版本号 * * @type {string} */ version: '3.11.1', // #[begin] devtool /** * 是否开启调试。开启调试时 devtool 会工作 * * @type {boolean} */ debug: true, // #[end] /** * 组件基类 * * @type {Function} */ Component: Component, /** * 创建组件类 * * @param {Object} proto 组件类的方法表 * @return {Function} */ defineComponent: defineComponent, /** * 创建组件Loader * * @param {Object|Function} options 创建组件Loader的参数。为Object时参考下方描述,为Function时代表load方法。 * @param {Function} options.load load方法 * @param {Function=} options.placeholder loading过程中渲染的占位组件 * @param {Function=} options.fallback load失败时渲染的组件 * @return {ComponentLoader} */ createComponentLoader: createComponentLoader, /** * 解析组件 template * * @param {Function} ComponentClass 组件类 * @return {ANode} */ parseComponentTemplate: parseComponentTemplate, /** * 解压缩 ANode * * @param {Array} source ANode 压缩数据 * @return {Object} */ unpackANode: unpackANode, /** * 解析 template * * @inner * @param {string} source template 源码 * @return {ANode} */ parseTemplate: parseTemplate, /** * 解析表达式 * * @param {string} source 源码 * @return {Object} */ parseExpr: parseExpr, /** * 表达式类型枚举 * * @const * @type {Object} */ ExprType: ExprType, /** * 生命周期 */ LifeCycle: LifeCycle, /** * 节点类型 * * @const * @type {Object} */ NodeType: NodeType, /** * 在下一个更新周期运行函数 * * @param {Function} fn 要运行的函数 */ nextTick: nextTick, /** * 数据类 * * @class * @param {Object?} data 初始数据 * @param {Data?} parent 父级数据对象 */ Data: Data, /** * 计算表达式的值 * * @param {Object} expr 表达式对象 * @param {Data} data 数据对象 * @param {Component=} owner 组件对象,用于表达式中filter的执行 * @return {*} */ evalExpr: evalExpr, /** * 构建类之间的继承关系 * * @param {Function} subClass 子类函数 * @param {Function} superClass 父类函数 */ inherits: inherits, /** * DataTypes * * @type {Object} */ DataTypes: DataTypes }; // export if (typeof exports === 'object' && typeof module === 'object') { // For CommonJS exports = module.exports = san; } else if (typeof define === 'function' && define.amd) { // For AMD define('san', [], san); } else { // For <script src="..." root.san = san; } // #[begin] devtool emitDevtool.start(san); // #[end] })(this); //@ sourceMappingURL=san.spa.dev.js.map
const { STRING, ENUM, TEXT } = require('sequelize') module.exports = db => db.define('reviews', { title: { type: STRING(30), allowNull: false }, description: { type: TEXT, allowNull: false }, rating: { type: ENUM, values: ['1', '2', '3', '4', '5'] } }, { getterMethods: { shortTitle() { return this.title.substring(0, 20) + '...' } } }) module.exports.associations = (Review, {Product, User}) => { Review.belongsTo(User) Review.belongsTo(Product) }
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = createPalette; exports.dark = exports.light = void 0; var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties")); var _utils = require("@material-ui/utils"); var _common = _interopRequireDefault(require("../colors/common")); var _grey = _interopRequireDefault(require("../colors/grey")); var _indigo = _interopRequireDefault(require("../colors/indigo")); var _pink = _interopRequireDefault(require("../colors/pink")); var _red = _interopRequireDefault(require("../colors/red")); var _orange = _interopRequireDefault(require("../colors/orange")); var _blue = _interopRequireDefault(require("../colors/blue")); var _green = _interopRequireDefault(require("../colors/green")); var _colorManipulator = require("./colorManipulator"); var light = { // The colors used to style the text. text: { // The most important text. primary: 'rgba(0, 0, 0, 0.87)', // Secondary text. secondary: 'rgba(0, 0, 0, 0.54)', // Disabled text have even lower visual prominence. disabled: 'rgba(0, 0, 0, 0.38)', // Text hints. hint: 'rgba(0, 0, 0, 0.38)' }, // The color used to divide different elements. divider: 'rgba(0, 0, 0, 0.12)', // The background colors used to style the surfaces. // Consistency between these values is important. background: { paper: _common.default.white, default: _grey.default[50] }, // The colors used to style the action elements. action: { // The color of an active action like an icon button. active: 'rgba(0, 0, 0, 0.54)', // The color of an hovered action. hover: 'rgba(0, 0, 0, 0.04)', hoverOpacity: 0.04, // The color of a selected action. selected: 'rgba(0, 0, 0, 0.08)', selectedOpacity: 0.08, // The color of a disabled action. disabled: 'rgba(0, 0, 0, 0.26)', // The background color of a disabled action. disabledBackground: 'rgba(0, 0, 0, 0.12)' } }; exports.light = light; var dark = { text: { primary: _common.default.white, secondary: 'rgba(255, 255, 255, 0.7)', disabled: 'rgba(255, 255, 255, 0.5)', hint: 'rgba(255, 255, 255, 0.5)', icon: 'rgba(255, 255, 255, 0.5)' }, divider: 'rgba(255, 255, 255, 0.12)', background: { paper: _grey.default[800], default: '#303030' }, action: { active: _common.default.white, hover: 'rgba(255, 255, 255, 0.08)', hoverOpacity: 0.08, selected: 'rgba(255, 255, 255, 0.16)', selectedOpacity: 0.16, disabled: 'rgba(255, 255, 255, 0.3)', disabledBackground: 'rgba(255, 255, 255, 0.12)' } }; exports.dark = dark; function addLightOrDark(intent, direction, shade, tonalOffset) { if (!intent[direction]) { if (intent.hasOwnProperty(shade)) { intent[direction] = intent[shade]; } else if (direction === 'light') { intent.light = (0, _colorManipulator.lighten)(intent.main, tonalOffset); } else if (direction === 'dark') { intent.dark = (0, _colorManipulator.darken)(intent.main, tonalOffset * 1.5); } } } function createPalette(palette) { var _palette$primary = palette.primary, primary = _palette$primary === void 0 ? { light: _indigo.default[300], main: _indigo.default[500], dark: _indigo.default[700] } : _palette$primary, _palette$secondary = palette.secondary, secondary = _palette$secondary === void 0 ? { light: _pink.default.A200, main: _pink.default.A400, dark: _pink.default.A700 } : _palette$secondary, _palette$error = palette.error, error = _palette$error === void 0 ? { light: _red.default[300], main: _red.default[500], dark: _red.default[700] } : _palette$error, _palette$warning = palette.warning, warning = _palette$warning === void 0 ? { light: _orange.default[300], main: _orange.default[500], dark: _orange.default[700] } : _palette$warning, _palette$info = palette.info, info = _palette$info === void 0 ? { light: _blue.default[300], main: _blue.default[500], dark: _blue.default[700] } : _palette$info, _palette$success = palette.success, success = _palette$success === void 0 ? { light: _green.default[300], main: _green.default[500], dark: _green.default[700] } : _palette$success, _palette$type = palette.type, type = _palette$type === void 0 ? 'light' : _palette$type, _palette$contrastThre = palette.contrastThreshold, contrastThreshold = _palette$contrastThre === void 0 ? 3 : _palette$contrastThre, _palette$tonalOffset = palette.tonalOffset, tonalOffset = _palette$tonalOffset === void 0 ? 0.2 : _palette$tonalOffset, other = (0, _objectWithoutProperties2.default)(palette, ["primary", "secondary", "error", "warning", "info", "success", "type", "contrastThreshold", "tonalOffset"]); // Use the same logic as // Bootstrap: https://github.com/twbs/bootstrap/blob/1d6e3710dd447de1a200f29e8fa521f8a0908f70/scss/_functions.scss#L59 // and material-components-web https://github.com/material-components/material-components-web/blob/ac46b8863c4dab9fc22c4c662dc6bd1b65dd652f/packages/mdc-theme/_functions.scss#L54 function getContrastText(background) { if (!background) { throw new TypeError("Material-UI: missing background argument in getContrastText(".concat(background, ").")); } var contrastText = (0, _colorManipulator.getContrastRatio)(background, dark.text.primary) >= contrastThreshold ? dark.text.primary : light.text.primary; if (process.env.NODE_ENV !== 'production') { var contrast = (0, _colorManipulator.getContrastRatio)(background, contrastText); if (contrast < 3) { console.error(["Material-UI: the contrast ratio of ".concat(contrast, ":1 for ").concat(contrastText, " on ").concat(background), 'falls below the WCAG recommended absolute minimum contrast ratio of 3:1.', 'https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast'].join('\n')); } } return contrastText; } function augmentColor(color) { var mainShade = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 500; var lightShade = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 300; var darkShade = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 700; color = (0, _extends2.default)({}, color); if (!color.main && color[mainShade]) { color.main = color[mainShade]; } if (process.env.NODE_ENV !== 'production') { if (!color.main) { throw new Error(['Material-UI: the color provided to augmentColor(color) is invalid.', "The color object needs to have a `main` property or a `".concat(mainShade, "` property.")].join('\n')); } } addLightOrDark(color, 'light', lightShade, tonalOffset); addLightOrDark(color, 'dark', darkShade, tonalOffset); if (!color.contrastText) { color.contrastText = getContrastText(color.main); } return color; } var types = { dark: dark, light: light }; if (process.env.NODE_ENV !== 'production') { if (!types[type]) { console.error("Material-UI: the palette type `".concat(type, "` is not supported.")); } } var paletteOutput = (0, _utils.deepmerge)((0, _extends2.default)({ // A collection of common colors. common: _common.default, // The palette type, can be light or dark. type: type, // The colors used to represent primary interface elements for a user. primary: augmentColor(primary), // The colors used to represent secondary interface elements for a user. secondary: augmentColor(secondary, 'A400', 'A200', 'A700'), // The colors used to represent interface elements that the user should be made aware of. error: augmentColor(error), // The colors used to represent potentially dangerous actions or important messages. warning: augmentColor(warning), // The colors used to present information to the user that is neutral and not necessarily important. info: augmentColor(info), // The colors used to indicate the successful completion of an action that user triggered. success: augmentColor(success), // The grey colors. grey: _grey.default, // Used by `getContrastText()` to maximize the contrast between // the background and the text. contrastThreshold: contrastThreshold, // Takes a background color and returns the text color that maximizes the contrast. getContrastText: getContrastText, // Generate a rich color object. augmentColor: augmentColor, // Used by the functions below to shift a color's luminance by approximately // two indexes within its tonal palette. // E.g., shift from Red 500 to Red 300 or Red 700. tonalOffset: tonalOffset }, types[type]), other); return paletteOutput; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.DragProxy = void 0; const internal_error_1 = require("../errors/internal-error"); const stack_1 = require("../items/stack"); const event_emitter_1 = require("../utils/event-emitter"); const jquery_legacy_1 = require("../utils/jquery-legacy"); const types_1 = require("../utils/types"); const utils_1 = require("../utils/utils"); /** * This class creates a temporary container * for the component whilst it is being dragged * and handles drag events * @internal */ class DragProxy extends event_emitter_1.EventEmitter { /** * @param x - The initial x position * @param y - The initial y position * @internal */ constructor(x, y, _dragListener, _layoutManager, _componentItem, _originalParent) { super(); this._dragListener = _dragListener; this._layoutManager = _layoutManager; this._componentItem = _componentItem; this._originalParent = _originalParent; this._area = null; this._lastValidArea = null; this._dragListener.on('drag', (offsetX, offsetY, event) => this.onDrag(offsetX, offsetY, event)); this._dragListener.on('dragStop', () => this.onDrop()); this.createDragProxyElements(x, y); if (this._componentItem.parent === null) { // Note that _contentItem will have dummy GroundItem as parent if initiated by a external drag source throw new internal_error_1.UnexpectedNullError('DPC10097'); } this._componentItemFocused = this._componentItem.focused; if (this._componentItemFocused) { this._componentItem.blur(); } this._componentItem.parent.removeChild(this._componentItem, true); this.setDimensions(); document.body.appendChild(this._element); this.determineMinMaxXY(); if (this._layoutManager.layoutConfig.settings.constrainDragToContainer) { const constrainedPosition = this.getXYWithinMinMax(x, y); x = constrainedPosition.x; y = constrainedPosition.y; } this._layoutManager.calculateItemAreas(); this.setDropPosition(x, y); } get element() { return this._element; } /** Create Stack-like structure to contain the dragged component */ createDragProxyElements(initialX, initialY) { this._element = document.createElement('div'); this._element.classList.add("lm_dragProxy" /* DragProxy */); const headerElement = document.createElement('div'); headerElement.classList.add("lm_header" /* Header */); const tabsElement = document.createElement('div'); tabsElement.classList.add("lm_tabs" /* Tabs */); const tabElement = document.createElement('div'); tabElement.classList.add("lm_tab" /* Tab */); const titleElement = document.createElement('span'); titleElement.classList.add("lm_title" /* Title */); tabElement.appendChild(titleElement); tabsElement.appendChild(tabElement); headerElement.appendChild(tabsElement); this._proxyContainerElement = document.createElement('div'); this._proxyContainerElement.classList.add("lm_content" /* Content */); this._element.appendChild(headerElement); this._element.appendChild(this._proxyContainerElement); if (this._originalParent instanceof stack_1.Stack && this._originalParent.headerShow) { this._sided = this._originalParent.headerLeftRightSided; this._element.classList.add('lm_' + this._originalParent.headerSide); if ([types_1.Side.right, types_1.Side.bottom].indexOf(this._originalParent.headerSide) >= 0) { this._proxyContainerElement.insertAdjacentElement('afterend', headerElement); } } this._element.style.left = utils_1.numberToPixels(initialX); this._element.style.top = utils_1.numberToPixels(initialY); tabElement.setAttribute('title', utils_1.stripTags(this._componentItem.title)); titleElement.insertAdjacentText('afterbegin', this._componentItem.title); this._proxyContainerElement.appendChild(this._componentItem.element); } determineMinMaxXY() { const offset = jquery_legacy_1.getJQueryOffset(this._layoutManager.container); this._minX = offset.left; this._minY = offset.top; const { width: containerWidth, height: containerHeight } = utils_1.getElementWidthAndHeight(this._layoutManager.container); this._maxX = containerWidth + this._minX; this._maxY = containerHeight + this._minY; } getXYWithinMinMax(x, y) { if (x <= this._minX) { x = Math.ceil(this._minX + 1); } else if (x >= this._maxX) { x = Math.floor(this._maxX - 1); } if (y <= this._minY) { y = Math.ceil(this._minY + 1); } else if (y >= this._maxY) { y = Math.floor(this._maxY - 1); } return { x, y }; } /** * Callback on every mouseMove event during a drag. Determines if the drag is * still within the valid drag area and calls the layoutManager to highlight the * current drop area * * @param offsetX - The difference from the original x position in px * @param offsetY - The difference from the original y position in px * @param event - * @internal */ onDrag(offsetX, offsetY, event) { const x = event.pageX; const y = event.pageY; if (!this._layoutManager.layoutConfig.settings.constrainDragToContainer) { this.setDropPosition(x, y); } else { const isWithinContainer = x > this._minX && x < this._maxX && y > this._minY && y < this._maxY; if (isWithinContainer) { this.setDropPosition(x, y); } } } /** * Sets the target position, highlighting the appropriate area * * @param x - The x position in px * @param y - The y position in px * * @internal */ setDropPosition(x, y) { this._element.style.left = utils_1.numberToPixels(x); this._element.style.top = utils_1.numberToPixels(y); this._area = this._layoutManager.getArea(x, y); if (this._area !== null) { this._lastValidArea = this._area; this._area.contentItem.highlightDropZone(x, y, this._area); } } /** * Callback when the drag has finished. Determines the drop area * and adds the child to it * @internal */ onDrop() { const dropTargetIndicator = this._layoutManager.dropTargetIndicator; if (dropTargetIndicator === null) { throw new internal_error_1.UnexpectedNullError('DPOD30011'); } else { dropTargetIndicator.hide(); } /* * Valid drop area found */ let droppedComponentItem; if (this._area !== null) { droppedComponentItem = this._componentItem; this._area.contentItem.onDrop(droppedComponentItem, this._area); /** * No valid drop area available at present, but one has been found before. * Use it */ } else if (this._lastValidArea !== null) { droppedComponentItem = this._componentItem; const newParentContentItem = this._lastValidArea.contentItem; newParentContentItem.onDrop(droppedComponentItem, this._lastValidArea); /** * No valid drop area found during the duration of the drag. Return * content item to its original position if a original parent is provided. * (Which is not the case if the drag had been initiated by createDragSource) */ } else if (this._originalParent) { droppedComponentItem = this._componentItem; this._originalParent.addChild(droppedComponentItem); /** * The drag didn't ultimately end up with adding the content item to * any container. In order to ensure clean up happens, destroy the * content item. */ } else { this._componentItem.destroy(); // contentItem children are now destroyed as well } this._element.remove(); this._layoutManager.emit('itemDropped', this._componentItem); if (this._componentItemFocused && droppedComponentItem !== undefined) { droppedComponentItem.focus(); } } /** * Updates the Drag Proxy's dimensions * @internal */ setDimensions() { const dimensions = this._layoutManager.layoutConfig.dimensions; if (dimensions === undefined) { throw new Error('DragProxy.setDimensions: dimensions undefined'); } let width = dimensions.dragProxyWidth; let height = dimensions.dragProxyHeight; if (width === undefined || height === undefined) { throw new Error('DragProxy.setDimensions: width and/or height undefined'); } const headerHeight = this._layoutManager.layoutConfig.header.show === false ? 0 : dimensions.headerHeight; this._element.style.width = utils_1.numberToPixels(width); this._element.style.height = utils_1.numberToPixels(height); width -= (this._sided ? headerHeight : 0); height -= (!this._sided ? headerHeight : 0); this._proxyContainerElement.style.width = utils_1.numberToPixels(width); this._proxyContainerElement.style.height = utils_1.numberToPixels(height); this._componentItem.setDragSize(width, height); this._componentItem.show(); } } exports.DragProxy = DragProxy; //# sourceMappingURL=drag-proxy.js.map
/*! * Native JavaScript for Bootstrap Tab v4.0.3 (https://thednp.github.io/bootstrap.native/) * Copyright 2015-2021 © dnp_theme * Licensed under MIT (https://github.com/thednp/bootstrap.native/blob/master/LICENSE) */ const supportTransition = 'webkitTransition' in document.head.style || 'transition' in document.head.style; const transitionEndEvent = 'webkitTransition' in document.head.style ? 'webkitTransitionEnd' : 'transitionend'; const transitionDuration = 'webkitTransition' in document.head.style ? 'webkitTransitionDuration' : 'transitionDuration'; const transitionProperty = 'webkitTransition' in document.head.style ? 'webkitTransitionProperty' : 'transitionProperty'; function getElementTransitionDuration(element) { const computedStyle = getComputedStyle(element); const propertyValue = computedStyle[transitionProperty]; const durationValue = computedStyle[transitionDuration]; const durationScale = durationValue.includes('ms') ? 1 : 1000; const duration = supportTransition && propertyValue && propertyValue !== 'none' ? parseFloat(durationValue) * durationScale : 0; return !Number.isNaN(duration) ? duration : 0; } function emulateTransitionEnd(element, handler) { let called = 0; const endEvent = new Event(transitionEndEvent); const duration = getElementTransitionDuration(element); if (duration) { element.addEventListener(transitionEndEvent, function transitionEndWrapper(e) { if (e.target === element) { handler.apply(element, [e]); element.removeEventListener(transitionEndEvent, transitionEndWrapper); called = 1; } }); setTimeout(() => { if (!called) element.dispatchEvent(endEvent); }, duration + 17); } else { handler.apply(element, [endEvent]); } } function reflow(element) { return element.offsetHeight; } function queryElement(selector, parent) { const lookUp = parent && parent instanceof Element ? parent : document; return selector instanceof Element ? selector : lookUp.querySelector(selector); } function addClass(element, classNAME) { element.classList.add(classNAME); } function hasClass(element, classNAME) { return element.classList.contains(classNAME); } function removeClass(element, classNAME) { element.classList.remove(classNAME); } const addEventListener = 'addEventListener'; const removeEventListener = 'removeEventListener'; const ariaSelected = 'aria-selected'; // collapse / tab const collapsingClass = 'collapsing'; const activeClass = 'active'; const fadeClass = 'fade'; const showClass = 'show'; const dropdownMenuClasses = ['dropdown', 'dropup', 'dropstart', 'dropend']; const dropdownMenuClass = 'dropdown-menu'; const dataBsToggle = 'data-bs-toggle'; function bootstrapCustomEvent(namespacedEventType, eventProperties) { const OriginalCustomEvent = new CustomEvent(namespacedEventType, { cancelable: true }); if (eventProperties instanceof Object) { Object.keys(eventProperties).forEach((key) => { Object.defineProperty(OriginalCustomEvent, key, { value: eventProperties[key], }); }); } return OriginalCustomEvent; } function normalizeValue(value) { if (value === 'true') { return true; } if (value === 'false') { return false; } if (!Number.isNaN(+value)) { return +value; } if (value === '' || value === 'null') { return null; } // string / function / Element / Object return value; } function normalizeOptions(element, defaultOps, inputOps, ns) { const normalOps = {}; const dataOps = {}; const data = { ...element.dataset }; Object.keys(data) .forEach((k) => { const key = k.includes(ns) ? k.replace(ns, '').replace(/[A-Z]/, (match) => match.toLowerCase()) : k; dataOps[key] = normalizeValue(data[k]); }); Object.keys(inputOps) .forEach((k) => { inputOps[k] = normalizeValue(inputOps[k]); }); Object.keys(defaultOps) .forEach((k) => { if (k in inputOps) { normalOps[k] = inputOps[k]; } else if (k in dataOps) { normalOps[k] = dataOps[k]; } else { normalOps[k] = defaultOps[k]; } }); return normalOps; } /* Native JavaScript for Bootstrap 5 | Base Component ----------------------------------------------------- */ class BaseComponent { constructor(name, target, defaults, config) { const self = this; const element = queryElement(target); if (element[name]) element[name].dispose(); self.element = element; if (defaults && Object.keys(defaults).length) { self.options = normalizeOptions(element, defaults, (config || {}), 'bs'); } element[name] = self; } dispose(name) { const self = this; self.element[name] = null; Object.keys(self).forEach((prop) => { self[prop] = null; }); } } /* Native JavaScript for Bootstrap 5 | Tab ------------------------------------------ */ // TAB PRIVATE GC // ================ const tabString = 'tab'; const tabComponent = 'Tab'; const tabSelector = `[${dataBsToggle}="${tabString}"]`; // TAB CUSTOM EVENTS // ================= const showTabEvent = bootstrapCustomEvent(`show.bs.${tabString}`); const shownTabEvent = bootstrapCustomEvent(`shown.bs.${tabString}`); const hideTabEvent = bootstrapCustomEvent(`hide.bs.${tabString}`); const hiddenTabEvent = bootstrapCustomEvent(`hidden.bs.${tabString}`); let nextTab; let nextTabContent; let nextTabHeight; let activeTab; let activeTabContent; let tabContainerHeight; let tabEqualContents; // TAB PRIVATE METHODS // =================== function triggerTabEnd(self) { const { tabContent, nav } = self; tabContent.style.height = ''; removeClass(tabContent, collapsingClass); nav.isAnimating = false; } function triggerTabShow(self) { const { tabContent, nav } = self; if (tabContent) { // height animation if (tabEqualContents) { triggerTabEnd(self); } else { setTimeout(() => { // enables height animation tabContent.style.height = `${nextTabHeight}px`; // height animation reflow(tabContent); emulateTransitionEnd(tabContent, () => triggerTabEnd(self)); }, 50); } } else { nav.isAnimating = false; } shownTabEvent.relatedTarget = activeTab; nextTab.dispatchEvent(shownTabEvent); } function triggerTabHide(self) { const { tabContent } = self; if (tabContent) { activeTabContent.style.float = 'left'; nextTabContent.style.float = 'left'; tabContainerHeight = activeTabContent.scrollHeight; } // update relatedTarget and dispatch event showTabEvent.relatedTarget = activeTab; hiddenTabEvent.relatedTarget = nextTab; nextTab.dispatchEvent(showTabEvent); if (showTabEvent.defaultPrevented) return; addClass(nextTabContent, activeClass); removeClass(activeTabContent, activeClass); if (tabContent) { nextTabHeight = nextTabContent.scrollHeight; tabEqualContents = nextTabHeight === tabContainerHeight; addClass(tabContent, collapsingClass); tabContent.style.height = `${tabContainerHeight}px`; // height animation reflow(tabContent); activeTabContent.style.float = ''; nextTabContent.style.float = ''; } if (hasClass(nextTabContent, fadeClass)) { setTimeout(() => { addClass(nextTabContent, showClass); emulateTransitionEnd(nextTabContent, () => { triggerTabShow(self); }); }, 20); } else { triggerTabShow(self); } activeTab.dispatchEvent(hiddenTabEvent); } function getActiveTab({ nav }) { const activeTabs = nav.getElementsByClassName(activeClass); if (activeTabs.length === 1 && !dropdownMenuClasses.some((c) => hasClass(activeTabs[0].parentNode, c))) { [activeTab] = activeTabs; } else if (activeTabs.length > 1) { activeTab = activeTabs[activeTabs.length - 1]; } return activeTab; } function getActiveTabContent(self) { return queryElement(getActiveTab(self).getAttribute('href')); } function toggleTabHandler(self, add) { const action = add ? addEventListener : removeEventListener; self.element[action]('click', tabClickHandler); } // TAB EVENT HANDLER // ================= function tabClickHandler(e) { const self = this[tabComponent]; e.preventDefault(); if (!self.nav.isAnimating) self.show(); } // TAB DEFINITION // ============== class Tab extends BaseComponent { constructor(target) { super(tabComponent, target); // bind const self = this; // initialization element const { element } = self; // event targets self.nav = element.closest('.nav'); const { nav } = self; self.dropdown = nav && queryElement(`.${dropdownMenuClasses[0]}-toggle`, nav); activeTabContent = getActiveTabContent(self); self.tabContent = supportTransition && activeTabContent.closest('.tab-content'); tabContainerHeight = activeTabContent.scrollHeight; // set default animation state nav.isAnimating = false; // add event listener toggleTabHandler(self, 1); } // TAB PUBLIC METHODS // ================== show() { // the tab we clicked is now the nextTab tab const self = this; const { element, nav, dropdown } = self; nextTab = element; if (!hasClass(nextTab, activeClass)) { // this is the actual object, the nextTab tab content to activate nextTabContent = queryElement(nextTab.getAttribute('href')); activeTab = getActiveTab({ nav }); activeTabContent = getActiveTabContent({ nav }); // update relatedTarget and dispatch hideTabEvent.relatedTarget = nextTab; activeTab.dispatchEvent(hideTabEvent); if (hideTabEvent.defaultPrevented) return; nav.isAnimating = true; removeClass(activeTab, activeClass); activeTab.setAttribute(ariaSelected, 'false'); addClass(nextTab, activeClass); nextTab.setAttribute(ariaSelected, 'true'); if (dropdown) { if (!hasClass(element.parentNode, dropdownMenuClass)) { if (hasClass(dropdown, activeClass)) removeClass(dropdown, activeClass); } else if (!hasClass(dropdown, activeClass)) addClass(dropdown, activeClass); } if (hasClass(activeTabContent, fadeClass)) { removeClass(activeTabContent, showClass); emulateTransitionEnd(activeTabContent, () => triggerTabHide(self)); } else { triggerTabHide(self); } } } dispose() { toggleTabHandler(this); super.dispose(tabComponent); } } Tab.init = { component: tabComponent, selector: tabSelector, constructor: Tab, }; export default Tab;
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2019 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ var Length = require('./Length'); var Point = require('../point/Point'); /** * Get a number of points along a line's length. * * Provide a `quantity` to get an exact number of points along the line. * * Provide a `stepRate` to ensure a specific distance between each point on the line. Set `quantity` to `0` when * providing a `stepRate`. * * @function Phaser.Geom.Line.GetPoints * @since 3.0.0 * * @generic {Phaser.Geom.Point[]} O - [out,$return] * * @param {Phaser.Geom.Line} line - The line. * @param {integer} quantity - The number of points to place on the line. Set to `0` to use `stepRate` instead. * @param {number} [stepRate] - The distance between each point on the line. When set, `quantity` is implied and should be set to `0`. * @param {(array|Phaser.Geom.Point[])} [out] - An optional array of Points, or point-like objects, to store the coordinates of the points on the line. * * @return {(array|Phaser.Geom.Point[])} An array of Points, or point-like objects, containing the coordinates of the points on the line. */ var GetPoints = function (line, quantity, stepRate, out) { if (out === undefined) { out = []; } // If quantity is a falsey value (false, null, 0, undefined, etc) then we calculate it based on the stepRate instead. if (!quantity) { quantity = Length(line) / stepRate; } var x1 = line.x1; var y1 = line.y1; var x2 = line.x2; var y2 = line.y2; for (var i = 0; i < quantity; i++) { var position = i / quantity; var x = x1 + (x2 - x1) * position; var y = y1 + (y2 - y1) * position; out.push(new Point(x, y)); } return out; }; module.exports = GetPoints;
/** * * AttributeOption * */ import React from 'react'; import PropTypes from 'prop-types'; import { useIntl } from 'react-intl'; import { Box } from '@strapi/design-system/Box'; import { Flex } from '@strapi/design-system/Flex'; import { Typography } from '@strapi/design-system/Typography'; import useFormModalNavigation from '../../../hooks/useFormModalNavigation'; import getTrad from '../../../utils/getTrad'; import AttributeIcon from '../../AttributeIcon'; import BoxWrapper from './BoxWrapper'; const AttributeOption = ({ type }) => { const { formatMessage } = useIntl(); const { onClickSelectField } = useFormModalNavigation(); const handleClick = () => { const step = type === 'component' ? '1' : null; onClickSelectField({ attributeType: type, step, }); }; return ( <BoxWrapper padding={4} as="button" hasRadius type="button" onClick={handleClick}> <Flex> <AttributeIcon type={type} /> <Box paddingLeft={4}> <Flex> <Typography fontWeight="bold"> {formatMessage({ id: getTrad(`attribute.${type}`), defaultMessage: type })} </Typography> </Flex> <Flex> <Typography variant="pi" textColor="neutral600"> {formatMessage({ id: getTrad(`attribute.${type}.description`) })} </Typography> </Flex> </Box> </Flex> </BoxWrapper> ); }; AttributeOption.defaultProps = { type: 'text', }; AttributeOption.propTypes = { type: PropTypes.string, }; export default AttributeOption;
!function ($) { "use strict"; var FOUNDATION_VERSION = '6.2.4'; // Global Foundation object // This is attached to the window, or used as a module for AMD/Browserify var Foundation = { version: FOUNDATION_VERSION, /** * Stores initialized plugins. */ _plugins: {}, /** * Stores generated unique ids for plugin instances */ _uuids: [], /** * Returns a boolean for RTL support */ rtl: function () { return $('html').attr('dir') === 'rtl'; }, /** * Defines a Foundation plugin, adding it to the `Foundation` namespace and the list of plugins to initialize when reflowing. * @param {Object} plugin - The constructor of the plugin. */ plugin: function (plugin, name) { // Object key to use when adding to global Foundation object // Examples: Foundation.Reveal, Foundation.OffCanvas var className = name || functionName(plugin); // Object key to use when storing the plugin, also used to create the identifying data attribute for the plugin // Examples: data-reveal, data-off-canvas var attrName = hyphenate(className); // Add to the Foundation object and the plugins list (for reflowing) this._plugins[attrName] = this[className] = plugin; }, /** * @function * Populates the _uuids array with pointers to each individual plugin instance. * Adds the `zfPlugin` data-attribute to programmatically created plugins to allow use of $(selector).foundation(method) calls. * Also fires the initialization event for each plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @param {String} name - the name of the plugin, passed as a camelCased string. * @fires Plugin#init */ registerPlugin: function (plugin, name) { var pluginName = name ? hyphenate(name) : functionName(plugin.constructor).toLowerCase(); plugin.uuid = this.GetYoDigits(6, pluginName); if (!plugin.$element.attr('data-' + pluginName)) { plugin.$element.attr('data-' + pluginName, plugin.uuid); } if (!plugin.$element.data('zfPlugin')) { plugin.$element.data('zfPlugin', plugin); } /** * Fires when the plugin has initialized. * @event Plugin#init */ plugin.$element.trigger('init.zf.' + pluginName); this._uuids.push(plugin.uuid); return; }, /** * @function * Removes the plugins uuid from the _uuids array. * Removes the zfPlugin data attribute, as well as the data-plugin-name attribute. * Also fires the destroyed event for the plugin, consolidating repetitive code. * @param {Object} plugin - an instance of a plugin, usually `this` in context. * @fires Plugin#destroyed */ unregisterPlugin: function (plugin) { var pluginName = hyphenate(functionName(plugin.$element.data('zfPlugin').constructor)); this._uuids.splice(this._uuids.indexOf(plugin.uuid), 1); plugin.$element.removeAttr('data-' + pluginName).removeData('zfPlugin') /** * Fires when the plugin has been destroyed. * @event Plugin#destroyed */ .trigger('destroyed.zf.' + pluginName); for (var prop in plugin) { plugin[prop] = null; //clean up script to prep for garbage collection. } return; }, /** * @function * Causes one or more active plugins to re-initialize, resetting event listeners, recalculating positions, etc. * @param {String} plugins - optional string of an individual plugin key, attained by calling `$(element).data('pluginName')`, or string of a plugin class i.e. `'dropdown'` * @default If no argument is passed, reflow all currently active plugins. */ reInit: function (plugins) { var isJQ = plugins instanceof $; try { if (isJQ) { plugins.each(function () { $(this).data('zfPlugin')._init(); }); } else { var type = typeof plugins, _this = this, fns = { 'object': function (plgs) { plgs.forEach(function (p) { p = hyphenate(p); $('[data-' + p + ']').foundation('_init'); }); }, 'string': function () { plugins = hyphenate(plugins); $('[data-' + plugins + ']').foundation('_init'); }, 'undefined': function () { this['object'](Object.keys(_this._plugins)); } }; fns[type](plugins); } } catch (err) { console.error(err); } finally { return plugins; } }, /** * returns a random base-36 uid with namespacing * @function * @param {Number} length - number of random base-36 digits desired. Increase for more random strings. * @param {String} namespace - name of plugin to be incorporated in uid, optional. * @default {String} '' - if no plugin name is provided, nothing is appended to the uid. * @returns {String} - unique id */ GetYoDigits: function (length, namespace) { length = length || 6; return Math.round(Math.pow(36, length + 1) - Math.random() * Math.pow(36, length)).toString(36).slice(1) + (namespace ? '-' + namespace : ''); }, /** * Initialize plugins on any elements within `elem` (and `elem` itself) that aren't already initialized. * @param {Object} elem - jQuery object containing the element to check inside. Also checks the element itself, unless it's the `document` object. * @param {String|Array} plugins - A list of plugins to initialize. Leave this out to initialize everything. */ reflow: function (elem, plugins) { // If plugins is undefined, just grab everything if (typeof plugins === 'undefined') { plugins = Object.keys(this._plugins); } // If plugins is a string, convert it to an array with one item else if (typeof plugins === 'string') { plugins = [plugins]; } var _this = this; // Iterate through each plugin $.each(plugins, function (i, name) { // Get the current plugin var plugin = _this._plugins[name]; // Localize the search to all elements inside elem, as well as elem itself, unless elem === document var $elem = $(elem).find('[data-' + name + ']').addBack('[data-' + name + ']'); // For each plugin found, initialize it $elem.each(function () { var $el = $(this), opts = {}; // Don't double-dip on plugins if ($el.data('zfPlugin')) { console.warn("Tried to initialize " + name + " on an element that already has a Foundation plugin."); return; } if ($el.attr('data-options')) { var thing = $el.attr('data-options').split(';').forEach(function (e, i) { var opt = e.split(':').map(function (el) { return el.trim(); }); if (opt[0]) opts[opt[0]] = parseValue(opt[1]); }); } try { $el.data('zfPlugin', new plugin($(this), opts)); } catch (er) { console.error(er); } finally { return; } }); }); }, getFnName: functionName, transitionend: function ($elem) { var transitions = { 'transition': 'transitionend', 'WebkitTransition': 'webkitTransitionEnd', 'MozTransition': 'transitionend', 'OTransition': 'otransitionend' }; var elem = document.createElement('div'), end; for (var t in transitions) { if (typeof elem.style[t] !== 'undefined') { end = transitions[t]; } } if (end) { return end; } else { end = setTimeout(function () { $elem.triggerHandler('transitionend', [$elem]); }, 1); return 'transitionend'; } } }; Foundation.util = { /** * Function for applying a debounce effect to a function call. * @function * @param {Function} func - Function to be called at end of timeout. * @param {Number} delay - Time in ms to delay the call of `func`. * @returns function */ throttle: function (func, delay) { var timer = null; return function () { var context = this, args = arguments; if (timer === null) { timer = setTimeout(function () { func.apply(context, args); timer = null; }, delay); } }; } }; // TODO: consider not making this a jQuery function // TODO: need way to reflow vs. re-initialize /** * The Foundation jQuery method. * @param {String|Array} method - An action to perform on the current jQuery object. */ var foundation = function (method) { var type = typeof method, $meta = $('meta.foundation-mq'), $noJS = $('.no-js'); if (!$meta.length) { $('<meta class="foundation-mq">').appendTo(document.head); } if ($noJS.length) { $noJS.removeClass('no-js'); } if (type === 'undefined') { //needs to initialize the Foundation object, or an individual plugin. Foundation.MediaQuery._init(); Foundation.reflow(this); } else if (type === 'string') { //an individual method to invoke on a plugin or group of plugins var args = Array.prototype.slice.call(arguments, 1); //collect all the arguments, if necessary var plugClass = this.data('zfPlugin'); //determine the class of plugin if (plugClass !== undefined && plugClass[method] !== undefined) { //make sure both the class and method exist if (this.length === 1) { //if there's only one, call it directly. plugClass[method].apply(plugClass, args); } else { this.each(function (i, el) { //otherwise loop through the jQuery collection and invoke the method on each plugClass[method].apply($(el).data('zfPlugin'), args); }); } } else { //error for no class or no method throw new ReferenceError("We're sorry, '" + method + "' is not an available method for " + (plugClass ? functionName(plugClass) : 'this element') + '.'); } } else { //error for invalid argument type throw new TypeError('We\'re sorry, ' + type + ' is not a valid parameter. You must use a string representing the method you wish to invoke.'); } return this; }; window.Foundation = Foundation; $.fn.foundation = foundation; // Polyfill for requestAnimationFrame (function () { if (!Date.now || !window.Date.now) window.Date.now = Date.now = function () { return new Date().getTime(); }; var vendors = ['webkit', 'moz']; for (var i = 0; i < vendors.length && !window.requestAnimationFrame; ++i) { var vp = vendors[i]; window.requestAnimationFrame = window[vp + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vp + 'CancelAnimationFrame'] || window[vp + 'CancelRequestAnimationFrame']; } if (/iP(ad|hone|od).*OS 6/.test(window.navigator.userAgent) || !window.requestAnimationFrame || !window.cancelAnimationFrame) { var lastTime = 0; window.requestAnimationFrame = function (callback) { var now = Date.now(); var nextTime = Math.max(lastTime + 16, now); return setTimeout(function () { callback(lastTime = nextTime); }, nextTime - now); }; window.cancelAnimationFrame = clearTimeout; } /** * Polyfill for performance.now, required by rAF */ if (!window.performance || !window.performance.now) { window.performance = { start: Date.now(), now: function () { return Date.now() - this.start; } }; } })(); if (!Function.prototype.bind) { Function.prototype.bind = function (oThis) { if (typeof this !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable'); } var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP = function () {}, fBound = function () { return fToBind.apply(this instanceof fNOP ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments))); }; if (this.prototype) { // native functions don't have a prototype fNOP.prototype = this.prototype; } fBound.prototype = new fNOP(); return fBound; }; } // Polyfill to get the name of a function in IE9 function functionName(fn) { if (Function.prototype.name === undefined) { var funcNameRegex = /function\s([^(]{1,})\(/; var results = funcNameRegex.exec(fn.toString()); return results && results.length > 1 ? results[1].trim() : ""; } else if (fn.prototype === undefined) { return fn.constructor.name; } else { return fn.prototype.constructor.name; } } function parseValue(str) { if (/true/.test(str)) return true;else if (/false/.test(str)) return false;else if (!isNaN(str * 1)) return parseFloat(str); return str; } // Convert PascalCase to kebab-case // Thank you: http://stackoverflow.com/a/8955580 function hyphenate(str) { return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); } }(jQuery); 'use strict'; !function ($) { // Default set of media queries var defaultQueries = { 'default': 'only screen', landscape: 'only screen and (orientation: landscape)', portrait: 'only screen and (orientation: portrait)', retina: 'only screen and (-webkit-min-device-pixel-ratio: 2),' + 'only screen and (min--moz-device-pixel-ratio: 2),' + 'only screen and (-o-min-device-pixel-ratio: 2/1),' + 'only screen and (min-device-pixel-ratio: 2),' + 'only screen and (min-resolution: 192dpi),' + 'only screen and (min-resolution: 2dppx)' }; var MediaQuery = { queries: [], current: '', /** * Initializes the media query helper, by extracting the breakpoint list from the CSS and activating the breakpoint watcher. * @function * @private */ _init: function () { var self = this; var extractedStyles = $('.foundation-mq').css('font-family'); var namedQueries; namedQueries = parseStyleToObject(extractedStyles); for (var key in namedQueries) { if (namedQueries.hasOwnProperty(key)) { self.queries.push({ name: key, value: 'only screen and (min-width: ' + namedQueries[key] + ')' }); } } this.current = this._getCurrentSize(); this._watcher(); }, /** * Checks if the screen is at least as wide as a breakpoint. * @function * @param {String} size - Name of the breakpoint to check. * @returns {Boolean} `true` if the breakpoint matches, `false` if it's smaller. */ atLeast: function (size) { var query = this.get(size); if (query) { return window.matchMedia(query).matches; } return false; }, /** * Gets the media query of a breakpoint. * @function * @param {String} size - Name of the breakpoint to get. * @returns {String|null} - The media query of the breakpoint, or `null` if the breakpoint doesn't exist. */ get: function (size) { for (var i in this.queries) { if (this.queries.hasOwnProperty(i)) { var query = this.queries[i]; if (size === query.name) return query.value; } } return null; }, /** * Gets the current breakpoint name by testing every breakpoint and returning the last one to match (the biggest one). * @function * @private * @returns {String} Name of the current breakpoint. */ _getCurrentSize: function () { var matched; for (var i = 0; i < this.queries.length; i++) { var query = this.queries[i]; if (window.matchMedia(query.value).matches) { matched = query; } } if (typeof matched === 'object') { return matched.name; } else { return matched; } }, /** * Activates the breakpoint watcher, which fires an event on the window whenever the breakpoint changes. * @function * @private */ _watcher: function () { var _this = this; $(window).on('resize.zf.mediaquery', function () { var newSize = _this._getCurrentSize(), currentSize = _this.current; if (newSize !== currentSize) { // Change the current media query _this.current = newSize; // Broadcast the media query change on the window $(window).trigger('changed.zf.mediaquery', [newSize, currentSize]); } }); } }; Foundation.MediaQuery = MediaQuery; // matchMedia() polyfill - Test a CSS media type/query in JS. // Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas, David Knight. Dual MIT/BSD license window.matchMedia || (window.matchMedia = function () { 'use strict'; // For browsers that support matchMedium api such as IE 9 and webkit var styleMedia = window.styleMedia || window.media; // For those that don't support matchMedium if (!styleMedia) { var style = document.createElement('style'), script = document.getElementsByTagName('script')[0], info = null; style.type = 'text/css'; style.id = 'matchmediajs-test'; script && script.parentNode && script.parentNode.insertBefore(style, script); // 'style.currentStyle' is used by IE <= 8 and 'window.getComputedStyle' for all other browsers info = 'getComputedStyle' in window && window.getComputedStyle(style, null) || style.currentStyle; styleMedia = { matchMedium: function (media) { var text = '@media ' + media + '{ #matchmediajs-test { width: 1px; } }'; // 'style.styleSheet' is used by IE <= 8 and 'style.textContent' for all other browsers if (style.styleSheet) { style.styleSheet.cssText = text; } else { style.textContent = text; } // Test if media query is true or false return info.width === '1px'; } }; } return function (media) { return { matches: styleMedia.matchMedium(media || 'all'), media: media || 'all' }; }; }()); // Thank you: https://github.com/sindresorhus/query-string function parseStyleToObject(str) { var styleObject = {}; if (typeof str !== 'string') { return styleObject; } str = str.trim().slice(1, -1); // browsers re-quote string style values if (!str) { return styleObject; } styleObject = str.split('&').reduce(function (ret, param) { var parts = param.replace(/\+/g, ' ').split('='); var key = parts[0]; var val = parts[1]; key = decodeURIComponent(key); // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeURIComponent(val); if (!ret.hasOwnProperty(key)) { ret[key] = val; } else if (Array.isArray(ret[key])) { ret[key].push(val); } else { ret[key] = [ret[key], val]; } return ret; }, {}); return styleObject; } Foundation.MediaQuery = MediaQuery; }(jQuery); 'use strict'; !function ($) { Foundation.Box = { ImNotTouchingYou: ImNotTouchingYou, GetDimensions: GetDimensions, GetOffsets: GetOffsets }; /** * Compares the dimensions of an element to a container and determines collision events with container. * @function * @param {jQuery} element - jQuery object to test for collisions. * @param {jQuery} parent - jQuery object to use as bounding container. * @param {Boolean} lrOnly - set to true to check left and right values only. * @param {Boolean} tbOnly - set to true to check top and bottom values only. * @default if no parent object passed, detects collisions with `window`. * @returns {Boolean} - true if collision free, false if a collision in any direction. */ function ImNotTouchingYou(element, parent, lrOnly, tbOnly) { var eleDims = GetDimensions(element), top, bottom, left, right; if (parent) { var parDims = GetDimensions(parent); bottom = eleDims.offset.top + eleDims.height <= parDims.height + parDims.offset.top; top = eleDims.offset.top >= parDims.offset.top; left = eleDims.offset.left >= parDims.offset.left; right = eleDims.offset.left + eleDims.width <= parDims.width + parDims.offset.left; } else { bottom = eleDims.offset.top + eleDims.height <= eleDims.windowDims.height + eleDims.windowDims.offset.top; top = eleDims.offset.top >= eleDims.windowDims.offset.top; left = eleDims.offset.left >= eleDims.windowDims.offset.left; right = eleDims.offset.left + eleDims.width <= eleDims.windowDims.width; } var allDirs = [bottom, top, left, right]; if (lrOnly) { return left === right === true; } if (tbOnly) { return top === bottom === true; } return allDirs.indexOf(false) === -1; }; /** * Uses native methods to return an object of dimension values. * @function * @param {jQuery || HTML} element - jQuery object or DOM element for which to get the dimensions. Can be any element other that document or window. * @returns {Object} - nested object of integer pixel values * TODO - if element is window, return only those values. */ function GetDimensions(elem, test) { elem = elem.length ? elem[0] : elem; if (elem === window || elem === document) { throw new Error("I'm sorry, Dave. I'm afraid I can't do that."); } var rect = elem.getBoundingClientRect(), parRect = elem.parentNode.getBoundingClientRect(), winRect = document.body.getBoundingClientRect(), winY = window.pageYOffset, winX = window.pageXOffset; return { width: rect.width, height: rect.height, offset: { top: rect.top + winY, left: rect.left + winX }, parentDims: { width: parRect.width, height: parRect.height, offset: { top: parRect.top + winY, left: parRect.left + winX } }, windowDims: { width: winRect.width, height: winRect.height, offset: { top: winY, left: winX } } }; } /** * Returns an object of top and left integer pixel values for dynamically rendered elements, * such as: Tooltip, Reveal, and Dropdown * @function * @param {jQuery} element - jQuery object for the element being positioned. * @param {jQuery} anchor - jQuery object for the element's anchor point. * @param {String} position - a string relating to the desired position of the element, relative to it's anchor * @param {Number} vOffset - integer pixel value of desired vertical separation between anchor and element. * @param {Number} hOffset - integer pixel value of desired horizontal separation between anchor and element. * @param {Boolean} isOverflow - if a collision event is detected, sets to true to default the element to full width - any desired offset. * TODO alter/rewrite to work with `em` values as well/instead of pixels */ function GetOffsets(element, anchor, position, vOffset, hOffset, isOverflow) { var $eleDims = GetDimensions(element), $anchorDims = anchor ? GetDimensions(anchor) : null; switch (position) { case 'top': return { left: Foundation.rtl() ? $anchorDims.offset.left - $eleDims.width + $anchorDims.width : $anchorDims.offset.left, top: $anchorDims.offset.top - ($eleDims.height + vOffset) }; break; case 'left': return { left: $anchorDims.offset.left - ($eleDims.width + hOffset), top: $anchorDims.offset.top }; break; case 'right': return { left: $anchorDims.offset.left + $anchorDims.width + hOffset, top: $anchorDims.offset.top }; break; case 'center top': return { left: $anchorDims.offset.left + $anchorDims.width / 2 - $eleDims.width / 2, top: $anchorDims.offset.top - ($eleDims.height + vOffset) }; break; case 'center bottom': return { left: isOverflow ? hOffset : $anchorDims.offset.left + $anchorDims.width / 2 - $eleDims.width / 2, top: $anchorDims.offset.top + $anchorDims.height + vOffset }; break; case 'center left': return { left: $anchorDims.offset.left - ($eleDims.width + hOffset), top: $anchorDims.offset.top + $anchorDims.height / 2 - $eleDims.height / 2 }; break; case 'center right': return { left: $anchorDims.offset.left + $anchorDims.width + hOffset + 1, top: $anchorDims.offset.top + $anchorDims.height / 2 - $eleDims.height / 2 }; break; case 'center': return { left: $eleDims.windowDims.offset.left + $eleDims.windowDims.width / 2 - $eleDims.width / 2, top: $eleDims.windowDims.offset.top + $eleDims.windowDims.height / 2 - $eleDims.height / 2 }; break; case 'reveal': return { left: ($eleDims.windowDims.width - $eleDims.width) / 2, top: $eleDims.windowDims.offset.top + vOffset }; case 'reveal full': return { left: $eleDims.windowDims.offset.left, top: $eleDims.windowDims.offset.top }; break; case 'left bottom': return { left: $anchorDims.offset.left, top: $anchorDims.offset.top + $anchorDims.height }; break; case 'right bottom': return { left: $anchorDims.offset.left + $anchorDims.width + hOffset - $eleDims.width, top: $anchorDims.offset.top + $anchorDims.height }; break; default: return { left: Foundation.rtl() ? $anchorDims.offset.left - $eleDims.width + $anchorDims.width : $anchorDims.offset.left + hOffset, top: $anchorDims.offset.top + $anchorDims.height + vOffset }; } } }(jQuery); 'use strict'; !function ($) { /** * Motion module. * @module foundation.motion */ var initClasses = ['mui-enter', 'mui-leave']; var activeClasses = ['mui-enter-active', 'mui-leave-active']; var Motion = { animateIn: function (element, animation, cb) { animate(true, element, animation, cb); }, animateOut: function (element, animation, cb) { animate(false, element, animation, cb); } }; function Move(duration, elem, fn) { var anim, prog, start = null; // console.log('called'); function move(ts) { if (!start) start = window.performance.now(); // console.log(start, ts); prog = ts - start; fn.apply(elem); if (prog < duration) { anim = window.requestAnimationFrame(move, elem); } else { window.cancelAnimationFrame(anim); elem.trigger('finished.zf.animate', [elem]).triggerHandler('finished.zf.animate', [elem]); } } anim = window.requestAnimationFrame(move); } /** * Animates an element in or out using a CSS transition class. * @function * @private * @param {Boolean} isIn - Defines if the animation is in or out. * @param {Object} element - jQuery or HTML object to animate. * @param {String} animation - CSS class to use. * @param {Function} cb - Callback to run when animation is finished. */ function animate(isIn, element, animation, cb) { element = $(element).eq(0); if (!element.length) return; var initClass = isIn ? initClasses[0] : initClasses[1]; var activeClass = isIn ? activeClasses[0] : activeClasses[1]; // Set up the animation reset(); element.addClass(animation).css('transition', 'none'); requestAnimationFrame(function () { element.addClass(initClass); if (isIn) element.show(); }); // Start the animation requestAnimationFrame(function () { element[0].offsetWidth; element.css('transition', '').addClass(activeClass); }); // Clean up the animation when it finishes element.one(Foundation.transitionend(element), finish); // Hides the element (for out animations), resets the element, and runs a callback function finish() { if (!isIn) element.hide(); reset(); if (cb) cb.apply(element); } // Resets transitions and removes motion-specific classes function reset() { element[0].style.transitionDuration = 0; element.removeClass(initClass + ' ' + activeClass + ' ' + animation); } } Foundation.Move = Move; Foundation.Motion = Motion; }(jQuery); 'use strict'; !function ($) { var MutationObserver = function () { var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']; for (var i = 0; i < prefixes.length; i++) { if (prefixes[i] + 'MutationObserver' in window) { return window[prefixes[i] + 'MutationObserver']; } } return false; }(); var triggers = function (el, type) { el.data(type).split(' ').forEach(function (id) { $('#' + id)[type === 'close' ? 'trigger' : 'triggerHandler'](type + '.zf.trigger', [el]); }); }; // Elements with [data-open] will reveal a plugin that supports it when clicked. $(document).on('click.zf.trigger', '[data-open]', function () { triggers($(this), 'open'); }); // Elements with [data-close] will close a plugin that supports it when clicked. // If used without a value on [data-close], the event will bubble, allowing it to close a parent component. $(document).on('click.zf.trigger', '[data-close]', function () { var id = $(this).data('close'); if (id) { triggers($(this), 'close'); } else { $(this).trigger('close.zf.trigger'); } }); // Elements with [data-toggle] will toggle a plugin that supports it when clicked. $(document).on('click.zf.trigger', '[data-toggle]', function () { triggers($(this), 'toggle'); }); // Elements with [data-closable] will respond to close.zf.trigger events. $(document).on('close.zf.trigger', '[data-closable]', function (e) { e.stopPropagation(); var animation = $(this).data('closable'); if (animation !== '') { Foundation.Motion.animateOut($(this), animation, function () { $(this).trigger('closed.zf'); }); } else { $(this).fadeOut().trigger('closed.zf'); } }); $(document).on('focus.zf.trigger blur.zf.trigger', '[data-toggle-focus]', function () { var id = $(this).data('toggle-focus'); $('#' + id).triggerHandler('toggle.zf.trigger', [$(this)]); }); /** * Fires once after all other scripts have loaded * @function * @private */ $(window).on('load', function () { checkListeners(); }); function checkListeners() { eventsListener(); resizeListener(); scrollListener(); closemeListener(); } //******** only fires this function once on load, if there's something to watch ******** function closemeListener(pluginName) { var yetiBoxes = $('[data-yeti-box]'), plugNames = ['dropdown', 'tooltip', 'reveal']; if (pluginName) { if (typeof pluginName === 'string') { plugNames.push(pluginName); } else if (typeof pluginName === 'object' && typeof pluginName[0] === 'string') { plugNames.concat(pluginName); } else { console.error('Plugin names must be strings'); } } if (yetiBoxes.length) { var listeners = plugNames.map(function (name) { return 'closeme.zf.' + name; }).join(' '); $(window).off(listeners).on(listeners, function (e, pluginId) { var plugin = e.namespace.split('.')[0]; var plugins = $('[data-' + plugin + ']').not('[data-yeti-box="' + pluginId + '"]'); plugins.each(function () { var _this = $(this); _this.triggerHandler('close.zf.trigger', [_this]); }); }); } } function resizeListener(debounce) { var timer = void 0, $nodes = $('[data-resize]'); if ($nodes.length) { $(window).off('resize.zf.trigger').on('resize.zf.trigger', function (e) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { $(this).triggerHandler('resizeme.zf.trigger'); }); } //trigger all listening elements and signal a resize event $nodes.attr('data-events', "resize"); }, debounce || 10); //default time to emit resize event }); } } function scrollListener(debounce) { var timer = void 0, $nodes = $('[data-scroll]'); if ($nodes.length) { $(window).off('scroll.zf.trigger').on('scroll.zf.trigger', function (e) { if (timer) { clearTimeout(timer); } timer = setTimeout(function () { if (!MutationObserver) { //fallback for IE 9 $nodes.each(function () { $(this).triggerHandler('scrollme.zf.trigger'); }); } //trigger all listening elements and signal a scroll event $nodes.attr('data-events', "scroll"); }, debounce || 10); //default time to emit scroll event }); } } function eventsListener() { if (!MutationObserver) { return false; } var nodes = document.querySelectorAll('[data-resize], [data-scroll], [data-mutate]'); //element callback var listeningElementsMutation = function (mutationRecordsList) { var $target = $(mutationRecordsList[0].target); //trigger the event handler for the element depending on type switch ($target.attr("data-events")) { case "resize": $target.triggerHandler('resizeme.zf.trigger', [$target]); break; case "scroll": $target.triggerHandler('scrollme.zf.trigger', [$target, window.pageYOffset]); break; // case "mutate" : // console.log('mutate', $target); // $target.triggerHandler('mutate.zf.trigger'); // // //make sure we don't get stuck in an infinite loop from sloppy codeing // if ($target.index('[data-mutate]') == $("[data-mutate]").length-1) { // domMutationObserver(); // } // break; default: return false; //nothing } }; if (nodes.length) { //for each element that needs to listen for resizing, scrolling, (or coming soon mutation) add a single observer for (var i = 0; i <= nodes.length - 1; i++) { var elementObserver = new MutationObserver(listeningElementsMutation); elementObserver.observe(nodes[i], { attributes: true, childList: false, characterData: false, subtree: false, attributeFilter: ["data-events"] }); } } } // ------------------------------------ // [PH] // Foundation.CheckWatchers = checkWatchers; Foundation.IHearYou = checkListeners; // Foundation.ISeeYou = scrollListener; // Foundation.IFeelYou = closemeListener; }(jQuery); // function domMutationObserver(debounce) { // // !!! This is coming soon and needs more work; not active !!! // // var timer, // nodes = document.querySelectorAll('[data-mutate]'); // // // if (nodes.length) { // // var MutationObserver = (function () { // // var prefixes = ['WebKit', 'Moz', 'O', 'Ms', '']; // // for (var i=0; i < prefixes.length; i++) { // // if (prefixes[i] + 'MutationObserver' in window) { // // return window[prefixes[i] + 'MutationObserver']; // // } // // } // // return false; // // }()); // // // //for the body, we need to listen for all changes effecting the style and class attributes // var bodyObserver = new MutationObserver(bodyMutation); // bodyObserver.observe(document.body, { attributes: true, childList: true, characterData: false, subtree:true, attributeFilter:["style", "class"]}); // // // //body callback // function bodyMutation(mutate) { // //trigger all listening elements and signal a mutation event // if (timer) { clearTimeout(timer); } // // timer = setTimeout(function() { // bodyObserver.disconnect(); // $('[data-mutate]').attr('data-events',"mutate"); // }, debounce || 150); // } // } // } /******************************************* * * * This util was created by Marius Olbertz * * Please thank Marius on GitHub /owlbertz * * or the web http://www.mariusolbertz.de/ * * * ******************************************/ 'use strict'; !function ($) { var keyCodes = { 9: 'TAB', 13: 'ENTER', 27: 'ESCAPE', 32: 'SPACE', 37: 'ARROW_LEFT', 38: 'ARROW_UP', 39: 'ARROW_RIGHT', 40: 'ARROW_DOWN' }; var commands = {}; var Keyboard = { keys: getKeyCodes(keyCodes), /** * Parses the (keyboard) event and returns a String that represents its key * Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE * @param {Event} event - the event generated by the event handler * @return String key - String that represents the key pressed */ parseKey: function (event) { var key = keyCodes[event.which || event.keyCode] || String.fromCharCode(event.which).toUpperCase(); if (event.shiftKey) key = 'SHIFT_' + key; if (event.ctrlKey) key = 'CTRL_' + key; if (event.altKey) key = 'ALT_' + key; return key; }, /** * Handles the given (keyboard) event * @param {Event} event - the event generated by the event handler * @param {String} component - Foundation component's name, e.g. Slider or Reveal * @param {Objects} functions - collection of functions that are to be executed */ handleKey: function (event, component, functions) { var commandList = commands[component], keyCode = this.parseKey(event), cmds, command, fn; if (!commandList) return console.warn('Component not defined!'); if (typeof commandList.ltr === 'undefined') { // this component does not differentiate between ltr and rtl cmds = commandList; // use plain list } else { // merge ltr and rtl: if document is rtl, rtl overwrites ltr and vice versa if (Foundation.rtl()) cmds = $.extend({}, commandList.ltr, commandList.rtl);else cmds = $.extend({}, commandList.rtl, commandList.ltr); } command = cmds[keyCode]; fn = functions[command]; if (fn && typeof fn === 'function') { // execute function if exists var returnValue = fn.apply(); if (functions.handled || typeof functions.handled === 'function') { // execute function when event was handled functions.handled(returnValue); } } else { if (functions.unhandled || typeof functions.unhandled === 'function') { // execute function when event was not handled functions.unhandled(); } } }, /** * Finds all focusable elements within the given `$element` * @param {jQuery} $element - jQuery object to search within * @return {jQuery} $focusable - all focusable elements within `$element` */ findFocusable: function ($element) { return $element.find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]').filter(function () { if (!$(this).is(':visible') || $(this).attr('tabindex') < 0) { return false; } //only have visible elements and those that have a tabindex greater or equal 0 return true; }); }, /** * Returns the component name name * @param {Object} component - Foundation component, e.g. Slider or Reveal * @return String componentName */ register: function (componentName, cmds) { commands[componentName] = cmds; } }; /* * Constants for easier comparing. * Can be used like Foundation.parseKey(event) === Foundation.keys.SPACE */ function getKeyCodes(kcs) { var k = {}; for (var kc in kcs) { k[kcs[kc]] = kcs[kc]; }return k; } Foundation.Keyboard = Keyboard; }(jQuery); 'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } !function ($) { /** * Reveal module. * @module foundation.reveal * @requires foundation.util.keyboard * @requires foundation.util.box * @requires foundation.util.triggers * @requires foundation.util.mediaQuery * @requires foundation.util.motion if using animations */ var Reveal = function () { /** * Creates a new instance of Reveal. * @class * @param {jQuery} element - jQuery object to use for the modal. * @param {Object} options - optional parameters. */ function Reveal(element, options) { _classCallCheck(this, Reveal); this.$element = element; this.options = $.extend({}, Reveal.defaults, this.$element.data(), options); this._init(); Foundation.registerPlugin(this, 'Reveal'); Foundation.Keyboard.register('Reveal', { 'ENTER': 'open', 'SPACE': 'open', 'ESCAPE': 'close', 'TAB': 'tab_forward', 'SHIFT_TAB': 'tab_backward' }); } /** * Initializes the modal by adding the overlay and close buttons, (if selected). * @private */ _createClass(Reveal, [{ key: '_init', value: function _init() { this.id = this.$element.attr('id'); this.isActive = false; this.cached = { mq: Foundation.MediaQuery.current }; this.isMobile = mobileSniff(); this.$anchor = $('[data-open="' + this.id + '"]').length ? $('[data-open="' + this.id + '"]') : $('[data-toggle="' + this.id + '"]'); this.$anchor.attr({ 'aria-controls': this.id, 'aria-haspopup': true, 'tabindex': 0 }); if (this.options.fullScreen || this.$element.hasClass('full')) { this.options.fullScreen = true; this.options.overlay = false; } if (this.options.overlay && !this.$overlay) { this.$overlay = this._makeOverlay(this.id); } this.$element.attr({ 'role': 'dialog', 'aria-hidden': true, 'data-yeti-box': this.id, 'data-resize': this.id }); if (this.$overlay) { this.$element.detach().appendTo(this.$overlay); } else { this.$element.detach().appendTo($('body')); this.$element.addClass('without-overlay'); } this._events(); if (this.options.deepLink && window.location.hash === '#' + this.id) { $(window).one('load.zf.reveal', this.open.bind(this)); } } /** * Creates an overlay div to display behind the modal. * @private */ }, { key: '_makeOverlay', value: function _makeOverlay(id) { var $overlay = $('<div></div>').addClass('reveal-overlay').appendTo('body'); return $overlay; } /** * Updates position of modal * TODO: Figure out if we actually need to cache these values or if it doesn't matter * @private */ }, { key: '_updatePosition', value: function _updatePosition() { var width = this.$element.outerWidth(); var outerWidth = $(window).width(); var height = this.$element.outerHeight(); var outerHeight = $(window).height(); var left, top; if (this.options.hOffset === 'auto') { left = parseInt((outerWidth - width) / 2, 10); } else { left = parseInt(this.options.hOffset, 10); } if (this.options.vOffset === 'auto') { if (height > outerHeight) { top = parseInt(Math.min(100, outerHeight / 10), 10); } else { top = parseInt((outerHeight - height) / 4, 10); } } else { top = parseInt(this.options.vOffset, 10); } this.$element.css({ top: top + 'px' }); // only worry about left if we don't have an overlay or we havea horizontal offset, // otherwise we're perfectly in the middle if (!this.$overlay || this.options.hOffset !== 'auto') { this.$element.css({ left: left + 'px' }); this.$element.css({ margin: '0px' }); } } /** * Adds event handlers for the modal. * @private */ }, { key: '_events', value: function _events() { var _this2 = this; var _this = this; this.$element.on({ 'open.zf.trigger': this.open.bind(this), 'close.zf.trigger': function (event, $element) { if (event.target === _this.$element[0] || $(event.target).parents('[data-closable]')[0] === $element) { // only close reveal when it's explicitly called return _this2.close.apply(_this2); } }, 'toggle.zf.trigger': this.toggle.bind(this), 'resizeme.zf.trigger': function () { _this._updatePosition(); } }); if (this.$anchor.length) { this.$anchor.on('keydown.zf.reveal', function (e) { if (e.which === 13 || e.which === 32) { e.stopPropagation(); e.preventDefault(); _this.open(); } }); } if (this.options.closeOnClick && this.options.overlay) { this.$overlay.off('.zf.reveal').on('click.zf.reveal', function (e) { if (e.target === _this.$element[0] || $.contains(_this.$element[0], e.target) || !$.contains(document, e.target)) { return; } _this.close(); }); } if (this.options.deepLink) { $(window).on('popstate.zf.reveal:' + this.id, this._handleState.bind(this)); } } /** * Handles modal methods on back/forward button clicks or any other event that triggers popstate. * @private */ }, { key: '_handleState', value: function _handleState(e) { if (window.location.hash === '#' + this.id && !this.isActive) { this.open(); } else { this.close(); } } /** * Opens the modal controlled by `this.$anchor`, and closes all others by default. * @function * @fires Reveal#closeme * @fires Reveal#open */ }, { key: 'open', value: function open() { var _this3 = this; if (this.options.deepLink) { var hash = '#' + this.id; if (window.history.pushState) { window.history.pushState(null, null, hash); } else { window.location.hash = hash; } } this.isActive = true; // Make elements invisible, but remove display: none so we can get size and positioning this.$element.css({ 'visibility': 'hidden' }).show().scrollTop(0); if (this.options.overlay) { this.$overlay.css({ 'visibility': 'hidden' }).show(); } this._updatePosition(); this.$element.hide().css({ 'visibility': '' }); if (this.$overlay) { this.$overlay.css({ 'visibility': '' }).hide(); if (this.$element.hasClass('fast')) { this.$overlay.addClass('fast'); } else if (this.$element.hasClass('slow')) { this.$overlay.addClass('slow'); } } if (!this.options.multipleOpened) { /** * Fires immediately before the modal opens. * Closes any other modals that are currently open * @event Reveal#closeme */ this.$element.trigger('closeme.zf.reveal', this.id); } // Motion UI method of reveal if (this.options.animationIn) { var _this; (function () { var afterAnimationFocus = function () { _this.$element.attr({ 'aria-hidden': false, 'tabindex': -1 }).focus(); }; _this = _this3; if (_this3.options.overlay) { Foundation.Motion.animateIn(_this3.$overlay, 'fade-in'); } Foundation.Motion.animateIn(_this3.$element, _this3.options.animationIn, function () { _this3.focusableElements = Foundation.Keyboard.findFocusable(_this3.$element); afterAnimationFocus(); }); })(); } // jQuery method of reveal else { if (this.options.overlay) { this.$overlay.show(0); } this.$element.show(this.options.showDelay); } // handle accessibility this.$element.attr({ 'aria-hidden': false, 'tabindex': -1 }).focus(); /** * Fires when the modal has successfully opened. * @event Reveal#open */ this.$element.trigger('open.zf.reveal'); if (this.isMobile) { this.originalScrollPos = window.pageYOffset; $('html, body').addClass('is-reveal-open'); } else { $('body').addClass('is-reveal-open'); } setTimeout(function () { _this3._extraHandlers(); }, 0); } /** * Adds extra event handlers for the body and window if necessary. * @private */ }, { key: '_extraHandlers', value: function _extraHandlers() { var _this = this; this.focusableElements = Foundation.Keyboard.findFocusable(this.$element); if (!this.options.overlay && this.options.closeOnClick && !this.options.fullScreen) { $('body').on('click.zf.reveal', function (e) { if (e.target === _this.$element[0] || $.contains(_this.$element[0], e.target) || !$.contains(document, e.target)) { return; } _this.close(); }); } if (this.options.closeOnEsc) { $(window).on('keydown.zf.reveal', function (e) { Foundation.Keyboard.handleKey(e, 'Reveal', { close: function () { if (_this.options.closeOnEsc) { _this.close(); _this.$anchor.focus(); } } }); }); } // lock focus within modal while tabbing this.$element.on('keydown.zf.reveal', function (e) { var $target = $(this); // handle keyboard event with keyboard util Foundation.Keyboard.handleKey(e, 'Reveal', { tab_forward: function () { _this.focusableElements = Foundation.Keyboard.findFocusable(_this.$element); if (_this.$element.find(':focus').is(_this.focusableElements.eq(-1))) { // left modal downwards, setting focus to first element _this.focusableElements.eq(0).focus(); return true; } if (_this.focusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general return true; } }, tab_backward: function () { _this.focusableElements = Foundation.Keyboard.findFocusable(_this.$element); if (_this.$element.find(':focus').is(_this.focusableElements.eq(0)) || _this.$element.is(':focus')) { // left modal upwards, setting focus to last element _this.focusableElements.eq(-1).focus(); return true; } if (_this.focusableElements.length === 0) { // no focusable elements inside the modal at all, prevent tabbing in general return true; } }, open: function () { if (_this.$element.find(':focus').is(_this.$element.find('[data-close]'))) { setTimeout(function () { // set focus back to anchor if close button has been activated _this.$anchor.focus(); }, 1); } else if ($target.is(_this.focusableElements)) { // dont't trigger if acual element has focus (i.e. inputs, links, ...) _this.open(); } }, close: function () { if (_this.options.closeOnEsc) { _this.close(); _this.$anchor.focus(); } }, handled: function (preventDefault) { if (preventDefault) { e.preventDefault(); } } }); }); } /** * Closes the modal. * @function * @fires Reveal#closed */ }, { key: 'close', value: function close() { if (!this.isActive || !this.$element.is(':visible')) { return false; } var _this = this; // Motion UI method of hiding if (this.options.animationOut) { if (this.options.overlay) { Foundation.Motion.animateOut(this.$overlay, 'fade-out', finishUp); } else { finishUp(); } Foundation.Motion.animateOut(this.$element, this.options.animationOut); } // jQuery method of hiding else { if (this.options.overlay) { this.$overlay.hide(0, finishUp); } else { finishUp(); } this.$element.hide(this.options.hideDelay); } // Conditionals to remove extra event listeners added on open if (this.options.closeOnEsc) { $(window).off('keydown.zf.reveal'); } if (!this.options.overlay && this.options.closeOnClick) { $('body').off('click.zf.reveal'); } this.$element.off('keydown.zf.reveal'); function finishUp() { if (_this.isMobile) { $('html, body').removeClass('is-reveal-open'); if (_this.originalScrollPos) { $('body').scrollTop(_this.originalScrollPos); _this.originalScrollPos = null; } } else { $('body').removeClass('is-reveal-open'); } _this.$element.attr('aria-hidden', true); /** * Fires when the modal is done closing. * @event Reveal#closed */ _this.$element.trigger('closed.zf.reveal'); } /** * Resets the modal content * This prevents a running video to keep going in the background */ if (this.options.resetOnClose) { this.$element.html(this.$element.html()); } this.isActive = false; if (_this.options.deepLink) { if (window.history.replaceState) { window.history.replaceState("", document.title, window.location.pathname); } else { window.location.hash = ''; } } } /** * Toggles the open/closed state of a modal. * @function */ }, { key: 'toggle', value: function toggle() { if (this.isActive) { this.close(); } else { this.open(); } } }, { key: 'destroy', /** * Destroys an instance of a modal. * @function */ value: function destroy() { if (this.options.overlay) { this.$element.appendTo($('body')); // move $element outside of $overlay to prevent error unregisterPlugin() this.$overlay.hide().off().remove(); } this.$element.hide().off(); this.$anchor.off('.zf'); $(window).off('.zf.reveal:' + this.id); Foundation.unregisterPlugin(this); } }]); return Reveal; }(); Reveal.defaults = { /** * Motion-UI class to use for animated elements. If none used, defaults to simple show/hide. * @option * @example 'slide-in-left' */ animationIn: '', /** * Motion-UI class to use for animated elements. If none used, defaults to simple show/hide. * @option * @example 'slide-out-right' */ animationOut: '', /** * Time, in ms, to delay the opening of a modal after a click if no animation used. * @option * @example 10 */ showDelay: 0, /** * Time, in ms, to delay the closing of a modal after a click if no animation used. * @option * @example 10 */ hideDelay: 0, /** * Allows a click on the body/overlay to close the modal. * @option * @example true */ closeOnClick: true, /** * Allows the modal to close if the user presses the `ESCAPE` key. * @option * @example true */ closeOnEsc: true, /** * If true, allows multiple modals to be displayed at once. * @option * @example false */ multipleOpened: false, /** * Distance, in pixels, the modal should push down from the top of the screen. * @option * @example auto */ vOffset: 'auto', /** * Distance, in pixels, the modal should push in from the side of the screen. * @option * @example auto */ hOffset: 'auto', /** * Allows the modal to be fullscreen, completely blocking out the rest of the view. JS checks for this as well. * @option * @example false */ fullScreen: false, /** * Percentage of screen height the modal should push up from the bottom of the view. * @option * @example 10 */ btmOffsetPct: 10, /** * Allows the modal to generate an overlay div, which will cover the view when modal opens. * @option * @example true */ overlay: true, /** * Allows the modal to remove and reinject markup on close. Should be true if using video elements w/o using provider's api, otherwise, videos will continue to play in the background. * @option * @example false */ resetOnClose: false, /** * Allows the modal to alter the url on open/close, and allows the use of the `back` button to close modals. ALSO, allows a modal to auto-maniacally open on page load IF the hash === the modal's user-set id. * @option * @example false */ deepLink: false }; // Window exports Foundation.plugin(Reveal, 'Reveal'); function iPhoneSniff() { return (/iP(ad|hone|od).*OS/.test(window.navigator.userAgent) ); } function androidSniff() { return (/Android/.test(window.navigator.userAgent) ); } function mobileSniff() { return iPhoneSniff() || androidSniff(); } }(jQuery);
export default function makeInterval (begin, end, type) { return { begin, end, type }; }
var chai = require("chai"), sinon = require("sinon"), sinonChai = require("sinon-chai"), expect = chai.expect; var async = require('async'), _ = require('lodash'); chai.use(sinonChai); /************************************************************************** * Begin of tests *************************************************************************/ var app = require('../../../app'); var multisetPlugin = require('./multiset'); var mongoose = require('mongoose'); describe('Mongoose.Plugin.multiset', function(){ var schema, Model; before(function(){ schema = new mongoose.Schema({ name : { type : String, default: 'nothing' }, data : { first : {type: String}, sub : {} }, __v: {type: Number, default: 199}, updatedAt : {type: String}, createdAt : {type: String} }); multisetPlugin(schema); Model = mongoose.model('TestMultiSetPlugin', schema); }); describe('#multiSetPlugin()', function(){ before(function(done){ if ('testmultisetplugins' in mongoose.connection.collections) { mongoose.connection.collections['testmultisetplugins'].drop(function(err){ if (err && err.errmsg == 'ns not found') { return done(); } done(err); }); } else { done(); } }); it('should be a function', function(){ expect(multisetPlugin).to.be.a('function'); }); describe('adds multiSet functionality to schemas', function(done){ afterEach(function(done){ Model.remove({}, done); }); it('injects a document#multiSet() method', function(){ var doc = new Model({}); expect(doc.multiSet).to.be.a('function'); }); it('allows to set multiple values at once', function() { var doc = new Model({name: 'test', data: {first: 'test'}}); expect(doc).to.have.a.deep.property('name', 'test'); expect(doc).to.have.a.deep.property('data.first', 'test'); expect(doc).to.have.a.deep.property('__v', 199); doc.multiSet({name: 'test2', data: {sub: { test: 1}}}); expect(doc).to.have.a.deep.property('name', 'test2'); expect(doc).to.have.a.deep.property('data.first', 'test'); // not overwritten expect(doc).to.have.a.deep.property('data.sub.test', 1); expect(doc).to.have.a.deep.property('__v', 199); }) it('prevents modification of id, _id, __v, createdAt and updatedAt', function() { var doc = new Model({name: 'test', createdAt: 'justnow', updatedAt:'justnow'}); var currentId = doc._id.toString(); doc.multiSet({ name: 'changed', id: '537b03bb4c3c4eb17ec61724', _id: '537b03bb4c3c4eb17ec61724', __v: 1, createdAt: 'now', updatedAt:'now' }); expect(doc).to.have.a.deep.property('name', 'changed'); expect(doc._id.toString()).to.equal(currentId); expect(doc).to.have.a.deep.property('__v', 199); expect(doc).to.have.a.deep.property('createdAt', 'justnow'); expect(doc).to.have.a.deep.property('updatedAt', 'justnow'); }); }); }); });
module.exports = function (config) { var configuration = { // 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: [ 'node_modules/jquery/dist/jquery.js', 'node_modules/jasmine-jquery/lib/jasmine-jquery.js', 'node_modules/jasmine2-custom-message/jasmine2-custom-message.js', { pattern: 'Tests/*.html', included: true }, { pattern: 'Tests/*.js', included: true }, 'Scripts/moment.min.js', 'Scripts/bootstrap-sortable.js' ], // list of files to exclude exclude: [ ], // 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: ['mocha'], // 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: false, // 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: true }; config.set(configuration); }
define([], function() { return { errorMessage: "Error on loading Organization Chart", "PropertyPaneDescription": "Modern Organization Chart, With Presence", "BasicGroupName": "Properties", "DescriptionFieldLabel": "Title", } });
export default function (m, v) { m[3] = v[0]; m[4] = v[1]; m[5] = v[2]; return m; }
// Flags: --expose-http2 'use strict'; const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); const http2 = require('http2'); const server = http2.createServer(); server.on('stream', common.mustNotCall()); const count = 32; server.listen(0, common.mustCall(() => { const client = http2.connect(`http://localhost:${server.address().port}`); let remaining = count + 1; function maybeClose() { if (--remaining === 0) { server.close(); client.destroy(); } } // nghttp2 will catch the bad header value for us. function doTest(i) { const req = client.request({ ':path': `bad${String.fromCharCode(i)}path` }); req.on('error', common.expectsError({ code: 'ERR_HTTP2_STREAM_ERROR', type: Error, message: 'Stream closed with error code 1' })); req.on('streamClosed', common.mustCall(maybeClose)); } for (let i = 0; i <= count; i += 1) doTest(i); }));
angular.module("umbraco").controller("SendTestEmailController.Controller", function ($scope, assetsService, $http, $routeParams, notificationsService) { $scope.loading = false; $scope.init = function () { if ($scope.model.value == null || $scope.model.value == "") { // Set default if nothing was set yet $scope.model.value = { recipients: [{}], tags: [{}], } } else if ($scope.model.value.constructor.name === 'Array') { // For old versions, $scope.model.value was the array of tags. // We have made $scope.model.value into an object, with a key 'tags', among others. // If we see an old model.value (an Array), transform it into the new format var tags = $scope.model.value; $scope.model.value = { recipients: [{}], tags: tags, }; } }; $scope.sendTestEmail = function () { $scope.loading = true; if ($scope.model.value.recipient != "") { $http.post("/base/PerplexMail/SendTestMail?id=" + $routeParams.id, { EmailAddresses: _.pluck($scope.model.value.recipients, 'value'), EmailNodeId: $routeParams.id, Tags: $scope.model.value.tags }) .then(function (response) { // Notify the user notificationsService.add({ type: (response.data.Success ? "success" : "error"), headline: response.data.Message }); $scope.loading = false; }), function (err) { //display the error notificationsService.error(err.errorMsg); $scope.loading = false; }; } } $scope.addRecipient = function () { $scope.model.value.recipients.push({}); } $scope.removeRecipient = function (index) { // Laatste element gaan we niet verwijderen, maar leegmaken if ($scope.model.value.recipients.length === 1) { $scope.model.value.recipients = [{}]; } else { $scope.model.value.recipients.splice(index, 1); } } $scope.addTag = function () { // Add an empty value $scope.model.value.tags.push({}); }; $scope.removeTag = function (index) { // Laatste element gaan we niet verwijderen, maar leegmaken if ($scope.model.value.tags.length === 1) { $scope.model.value.tags = [{}]; } else { $scope.model.value.tags.splice(index, 1); } }; });
var config = require('./config.js'); var r = require('../lib')(config); var util = require(__dirname+'/util/common.js'); var assert = require('assert'); var uuid = util.uuid; var It = util.It var dbName, tableName, tableName2, cursor, result, pks, feed; var numDocs = 100; // Number of documents in the "big table" used to test the SUCCESS_PARTIAL var smallNumDocs = 5; // Number of documents in the "small table" It('Init for `cursor.js`', function* (done) { try { dbName = uuid(); tableName = uuid(); // Big table to test partial sequence tableName2 = uuid(); // small table to test success sequence result = yield r.dbCreate(dbName).run() assert.equal(result.dbs_created, 1); result = yield [r.db(dbName).tableCreate(tableName)('tables_created').run(), r.db(dbName).tableCreate(tableName2)('tables_created').run()] assert.deepEqual(result, [1, 1]); done(); } catch(e) { done(e); } }) It('Inserting batch - table 1', function* (done) { try { result = yield r.db(dbName).table(tableName).insert(eval('['+new Array(numDocs).join('{}, ')+'{}]')).run(); assert.equal(result.inserted, numDocs); done(); } catch(e) { done(e); } }) It('Inserting batch - table 2', function* (done) { try { result = yield r.db(dbName).table(tableName2).insert(eval('['+new Array(smallNumDocs).join('{}, ')+'{}]')).run(); assert.equal(result.inserted, smallNumDocs); done(); } catch(e) { done(e); } }) It('Updating batch', function* (done) { try { // Add a date result = yield r.db(dbName).table(tableName).update({ date: r.now().sub(r.random().mul(1000000)), value: r.random() }, {nonAtomic: true}).run(); done(); } catch(e) { done(e); } }) It('`table` should return a cursor', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); assert.equal(cursor.toString(), '[object Cursor]'); done(); } catch(e) { done(e); } }) It('`next` should return a document', function* (done) { try { result = yield cursor.next(); assert(result); assert(result.id); done(); } catch(e) { done(e); } }) It('`each` should work', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); var count = 0; cursor.each(function(err, result) { count++; if (count === numDocs) { done(); } }) } catch(e) { done(e); } }) It('`eachAsync` should work', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); var history = []; var count = 0; var promisesWait = 0; cursor.eachAsync(function(result) { history.push(count); count++; return new Promise(function(resolve, reject) { setTimeout(function() { history.push(promisesWait); promisesWait--; if (count === numDocs) { var expected = []; for(var i=0; i<numDocs; i++) { expected.push(i); expected.push(-1*i); } assert.deepEqual(history, expected) } resolve(); }, 1); }); }).then(done); } catch(e) { done(e); } }) It('`eachAsync` should work - callback style', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); var count = 0; var now = Date.now(); var timeout = 10; cursor.eachAsync(function(result, onRowFinished) { count++; setTimeout(function() { onRowFinished(); }, timeout) }).then(function() { var elapsed = Date.now()-now; assert(elapsed >= timeout*count); done(); }); } catch(e) { done(e); } }) It('`each` should work - onFinish - reach end', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); var count = 0; cursor.each(function(err, result) { }, done) } catch(e) { done(e); } }) It('`each` should work - onFinish - return false', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); assert(cursor); var count = 0; cursor.each(function(err, result) { count++ return false }, function() { assert.equal(count, 1); done(); }) } catch(e) { done(e); } }) It('`toArray` should work', function* (done) { try { cursor = yield r.db(dbName).table(tableName).run({cursor: true}); result = yield cursor.toArray(); assert.equal(result.length, numDocs); done(); } catch(e) { done(e); } }) It('`toArray` should work -- with a profile', function* (done) { try { result = yield r.db(dbName).table(tableName).run({cursor: true, profile: true}); result = yield result.result.toArray(); assert.equal(result.length, numDocs); done(); } catch(e) { done(e); } }) It('`toArray` should work with a datum', function* (done) { try { cursor = yield r.expr([1,2,3]).run({cursor: true}); result = yield cursor.toArray(); assert.deepEqual(result, [1,2,3]); done(); } catch(e) { done(e); } }) It('`table` should return a cursor - 2', function* (done) { try { cursor = yield r.db(dbName).table(tableName2).run({cursor: true}); assert(cursor); done(); } catch(e) { done(e); } }) It('`next` should return a document - 2', function* (done) { try { result = yield cursor.next(); assert(result); assert(result.id); done(); } catch(e) { done(e); } }) It('`next` should work -- testing common pattern', function* (done) { try { cursor = yield r.db(dbName).table(tableName2).run({cursor: true}); assert(cursor); var i=0; while(true) { try{ result = yield cursor.next(); assert(result); i++; } catch(e) { if (e.message === "No more rows in the cursor.") { assert.equal(smallNumDocs, i); done(); break; } else { done(e); break; } } } } catch(e) { done(e); } }) It('`toArray` should work - 2', function* (done) { try { var cursor = yield r.db(dbName).table(tableName2).run({cursor: true}); result = yield cursor.toArray(); assert.equal(result.length, smallNumDocs); done(); } catch(e) { done(e); } }) It('`cursor.close` should return a promise', function* (done) { try { var cursor = yield r.db(dbName).table(tableName2).run({cursor: true}); yield cursor.close(); done(); } catch(e) { done(e); } }) It('`cursor.close` should still return a promise if the cursor was closed', function* (done) { try { var cursor = yield r.db(dbName).table(tableName2).changes().run(); yield cursor.close(); yield cursor.close(); done(); } catch(e) { done(e); } }) It('cursor shouldn\'t throw if the user try to serialize it in JSON', function* (done) { try { var cursor = yield r.db(dbName).table(tableName).run({cursor: true}); cursor.toJSON() done(new Error('Was expecting an error')); } catch(e) { assert.equal(e.message, "You cannot serialize a Cursor to JSON. Retrieve data from the cursor with `toArray` or `next`."); done(); } }) // This test is not working for now -- need more data? Server bug? It('Remove the field `val` in some docs', function* (done) { var i=0; try { result = yield r.db(dbName).table(tableName).update({val: 1}).run(); //assert.equal(result.replaced, numDocs); result = yield r.db(dbName).table(tableName) .orderBy({index: r.desc("id")}).limit(5).replace(r.row.without("val")) //.sample(1).replace(r.row.without("val")) .run({cursor: true}); assert.equal(result.replaced, 5); done(); } catch(e) { done(e); } }) It('`toArray` with multiple batches - testing empty SUCCESS_COMPLETE', function* (done) { var i=0; try { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); cursor = yield r.db(dbName).table(tableName).run(connection, {cursor: true, maxBatchRows: 1}); assert(cursor); result = yield cursor.toArray(); done(); } catch(e) { done(e); } }) It('Automatic coercion from cursor to table with multiple batches', function* (done) { var i=0; try { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); result = yield r.db(dbName).table(tableName).run(connection, {maxBatchRows: 1}); assert(result.length > 0); done(); } catch(e) { done(e); } }) It('`next` with multiple batches', function* (done) { var i=0; try { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); cursor = yield r.db(dbName).table(tableName).run(connection, {cursor: true, maxBatchRows: 1}); assert(cursor); while(true) { try { result = yield cursor.next(); i++; } catch(e) { if ((i > 0) && (e.message === "No more rows in the cursor.")) { connection.close(); done() } else { done(e); } break; } } } catch(e) { done(e); } }) It('`next` should error when hitting an error -- not on the first batch', function* (done) { var i=0; try { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); var cursor = yield r.db(dbName).table(tableName) .orderBy({index: "id"}) .map(r.row("val").add(1)) .run(connection, {cursor: true, maxBatchRows: 10}); assert(cursor); while(true) { try { result = yield cursor.next(); i++; } catch(e) { if ((i > 0) && (e.message.match(/^No attribute `val` in object/))) { connection.close(); done() } else { done(e); } break; } } } catch(e) { done(e); } }) It('`changes` should return a feed', function* (done) { try { feed = yield r.db(dbName).table(tableName).changes().run(); assert(feed); assert.equal(feed.toString(), '[object Feed]'); yield feed.close(); done(); } catch(e) { done(e); } }) It('`changes` should work with squash: true', function* (done) { try { feed = yield r.db(dbName).table(tableName).changes({squash: true}).run(); assert(feed); assert.equal(feed.toString(), '[object Feed]'); yield feed.close(); done(); } catch(e) { done(e); } }) It('`get.changes` should return a feed', function* (done) { try { feed = yield r.db(dbName).table(tableName).get(1).changes().run(); assert(feed); assert.equal(feed.toString(), '[object AtomFeed]'); yield feed.close(); done(); } catch(e) { done(e); } }) It('`orderBy.limit.changes` should return a feed', function* (done) { try { feed = yield r.db(dbName).table(tableName).orderBy({index: 'id'}).limit(2).changes().run(); assert(feed); assert.equal(feed.toString(), '[object OrderByLimitFeed]'); yield feed.close(); done(); } catch(e) { done(e); } }) It('`changes` with `includeOffsets` should work', function* (done) { try { feed = yield r.db(dbName).table(tableName).orderBy({index: 'id'}).limit(2).changes({ includeOffsets: true, includeInitial: true }).run(); var counter = 0; feed.each(function(error, change) { assert(typeof change.new_offset === 'number'); if (counter >= 2) { assert(typeof change.old_offset === 'number'); feed.close().then(function() { done(); }).error(done); } counter++; }); yield r.db(dbName).table(tableName).insert({id: 0}); //done(); } catch(e) { done(e); } }) It('`changes` with `includeTypes` should work', function* (done) { try { feed = yield r.db(dbName).table(tableName).orderBy({index: 'id'}).limit(2).changes({ includeTypes: true, includeInitial: true }).run(); var counter = 0; feed.each(function(error, change) { assert(typeof change.type === 'string'); if (counter > 0) { feed.close().then(function() { done(); }).error(done); } counter++; }); yield r.db(dbName).table(tableName).insert({id: 0}); //done(); } catch(e) { done(e); } }) It('`next` should work on a feed', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).update({foo: r.now()}).run(); }, 100) assert(feed); var i=0; while(true) { result = yield feed.next(); assert(result); i++; if (i === smallNumDocs) { yield feed.close(); done(); break; } } } catch(e) { done(e); } }) It('`next` should work on an atom feed', function* (done) { try { var idValue = uuid(); feed = yield r.db(dbName).table(tableName2).get(idValue).changes({includeInitial: true}).run(); setTimeout(function() { r.db(dbName).table(tableName2).insert({id: idValue}).run(); }, 100) assert(feed); var i=0; var change = yield feed.next(); assert.deepEqual(change, {new_val: null}); change = yield feed.next(); assert.deepEqual(change, {new_val: {id: idValue}, old_val: null}); yield feed.close(); done(); } catch(e) { done(e); } }) It('`close` should work on feed', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { feed.close().then(function() { done(); }); }, 1000) assert(feed); } catch(e) { done(e); } }) It('`close` should work on feed with events', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { feed.close(); }, 1000) assert(feed); feed.on('error', function() { // Ignore the error }); feed.on('end', function() { done(); }); } catch(e) { done(e); } }) It('`on` should work on feed', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).update({foo: r.now()}).run(); }, 100) var i=0; feed.on('data', function() { i++; if (i === smallNumDocs) { feed.close().then(function() { done(); }).error(function(error) { done(error); }); } }); feed.on('error', function(e) { done(e) }) } catch(e) { done(e); } }) It('`on` should work on cursor - a `end` event shoul be eventually emitted on a cursor', function* (done) { try { cursor = yield r.db(dbName).table(tableName2).run({cursor: true}); setTimeout(function() { r.db(dbName).table(tableName2).update({foo: r.now()}).run(); }, 100) cursor.on('end', function() { done() }); cursor.on('error', function(e) { done(e) }) } catch(e) { done(e); } }) It('`next`, `each`, `toArray` should be deactivated if the EventEmitter interface is used', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).update({foo: r.now()}).run(); }, 100) feed.on('data', function() { }); feed.on('error', function(error) { done(error); }); assert.throws(function() { feed.next(); }, function(e) { if (e.message === 'You cannot call `next` once you have bound listeners on the Feed.') { feed.close().then(function() { done(); }).error(function(error) { done(error); }); } else { done(e); } return true; }) } catch(e) { done(e); } }) It('Import with cursor as default', function* (done) { yield util.sleep(1000); var r1 = require('../lib')({cursor: true, host: config.host, port: config.port, authKey: config.authKey, buffer: config.buffer, max: config.max, silent: true}); var i=0; try { cursor = yield r1.db(dbName).table(tableName).run(); assert.equal(cursor.toString(), '[object Cursor]'); yield cursor.close(); done(); } catch(e) { done(e); } }) It('`each` should not return an error if the feed is closed - 1', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).limit(2).update({foo: r.now()}).run(); }, 100) var count = 0; feed.each(function(err, result) { if (result.new_val.foo instanceof Date) { count++; } if (count === 1) { setTimeout(function() { feed.close().then(function() { done(); }).error(done); }, 100); } }); } catch(e) { done(e); } }) It('`each` should not return an error if the feed is closed - 2', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).limit(2).update({foo: r.now()}).run(); }, 100) var count = 0; feed.each(function(err, result) { if (result.new_val.foo instanceof Date) { count++; } if (count === 2) { setTimeout(function() { feed.close().then(function() { done(); }).error(done); }, 100); } }); } catch(e) { done(e); } }) It('events should not return an error if the feed is closed - 1', function* (done) { try { feed = yield r.db(dbName).table(tableName2).get(1).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).insert({id: 1}).run(); }, 100) feed.each(function(err, result) { if (err) { return done(err); } if ((result.new_val != null) && (result.new_val.id === 1)) { feed.close().then(function() { done(); }).error(done); } }); } catch(e) { done(e); } }) It('events should not return an error if the feed is closed - 2', function* (done) { try { feed = yield r.db(dbName).table(tableName2).changes().run(); setTimeout(function() { r.db(dbName).table(tableName2).limit(2).update({foo: r.now()}).run(); },100) var count = 0; feed.on('data', function(result) { if (result.new_val.foo instanceof Date) { count++; } if (count === 1) { setTimeout(function() { feed.close().then(function() { done(); }).error(done); }, 100); } }); } catch(e) { done(e); } }) It('`includeStates` should work', function* (done) { try { feed = yield r.db(dbName).table(tableName).orderBy({index: 'id'}).limit(10).changes({includeStates: true, includeInitial: true}).run(); var i = 0; feed.each(function(err, change) { i++; if (i === 10) { feed.close(); done(); } }); } catch(e) { done(e); } }) It('`each` should return an error if the connection dies', function* (done) { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); var feed = yield r.db(dbName).table(tableName).changes().run(connection); feed.each(function(err, change) { assert(err.message.match(/^The connection was closed before the query could be completed for/)) done(); }); // Kill the TCP connection connection.connection.end() }) It('`eachAync` should return an error if the connection dies', function* (done) { var connection = yield r.connect({host: config.host, port: config.port, authKey: config.authKey}); assert(connection); var feed = yield r.db(dbName).table(tableName).changes().run(connection); feed.eachAsync(function(change) {}).error(function(err) { assert(err.message.match(/^The connection was closed before the query could be completed for/)) done(); }); // Kill the TCP connection connection.connection.end() })
/** * GKA (generate keyframes animation) * author: joeyguo * HomePage: https://github.com/gkajs/gka-utils * * gka utils */ const css = require('./core/css'); const html = require('./core/html'); const data = require('./core/data'); const _ = require('./core/_'); module.exports = { html, css, data, _, }
Vue.http.options.emulateJSON = true; vm = new Vue({ el: '#app', data: { debug: true, //debug mode? answered: 0, //the count of answered questions currentTags: {}, //the answered tags results: null, //the resulting distros comment: "", //the user's comment for the result commentSent: false, statistics: null, visitorCount: 0, loaded: false, i18n: null, firstQuestionNumber:1, lastQuestionNumber: -1, currentTestLoading: false, currentTest: -1, deniedWhy: [], isOldTest:false, donationEnabled:false, displayExcluded:true, displayFilters: true, otherUserResults:[], givenAnswers:[], //stores the currently given answers to avoid double iteration at getCurrentTags() modalOpen:false, version: "3.0 (2017)", allowDifferentBackends: false, backends: { "waldorf": "https://waldorf.distrochooser.de", "stetler": "https://beta.distrochooser.de/distrochooser-backend-php", }, backend: null, lang:"de", rawDistros: [], questions: [ { "id":"welcome", "text":"", "help":"", "important":false, "single":false, "answers":[ ], "number":-1 } ], langs: ["de","en"] }, created: function(){ console.log(" _ ___ ___ ____"); console.log(" | | | \\ / __| |__ /"); console.log(" | |__ | |) | |(__ |_ \\ "); console.log(" |____ |___/ \\___| |___/ "); console.log("Starting Linux Distribution Chooser "+this.version); console.log("Started: " + new Date()); this.chooseBackend(); this.init(); this.getStatistics(); this.getRatings(); setTimeout(this.getRatings, 10000); }, computed: { langCode: function(){ var index = this.langs.indexOf(this.lang); return index !== -1 ? index + 1 : 1; }, shareLink : function(){ var baseUrl = "https://beta.distrochooser.de/?l="+this.langCode; if (this.currentTest === -1){ return baseUrl; } return baseUrl+ "&test="+this.currentTest; }, ratingSent : function (){ return false; }, answeredQuestionsCount: function(){ this.answered = this.answeredQuestions(); return this.answered.length; }, questionsCount: function(){ var count = 0; for(var i = 0; i < this.questions.length;i++){ if (this.questions[i].answers.length !== 0){ count++; } } return count; }, excludedDistros : function(){ var distros = []; for(var i=0;i<this.rawDistros.length;i++){ if (this.rawDistros[i].excluded){ distros.push(this.rawDistros[i]); } } return distros; }, distributions : function(){ //Reset percentages if needed if (Object.keys(this.currentTags).length === 0){ for (var i = 0; i < this.rawDistros.length;i++){ this.rawDistros[i].percentage = 0; } return this.rawDistros; } this.results = []; this.deniedWhy = {}; var pointSum = 0; for (var tag in this.currentTags) { var weight = this.currentTags[tag]; var isNoTag = tag.indexOf("!") !== -1; if (!isNoTag){ pointSum += weight; //Do not count no-tags } } for (var i = 0; i < this.rawDistros.length;i++){ var distro = this.rawDistros[i]; var points = 0; var hittedTags = 0; this.rawDistros[i].excluded = false; //reset flag for (var tag in this.currentTags) { var weight = this.currentTags[tag]; var isNoTag = tag.indexOf("!") !== -1; var needle = tag.replace("!",""); //get percentage if (distro.tags.indexOf(needle) !== -1){ if (isNoTag){ this.rawDistros[i].excluded = true; if (Object.keys(this.deniedWhy).indexOf(needle) === -1){ this.deniedWhy[needle] = 1; }else{ this.deniedWhy[needle]++; } points = 0; //break; } points += weight; hittedTags++; } } if (points > 0){ distro.percentage = Math.round(100 / (pointSum/points),2); }else{ distro.percentage = 0; } if (distro.percentage > 0){ this.results.push(distro); } } this.commentSent = false; this.results.sort( function compare(a,b) { if (a.percentage > b.percentage) return -1; if (a.percentage < b.percentage) return 1; return 0; }); return this.results; } }, methods: { chooseBackend:function(){ if (this.allowDifferentBackends){ var backends = Object.keys(this.backends); var index = Math.floor((Math.random() * 100)); if (index > 2){ this.backend = this.backends.stetler; console.log("Backend: stetler"); }else{ this.backend = this.backends.waldorf; console.log("Backend: waldorf"); } }else{ this.backend = this.backends.stetler; } }, showTooltip:function(tooltip){ alert(tooltip); }, translateExcludedTags:function(answer){ var result = this.text('excludes') +": \n"; var _t = this; answer.notags.forEach(function(t){ result += _t.text(t) + "\n"; }); return result.trim(); }, text:function(value){ return this.i18n !== null &&typeof this.i18n[value] !== 'undefined'? this.i18n[value].val:''; }, isTagChoosed:function(tag){ for (var key in this.currentTags) { if (key === tag){ return true; } } return false; }, getExcludingAnswer: function(tag){ if (this.givenAnswers.length === 0){ return ""; } var tag = tag.replace("!",""); var text = ""; var question =""; for(var a in this.givenAnswers){ var answer = this.givenAnswers[a]; answer.notags.forEach(function(t){ if (t === tag && text === ""){ text = answer.text; } }); if (text !== ""){ question = this.getQuestionByAnswer(answer.id); break; } } return question.number+ ". " + question.text + ": " + text; }, updateCurrentTags: function(){ //get the currently answered tags this.currentTags = {}; for (var i = 0; i < this.givenAnswers.length;i++){ var answer = this.givenAnswers[i]; for(var y = 0 ; y < answer.tags.length; y++){ var tag = answer.tags[y]; if (Object.keys(this.currentTags).indexOf(tag) === -1){ this.currentTags[tag] = 1; }else{ this.currentTags[tag]++; } if (answer.important){ this.currentTags[tag] *=2; } } for(var y = 0 ; y < answer.notags.length; y++){ var tag = "!"+answer.notags[y]; if (Object.keys(this.currentTags).indexOf(tag) === -1){ this.currentTags[tag] = 1; }else{ this.currentTags[tag]++; } if (answer.important){ this.currentTags[tag] *=2; } } } return this.currentTags; }, init : function(){ this.getLanguage(); this.loaded = false; var _t = this; this.$http.get(this.backend + "/get/"+this.lang+"/").then(function(data){ var result = data.json(); console.log("Hello #"+result.visitor); _t.rawDistros = result.distros; _t.results = result.distros; _t.i18n = result.i18n; _t.questions = _t.questions.concat(result.questions); _t.questions[0].text = _t.text("welcomeTextHeader"); _t.questions[0].help = _t.text("welcomeText"); _t.loaded = true; _t.lastQuestionNumber = result.questions.length; _t.displayRatings(result.lastRatings); console.log("Finished: " + new Date()); _t.getOldTest(); }); }, getStatistics: function(){ this.$http.get(this.backend + "/getstats/").then(function(data){ this.statistics = data.json(); }); }, getRatings: function(){ var _t = this; this.$http.get(this.backend + "/getratings/" + this.lang +"/").then(function(data){ this.otherUserResults = []; var got = JSON.parse(data.body).reverse(); _t.displayRatings(got); }); }, displayRatings(ratings){ for(var rating in ratings){ var tuple = {}; tuple.comment = ratings[rating].Comment; tuple.stars = Math.ceil(ratings[rating].Rating); tuple.os = "Windows"; if (ratings[rating].UserAgent.indexOf("Linux") !== -1){ tuple.os = "Linux"; }else if (ratings[rating].UserAgent.indexOf("ac") !== -1){ tuple.os = "macOS"; }else if (ratings[rating].UserAgent.indexOf("unix") !== -1){ tuple.os = "Unix"; }else if (ratings[rating].UserAgent.indexOf("Android") !== -1){ tuple.os = "Android"; }else if (ratings[rating].UserAgent.indexOf("iPhone") !== -1){ tuple.os = "iPhone"; } this.otherUserResults.unshift(tuple); } }, getOldTest: function(){ var parts = this.getUrlParts(); if (typeof parts["answers"] !== 'undefined'){ this.isOldTest = true; }else{ if (typeof parts["test"] !== 'undefined'){ var test = parseInt(parts["test"]); //Load old test results var _t = this; this.$http.get(this.backend +"/test/" + test +"/").then(function(data){ var obj = data.json(); var answers = JSON.parse(obj.answers); var important = JSON.parse(obj.important); for(var a =0; a < answers.length;a++){ this.selectAnswer(answers[a]); } for (var i = 0; i < _t.questions.length;i++){ var count = important.filter(function(q){ return q === _t.questions[i].id; }); _t.questions[i].important = count.length !== 0; } }); } } }, answeredQuestions: function(){ var answered = []; for (var i = 0; i < this.questions.length;i++){ for(var x = 0; x < this.questions[i].answers.length;x++){ if (this.questions[i].answers[x].selected){ answered.push(this.questions[i]); break; } } } return answered; }, getAnswer : function(id){ for (var i = 0; i < this.questions.length;i++){ for(var x = 0; x < this.questions[i].answers.length;x++){ if (this.questions[i].answers[x].id === id){ return this.questions[i].answers[x]; } } } return null; }, getQuestionByAnswer : function(id){ for (var i = 0; i < this.questions.length;i++){ for(var x = 0; x < this.questions[i].answers.length;x++){ if (this.questions[i].answers[x].id === id){ return this.questions[i]; } } } return null; }, getQuestion : function(id){ for (var i = 0; i < this.questions.length;i++){ if (this.questions[i].id === id){ return this.questions[i] } } return null; }, selectAnswer : function (id){ var answer = this.getAnswer(id); var question = this.getQuestionByAnswer(id); this.addAnswerToList(answer); if (answer !== null && !answer.selected){ answer.selected = true; question.answered = true; return answer.selected; } else if (answer.selected){ answer.selected = false; question.answered = false; for (var i=0;i<question.answers.length;i++){ if (question.answers[i].selected === true){ question.answered = true; break; } } return answer.selected; } else{ return false; } }, makeImportant : function (question){ if (question !== null){ if (question.important){ question.important = false; }else{ question.important = true; } this.setGivenAnswerImportantFlag(question,question.important); return question.important; }else{ return false; } }, removeAnswers: function(question){ for(var i=0;i<question.answers.length;i++){ question.answers[i].selected = false; this.removeAnswerFromList(question.answers[i]); } question.answered = false; }, getGivenAnswerIndex: function(answer){ var index = -1; this.givenAnswers.forEach(function(a,i,array){ if (a.id === answer.id){ index = i; } }); return index; }, removeAnswerFromList: function(answer){ var index = this.getGivenAnswerIndex(answer); if (index !== -1){ this.givenAnswers.splice(index,1); } }, addAnswerToList: function(answer,important){ var index = this.getGivenAnswerIndex(answer); if (index === -1) { //no duplicates answer.important = important; this.givenAnswers.push(answer); } }, setGivenAnswerImportantFlag: function(question,state){ for (var i = 0; i < question.answers.length;i++){ var index = this.getGivenAnswerIndex(question.answers[i]); if (index !== -1){ this.givenAnswers[index].important = state; } } }, updateAnsweredFlag : function(args,answer,question){ var _t = this; if (question.single){ question.answers.forEach(function(a){ if (answer.id !== a.id){ a.selected = false; } if (!a.selected){ _t.removeAnswerFromList(a); } }); answer.selected = true; question.answered = true; this.addAnswerToList(answer,question.important); }else{ var answered = 0; question.answers.forEach(function(a){ if (a.selected){ answered++; _t.addAnswerToList(a,question.important); }else{ _t.removeAnswerFromList(a); } }); question.answered = answered >0; } }, publishRating : function(args){ var rating = $("#rating-stars").rateYo().rateYo("rating"); var _this = this; this.$http.post(this.backend + "/addrating/"+this.lang + "/",{ test: _this.currentTest, rating: rating, comment: _this.comment }).then(function(data){ this.commentSent = true; this.getRatings(); }); }, displayResults: function(){ if ($("#Result").attr("aria-expanded") !== "true"){ //no recalculation if already open $("#Result").trigger("click"); this.addResult(); } window.scroll(0, $("#Result").offset().top - 50); }, addResult: function (){ var answers = []; var important = []; this.updateCurrentTags() for(var i = 0; i < this.answered.length;i++){ var question = this.answered[i]; for(var x = 0; x < question.answers.length;x++){ if (question.answers[x].selected){ answers.push(question.answers[x].id); } } if (question.important){ important.push(question.id) } } $("#rating-stars").rateYo(); this.currentTestLoading = false; this.$http.post(this.backend + "/addresult/",{ distros: JSON.stringify(this.rawDistros), tags: JSON.stringify(this.currentTags), answers: JSON.stringify(answers), important: JSON.stringify(important) }).then(function(data){ this.currentTest = parseInt(data.body); this.getStatistics(); }); }, getUrlParts: function(){ var vars = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { vars[key] = value; }); return vars; }, getLanguage: function(){ var langcode = this.getLanguageKey(); var browserLang = navigator.language || navigator.userLanguage; if (this.langs.indexOf(browserLang) !== -1 && langcode === null){ this.lang = browserLang; }else{ if (langcode === null){ this.lang = "en"; //falback if the browser language is not currently configured and there is no language key given }else{ this.lang = parseInt(langcode) === 1 ? 'de' : 'en'; } } }, getLanguageKey: function(){ var parts = this.getUrlParts(); var langcode = 1; if (typeof parts["l"] !== 'undefined'){ return parts["l"]; } return null; }, nextTrigger: function(id){ var needleIndex = -1; var needle = id; for(var i=0;i<this.questions.length;i++){ if (i < this.questions.length && this.questions[i].id === needle){ needleIndex = i; break; } } if (needleIndex === this.questions.length -1){ this.displayResults(); }else{ $("[ldc-header='"+this.questions[needleIndex+1].id+"']").trigger("click",function(){ window.scroll(0,$("[ldc-header='"+this.questions[needleIndex+1].id+"']").top); }); } }, getTagTranslation : function(value){ var anti = value.indexOf("!") !== -1; var text = this.text(value.replace("!","")); return text !== "" ? (anti ? this.text("NotComplied") +": " : "") + text : value; } } });
/** * @fileoverview * Test suite for 00-skeleton * * @author Graham Klyne * @version $Id$ * * Coypyright (C) 2010, University of Oxford * * Licensed under the MIT License. You may obtain a copy of the license at: * * http://www.opensource.org/licenses/mit-license.php * * 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. */ /** * @fileoverview * Test suite for workspace saving functions * * @author Graham Klyne * @version $Id$ * * Coypyright (C) 2009, University of Oxford * * Licensed under the MIT License. You may obtain a copy of the license at: * * http://www.opensource.org/licenses/mit-license.php * * 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. */ /** * Dependencies: * test-shuffl-saveworkspace-layout.json * eXist server running at localhost:8080 * The test page must be loaded from the eXist server for the test to run * (due to same-origin security restriction). */ /** * Function to register tests */ TestSaveWorkspace = function() { module("TestSaveWorkspace"); // Figure base URI based on page URI var pageuri = jQuery.uri().toString(); var baseuri = null; var baseuri_list = [ "http://localhost/webdav/" , "http://zoo-samos.zoo.ox.ac.uk/webdav/" , "http://localhost:8080/exist/" ]; for (i in baseuri_list) { var b = baseuri_list[i]; if (shuffl.starts(b, pageuri)) { baseuri = b; } } // Check we have a suitable base URI test("NOTE: this test must be run from the web server used to store shuffl workspace data", function () { logtest("TestSaveWorkspace source check"); if (!baseuri) { ok(baseuri, "TestSaveWorkspace must be served from exist/atom or WebDAV location"); throw "TestSaveWorkspace must be served from exist/atom or WebDAV location"; } }); // Figure out collection URI with special handling for eXist (AtomPub): var coluri = baseuri+"shuffltest/"; var nocoluri = baseuri+"shuffltest_nofeed/"; if (shuffl.ends("exist/", baseuri)) { coluri = baseuri + "atom/edit/shuffltest/"; nocoluri = baseuri + "atom/edit/shuffltest_nofeed/"; } // Set up rekmaining URIs var baduri = baseuri+"shuffltest?bad#feed"; var layoutname = "test-shuffl-saveworkspace-layout"; var layoutcol = coluri+layoutname+"/"; var layoutref = layoutname+".json"; var layoutloc = "data/test-shuffl-saveworkspace-layout.json"; var layouturi = jQuery.uri(layoutref, layoutcol); var initialuri = jQuery.uri(layoutloc); var card3ref = "test-shuffl-loadworkspace-card_3.json"; var card3uri = jQuery.uri(card3ref, layoutcol); var shuffl_prefixes = { "shuffl:": "http://purl.org/NET/Shuffl/vocab#" , "rdf:": "http://www.w3.org/1999/02/22-rdf-syntax-ns#" , "rdfs:": "http://www.w3.org/2000/01/rdf-schema#" , "owl:": "http://www.w3.org/2002/07/owl#" , "xsd:": "http://www.w3.org/2001/XMLSchema#" , "": "http://purl.org/NET/Shuffl/default#" }; test("TestSaveWorkspace(init)", function () { logtest("TestSaveWorkspace(init)"); shuffl.resetStorageHandlers(); shuffl.addStorageHandler( { uri: "file:///" , name: "LocalFile" , factory: shuffl.LocalFileStorage }); shuffl.addStorageHandler( { uri: "http://localhost:8080/exist/shuffl/" , name: "ExistFile" , factory: shuffl.LocalFileStorage }); shuffl.addStorageHandler( { uri: "http://zoo-samos.zoo.ox.ac.uk/webdav/shuffl/" , name: "ExistFile" , factory: shuffl.LocalFileStorage }); shuffl.addStorageHandler( { uri: "http://localhost:8080/exist/atom/" , name: "ExistAtom" , factory: shuffl.ExistAtomStorage }); shuffl.addStorageHandler( { uri: "http://zoo-samos.zoo.ox.ac.uk/webdav/" , name: "WebDAVsamos" , factory: shuffl.WebDAVStorage }); shuffl.addStorageHandler( { uri: "http://localhost/webdav/" , name: "WebDAVlocalhost" , factory: shuffl.WebDAVStorage }); log.debug("Storage handlers: "+jQuery.toJSON(shuffl.listStorageHandlers())); ok(true, "TestSaveWorkspace running OK"); }); test("shuffl.loadWorkspace (empty)", function () { logtest("shuffl.loadWorkspace empty workspace"); expect(36); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { shuffl.loadWorkspace(layoutloc, callback); }); m.eval(function(val,callback) { // Check empty workspace var u = jQuery.uri().resolve(layoutloc); equals(jQuery('#workspace_status').text(), u.toString(), '#workspace_status'); equals(jQuery('#workspace').data('location'), u.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); equals(jQuery('#workspace').data('wsdata')['shuffl:base-uri'], "#", "shuffl:base-uri"); // More tests as needed var stockcolour=["yellow","blue","green","orange","pink","purple"]; var stocklabel=["Ye","Bl","Gr","Or","Pi","Pu"]; for (var i = 0; i<6; i++) { var s = jQuery('.shuffl-stockpile').eq(i); equals(s.attr('id'), "", "["+i+"] stock id "); // No ID on stockpiles ok(s.hasClass('stock-'+stockcolour[i]), "["+i+"] stock-"+stockcolour[i]); equals(s.text(), stocklabel[i], "["+i+"] stock text "+stocklabel[i]); equals(s.data('CardType'), "shuffl-freetext-"+stockcolour[i], "["+i+"] stock CardType "+"shuffl-freetext-"+stockcolour[i]); ok(typeof s.data('makeCard') == "function", "["+i+"] stock makeCard"); }; // Empty workspace? equals(jQuery("#layout").children().length, 0, "no cards in workspace"); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.LoadWorkspace (empty) initiated"); stop(3000); }); test("shuffl.saveNewWorkspace (empty)", function () { logtest("shuffl.saveNewWorkspace (empty)"); expect(7); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load empty workspace"); shuffl.loadWorkspace(layoutloc, callback); }); m.eval(function(val,callback) { log.debug("Check workspace loaded"); equals(jQuery('#workspace').data('location'), initialuri.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); log.debug("Delete old workspace"); shuffl.deleteWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Save empty workspace: "+layoutcol+", "+layoutname); shuffl.saveNewWorkspace(coluri, layoutname, callback); }); m.eval(function(val,callback) { //log.debug("Check result from save: "+shuffl.objectString(val)); log.debug("Check result from save: "+jQuery.toJSON(val)); equals(val.wscoluri, layoutcol, "val.wscoluri"); equals(val.wsuri, layouturi.toString(), "val.wsuri"); equals(val.wsref, layoutref, "val.wsref"); equals(val.wsid, layoutname, "val.wsid"); log.debug("Reset workspace..."); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.SaveNewWorkspace (empty) initiated"); stop(3000); }); test("shuffl.saveNewWorkspace (empty:check)", function () { logtest("shuffl.saveNewWorkspace (empty:check)"); expect(36); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { log.debug("Workspace is reset"); log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Check reloaded workspace "+layouturi); var u = jQuery.uri(layouturi); equals(jQuery('#workspace_status').text(), u.toString(), '#workspace_status'); equals(jQuery('#workspace').data('location'), u.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); equals(jQuery('#workspace').data('wsdata')['shuffl:base-uri'], "#", "shuffl:base-uri"); // More tests as needed var stockcolour=["yellow","blue","green","orange","pink","purple"]; var stocklabel=["Ye","Bl","Gr","Or","Pi","Pu"]; for (var i = 0; i<6; i++) { var s = jQuery('.shuffl-stockpile').eq(i); equals(s.attr('id'), "", "["+i+"] stock id "); // No ID on stockpiles ok(s.hasClass('stock-'+stockcolour[i]), "["+i+"] stock-"+stockcolour[i]); equals(s.text(), stocklabel[i], "["+i+"] stock text "+stocklabel[i]); equals(s.data('CardType'), "shuffl-freetext-"+stockcolour[i], "["+i+"] stock CardType "+"shuffl-freetext-"+stockcolour[i]); ok(typeof s.data('makeCard') == "function", "["+i+"] stock makeCard"); }; // Empty workspace? equals(jQuery("#layout").children().length, 0, "no cards in workspace"); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.SaveNewWorkspace (empty:check) initiated"); stop(3000); }); test("shuffl.saveCard", function () { logtest("shuffl.saveCard"); expect(30); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { log.debug("Workspace is reset"); log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Get new card data"); var session = shuffl.makeStorageSession("."); shuffl.readCard(session, "", "data/test-shuffl-loadworkspace-card_1.json", callback) }); m.eval(function(val,callback) { log.debug("Check new card data"); equals(val['shuffl:id'], 'id_1', "shuffl:id"); equals(val['shuffl:type'], 'shuffl-freetext-yellow', "shuffl:type"); equals(val['shuffl:version'], '0.1', "shuffl:version"); equals(val['shuffl:base-uri'], '#', "shuffl:base-uri"); for (var k in shuffl_prefixes) { same(val['__prefixes'][k], shuffl_prefixes[k], "__prefixes__["+k+"]"); }; equals(val['rdf:type']['__iri'], "shuffl:Card", "rdf:type"); equals(val['shuffl:data']['shuffl:title'], "Card 1 title", 'shuffl:data-title'); same (val['shuffl:data']['shuffl:tags'], [ 'card_1_tag', 'yellowtag' ], 'shuffl:data-tags'); equals(val['shuffl:data']['shuffl:text'], "Card 1 free-form text here<br/>line 2<br/>line3<br/>yellow", 'shuffl:data-text (1)'); log.debug("Save card data"); var card = shuffl.createCardFromData(val['shuffl:id'], val['shuffl:type'], val); var session = shuffl.makeStorageSession(layoutcol); shuffl.saveCard(session, "", val['shuffl:id']+".json", card, callback); }); m.eval(function(val,callback) { log.debug("Check shuffl.saveCard response "+shuffl.objectString(val)); if (val instanceof shuffl.Error) { log.error("shuffl.saveCard returns error "+val.toString()); callback(val); return; }; equals(val, "id_1.json", "card relative URI"); log.debug("Read back card "+val); var session = shuffl.makeStorageSession(layoutcol); shuffl.readCard(session, "", val, callback); }); m.eval(function(val,callback) { log.debug("Check card values "+shuffl.objectString(val)); equals(val['shuffl:id'], 'id_1', "shuffl:id"); equals(val['shuffl:type'], 'shuffl-freetext-yellow', "shuffl:type"); equals(val['shuffl:version'], '0.1', "shuffl:version"); equals(val['shuffl:base-uri'], '#', "shuffl:base-uri"); for (var k in shuffl_prefixes) { same(val['__prefixes'][k], shuffl_prefixes[k], "__prefixes__["+k+"]"); }; equals(val['rdf:type']['__iri'], "shuffl:Card", "rdf:type"); equals(val['shuffl:data']['shuffl:title'], "Card 1 title", 'shuffl:data-title'); same (val['shuffl:data']['shuffl:tags'], [ 'card_1_tag', 'yellowtag' ], 'shuffl:data-tags'); equals(val['shuffl:data']['shuffl:text'], "Card 1 free-form text here<br/>line 2<br/>line3<br/>yellow", 'shuffl:data-text (2)'); callback({}); }); m.exec({}, start); ok(true, "shuffl.saveCard initiated"); stop(3000); }); // eXist won't delete a media resource notest("shuffl.deleteCard", function () { logtest("shuffl.deleteCard"); expect(3); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Read back card again"); var session = shuffl.makeStorageSession(layoutcol); shuffl.readCard(session, "", "id_1.json", callback); }); m.eval(function(val,callback) { log.debug("Check card is read OK"); equals(val['shuffl:id'], 'id_1', "shuffl:id"); log.debug("Delete card"); shuffl.deleteCard(jQuery.uri("id_1.json", layoutcol), callback); }); m.eval(function(val,callback) { log.debug("deleteCard returns: "+val); same(val, null, "deleteCard return"); callback(val); }); m.exec({}, start); ok(true, "shuffl.deleteCard initiated"); stop(3000); }); // This "test" is run to remove the card saved previously. test("Recreate empty workspace", function() { logtest("Recreate empty workspace"); expect(7); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load empty workspace"); shuffl.loadWorkspace(layoutloc, callback); }); m.eval(function(val,callback) { log.debug("Delete old workspace"); shuffl.deleteWorkspace(layouturi, callback); }); m.eval(function(val,callback) { same(val, null, "shuffl.deleteWorkspace return"); log.debug("Save empty workspace"); shuffl.saveNewWorkspace(coluri, layoutname, callback); }); m.eval(function(val,callback) { ////log.debug("Check result from save: "+shuffl.objectString(val)); log.debug("Check result from save: "+val.wsuri); equals(val.wscoluri, layoutcol, "val.wscoluri"); equals(val.wsuri, layouturi, "val.wsuri"); equals(val.wsref, layoutref, "val.wsref"); equals(val.wsid, layoutname, "val.wsid"); this.wsuri = val.wsuri; log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(this.wsuri, callback); }); m.eval(function(val,callback) { log.debug("Check reloaded workspace "+this.wsuri); var u = jQuery.uri(this.wsuri); equals(jQuery('#workspace_status').text(), u.toString(), '#workspace_status'); callback(true); }); m.exec({}, start); ok(true, "Reload empty workspace initiated"); stop(3000); }); // Add card to workspace, save workspace, read back, check content test("shuffl.saveNewWorkspace (with card)", function () { logtest("shuffl.saveNewWorkspace (with card)"); expect(72); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load empty workspace"); shuffl.loadWorkspace(layoutloc, callback); }); m.eval(function(val,callback) { log.debug("Read card data from local file"); // Note use of base URI so that dataref matches existing value in layout var session = shuffl.makeStorageSession("."); shuffl.readCard(session, "data/", "test-shuffl-loadworkspace-card_3.json", callback); }); m.eval(function(val,callback) { //log.debug("readCard response: "+shuffl.objectString(val)); equals(val['shuffl:id'], "id_3", "new card shuffl:id"); equals(val['shuffl:type'], "shuffl-freetext-green", "new card shuffl:type"); equals(val['shuffl:dataref'], "test-shuffl-loadworkspace-card_3.json", "new card shuffl:dataref"); equals(val['shuffl:datauri'], baseuri+"shuffl/static/test/data/test-shuffl-loadworkspace-card_3.json", "new card shuffl:datauri"); //equals(val['shuffl:datamod'], undefined, "new card shuffl:datamod"); equals(val['shuffl:dataRW'], false, "new card shuffl:dataRW"); log.debug("Add card to workspace"); var layout = { 'id': 'card_3' , 'class': 'stock_3' , 'data': 'test-shuffl-loadworkspace-card_3.json' , 'pos': {left:200, top:90} }; shuffl.placeCardFromData(layout, val); log.debug("Check card added to workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined"); ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 title", "Card 3 title"); equals(c3.data('shuffl:id'), "id_3", "card 3 data id"); equals(c3.data('shuffl:type' ), "shuffl-freetext-green", "card 3 data class/type"); equals(c3.data('shuffl:dataref'), "test-shuffl-loadworkspace-card_3.json", "card 3 shuffl:dataref"); equals(c3.data('shuffl:datauri'), baseuri+"shuffl/static/test/data/test-shuffl-loadworkspace-card_3.json", "card 3 shuffl:datauri"); equals(c3.data('shuffl:datamod'), false, "card 3 shuffl:datamod"); equals(c3.data('shuffl:dataRW'), false, "card 3 shuffl:dataRW"); log.debug("Reset workspace..."); var p3 = c3.position(); range(p3.left, 199, 201, "position-left"); range(p3.top, 89, 91, "position-top"); equals(c3.css("zIndex"), "11", "card zIndex"); log.debug("Delete old workspace"); shuffl.deleteWorkspace(layouturi, callback); }); m.eval(function(val,callback) { same(val, null, "shuffl.deleteWorkspace return"); log.debug("Save new workspace with card"); shuffl.saveNewWorkspace(coluri, layoutname, callback); }); m.eval(function(val,callback) { //log.debug("Check result from save: "+shuffl.objectString(val)); log.debug("Check result from save: "+val.uri); equals(val.wscoluri, layoutcol, "val.wscoluri"); equals(val.wsuri, layouturi, "val.wsuri"); equals(val.wsref, layoutref, "val.wsref"); equals(val.wsid, layoutname, "val.wsid"); this.wsuri = val.wsuri; log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { ok(true, "Workspace is reset: "+this.wsuri); log.debug("Workspace is reset"); log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(this.wsuri, callback); }); m.eval(function(val,callback) { ok(true, "Workspace is reloaded: "+this.wsuri); log.debug("Check reloaded workspace "+this.wsuri); var u = jQuery.uri(this.wsuri); equals(jQuery('#workspace_status').text(), u.toString(), '#workspace_status'); equals(jQuery('#workspace').data('location'), u.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); equals(jQuery('#workspace').data('wsdata')['shuffl:base-uri'], "#", "shuffl:base-uri"); // More tests as needed var stockcolour=["yellow","blue","green","orange","pink","purple"]; var stocklabel=["Ye","Bl","Gr","Or","Pi","Pu"]; for (var i = 0; i<6; i++) { var s = jQuery('.shuffl-stockpile').eq(i); equals(s.attr('id'), "", "["+i+"] stock id "); // No ID on stockpiles ok(s.hasClass('stock-'+stockcolour[i]), "["+i+"] stock-"+stockcolour[i]); equals(s.text(), stocklabel[i], "["+i+"] stock text "+stocklabel[i]); equals(s.data('CardType'), "shuffl-freetext-"+stockcolour[i], "["+i+"] stock CardType "+"shuffl-freetext-"+stockcolour[i]); ok(typeof s.data('makeCard') == "function", "["+i+"] stock makeCard"); }; // Check card in workspace equals(jQuery("#layout").children().length, 1, "one card in workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined") ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 title", "Card 3 title"); equals(c3.data('shuffl:id'), "id_3", "card 3 data id"); equals(c3.data('shuffl:type' ), "shuffl-freetext-green", "card 3 data class/type"); equals(c3.data('shuffl:dataref'), "test-shuffl-loadworkspace-card_3.json", "card 3 shuffl:dataref"); equals(c3.data('shuffl:datauri'), layoutcol+"test-shuffl-loadworkspace-card_3.json", "card 3 shuffl:datauri"); equals(c3.data('shuffl:datamod'), false, "card 3 shuffl:datamod"); equals(c3.data('shuffl:dataRW'), false, "card 3 shuffl:dataRW"); var p3 = c3.position(); range(p3.left, 199, 202, "position-left"); range(p3.top, 89, 92, "position-top"); equals(c3.css("zIndex"), "11", "card zIndex"); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.SaveNewWorkspace (with card) initiated"); stop(3000); }); // Update card in atom feed, re-read workspace, check content test("shuffl.updateCard", function () { logtest("shuffl.updateCard"); expect(51); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load workspace"); // Read workspace from AtomPub service shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { // Check for card equals(jQuery("#layout").children().length, 1, "one card in workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined") ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 title", "Card 3 title"); // Update card in workspace c3.model("shuffl:title", "Card 3 updated"); equals(c3.model('shuffl:dataref'), "test-shuffl-loadworkspace-card_3.json", "card 3 shuffl:dataref"); equals(c3.find("ctitle").text(), "Card 3 updated", "ctitle(c3) updated in DOM"); var session = shuffl.makeStorageSession(layoutcol); shuffl.updateCard(session, "", c3, callback); }); m.eval(function(val, callback) { log.debug("Card saved: "+shuffl.objectString(val)); equals(val.carduri, card3uri, "updateCard URI returned"); equals(val.cardref, card3ref, "updateCard ref returned"); equals(val.cardid, "id_3", "updateCard id returned"); log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { log.debug("Workspace is reset"); log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Check reloaded workspace "); equals(jQuery('#workspace_status').text(), layouturi.toString(), '#workspace_status'); equals(jQuery('#workspace').data('location'), layouturi.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); equals(jQuery('#workspace').data('wsdata')['shuffl:base-uri'], "#", "shuffl:base-uri"); // More tests as needed var stockcolour=["yellow","blue","green","orange","pink","purple"]; var stocklabel=["Ye","Bl","Gr","Or","Pi","Pu"]; for (var i = 0; i<6; i++) { var s = jQuery('.shuffl-stockpile').eq(i); equals(s.attr('id'), "", "["+i+"] stock id "); // No ID on stockpiles ok(s.hasClass('stock-'+stockcolour[i]), "["+i+"] stock-"+stockcolour[i]); equals(s.text(), stocklabel[i], "["+i+"] stock text "+stocklabel[i]); equals(s.data('CardType'), "shuffl-freetext-"+stockcolour[i], "["+i+"] stock CardType "+"shuffl-freetext-"+stockcolour[i]); ok(typeof s.data('makeCard') == "function", "["+i+"] stock makeCard"); }; // Check card in workspace equals(jQuery("#layout").children().length, 1, "one card in workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined") ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 updated", "Card 3 updated"); var p3 = c3.position(); range(p3.left, 199, 202, "position-left"); range(p3.top, 89, 92, "position-top"); equals(c3.css("zIndex"), "11", "card zIndex"); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.updateCard"); stop(3000); }); // Update and move card in workspace, save workspace, read back, check content test("shuffl.saveWorkspace (updated moved card)", function () { logtest("shuffl.saveWorkspace (updated moved card)"); expect(51); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load workspace"); // Read workspace from AtomPub service shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { // Check for card equals(jQuery("#layout").children().length, 1, "one card in workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined") ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 updated", "Card 3 title"); // Update and move card in workspace c3.model("shuffl:title", "Card 3 updated and moved"); equals(c3.find("ctitle").text(), "Card 3 updated and moved", "ctitle(c3) updated in DOM"); c3.css({left:20, top:10}); c3.data('shuffl:datamod', true); // Note card has been updated // Save workspace log.debug("Save workspace with updated and moved card"); shuffl.updateWorkspace(callback); }); m.eval(function(val, callback) { log.debug("Check result from update: "+shuffl.objectString(val)); this.wsuri = jQuery.uri(val.uri, val.itemuri).toString(); equals(val.wscoluri, layoutcol, "val.wscoluri"); equals(val.wsuri, layouturi, "val.wsuri"); equals(val.wsref, layoutref, "val.wsref"); equals(val.wsid, layoutname, "val.wsid"); log.debug("Reset workspace..."); shuffl.resetWorkspace(callback); }); m.eval(function(val,callback) { log.debug("Workspace is reset"); log.debug("Reload empty workspace from AtomPub..."); shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Check reloaded workspace "); equals(jQuery('#workspace_status').text(), layouturi.toString(), '#workspace_status'); equals(jQuery('#workspace').data('location'), layouturi.toString(), "location"); equals(jQuery('#workspace').data('wsname'), layoutref, "wsname"); equals(jQuery('#workspace').data('wsdata')['shuffl:base-uri'], "#", "shuffl:base-uri"); // More tests as needed var stockcolour=["yellow","blue","green","orange","pink","purple"]; var stocklabel=["Ye","Bl","Gr","Or","Pi","Pu"]; for (var i = 0; i<6; i++) { var s = jQuery('.shuffl-stockpile').eq(i); equals(s.attr('id'), "", "["+i+"] stock id "); // No ID on stockpiles ok(s.hasClass('stock-'+stockcolour[i]), "["+i+"] stock-"+stockcolour[i]); equals(s.text(), stocklabel[i], "["+i+"] stock text "+stocklabel[i]); equals(s.data('CardType'), "shuffl-freetext-"+stockcolour[i], "["+i+"] stock CardType "+"shuffl-freetext-"+stockcolour[i]); ok(typeof s.data('makeCard') == "function", "["+i+"] stock makeCard"); }; // Check card in workspace equals(jQuery("#layout").children().length, 1, "one card in workspace"); var c3 = jQuery("#id_3"); ok(c3 != undefined, "card id_3 defined") ok(c3.hasClass('shuffl-card'), "card 3 shuffl card class"); equals(c3.find("ctitle").text(), "Card 3 updated and moved", "Card 3 title"); var p3 = c3.position(); range(p3.left, 19, 22, "position-left"); range(p3.top, 9, 12, "position-top"); equals(c3.css("zIndex"), "11", "card zIndex"); // Done callback(true); }); m.exec({}, start); ok(true, "shuffl.SaveNewWorkspace (updated moved card) initiated"); stop(3000); }); // TODO: create workspace with mix of absolute and relative card references // save workspace as new // reload workspace // check card URIs test("shuffl.saveCard (non-existent feed)", function () { logtest("shuffl.saveCard (non-existent feed)"); expect(3); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load empty workspace"); shuffl.loadWorkspace(layouturi, callback); }); m.eval(function(val,callback) { log.debug("Get new card data"); var session = shuffl.makeStorageSession("."); shuffl.readCard(session, "", "data/test-shuffl-loadworkspace-card_1.json", callback) }); m.eval(function(val,callback) { log.debug("Check new card data"); equals(val['shuffl:id'], 'id_1', "shuffl:id"); log.debug("Attempt to aave card data"); var card = shuffl.createCardFromData(val['shuffl:id'], val['shuffl:type'], val); var session = shuffl.makeStorageSession(layoutcol); shuffl.saveCard(session, nocoluri, val['shuffl:id']+".json", card, callback); }); m.eval(function(val,callback) { log.debug("Check shuffl.saveCard response"); ok(val instanceof shuffl.Error, "Error value returned"); callback(true); }); m.exec({}, start); ok(true, "shuffl.saveCard (non-existent feed) initiated"); stop(3000); }); test("shuffl.saveNewWorkspace (forced error)", function () { logtest("shuffl.saveNewWorkspace (forced error)"); expect(5); var m = new shuffl.AsyncComputation(); m.eval(function(val,callback) { log.debug("Load empty workspace"); shuffl.loadWorkspace(layoutloc, callback); }); m.eval(function(val,callback) { log.debug("Check workspace loaded"); equals(jQuery('#workspace').data('location'), initialuri.toString(), "location"); log.debug("Try to save workspace"); shuffl.saveNewWorkspace(baduri, layoutname, callback); }); m.eval(function(val,callback) { log.debug("Check shuffl.saveNewWorkspace response "); ok(val instanceof shuffl.Error, "Error value returned"); equals(val.toString(), "shuffl error: shuffl.saveNewWorkspace: "+ "invalid collection URI: "+baduri, "Error message returned"); equals(val.response, undefined, "AtomPub HTTP response details"); callback(true); }); m.exec({}, start); ok(true, "shuffl.SaveNewWorkspace (forced error) initiated"); stop(3000); }); }; // End
function classFactory() { var _class, _foo, _bar; return _foo = /*#__PURE__*/new WeakMap(), (_class = class Foo { constructor() { babelHelpers.classPrivateFieldInitSpec(this, _foo, { writable: true, value: "foo" }); } instance() { return babelHelpers.classPrivateFieldGet(this, _foo); } static() { return babelHelpers.classStaticPrivateFieldSpecGet(Foo, _class, _bar); } static instance(inst) { return babelHelpers.classPrivateFieldGet(inst, _foo); } static static() { return babelHelpers.classStaticPrivateFieldSpecGet(Foo, _class, _bar); } }, _bar = { writable: true, value: "bar" }, _class); }
/** * The application header displayed at the top of the viewport * @extends Ext.Component */ Ext.define('CF.view.Header', { extend: 'Ext.Component', dock: 'top', baseCls: 'cf-header', initComponent: function() { Ext.applyIf(this, { html: 'MVC simple application example called CF ' + '(Cartography Framework)' }); this.callParent(arguments); } });
'use strict' var request = require('supertest') , assert = require('assert') , models = require('../models'); describe('makeUser', function() { // 정상적인 유저 생성 확인 it('valid make user', function (done) { var gameId = 1000; var facebookId = 0; var inventorySize = 100; var maxHeart = 80; var status = 1; models.makeUser(gameId, facebookId, inventorySize, maxHeart, status) .then(function (userId) { assert(userId > 0); }).then(done, done); }) // 비정상적인 유저 생성 확인 it('invalid make user', function (done) { models.makeUser() .catch(function (err) { assert(err); }).then(done, done); }) // 유저정보 로딩 확인 it('load user', function (done) { var gameId = 1000; var facebookId = 0; var inventorySize = 100; var maxHeart = 100; var status = 1; models.makeUser(gameId, facebookId, inventorySize, maxHeart, status) .then(function (userId) { assert(userId > 0); models.loadUser(userId).then(function (results) { assert(results); }).then(done, done); }).then(null, done); }) })
var struct_tempest_1_1_abstract_list_delegate_1_1_list_item = [ [ "ListItem", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a9c11b618acf99ff46e8d3b369e22bbe8", null ], [ "emitClick", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a46adebd1adca8d23768023144cbbe32b", null ], [ "clicked", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a7a67d04c648280bbdcb2fb8ea370a05b", null ], [ "id", "struct_tempest_1_1_abstract_list_delegate_1_1_list_item.html#a8d31d29e4a483ee3dfec2aa8324a8452", null ] ];
(function () { angular .module('kalendr.accounts', [ 'kalendr.accounts.controllers', 'kalendr.accounts.services' ]); angular .module('kalendr.accounts.controllers', ['ngDialog']); angular .module('kalendr.accounts.services', []); })();
/** * @class Cogwheels.SassError * @extends Error */ 'use strict'; var util = require('util') , indent = require('indent-string') ; function SassError(properties) { Error.call(this); if (typeof properties === 'object') { for (var key in properties) { this[key] = properties[key]; } } else if (typeof properties === 'string') { this.message = properties; } if (!this.message) { this.message = 'Sass Error'; } } module.exports = SassError; util.inherits(SassError, Error); SassError.prototype.status = 1; SassError.prototype.line = 1; SassError.prototype.column = 1; SassError.prototype.code = undefined; SassError.prototype.file = undefined; var FULL_MESSAGE_FORMAT = '[SassError] in file `%s` on line %d column %d code %d:\n%s\n\n'; Object.defineProperty(SassError.prototype, 'full_message', { get: function() { return util.format(FULL_MESSAGE_FORMAT, this.file || '-', this.line, this.column, this.code || 3, indent(this.message, ' ')); } });
{ "AD" : "d.C.", "Africa/Abidjan_Z_abbreviated" : "Hora de Costa de Marfil", "Africa/Abidjan_Z_short" : "GMT", "Africa/Accra_Z_abbreviated" : "Hora de Gana", "Africa/Accra_Z_short" : "GMT", "Africa/Addis_Ababa_Z_abbreviated" : "Hora de Etiopía", "Africa/Addis_Ababa_Z_short" : "EAT", "Africa/Algiers_Z_abbreviated" : "Hora de Arxelia", "Africa/Algiers_Z_short" : "WET", "Africa/Asmara_Z_abbreviated" : "Hora de Eritrea", "Africa/Asmara_Z_short" : "EAT", "Africa/Bamako_Z_abbreviated" : "Hora de Mali", "Africa/Bamako_Z_short" : "GMT", "Africa/Bangui_Z_abbreviated" : "Hora de República Africana Central", "Africa/Bangui_Z_short" : "WAT", "Africa/Banjul_Z_abbreviated" : "Hora de Gambia", "Africa/Banjul_Z_short" : "GMT", "Africa/Bissau_Z_abbreviated" : "Hora de Guinea-Bissau", "Africa/Bissau_Z_short" : "GMT-01:00", "Africa/Blantyre_Z_abbreviated" : "Hora de Malaui", "Africa/Blantyre_Z_short" : "CAT", "Africa/Brazzaville_Z_abbreviated" : "Hora de Congo", "Africa/Brazzaville_Z_short" : "WAT", "Africa/Bujumbura_Z_abbreviated" : "Hora de Burundi", "Africa/Bujumbura_Z_short" : "CAT", "Africa/Cairo_Z_abbreviated" : "Hora de Exipto", "Africa/Cairo_Z_short" : "EET", "Africa/Casablanca_Z_abbreviated" : "Hora de Marrocos", "Africa/Casablanca_Z_short" : "WET", "Africa/Conakry_Z_abbreviated" : "Hora de Guinea", "Africa/Conakry_Z_short" : "GMT", "Africa/Dakar_Z_abbreviated" : "Hora de Senegal", "Africa/Dakar_Z_short" : "GMT", "Africa/Dar_es_Salaam_Z_abbreviated" : "Hora de Tanzania", "Africa/Dar_es_Salaam_Z_short" : "EAT", "Africa/Djibouti_Z_abbreviated" : "Hora de Xibuti", "Africa/Djibouti_Z_short" : "EAT", "Africa/Douala_Z_abbreviated" : "Hora de Camerún", "Africa/Douala_Z_short" : "WAT", "Africa/El_Aaiun_Z_abbreviated" : "Hora de Sahara Occidental", "Africa/El_Aaiun_Z_short" : "GMT-01:00", "Africa/Freetown_Z_abbreviated" : "Hora de Serra Leoa", "Africa/Freetown_Z_short" : "GMT", "Africa/Gaborone_Z_abbreviated" : "Hora de Botsuana", "Africa/Gaborone_Z_short" : "CAT", "Africa/Harare_Z_abbreviated" : "Hora de Cimbabue", "Africa/Harare_Z_short" : "CAT", "Africa/Johannesburg_Z_abbreviated" : "Hora de Sudáfrica", "Africa/Johannesburg_Z_short" : "SAST", "Africa/Juba_Z_abbreviated" : "Hora de Sudán", "Africa/Juba_Z_short" : "CAT", "Africa/Kampala_Z_abbreviated" : "Hora de Uganda", "Africa/Kampala_Z_short" : "EAT", "Africa/Khartoum_Z_abbreviated" : "Hora de Sudán", "Africa/Khartoum_Z_short" : "CAT", "Africa/Kigali_Z_abbreviated" : "Hora de Ruanda", "Africa/Kigali_Z_short" : "CAT", "Africa/Kinshasa_Z_abbreviated" : "República Democrática do Congo (Kinshasa)", "Africa/Kinshasa_Z_short" : "WAT", "Africa/Lagos_Z_abbreviated" : "Hora de Nixeria", "Africa/Lagos_Z_short" : "WAT", "Africa/Libreville_Z_abbreviated" : "Hora de Gabón", "Africa/Libreville_Z_short" : "WAT", "Africa/Lome_Z_abbreviated" : "Hora de Togo", "Africa/Lome_Z_short" : "GMT", "Africa/Luanda_Z_abbreviated" : "Hora de Angola", "Africa/Luanda_Z_short" : "WAT", "Africa/Lusaka_Z_abbreviated" : "Hora de Zambia", "Africa/Lusaka_Z_short" : "CAT", "Africa/Malabo_Z_abbreviated" : "Hora de Guinea Ecuatorial", "Africa/Malabo_Z_short" : "WAT", "Africa/Maputo_Z_abbreviated" : "Hora de Mozambique", "Africa/Maputo_Z_short" : "CAT", "Africa/Maseru_Z_abbreviated" : "Hora de Lesotho", "Africa/Maseru_Z_short" : "SAST", "Africa/Mbabane_Z_abbreviated" : "Hora de Suacilandia", "Africa/Mbabane_Z_short" : "SAST", "Africa/Mogadishu_Z_abbreviated" : "Hora de Somalia", "Africa/Mogadishu_Z_short" : "EAT", "Africa/Monrovia_Z_abbreviated" : "Hora de Liberia", "Africa/Monrovia_Z_short" : "GMT-00:44:30", "Africa/Nairobi_Z_abbreviated" : "Hora de Quenia", "Africa/Nairobi_Z_short" : "EAT", "Africa/Ndjamena_Z_abbreviated" : "Hora de TD", "Africa/Ndjamena_Z_short" : "WAT", "Africa/Niamey_Z_abbreviated" : "Hora de Níxer", "Africa/Niamey_Z_short" : "WAT", "Africa/Nouakchott_Z_abbreviated" : "Hora de Mauritania", "Africa/Nouakchott_Z_short" : "GMT", "Africa/Ouagadougou_Z_abbreviated" : "Hora de Burkina Faso", "Africa/Ouagadougou_Z_short" : "GMT", "Africa/Porto-Novo_Z_abbreviated" : "Hora de Benin", "Africa/Porto-Novo_Z_short" : "WAT", "Africa/Sao_Tome_Z_abbreviated" : "Hora de Santo Tomé e Príncipe", "Africa/Sao_Tome_Z_short" : "GMT", "Africa/Tripoli_Z_abbreviated" : "Hora de Libia", "Africa/Tripoli_Z_short" : "EET", "Africa/Tunis_Z_abbreviated" : "Hora de Tunisia", "Africa/Tunis_Z_short" : "CET", "Africa/Windhoek_Z_abbreviated" : "Hora de Namibia", "Africa/Windhoek_Z_short" : "SAST", "America/Anguilla_Z_abbreviated" : "Hora de Anguila", "America/Anguilla_Z_short" : "AST", "America/Antigua_Z_abbreviated" : "Hora de Antiga e Barbuda", "America/Antigua_Z_short" : "AST", "America/Araguaina_Z_abbreviated" : "Brasil (Araguaina)", "America/Araguaina_Z_short" : "BRT", "America/Argentina/Buenos_Aires_Z_abbreviated" : "Arxentina (Bos Aires)", "America/Argentina/Buenos_Aires_Z_short" : "ART", "America/Argentina/Catamarca_Z_abbreviated" : "Arxentina (Catamarca)", "America/Argentina/Catamarca_Z_short" : "ART", "America/Argentina/Cordoba_Z_abbreviated" : "Arxentina (Córdoba)", "America/Argentina/Cordoba_Z_short" : "ART", "America/Argentina/Jujuy_Z_abbreviated" : "Arxentina (Jujuy)", "America/Argentina/Jujuy_Z_short" : "ART", "America/Argentina/La_Rioja_Z_abbreviated" : "Arxentina (La Rioja)", "America/Argentina/La_Rioja_Z_short" : "ART", "America/Argentina/Mendoza_Z_abbreviated" : "Arxentina (Mendoza)", "America/Argentina/Mendoza_Z_short" : "ART", "America/Argentina/Rio_Gallegos_Z_abbreviated" : "Arxentina (Río Gallegos)", "America/Argentina/Rio_Gallegos_Z_short" : "ART", "America/Argentina/Salta_Z_abbreviated" : "Arxentina (Salta)", "America/Argentina/Salta_Z_short" : "ART", "America/Argentina/San_Juan_Z_abbreviated" : "Arxentina (San Juan)", "America/Argentina/San_Juan_Z_short" : "ART", "America/Argentina/San_Luis_Z_abbreviated" : "Arxentina (San Luis)", "America/Argentina/San_Luis_Z_short" : "ART", "America/Argentina/Tucuman_Z_abbreviated" : "Arxentina (Tucumán)", "America/Argentina/Tucuman_Z_short" : "ART", "America/Argentina/Ushuaia_Z_abbreviated" : "Arxentina (Ushuaia)", "America/Argentina/Ushuaia_Z_short" : "ART", "America/Aruba_Z_abbreviated" : "Hora de Aruba", "America/Aruba_Z_short" : "AST", "America/Asuncion_Z_abbreviated" : "Hora de Paraguai", "America/Asuncion_Z_short" : "PYT", "America/Bahia_Banderas_Z_abbreviated" : "México (Bahia Banderas)", "America/Bahia_Banderas_Z_short" : "PST", "America/Bahia_Z_abbreviated" : "Brasil (Bahia)", "America/Bahia_Z_short" : "BRT", "America/Barbados_Z_abbreviated" : "Hora de Barbados", "America/Barbados_Z_short" : "AST", "America/Belem_Z_abbreviated" : "Brasil (Belém)", "America/Belem_Z_short" : "BRT", "America/Belize_Z_abbreviated" : "Hora de Belice", "America/Belize_Z_short" : "CST", "America/Blanc-Sablon_Z_abbreviated" : "Canadá (Blanc-Sablon)", "America/Blanc-Sablon_Z_short" : "AST", "America/Boa_Vista_Z_abbreviated" : "Brasil (Boa Vista)", "America/Boa_Vista_Z_short" : "AMT", "America/Bogota_Z_abbreviated" : "Hora de Colombia", "America/Bogota_Z_short" : "COT", "America/Boise_Z_abbreviated" : "Estados Unidos de América (Boise)", "America/Boise_Z_short" : "MST", "America/Cambridge_Bay_Z_abbreviated" : "Canadá (Cambridge Bay)", "America/Cambridge_Bay_Z_short" : "MST", "America/Campo_Grande_Z_abbreviated" : "Brasil (Campo Grande)", "America/Campo_Grande_Z_short" : "AMT", "America/Cancun_Z_abbreviated" : "México (Cancún)", "America/Cancun_Z_short" : "CST", "America/Caracas_Z_abbreviated" : "Hora de Venezuela", "America/Caracas_Z_short" : "VET", "America/Cayenne_Z_abbreviated" : "Hora de Güiana Francesa", "America/Cayenne_Z_short" : "GFT", "America/Cayman_Z_abbreviated" : "Hora de Illas Caimán", "America/Cayman_Z_short" : "EST", "America/Chicago_Z_abbreviated" : "Estados Unidos de América (Chicago)", "America/Chicago_Z_short" : "CST", "America/Chihuahua_Z_abbreviated" : "México (Chihuahua)", "America/Chihuahua_Z_short" : "CST", "America/Costa_Rica_Z_abbreviated" : "Hora de Costa Rica", "America/Costa_Rica_Z_short" : "CST", "America/Cuiaba_Z_abbreviated" : "Brasil (Cuiaba)", "America/Cuiaba_Z_short" : "AMT", "America/Curacao_Z_abbreviated" : "Hora de Antillas Holandesas", "America/Curacao_Z_short" : "AST", "America/Danmarkshavn_Z_abbreviated" : "Grenlandia (Danmarkshavn)", "America/Danmarkshavn_Z_short" : "WGT", "America/Denver_Z_abbreviated" : "Estados Unidos de América (Denver)", "America/Denver_Z_short" : "MST", "America/Detroit_Z_abbreviated" : "Estados Unidos de América (Detroit)", "America/Detroit_Z_short" : "EST", "America/Dominica_Z_abbreviated" : "Hora de Dominica", "America/Dominica_Z_short" : "AST", "America/Edmonton_Z_abbreviated" : "Canadá (Edmonton)", "America/Edmonton_Z_short" : "MST", "America/Eirunepe_Z_abbreviated" : "Brasil (Eirunepe)", "America/Eirunepe_Z_short" : "ACT (Acre)", "America/El_Salvador_Z_abbreviated" : "Hora de El Salvador", "America/El_Salvador_Z_short" : "CST", "America/Fortaleza_Z_abbreviated" : "Brasil (Fortaleza)", "America/Fortaleza_Z_short" : "BRT", "America/Goose_Bay_Z_abbreviated" : "Canadá (Goose Bay)", "America/Goose_Bay_Z_short" : "AST", "America/Grand_Turk_Z_abbreviated" : "Hora de Illas Turks e Caicos", "America/Grand_Turk_Z_short" : "EST", "America/Grenada_Z_abbreviated" : "Hora de Granada", "America/Grenada_Z_short" : "AST", "America/Guadeloupe_Z_abbreviated" : "Hora de Guadalupe", "America/Guadeloupe_Z_short" : "AST", "America/Guatemala_Z_abbreviated" : "Hora de Guatemala", "America/Guatemala_Z_short" : "CST", "America/Guayaquil_Z_abbreviated" : "Ecuador (Guayaquil)", "America/Guayaquil_Z_short" : "ECT", "America/Guyana_Z_abbreviated" : "Hora de Güiana", "America/Guyana_Z_short" : "GYT", "America/Halifax_Z_abbreviated" : "Canadá (Halifax)", "America/Halifax_Z_short" : "AST", "America/Havana_Z_abbreviated" : "Hora de Cuba", "America/Havana_Z_short" : "CST (CU)", "America/Hermosillo_Z_abbreviated" : "México (Hermosillo)", "America/Hermosillo_Z_short" : "PST", "America/Indiana/Indianapolis_Z_abbreviated" : "Estados Unidos de América (Indianapolis)", "America/Indiana/Indianapolis_Z_short" : "EST", "America/Indiana/Knox_Z_abbreviated" : "Estados Unidos de América (Knox)", "America/Indiana/Knox_Z_short" : "CST", "America/Indiana/Marengo_Z_abbreviated" : "Estados Unidos de América (Marengo)", "America/Indiana/Marengo_Z_short" : "EST", "America/Indiana/Petersburg_Z_abbreviated" : "Estados Unidos de América (Petersburg)", "America/Indiana/Petersburg_Z_short" : "CST", "America/Indiana/Tell_City_Z_abbreviated" : "Estados Unidos de América (Tell City)", "America/Indiana/Tell_City_Z_short" : "EST", "America/Indiana/Vevay_Z_abbreviated" : "Estados Unidos de América (Vevay)", "America/Indiana/Vevay_Z_short" : "EST", "America/Indiana/Vincennes_Z_abbreviated" : "Estados Unidos de América (Vincennes)", "America/Indiana/Vincennes_Z_short" : "EST", "America/Indiana/Winamac_Z_abbreviated" : "Estados Unidos de América (Winamac)", "America/Indiana/Winamac_Z_short" : "EST", "America/Iqaluit_Z_abbreviated" : "Canadá (Iqaluit)", "America/Iqaluit_Z_short" : "EST", "America/Jamaica_Z_abbreviated" : "Hora de Xamaica", "America/Jamaica_Z_short" : "EST", "America/Juneau_Z_abbreviated" : "Estados Unidos de América (Juneau)", "America/Juneau_Z_short" : "PST", "America/Kentucky/Louisville_Z_abbreviated" : "Estados Unidos de América (Louisville)", "America/Kentucky/Louisville_Z_short" : "EST", "America/Kentucky/Monticello_Z_abbreviated" : "Estados Unidos de América (Monticello)", "America/Kentucky/Monticello_Z_short" : "CST", "America/La_Paz_Z_abbreviated" : "Hora de Bolivia", "America/La_Paz_Z_short" : "BOT", "America/Lima_Z_abbreviated" : "Hora de Perú", "America/Lima_Z_short" : "PET", "America/Los_Angeles_Z_abbreviated" : "Estados Unidos de América (Los Angeles)", "America/Los_Angeles_Z_short" : "PST", "America/Maceio_Z_abbreviated" : "Brasil (Maceió)", "America/Maceio_Z_short" : "BRT", "America/Managua_Z_abbreviated" : "Hora de Nicaragua", "America/Managua_Z_short" : "CST", "America/Manaus_Z_abbreviated" : "Brasil (Manaus)", "America/Manaus_Z_short" : "AMT", "America/Martinique_Z_abbreviated" : "Hora de Martinica", "America/Martinique_Z_short" : "AST", "America/Matamoros_Z_abbreviated" : "México (Matamoros)", "America/Matamoros_Z_short" : "CST", "America/Mazatlan_Z_abbreviated" : "México (Mazatlán)", "America/Mazatlan_Z_short" : "PST", "America/Menominee_Z_abbreviated" : "Estados Unidos de América (Menominee)", "America/Menominee_Z_short" : "EST", "America/Merida_Z_abbreviated" : "México (Mérida)", "America/Merida_Z_short" : "CST", "America/Mexico_City_Z_abbreviated" : "México (Cidade de México)", "America/Mexico_City_Z_short" : "CST", "America/Miquelon_Z_abbreviated" : "Hora de San Pedro e Miguelón", "America/Miquelon_Z_short" : "AST", "America/Moncton_Z_abbreviated" : "Canadá (Moncton)", "America/Moncton_Z_short" : "AST", "America/Monterrey_Z_abbreviated" : "México (Monterrei)", "America/Monterrey_Z_short" : "CST", "America/Montevideo_Z_abbreviated" : "Hora de Uruguai", "America/Montevideo_Z_short" : "UYT", "America/Montserrat_Z_abbreviated" : "Hora de Montserrat", "America/Montserrat_Z_short" : "AST", "America/Nassau_Z_abbreviated" : "Hora de Bahamas", "America/Nassau_Z_short" : "EST", "America/New_York_Z_abbreviated" : "Estados Unidos de América (New York)", "America/New_York_Z_short" : "EST", "America/Noronha_Z_abbreviated" : "Brasil (Noronha)", "America/Noronha_Z_short" : "FNT", "America/North_Dakota/Beulah_Z_abbreviated" : "Estados Unidos de América (Beulah)", "America/North_Dakota/Beulah_Z_short" : "MST", "America/North_Dakota/Center_Z_abbreviated" : "Estados Unidos de América (Central)", "America/North_Dakota/Center_Z_short" : "MST", "America/North_Dakota/New_Salem_Z_abbreviated" : "Estados Unidos de América (New Salem)", "America/North_Dakota/New_Salem_Z_short" : "MST", "America/Ojinaga_Z_abbreviated" : "México (Ojinaga)", "America/Ojinaga_Z_short" : "CST", "America/Panama_Z_abbreviated" : "Hora de Panamá", "America/Panama_Z_short" : "EST", "America/Pangnirtung_Z_abbreviated" : "Canadá (Pangnirtung)", "America/Pangnirtung_Z_short" : "AST", "America/Paramaribo_Z_abbreviated" : "Hora de Surinam", "America/Paramaribo_Z_short" : "NEGT", "America/Phoenix_Z_abbreviated" : "Estados Unidos de América (Phoenix)", "America/Phoenix_Z_short" : "MST", "America/Port-au-Prince_Z_abbreviated" : "Hora de Haití", "America/Port-au-Prince_Z_short" : "EST", "America/Port_of_Spain_Z_abbreviated" : "Hora de Trindade e Tobago", "America/Port_of_Spain_Z_short" : "AST", "America/Porto_Velho_Z_abbreviated" : "Brasil (Porto Velho)", "America/Porto_Velho_Z_short" : "AMT", "America/Puerto_Rico_Z_abbreviated" : "Hora de Porto Rico", "America/Puerto_Rico_Z_short" : "AST", "America/Rankin_Inlet_Z_abbreviated" : "Canadá (Rankin Inlet)", "America/Rankin_Inlet_Z_short" : "CST", "America/Recife_Z_abbreviated" : "Brasil (Recife)", "America/Recife_Z_short" : "BRT", "America/Regina_Z_abbreviated" : "Canadá (Regina)", "America/Regina_Z_short" : "CST", "America/Resolute_Z_abbreviated" : "Canadá (Resolute)", "America/Resolute_Z_short" : "CST", "America/Rio_Branco_Z_abbreviated" : "Brasil (Rio Branco)", "America/Rio_Branco_Z_short" : "ACT (Acre)", "America/Santa_Isabel_Z_abbreviated" : "México (Santa Isabel)", "America/Santa_Isabel_Z_short" : "PST", "America/Santarem_Z_abbreviated" : "Brasil (Santarem)", "America/Santarem_Z_short" : "AMT", "America/Santiago_Z_abbreviated" : "Chile (Santiago)", "America/Santiago_Z_short" : "CLST", "America/Santo_Domingo_Z_abbreviated" : "Hora de República Dominicana", "America/Santo_Domingo_Z_short" : "GMT-04:30", "America/Sao_Paulo_Z_abbreviated" : "Brasil (São Paulo)", "America/Sao_Paulo_Z_short" : "BRT", "America/St_Johns_Z_abbreviated" : "Canadá (St Johns)", "America/St_Johns_Z_short" : "NST", "America/St_Kitts_Z_abbreviated" : "Hora de San Cristovo e Nevis", "America/St_Kitts_Z_short" : "AST", "America/St_Lucia_Z_abbreviated" : "Hora de Santa Lucía", "America/St_Lucia_Z_short" : "AST", "America/St_Thomas_Z_abbreviated" : "Hora de Illas Virxes Estadounidenses", "America/St_Thomas_Z_short" : "AST", "America/St_Vincent_Z_abbreviated" : "Hora de San Vicente e Granadinas", "America/St_Vincent_Z_short" : "AST", "America/Tegucigalpa_Z_abbreviated" : "Hora de Honduras", "America/Tegucigalpa_Z_short" : "CST", "America/Tijuana_Z_abbreviated" : "México (Tijuana)", "America/Tijuana_Z_short" : "PST", "America/Toronto_Z_abbreviated" : "Canadá (Toronto)", "America/Toronto_Z_short" : "EST", "America/Tortola_Z_abbreviated" : "Hora de Illas Virxes Británicas", "America/Tortola_Z_short" : "AST", "America/Vancouver_Z_abbreviated" : "Canadá (Vancouver)", "America/Vancouver_Z_short" : "PST", "America/Winnipeg_Z_abbreviated" : "Canadá (Winnipeg)", "America/Winnipeg_Z_short" : "CST", "Antarctica/Casey_Z_abbreviated" : "Antártida (Casey)", "Antarctica/Casey_Z_short" : "AWST", "Antarctica/Davis_Z_abbreviated" : "Antártida (Davis)", "Antarctica/Davis_Z_short" : "DAVT", "Antarctica/DumontDUrville_Z_abbreviated" : "Antártida (Dumont-d'Urville)", "Antarctica/DumontDUrville_Z_short" : "DDUT", "Antarctica/Macquarie_Z_abbreviated" : "Antártida (Macquarie)", "Antarctica/Macquarie_Z_short" : "AEDT", "Antarctica/McMurdo_Z_abbreviated" : "Antártida (McMurdo)", "Antarctica/McMurdo_Z_short" : "NZST", "Antarctica/Palmer_Z_abbreviated" : "Antártida (Palmer)", "Antarctica/Palmer_Z_short" : "ART", "Antarctica/Rothera_Z_abbreviated" : "Antártida (Rothera)", "Antarctica/Rothera_Z_short" : "ROTT", "Antarctica/Syowa_Z_abbreviated" : "Antártida (Syowa)", "Antarctica/Syowa_Z_short" : "SYOT", "Antarctica/Vostok_Z_abbreviated" : "Antártida (Vostok)", "Antarctica/Vostok_Z_short" : "VOST", "Asia/Aden_Z_abbreviated" : "Hora de Iemen", "Asia/Aden_Z_short" : "AST (SA)", "Asia/Almaty_Z_abbreviated" : "Kazakhstan (Almaty)", "Asia/Almaty_Z_short" : "ALMT", "Asia/Amman_Z_abbreviated" : "Hora de Xordania", "Asia/Amman_Z_short" : "EET", "Asia/Anadyr_Z_abbreviated" : "Rusia (Anadyr)", "Asia/Anadyr_Z_short" : "ANAT", "Asia/Aqtau_Z_abbreviated" : "Kazakhstan (Aqtau)", "Asia/Aqtau_Z_short" : "SHET", "Asia/Aqtobe_Z_abbreviated" : "Kazakhstan (Aqtobe)", "Asia/Aqtobe_Z_short" : "AKTT", "Asia/Ashgabat_Z_abbreviated" : "Hora de Turkmenistán", "Asia/Ashgabat_Z_short" : "ASHT", "Asia/Baghdad_Z_abbreviated" : "Hora de Iraq", "Asia/Baghdad_Z_short" : "AST (SA)", "Asia/Bahrain_Z_abbreviated" : "Hora de Bahrein", "Asia/Bahrain_Z_short" : "GST", "Asia/Baku_Z_abbreviated" : "Hora de Acerbaixán", "Asia/Baku_Z_short" : "BAKT", "Asia/Bangkok_Z_abbreviated" : "Hora de Tailandia", "Asia/Bangkok_Z_short" : "ICT", "Asia/Beirut_Z_abbreviated" : "Hora de Líbano", "Asia/Beirut_Z_short" : "EET", "Asia/Bishkek_Z_abbreviated" : "Hora de Quirguicistán", "Asia/Bishkek_Z_short" : "FRUT", "Asia/Brunei_Z_abbreviated" : "Hora de Brunei", "Asia/Brunei_Z_short" : "BNT", "Asia/Choibalsan_Z_abbreviated" : "Mongolia (Choibalsan)", "Asia/Choibalsan_Z_short" : "ULAT", "Asia/Chongqing_Z_abbreviated" : "China (Chongqing)", "Asia/Chongqing_Z_short" : "LONT", "Asia/Colombo_Z_abbreviated" : "Hora de Sri Lanka", "Asia/Colombo_Z_short" : "IST", "Asia/Damascus_Z_abbreviated" : "Hora de Siria", "Asia/Damascus_Z_short" : "EET", "Asia/Dhaka_Z_abbreviated" : "Hora de Bangladesh", "Asia/Dhaka_Z_short" : "DACT", "Asia/Dili_Z_abbreviated" : "Hora de Timor Leste", "Asia/Dili_Z_short" : "TLT", "Asia/Dubai_Z_abbreviated" : "Hora de Emiratos Árabes Unidos", "Asia/Dubai_Z_short" : "GST", "Asia/Dushanbe_Z_abbreviated" : "Hora de Taxiquistán", "Asia/Dushanbe_Z_short" : "DUST", "Asia/Gaza_Z_abbreviated" : "Hora de Palestina", "Asia/Gaza_Z_short" : "IST (IL)", "Asia/Harbin_Z_abbreviated" : "China (Harbin)", "Asia/Harbin_Z_short" : "CHAT", "Asia/Hebron_Z_abbreviated" : "Hora de Palestina", "Asia/Hebron_Z_short" : "IST (IL)", "Asia/Ho_Chi_Minh_Z_abbreviated" : "Hora de Vietnam", "Asia/Ho_Chi_Minh_Z_short" : "ICT", "Asia/Hong_Kong_Z_abbreviated" : "Hora de Hong Kong RAE de China", "Asia/Hong_Kong_Z_short" : "HKT", "Asia/Hovd_Z_abbreviated" : "Mongolia (Hovd)", "Asia/Hovd_Z_short" : "HOVT", "Asia/Irkutsk_Z_abbreviated" : "Rusia (Irkutsk)", "Asia/Irkutsk_Z_short" : "IRKT", "Asia/Jakarta_Z_abbreviated" : "Indonesia (Iacarta)", "Asia/Jakarta_Z_short" : "WIT", "Asia/Jerusalem_Z_abbreviated" : "Hora de Israel", "Asia/Jerusalem_Z_short" : "IST (IL)", "Asia/Kabul_Z_abbreviated" : "Hora de Afganistán", "Asia/Kabul_Z_short" : "AFT", "Asia/Kamchatka_Z_abbreviated" : "Rusia (Kamchatka)", "Asia/Kamchatka_Z_short" : "PETT", "Asia/Karachi_Z_abbreviated" : "Hora de Paquistán", "Asia/Karachi_Z_short" : "KART", "Asia/Kashgar_Z_abbreviated" : "China (Kashgar)", "Asia/Kashgar_Z_short" : "KAST", "Asia/Kathmandu_Z_abbreviated" : "Hora de Nepal", "Asia/Kathmandu_Z_short" : "NPT", "Asia/Kolkata_Z_abbreviated" : "Hora de India", "Asia/Kolkata_Z_short" : "IST", "Asia/Krasnoyarsk_Z_abbreviated" : "Rusia (Krasnoyarsk)", "Asia/Krasnoyarsk_Z_short" : "KRAT", "Asia/Kuala_Lumpur_Z_abbreviated" : "Malaisia (Kuala Lumpur)", "Asia/Kuala_Lumpur_Z_short" : "MALT", "Asia/Kuching_Z_abbreviated" : "Malaisia (Kuching)", "Asia/Kuching_Z_short" : "BORT", "Asia/Kuwait_Z_abbreviated" : "Hora de Kuwait", "Asia/Kuwait_Z_short" : "AST (SA)", "Asia/Macau_Z_abbreviated" : "Hora de Macau RAE de China", "Asia/Macau_Z_short" : "MOT", "Asia/Magadan_Z_abbreviated" : "Rusia (Magadan)", "Asia/Magadan_Z_short" : "MAGT", "Asia/Manila_Z_abbreviated" : "Hora de Filipinas", "Asia/Manila_Z_short" : "PHT", "Asia/Muscat_Z_abbreviated" : "Hora de Omán", "Asia/Muscat_Z_short" : "GST", "Asia/Nicosia_Z_abbreviated" : "Hora de Chipre", "Asia/Nicosia_Z_short" : "EET", "Asia/Novokuznetsk_Z_abbreviated" : "Rusia (Novokuznetsk)", "Asia/Novokuznetsk_Z_short" : "KRAT", "Asia/Novosibirsk_Z_abbreviated" : "Rusia (Novosibirsk)", "Asia/Novosibirsk_Z_short" : "NOVT", "Asia/Omsk_Z_abbreviated" : "Rusia (Omsk)", "Asia/Omsk_Z_short" : "OMST", "Asia/Oral_Z_abbreviated" : "Kazakhstan (Oral)", "Asia/Oral_Z_short" : "URAT", "Asia/Phnom_Penh_Z_abbreviated" : "Hora de Cambodia", "Asia/Phnom_Penh_Z_short" : "ICT", "Asia/Pontianak_Z_abbreviated" : "Indonesia (Pontianak)", "Asia/Pontianak_Z_short" : "CIT", "Asia/Qatar_Z_abbreviated" : "Hora de Qatar", "Asia/Qatar_Z_short" : "GST", "Asia/Qyzylorda_Z_abbreviated" : "Kazakhstan (Qyzylorda)", "Asia/Qyzylorda_Z_short" : "KIZT", "Asia/Rangoon_Z_abbreviated" : "Hora de Myanmar", "Asia/Rangoon_Z_short" : "MMT", "Asia/Riyadh87_Z_abbreviated" : "Hora de Asia/Riyadh87", "Asia/Riyadh87_Z_short" : "GMT+03:07:04", "Asia/Riyadh88_Z_abbreviated" : "Hora de Asia/Riyadh88", "Asia/Riyadh88_Z_short" : "GMT+03:07:04", "Asia/Riyadh89_Z_abbreviated" : "Hora de Asia/Riyadh89", "Asia/Riyadh89_Z_short" : "GMT+03:07:04", "Asia/Riyadh_Z_abbreviated" : "Hora de Arabia Saudita", "Asia/Riyadh_Z_short" : "AST (SA)", "Asia/Sakhalin_Z_abbreviated" : "Rusia (Sakhalin)", "Asia/Sakhalin_Z_short" : "SAKT", "Asia/Samarkand_Z_abbreviated" : "Uzbekistán (Samarcanda)", "Asia/Samarkand_Z_short" : "SAMT (Samarkand)", "Asia/Seoul_Z_abbreviated" : "Hora de Corea do Sur", "Asia/Seoul_Z_short" : "KST", "Asia/Shanghai_Z_abbreviated" : "China (Shanghai)", "Asia/Shanghai_Z_short" : "CST (CN)", "Asia/Singapore_Z_abbreviated" : "Hora de Singapur", "Asia/Singapore_Z_short" : "SGT", "Asia/Taipei_Z_abbreviated" : "Hora de Taiwán", "Asia/Taipei_Z_short" : "CST (TW)", "Asia/Tbilisi_Z_abbreviated" : "Hora de Xeorxia", "Asia/Tbilisi_Z_short" : "TBIT", "Asia/Tehran_Z_abbreviated" : "Hora de Irán", "Asia/Tehran_Z_short" : "IRST", "Asia/Thimphu_Z_abbreviated" : "Hora de Bután", "Asia/Thimphu_Z_short" : "IST", "Asia/Tokyo_Z_abbreviated" : "Hora de Xapón", "Asia/Tokyo_Z_short" : "JST", "Asia/Ulaanbaatar_Z_abbreviated" : "Mongolia (Ulan Bator)", "Asia/Ulaanbaatar_Z_short" : "ULAT", "Asia/Urumqi_Z_abbreviated" : "China (Urumqi)", "Asia/Urumqi_Z_short" : "URUT", "Asia/Vientiane_Z_abbreviated" : "Hora de Laos", "Asia/Vientiane_Z_short" : "ICT", "Asia/Vladivostok_Z_abbreviated" : "Rusia (Vladivostok)", "Asia/Vladivostok_Z_short" : "VLAT", "Asia/Yakutsk_Z_abbreviated" : "Rusia (Yakutsk)", "Asia/Yakutsk_Z_short" : "YAKT", "Asia/Yekaterinburg_Z_abbreviated" : "Rusia (Ecaterinburgo)", "Asia/Yekaterinburg_Z_short" : "SVET", "Asia/Yerevan_Z_abbreviated" : "Hora de Armenia", "Asia/Yerevan_Z_short" : "YERT", "Atlantic/Bermuda_Z_abbreviated" : "Hora de Bermudas", "Atlantic/Bermuda_Z_short" : "AST", "Atlantic/Cape_Verde_Z_abbreviated" : "Hora de Cabo Verde", "Atlantic/Cape_Verde_Z_short" : "CVT", "Atlantic/Reykjavik_Z_abbreviated" : "Hora de Islandia", "Atlantic/Reykjavik_Z_short" : "GMT", "Atlantic/South_Georgia_Z_abbreviated" : "Hora de Xeorxia do Sur e Illas Sandwich", "Atlantic/South_Georgia_Z_short" : "GST (GS)", "Atlantic/St_Helena_Z_abbreviated" : "Hora de Santa Helena", "Atlantic/St_Helena_Z_short" : "GMT", "Atlantic/Stanley_Z_abbreviated" : "Hora de Illas Malvinas", "Atlantic/Stanley_Z_short" : "FKT", "Australia/Adelaide_Z_abbreviated" : "Australia (Adelaide)", "Australia/Adelaide_Z_short" : "ACST", "Australia/Brisbane_Z_abbreviated" : "Australia (Brisbane)", "Australia/Brisbane_Z_short" : "AEST", "Australia/Darwin_Z_abbreviated" : "Australia (Darwin)", "Australia/Darwin_Z_short" : "ACST", "Australia/Hobart_Z_abbreviated" : "Australia (Hobart)", "Australia/Hobart_Z_short" : "AEDT", "Australia/Lord_Howe_Z_abbreviated" : "Australia (Lord Howe)", "Australia/Lord_Howe_Z_short" : "AEST", "Australia/Melbourne_Z_abbreviated" : "Australia (Melbourne)", "Australia/Melbourne_Z_short" : "AEST", "Australia/Perth_Z_abbreviated" : "Australia (Perth)", "Australia/Perth_Z_short" : "AWST", "Australia/Sydney_Z_abbreviated" : "Australia (Sydney)", "Australia/Sydney_Z_short" : "AEST", "BC" : "a.C.", "DateTimeCombination" : "{1} {0}", "DateTimeTimezoneCombination" : "{1} {0} {2}", "DateTimezoneCombination" : "{1} {2}", "EST_Z_abbreviated" : "GMT-05:00", "EST_Z_short" : "GMT-05:00", "Etc/GMT-14_Z_abbreviated" : "GMT+14:00", "Etc/GMT-14_Z_short" : "GMT+14:00", "Etc/GMT_Z_abbreviated" : "GMT+00:00", "Etc/GMT_Z_short" : "GMT+00:00", "Europe/Amsterdam_Z_abbreviated" : "Hora de Países Baixos", "Europe/Amsterdam_Z_short" : "CET", "Europe/Andorra_Z_abbreviated" : "Hora de Andorra", "Europe/Andorra_Z_short" : "CET", "Europe/Athens_Z_abbreviated" : "Hora de Grecia", "Europe/Athens_Z_short" : "EET", "Europe/Belgrade_Z_abbreviated" : "Hora de Serbia", "Europe/Belgrade_Z_short" : "CET", "Europe/Berlin_Z_abbreviated" : "Hora de Alemaña", "Europe/Berlin_Z_short" : "CET", "Europe/Brussels_Z_abbreviated" : "Hora de Bélxica", "Europe/Brussels_Z_short" : "CET", "Europe/Bucharest_Z_abbreviated" : "Hora de Romanía", "Europe/Bucharest_Z_short" : "EET", "Europe/Budapest_Z_abbreviated" : "Hora de Hungría", "Europe/Budapest_Z_short" : "CET", "Europe/Chisinau_Z_abbreviated" : "Hora de Moldova", "Europe/Chisinau_Z_short" : "MSK", "Europe/Copenhagen_Z_abbreviated" : "Hora de Dinamarca", "Europe/Copenhagen_Z_short" : "CET", "Europe/Gibraltar_Z_abbreviated" : "Hora de Xibraltar", "Europe/Gibraltar_Z_short" : "CET", "Europe/Helsinki_Z_abbreviated" : "Hora de Finlandia", "Europe/Helsinki_Z_short" : "EET", "Europe/Istanbul_Z_abbreviated" : "Hora de Turquía", "Europe/Istanbul_Z_short" : "EET", "Europe/Kaliningrad_Z_abbreviated" : "Rusia (Kaliningrado)", "Europe/Kaliningrad_Z_short" : "MSK", "Europe/Kiev_Z_abbreviated" : "Ucraína (Kiev)", "Europe/Kiev_Z_short" : "MSK", "Europe/Lisbon_Z_abbreviated" : "Portugal (Lisbon)", "Europe/Lisbon_Z_short" : "CET", "Europe/London_Z_abbreviated" : "Hora de Reino Unido", "Europe/London_Z_short" : "GMT+01:00", "Europe/Luxembourg_Z_abbreviated" : "Hora de Luxemburgo", "Europe/Luxembourg_Z_short" : "CET", "Europe/Madrid_Z_abbreviated" : "España (Madrid)", "Europe/Madrid_Z_short" : "CET", "Europe/Malta_Z_abbreviated" : "Hora de Malta", "Europe/Malta_Z_short" : "CET", "Europe/Minsk_Z_abbreviated" : "Hora de Bielorrusia", "Europe/Minsk_Z_short" : "MSK", "Europe/Monaco_Z_abbreviated" : "Hora de Mónaco", "Europe/Monaco_Z_short" : "CET", "Europe/Moscow_Z_abbreviated" : "Rusia (Moscova)", "Europe/Moscow_Z_short" : "MSK", "Europe/Oslo_Z_abbreviated" : "Hora de Noruega", "Europe/Oslo_Z_short" : "CET", "Europe/Paris_Z_abbreviated" : "Hora de Francia", "Europe/Paris_Z_short" : "CET", "Europe/Prague_Z_abbreviated" : "Hora de República Checa", "Europe/Prague_Z_short" : "CET", "Europe/Riga_Z_abbreviated" : "Hora de Letonia", "Europe/Riga_Z_short" : "MSK", "Europe/Rome_Z_abbreviated" : "Hora de Italia", "Europe/Rome_Z_short" : "CET", "Europe/Samara_Z_abbreviated" : "Rusia (Samara)", "Europe/Samara_Z_short" : "KUYT", "Europe/Simferopol_Z_abbreviated" : "Ucraína (Simferopol)", "Europe/Simferopol_Z_short" : "MSK", "Europe/Sofia_Z_abbreviated" : "Hora de Bulgaria", "Europe/Sofia_Z_short" : "EET", "Europe/Stockholm_Z_abbreviated" : "Hora de Suecia", "Europe/Stockholm_Z_short" : "CET", "Europe/Tallinn_Z_abbreviated" : "Hora de Estonia", "Europe/Tallinn_Z_short" : "MSK", "Europe/Tirane_Z_abbreviated" : "Hora de Albania", "Europe/Tirane_Z_short" : "CET", "Europe/Uzhgorod_Z_abbreviated" : "Ucraína (Uzhgorod)", "Europe/Uzhgorod_Z_short" : "MSK", "Europe/Vaduz_Z_abbreviated" : "Hora de Liechtenstein", "Europe/Vaduz_Z_short" : "CET", "Europe/Vienna_Z_abbreviated" : "Hora de Austria", "Europe/Vienna_Z_short" : "CET", "Europe/Vilnius_Z_abbreviated" : "Hora de Lituania", "Europe/Vilnius_Z_short" : "MSK", "Europe/Volgograd_Z_abbreviated" : "Rusia (Volgogrado)", "Europe/Volgograd_Z_short" : "VOLT", "Europe/Warsaw_Z_abbreviated" : "Hora de Polonia", "Europe/Warsaw_Z_short" : "CET", "Europe/Zaporozhye_Z_abbreviated" : "Ucraína (Zaporozhye)", "Europe/Zaporozhye_Z_short" : "MSK", "Europe/Zurich_Z_abbreviated" : "Hora de Suíza", "Europe/Zurich_Z_short" : "CET", "HMS_long" : "{0} {1} {2}", "HMS_short" : "{0}:{1}:{2}", "HM_abbreviated" : "h:mm a", "HM_short" : "h:mm a", "H_abbreviated" : "h a", "Indian/Antananarivo_Z_abbreviated" : "Hora de Madagascar", "Indian/Antananarivo_Z_short" : "EAT", "Indian/Chagos_Z_abbreviated" : "Hora de Territorio Británico do Océano Índico", "Indian/Chagos_Z_short" : "IOT", "Indian/Christmas_Z_abbreviated" : "Hora de Illa Christmas", "Indian/Christmas_Z_short" : "CXT", "Indian/Cocos_Z_abbreviated" : "Hora de Illas Cocos", "Indian/Cocos_Z_short" : "CCT", "Indian/Comoro_Z_abbreviated" : "Hora de Comores", "Indian/Comoro_Z_short" : "EAT", "Indian/Kerguelen_Z_abbreviated" : "Hora de Territorios Franceses do Sul", "Indian/Kerguelen_Z_short" : "TFT", "Indian/Mahe_Z_abbreviated" : "Hora de SC", "Indian/Mahe_Z_short" : "SCT", "Indian/Maldives_Z_abbreviated" : "Hora de Maldivas", "Indian/Maldives_Z_short" : "MVT", "Indian/Mauritius_Z_abbreviated" : "Hora de Mauricio", "Indian/Mauritius_Z_short" : "MUT", "Indian/Mayotte_Z_abbreviated" : "Hora de Mayotte", "Indian/Mayotte_Z_short" : "EAT", "Indian/Reunion_Z_abbreviated" : "Hora de Reunión", "Indian/Reunion_Z_short" : "RET", "MD_abbreviated" : "d MMM", "MD_long" : "d MMMM", "MD_short" : "d-M", "M_abbreviated" : "MMM", "M_long" : "MMMM", "Pacific/Apia_Z_abbreviated" : "Hora de Samoa", "Pacific/Apia_Z_short" : "BST (Bering)", "Pacific/Auckland_Z_abbreviated" : "Nova Celandia (Auckland)", "Pacific/Auckland_Z_short" : "NZST", "Pacific/Chuuk_Z_abbreviated" : "Micronesia (Truk)", "Pacific/Chuuk_Z_short" : "TRUT", "Pacific/Efate_Z_abbreviated" : "Hora de Vanuatu", "Pacific/Efate_Z_short" : "VUT", "Pacific/Fakaofo_Z_abbreviated" : "Hora de Tokelau", "Pacific/Fakaofo_Z_short" : "TKT", "Pacific/Fiji_Z_abbreviated" : "Hora de Fixi", "Pacific/Fiji_Z_short" : "FJT", "Pacific/Funafuti_Z_abbreviated" : "Hora de Tuvalu", "Pacific/Funafuti_Z_short" : "TVT", "Pacific/Gambier_Z_abbreviated" : "Polinesia Francesa (Gambier)", "Pacific/Gambier_Z_short" : "GAMT", "Pacific/Guadalcanal_Z_abbreviated" : "Hora de Illas Salomón", "Pacific/Guadalcanal_Z_short" : "SBT", "Pacific/Guam_Z_abbreviated" : "Hora de Guam", "Pacific/Guam_Z_short" : "GST (GU)", "Pacific/Honolulu_Z_abbreviated" : "Estados Unidos de América (Honolulú)", "Pacific/Honolulu_Z_short" : "AHST", "Pacific/Johnston_Z_abbreviated" : "Illas Menores Distantes dos EUA. (Johnston)", "Pacific/Johnston_Z_short" : "AHST", "Pacific/Majuro_Z_abbreviated" : "Illas Marshall (Majuro)", "Pacific/Majuro_Z_short" : "MHT", "Pacific/Midway_Z_abbreviated" : "Illas Menores Distantes dos EUA. (Midway)", "Pacific/Midway_Z_short" : "BST (Bering)", "Pacific/Nauru_Z_abbreviated" : "Hora de Nauru", "Pacific/Nauru_Z_short" : "NRT", "Pacific/Niue_Z_abbreviated" : "Hora de Niue", "Pacific/Niue_Z_short" : "NUT", "Pacific/Norfolk_Z_abbreviated" : "Hora de Illa Norfolk", "Pacific/Norfolk_Z_short" : "NFT", "Pacific/Noumea_Z_abbreviated" : "Hora de Nova Caledonia", "Pacific/Noumea_Z_short" : "NCT", "Pacific/Pago_Pago_Z_abbreviated" : "Hora de Samoa Americana", "Pacific/Pago_Pago_Z_short" : "BST (Bering)", "Pacific/Palau_Z_abbreviated" : "Hora de Palau", "Pacific/Palau_Z_short" : "PWT", "Pacific/Pitcairn_Z_abbreviated" : "Hora de Pitcairn", "Pacific/Pitcairn_Z_short" : "PNT", "Pacific/Port_Moresby_Z_abbreviated" : "Hora de Papúa Nova Guinea", "Pacific/Port_Moresby_Z_short" : "PGT", "Pacific/Rarotonga_Z_abbreviated" : "Hora de Illas Cook", "Pacific/Rarotonga_Z_short" : "CKT", "Pacific/Saipan_Z_abbreviated" : "Hora de Illas Marianas do norte", "Pacific/Saipan_Z_short" : "MPT", "Pacific/Tarawa_Z_abbreviated" : "Kiribati (Tarawa)", "Pacific/Tarawa_Z_short" : "GILT", "Pacific/Tongatapu_Z_abbreviated" : "Hora de Tonga", "Pacific/Tongatapu_Z_short" : "TOT", "Pacific/Wake_Z_abbreviated" : "Illas Menores Distantes dos EUA. (Wake)", "Pacific/Wake_Z_short" : "WAKT", "Pacific/Wallis_Z_abbreviated" : "Hora de Wallis e Futuna", "Pacific/Wallis_Z_short" : "WFT", "RelativeTime/oneUnit" : "{0} ago", "RelativeTime/twoUnits" : "{0} {1} ago", "TimeTimezoneCombination" : "{0} {2}", "WET_Z_abbreviated" : "GMT+00:00", "WET_Z_short" : "GMT+00:00", "WMD_abbreviated" : "E d MMM", "WMD_long" : "EEEE, MMMM d", "WMD_short" : "E, d-M", "WYMD_abbreviated" : "EEE, d MMM y", "WYMD_long" : "EEEE dd MMMM y", "WYMD_short" : "EEE, M/d/yy", "W_abbreviated" : "EEE", "W_long" : "EEEE", "YMD_abbreviated" : "MMM d, y", "YMD_full" : "dd/MM/yy", "YMD_long" : "dd MMMM y", "YMD_short" : "dd/MM/yy", "YM_long" : "MMMM y", "currencyFormat" : "#,##0.00 ¤", "currencyPatternPlural" : "{0} {1}", "currencyPatternSingular" : "{0} {1}", "day" : "día", "day_abbr" : "día", "dayperiod" : "Dayperiod", "days" : "días", "days_abbr" : "días", "decimalFormat" : "#,##0.###", "decimalSeparator" : ",", "defaultCurrency" : "EUR", "exponentialSymbol" : "E", "groupingSeparator" : ".", "hour" : "hora", "hour_abbr" : "hora", "hours" : "horas", "hours_abbr" : "horas", "infinitySign" : "∞", "listPatternEnd" : "{0}, {1}", "listPatternMiddle" : "{0}, {1}", "listPatternStart" : "{0}, {1}", "listPatternTwo" : "{0}, {1}", "minusSign" : "-", "minute" : "minuto", "minute_abbr" : "minuto", "minutes" : "minutos", "minutes_abbr" : "minutos", "month" : "mes", "monthAprLong" : "Abril", "monthAprMedium" : "Abr", "monthAugLong" : "Agosto", "monthAugMedium" : "Ago", "monthDecLong" : "Decembro", "monthDecMedium" : "Dec", "monthFebLong" : "Febreiro", "monthFebMedium" : "Feb", "monthJanLong" : "Xaneiro", "monthJanMedium" : "Xan", "monthJulLong" : "Xullo", "monthJulMedium" : "Xul", "monthJunLong" : "Xuño", "monthJunMedium" : "Xuñ", "monthMarLong" : "Marzo", "monthMarMedium" : "Mar", "monthMayLong" : "Maio", "monthMayMedium" : "Mai", "monthNovLong" : "Novembro", "monthNovMedium" : "Nov", "monthOctLong" : "Outubro", "monthOctMedium" : "Out", "monthSepLong" : "Setembro", "monthSepMedium" : "Set", "month_abbr" : "mes", "months" : "meses", "months_abbr" : "meses", "nanSymbol" : "NaN", "numberZero" : "0", "perMilleSign" : "‰", "percentFormat" : "#,##0%", "percentSign" : "%", "periodAm" : "Dayperiod", "periodPm" : "Dayperiod", "pluralRule" : "set3", "plusSign" : "+", "scientificFormat" : "#E0", "second" : "segundo", "second_abbr" : "segundo", "seconds" : "segundos", "seconds_abbr" : "segundos", "today" : "hoxe", "tomorrow" : "mañá", "weekdayFriLong" : "Venres", "weekdayFriMedium" : "Ven", "weekdayMonLong" : "Luns", "weekdayMonMedium" : "Lun", "weekdaySatLong" : "Sábado", "weekdaySatMedium" : "Sáb", "weekdaySunLong" : "Domingo", "weekdaySunMedium" : "Dom", "weekdayThuLong" : "Xoves", "weekdayThuMedium" : "Xov", "weekdayTueLong" : "Martes", "weekdayTueMedium" : "Mar", "weekdayWedLong" : "Mércores", "weekdayWedMedium" : "Mér", "year" : "ano", "year_abbr" : "ano", "years" : "anos", "years_abbr" : "anos", "yesterday" : "onte" }
module.exports = { '/': { backLink: '/../priority_service_170705/filter/uncancelled', next: '/what-you-need' }, '/before-you-continue-overseas': { backLink: '/../priority_service_170705/overseas/uncancelled', next: '/what-you-need-overseas' }, '/what-you-need': { backLink: './', next: '/you-need-a-photo' }, '/what-you-need-overseas': { backLink: '/../priority_service_170705/overseas/try-service', next: '/you-need-a-photo-overseas' }, '/you-need-a-photo': { backLink: '../book-appointment/confirmation-scenario-1', next: '/choose-photo-method' }, '/you-need-a-photo-overseas': { backLink: './what-you-need-overseas', next: '/choose-photo-method' }, '/you-need-a-photo-v3': { backLink: './what-you-need', next: '/choose-photo-method' }, '/choose-photo-method': { fields: ['choose-photo'], next: '/../upload' }, '/choose-photo-method-overseas': { fields: ['choose-photo-overseas'], next: '/../upload' } };
// @ts-check // Protractor configuration file, see link for more information // https://github.com/angular/protractor/blob/master/lib/config.ts const { SpecReporter } = require('jasmine-spec-reporter'); /** * @type { import("protractor").Config } */ exports.config = { allScriptsTimeout: 11000, specs: ['./src/**/*.e2e-spec.ts'], capabilities: { browserName: 'chrome', chromeOptions: { args: ['--headless'], binary: require('puppeteer').executablePath(), }, }, directConnect: true, baseUrl: 'http://localhost:4200/', framework: 'jasmine', jasmineNodeOpts: { showColors: true, defaultTimeoutInterval: 30000, print: function () {}, }, onPrepare() { require('ts-node').register({ project: require('path').join(__dirname, './tsconfig.json'), }); jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); }, };
const { get } = require('lodash') const { postDetails, setJourneyDetails, setBreadcrumbs, renderTemplate, } = require('../middleware') const steps = require('../__fixtures__/steps')() describe('#postDetails', () => { const buildCurrentStep = (sendSpy) => { const macro = () => { return { children: [ { name: 'field4', validations: [ { type: 'required', message: 'You must select field 4', }, ], }, { name: 'field5', validations: [ { type: 'required', message: 'You must select field 5', }, ], }, ], } } const done = sendSpy ? { send: sendSpy, message: 'Data has been added', nextPath: ({ id }) => `/base/${id}`, } : null return { done, ...steps[0], macro, } } context('when there are partial validation errors', () => { beforeEach(async () => { this.flashSpy = sinon.spy() this.sendSpy = sinon.stub().callsFake((data, next) => { next() }) this.redirectSpy = sinon.spy() this.req = { body: {}, session: {}, flash: this.flashSpy, } this.res = { locals: { journey: { currentStep: buildCurrentStep(this.sendSpy), key: '/base/step-1', }, }, redirect: this.redirectSpy, } this.nextSpy = sinon.spy() await postDetails(this.req, this.res, this.nextSpy) }) it('should set the errors on locals', () => { expect(this.res.locals.form.errors.messages).to.deep.equal({ field4: ['You must select field 4'], field5: ['You must select field 5'], }) }) it('should set the step completed to false', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'] .completed expect(actual).to.be.false }) it('should not set the next path', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'].nextPath expect(actual).to.be.undefined }) it('should call next once', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.have.been.calledOnce }) it('should not send to the API', () => { expect(this.sendSpy).to.not.be.called }) it('should not set a flash message', () => { expect(this.flashSpy).to.not.be.called }) it('should not redirect', () => { expect(this.redirectSpy).to.not.be.called }) }) context('when the current step does not have a controller', () => { beforeEach(async () => { this.flashSpy = sinon.spy() this.sendSpy = sinon.stub().callsFake((data, next) => { next() }) this.redirectSpy = sinon.spy() this.req = { baseUrl: '/base', body: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, session: {}, flash: this.flashSpy, } this.res = { locals: { journey: { currentStep: buildCurrentStep(), key: '/base/step-1', }, }, redirect: this.redirectSpy, } this.nextSpy = sinon.spy() await postDetails(this.req, this.res, this.nextSpy) }) it('should not set the errors on locals', () => { const actual = get(this.res.locals, 'form.errors') expect(actual).to.be.undefined }) it('should set the step completed to true', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'] .completed expect(actual).to.be.true }) it('should set the next path', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'].nextPath expect(actual).to.equal('/step-2') }) it('should not call next', () => { expect(this.nextSpy).to.not.be.called }) it('should not send to the API', () => { expect(this.sendSpy).to.not.be.called }) it('should not set a flash message', () => { expect(this.flashSpy).to.not.be.called }) it('should redirect', () => { expect(this.redirectSpy).to.be.calledWithExactly('/base/step-2') expect(this.redirectSpy).to.have.been.calledOnce }) }) context( 'when the current step does have a send function and the API call is successful', () => { beforeEach(async () => { this.flashSpy = sinon.spy() this.sendSpy = sinon.stub().callsFake(() => { return { id: 1 } }) this.redirectSpy = sinon.spy() this.req = { baseUrl: '/base', body: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, session: { 'multi-step': { '/base/step-1': { steps: { '/step-1': { data: { selectedAtStep1: 'step-3-value', field4: 'field-4', field5: 'field-5', }, }, }, }, }, }, flash: this.flashSpy, } this.res = { locals: { journey: { currentStep: buildCurrentStep(this.sendSpy), key: '/base/step-1', }, }, redirect: this.redirectSpy, } this.nextSpy = sinon.spy() await postDetails(this.req, this.res, this.nextSpy) }) it('should not set the errors on locals', () => { const actual = get(this.res.locals, 'form.errors') expect(actual).to.be.undefined }) it('should remove the journey from state', () => { const actual = this.req.session['multi-step']['/base/step-1'] expect(actual).to.be.undefined }) it('should not call next', () => { expect(this.nextSpy).to.not.be.called }) it('should send to the API', () => { expect(this.sendSpy).to.be.calledWith({ selectedAtStep1: 'step-3-value', field4: 'field-4', field5: 'field-5', }) expect(this.sendSpy).to.have.been.calledOnce }) it('should set a flash message', () => { expect(this.flashSpy).to.be.calledWithExactly( 'success', 'Data has been added' ) expect(this.flashSpy).to.have.been.calledOnce }) it('should redirect', () => { expect(this.redirectSpy).to.be.calledWithExactly('base/1') expect(this.redirectSpy).to.have.been.calledOnce }) } ) context('when the controller has an error with status code 400', () => { beforeEach(async () => { this.flashSpy = sinon.spy() this.sendSpy = sinon.stub().callsFake(() => { const error = new Error() error.statusCode = 400 error.error = 'error' throw error }) this.redirectSpy = sinon.spy() this.req = { baseUrl: '/base', body: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, session: { 'multi-step': { '/base/step-1': { steps: { '/step-1': { data: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, }, }, }, }, }, flash: this.flashSpy, } this.res = { locals: { journey: { currentStep: buildCurrentStep(this.sendSpy), key: '/base/step-1', }, }, redirect: this.redirectSpy, } this.nextSpy = sinon.spy() await postDetails(this.req, this.res, this.nextSpy) }) it('should set the errors on locals', () => { expect(this.res.locals.form.errors.messages).to.equal('error') }) it('should set the step completed to false', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'] .completed expect(actual).to.be.false }) it('should not set the next path', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'].nextPath expect(actual).to.be.undefined }) it('should not remove the journey from state', () => { const actual = this.req.session['multi-step']['/base/step-1'] expect(actual).to.exist }) it('should call next', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.have.been.calledOnce }) it('should send to the API', () => { expect(this.sendSpy).to.be.calledWith({ selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }) expect(this.sendSpy).to.have.been.calledOnce }) it('should not set a flash message', () => { expect(this.flashSpy).to.not.be.called }) it('should not redirect', () => { expect(this.redirectSpy).to.not.be.called }) }) context('when the controller has another type of error', () => { beforeEach(async () => { this.flashSpy = sinon.spy() this.sendSpy = sinon.stub().callsFake(() => { throw new Error('error') }) this.redirectSpy = sinon.spy() this.req = { baseUrl: '/base', body: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, session: { 'multi-step': { '/base/step-1': { steps: { '/step-1': { data: { selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }, }, }, }, }, }, flash: this.flashSpy, } this.res = { locals: { journey: { currentStep: buildCurrentStep(this.sendSpy), key: '/base/step-1', }, }, redirect: this.redirectSpy, } this.nextSpy = sinon.spy() await postDetails(this.req, this.res, this.nextSpy) }) it('should not set the errors on locals', () => { const actual = get(this.res.locals, 'form.errors') expect(actual).to.be.undefined }) it('should set the step completed to false', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'] .completed expect(actual).to.be.false }) it('should not set the next path', () => { const actual = this.req.session['multi-step']['/base/step-1'].steps['/step-1'].nextPath expect(actual).to.be.undefined }) it('should not remove the journey from state', () => { const actual = this.req.session['multi-step']['/base/step-1'] expect(actual).to.exist }) it('should call next with the error', () => { expect(this.nextSpy).to.be.calledWith( sinon.match({ message: 'error', }) ) expect(this.nextSpy).to.be.calledOnce }) it('should send to the API', () => { expect(this.sendSpy).to.be.calledWith({ selectedAtStep1: 'step-2-value', field4: 'field-4', field5: 'field-5', }) expect(this.sendSpy).to.have.been.calledOnce }) it('should not set a flash message', () => { expect(this.flashSpy).to.not.be.called }) it('should not redirect', () => { expect(this.redirectSpy).to.not.be.called }) }) }) describe('#setJourneyDetails', () => { beforeEach(() => { this.req = { baseUrl: '/base', } this.res = { locals: {}, } this.nextSpy = sinon.spy() setJourneyDetails({ steps }, steps[1], 1)(this.req, this.res, this.nextSpy) }) it('should set the current step', () => { expect(this.res.locals.journey.currentStep).to.deep.equal(steps[1]) }) it('should set the current step ID', () => { expect(this.res.locals.journey.currentStepId).to.equal(1) }) it('should set the steps', () => { expect(this.res.locals.journey.steps).to.deep.equal(steps) }) it('should set the key', () => { expect(this.res.locals.journey.key).to.equal('/base/step-1') }) it('should call next once', () => { expect(this.nextSpy).to.be.calledOnce }) }) describe('#setBreadcrumbs', () => { context( 'when there are breadcrumbs on the whole journey and the step', () => { beforeEach(() => { this.breadcrumbSpy = sinon.spy() this.req = {} this.res = { locals: { journey: { breadcrumbs: [{ text: 'breadcrumb', href: '/url' }], currentStep: steps[0], }, }, breadcrumb: this.breadcrumbSpy, } this.nextSpy = sinon.spy() setBreadcrumbs(this.req, this.res, this.nextSpy) }) it('should set the breadcrumbs', () => { expect(this.breadcrumbSpy).to.be.calledWithExactly('breadcrumb', '/url') expect(this.breadcrumbSpy).to.be.calledWithExactly( 'Add something', '/url' ) expect(this.breadcrumbSpy).to.be.calledTwice }) it('should call next once', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.be.calledOnce }) } ) context( 'when there are breadcrumbs on the whole journey and not on the step', () => { beforeEach(() => { const currentStep = { ...steps[0], } delete currentStep.breadcrumbs this.breadcrumbSpy = sinon.spy() this.req = {} this.res = { locals: { journey: { currentStep, breadcrumbs: [{ text: 'breadcrumb', href: '/url' }], }, }, breadcrumb: this.breadcrumbSpy, } this.nextSpy = sinon.spy() setBreadcrumbs(this.req, this.res, this.nextSpy) }) it('should set the breadcrumbs', () => { expect(this.breadcrumbSpy).to.be.calledWithExactly('breadcrumb', '/url') expect(this.breadcrumbSpy).to.be.calledOnce }) it('should call next once', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.be.calledOnce }) } ) context( 'when there are breadcrumbs on the step and not the whole journey', () => { beforeEach(() => { this.breadcrumbSpy = sinon.spy() this.req = {} this.res = { locals: { journey: { currentStep: steps[0], }, }, breadcrumb: this.breadcrumbSpy, } this.nextSpy = sinon.spy() setBreadcrumbs(this.req, this.res, this.nextSpy) }) it('should set the breadcrumbs', () => { expect(this.breadcrumbSpy).to.be.calledWithExactly( 'Add something', '/url' ) expect(this.breadcrumbSpy).to.be.calledOnce }) it('should call next once', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.be.calledOnce }) } ) context( 'when there are not any breadcrumbs on either the whole journey or the step', () => { beforeEach(() => { const currentStep = { ...steps[0], } delete currentStep.breadcrumbs this.breadcrumbSpy = sinon.spy() this.req = {} this.res = { locals: { journey: { currentStep, }, }, breadcrumb: this.breadcrumbSpy, } this.nextSpy = sinon.spy() setBreadcrumbs(this.req, this.res, this.nextSpy) }) it('should not set the breadcrumbs', () => { expect(this.breadcrumbSpy).to.be.not.be.called }) it('should call next once', () => { expect(this.nextSpy).to.be.calledWithExactly() expect(this.nextSpy).to.be.calledOnce }) } ) }) describe('#renderTemplate', () => { beforeEach(() => { steps[0].macro = sinon.spy() this.req = {} this.res = { render: sinon.spy(), locals: { journey: { currentStep: steps[0], }, form: { previouslySet: 'previously-set', errors: { messages: { field: ['error'], }, }, returnLink: '/base', returnText: 'Cancel', state: { selectedAtStep1: 'step-3-value', }, }, }, } renderTemplate(this.req, this.res) }) it('should render the template once', () => { expect(this.res.render.firstCall.args[0]).to.equal('_layouts/form') expect(this.res.render).to.be.calledOnce }) it('should set the heading', () => { expect(this.res.render.firstCall.args[1].heading).to.equal('Add something') }) it('should maintain previously set form fields', () => { expect(this.res.render.firstCall.args[1].form.previouslySet).to.equal( 'previously-set' ) }) it('should call the form macro once', () => { expect(this.res.locals.journey.currentStep.macro).to.be.calledOnce }) it('should call the form macro with errors', () => { expect( this.res.locals.journey.currentStep.macro.firstCall.args[0].errors ).to.deep.equal({ field: ['error'] }) }) it('should call the form macro with return link', () => { expect( this.res.locals.journey.currentStep.macro.firstCall.args[0].returnLink ).to.equal('/base') }) it('should call the form macro with return text', () => { expect( this.res.locals.journey.currentStep.macro.firstCall.args[0].returnText ).to.equal('Cancel') }) it('should call the form macro with state', () => { expect( this.res.locals.journey.currentStep.macro.firstCall.args[0].state ).to.deep.equal({ selectedAtStep1: 'step-3-value' }) }) })
'use strict'; angular.module('openhds') .service('PregnancyResultService', ['EntityService', PregnancyResultService]); function PregnancyResultService(EntityService) { var service = this; var urlBase = "/pregnancyResults"; function Request(model) { console.log(model); return { collectedByUuid: model.fieldWorker.uuid, pregnancyOutcomeUuid: model.pregnancyOutcome.uuid, childUuid: model.child.uuid, pregnancyResult: { type: model.event.type, collectionDateTime: model.collectionDate } }; } service.submit = function(fieldWorker, collectionDate, visit, outcome, child, event) { var model = { fieldWorker: fieldWorker, collectionDate: collectionDate, visit: visit, pregnancyOutcome: outcome, child: child, event: event }; return EntityService.submit(urlBase, Request, model); }; return service; }
/*! * Bootstrap-select v1.12.4 (https://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2018 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ !function(e,t){"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"沒有選取任何項目",noneResultsText:"沒有找到符合的結果",countSelectedText:"已經選取{0}個項目",maxOptionsText:["超過限制 (最多選擇{n}項)","超過限制(最多選擇{n}組)"],selectAllText:"選取全部",deselectAllText:"全部取消",multipleSeparator:", "}});
'use strict'; var Lib = require('../../lib'); var handleXYZDefaults = require('../heatmap/xyz_defaults'); var attributes = require('./attributes'); var handleConstraintDefaults = require('../contour/constraint_defaults'); var handleContoursDefaults = require('../contour/contours_defaults'); var handleStyleDefaults = require('../contour/style_defaults'); module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { function coerce(attr, dflt) { return Lib.coerce(traceIn, traceOut, attributes, attr, dflt); } function coerce2(attr) { return Lib.coerce2(traceIn, traceOut, attributes, attr); } coerce('carpet'); // If either a or b is not present, then it's not a valid trace *unless* the carpet // axis has the a or b values we're looking for. So if these are not found, just defer // that decision until the calc step. // // NB: the calc step will modify the original data input by assigning whichever of // a or b are missing. This is necessary because panning goes right from supplyDefaults // to plot (skipping calc). That means on subsequent updates, this *will* need to be // able to find a and b. // // The long-term proper fix is that this should perhaps use underscored attributes to // at least modify the user input to a slightly lesser extent. Fully removing the // input mutation is challenging. The underscore approach is not currently taken since // it requires modification to all of the functions below that expect the coerced // attribute name to match the property name -- except '_a' !== 'a' so that is not // straightforward. if(traceIn.a && traceIn.b) { var len = handleXYZDefaults(traceIn, traceOut, coerce, layout, 'a', 'b'); if(!len) { traceOut.visible = false; return; } coerce('text'); var isConstraint = (coerce('contours.type') === 'constraint'); if(isConstraint) { handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, {hasHover: false}); } else { handleContoursDefaults(traceIn, traceOut, coerce, coerce2); handleStyleDefaults(traceIn, traceOut, coerce, layout, {hasHover: false}); } } else { traceOut._defaultColor = defaultColor; traceOut._length = null; } };
import {make} from '@ciscospark/common'; const data = new (make(WeakMap, Map))(); /** * Given a class property, this decorator changes it into a setter/getter pair; * the setter will trigger `change:${prop}` when invoked * @param {Object} target * @param {string} prop * @param {Object} descriptor * @returns {undefined} */ export default function evented(target, prop, descriptor) { const defaultValue = descriptor.initializer && descriptor.initializer(); Reflect.deleteProperty(descriptor, 'value'); Reflect.deleteProperty(descriptor, 'initializer'); Reflect.deleteProperty(descriptor, 'writable'); descriptor.get = function get() { const value = data.get(this, prop); if (typeof value !== 'undefined') { return value; } return defaultValue; }; descriptor.set = function set(value) { const previous = this[prop]; if (previous !== value) { data.set(this, prop, value); this.trigger(`change:${prop}`, value, previous); this.trigger('change'); } }; }
'use strict' module.exports = function pull (a) { var length = arguments.length if (typeof a === 'function' && a.length === 1) { var args = new Array(length) for(var i = 0; i < length; i++) args[i] = arguments[i] return function (read) { args.unshift(read) return pull.apply(null, args) } } var read = a if (read && typeof read.source === 'function') { read = read.source } for (var i = 1; i < length; i++) { var s = arguments[i] if (typeof s === 'function') { read = s(read) } else if (s && typeof s === 'object') { s.sink(read) read = s.source } } return read }
const JSONRPC = { Client: require("../Client") }; /** * Extend this class to link to extra worker RPC APIs on the master. */ class WorkerClient extends JSONRPC.Client { /** * @returns {never} */ async gracefulExit() { return this.rpc("gracefulExit", [], /*bNotification*/ true); } /** * This works as an internal router to a JSONRPC.Server's endpoints, used as libraries. * * Proxies RPC requests directly into potentially an internet facing JSONRPC.Server's registered endpoints. * * strEndpointPath is an endpoint path such as "/api-ws/ipc/bsi". * * **************** SKIPS ANY AUTHENTICATION OR AUTHORIZATION LAYERS*********************** * **************** as well as any other JSONRPC plugins *************************** * * @param {string} strEndpointPath * @param {string} strFunctionName * @param {Array} arrParams * @param {boolean} bNotification = false */ async rpcToInternalEndpointAsLibrary(strEndpointPath, strFunctionName, arrParams, bNotification = false) { return this.rpc("rpcToInternalEndpointAsLibrary", [...arguments]); } }; module.exports = WorkerClient;
/*global define*/ define([ '../Core/defaultValue', '../Core/defined', '../Core/defineProperties', '../Core/DeveloperError', '../Core/Event', './createDynamicPropertyDescriptor' ], function( defaultValue, defined, defineProperties, DeveloperError, Event, createDynamicPropertyDescriptor) { "use strict"; /** * An optionally time-dynamic polygon. * * @alias DynamicPolygon * @constructor */ var DynamicPolygon = function() { this._show = undefined; this._showSubscription = undefined; this._material = undefined; this._materialSubscription = undefined; this._height = undefined; this._heightSubscription = undefined; this._extrudedHeight = undefined; this._extrudedHeightSubscription = undefined; this._granularity = undefined; this._granularitySubscription = undefined; this._stRotation = undefined; this._stRotationSubscription = undefined; this._perPositionHeight = undefined; this._perPositionHeightSubscription = undefined; this._definitionChanged = new Event(); }; defineProperties(DynamicPolygon.prototype, { /** * Gets the event that is raised whenever a new property is assigned. * @memberof DynamicPolygon.prototype * * @type {Event} * @readonly */ definitionChanged : { get : function() { return this._definitionChanged; } }, /** * Gets or sets the boolean {@link Property} specifying the polygon's visibility. * @memberof DynamicPolygon.prototype * @type {Property} */ show : createDynamicPropertyDescriptor('show'), /** * Gets or sets the {@link MaterialProperty} specifying the appearance of the polygon. * @memberof DynamicPolygon.prototype * @type {MaterialProperty} */ material : createDynamicPropertyDescriptor('material'), /** * Gets or sets the Number {@link Property} specifying the height of the polygon. * If undefined, the polygon will be on the surface. * @memberof DynamicPolygon.prototype * @type {Property} */ height : createDynamicPropertyDescriptor('height'), /** * Gets or sets the Number {@link Property} specifying the extruded height of the polygon. * Setting this property creates a polygon shaped volume starting at height and ending * at the extruded height. * @memberof DynamicPolygon.prototype * @type {Property} */ extrudedHeight : createDynamicPropertyDescriptor('extrudedHeight'), /** * Gets or sets the Number {@link Property} specifying the sampling distance, in radians, * between each latitude and longitude point. * @memberof DynamicPolygon.prototype * @type {Property} */ granularity : createDynamicPropertyDescriptor('granularity'), /** * Gets or sets the Number {@link Property} specifying the rotation of the texture coordinates, * in radians. A positive rotation is counter-clockwise. * @memberof DynamicPolygon.prototype * @type {Property} */ stRotation : createDynamicPropertyDescriptor('stRotation'), /** * Gets or sets the Boolean {@link Property} specifying whether the polygon should be filled. * @memberof DynamicPolygon.prototype * @type {Property} */ fill : createDynamicPropertyDescriptor('fill'), /** * Gets or sets the Boolean {@link Property} specifying whether the polygon should be outlined. * @memberof DynamicPolygon.prototype * @type {Property} */ outline : createDynamicPropertyDescriptor('outline'), /** * Gets or sets the Color {@link Property} specifying whether the color of the outline. * @memberof DynamicPolygon.prototype * @type {Property} */ outlineColor : createDynamicPropertyDescriptor('outlineColor'), /** * Gets or sets the Boolean {@link Property} specifying whether the polygon uses per-position heights. * @memberof DynamicPolygon.prototype * @type {Property} */ perPositionHeight : createDynamicPropertyDescriptor('perPositionHeight') }); /** * Duplicates a DynamicPolygon instance. * * @param {DynamicPolygon} [result] The object onto which to store the result. * @returns {DynamicPolygon} The modified result parameter or a new instance if one was not provided. */ DynamicPolygon.prototype.clone = function(result) { if (!defined(result)) { result = new DynamicPolygon(); } result.show = this.show; result.material = this.material; result.height = this.height; result.extrudedHeight = this.extrudedHeight; result.granularity = this.granularity; result.stRotation = this.stRotation; result.fill = this.fill; result.outline = this.outline; result.outlineColor = this.outlineColor; result.perPositionHeight = this.perPositionHeight; return result; }; /** * Assigns each unassigned property on this object to the value * of the same property on the provided source object. * * @param {DynamicPolygon} source The object to be merged into this object. */ DynamicPolygon.prototype.merge = function(source) { //>>includeStart('debug', pragmas.debug); if (!defined(source)) { throw new DeveloperError('source is required.'); } //>>includeEnd('debug'); this.show = defaultValue(this.show, source.show); this.material = defaultValue(this.material, source.material); this.height = defaultValue(this.height, source.height); this.extrudedHeight = defaultValue(this.extrudedHeight, source.extrudedHeight); this.granularity = defaultValue(this.granularity, source.granularity); this.stRotation = defaultValue(this.stRotation, source.stRotation); this.fill = defaultValue(this.fill, source.fill); this.outline = defaultValue(this.outline, source.outline); this.outlineColor = defaultValue(this.outlineColor, source.outlineColor); this.perPositionHeight = defaultValue(this.perPositionHeight, source.perPositionHeight); }; return DynamicPolygon; });
var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username: {type: String, required: true, unique: true}, password: {type: String} }); mongoose.model('User', userSchema);
define({ "instruction": "Wybierz i skonfiguruj warstwy, które będą wyświetlane początkowo w tabeli atrybutów.", "label": "Warstwa", "show": "Pokaż", "actions": "Skonfiguruj pola warstwy", "field": "Pole", "alias": "Alias", "visible": "Widoczne", "linkField": "Pole łącza", "noLayers": "Brak warstw obiektu", "back": "Wstecz", "exportCSV": "Zezwalaj na eksport do pliku CSV", "expand": "Wstępnie rozwiń widżet", "filterByExtent": "Domyślnie włącz opcję Filtruj wg zasięgu mapy", "restore": "Przywróć wartość domyślną", "ok": "OK", "cancel": "Anuluj", "includePoint": "Dołącz współrzędne punktów do wyeksportowanego pliku", "configureLayerFields": "Skonfiguruj pola warstwy", "result": "Zapisano pomyślnie", "warning": "Wybierz najpierw element Pokaż opcję.", "fieldCheckWarning": "Należy zaznaczyć co najmniej jedno pole.", "unsupportQueryWarning": "Warstwa musi obsługiwać zapytania w celu wyświetlenia w widżecie tabeli atrybutów. Upewnij się, że funkcja zapytania w usłudze jest włączona.", "unsupportQueryLayers": "Ta warstwa musi obsługiwać zapytania w celu wyświetlenia w widżecie tabeli atrybutów. Upewnij się, że funkcja zapytania w usłudze jest włączona.", "fieldName": "Nazwa", "fieldAlias": "Alias", "fieldVisibility": "Widoczność", "fieldActions": "Operacje" });
'use strict'; angular.module('MobcastApp') .controller('Bestsellers_controller', function ($scope, gaEcommerce, Catalogue, $rootScope, $exceptionHandler, $filter, Bookset, SETTINGS, localize, IMPRESSIONS) { $scope.listType = $rootScope.listType || $rootScope.list_type.grid; gaEcommerce.waitFor(1); /** * Loads books for scope display in tabs. * * @param bookType The type of books you wish to load, fiction or non-fiction */ $scope.loadBooks = function(bookType){ var bookSet = 'bookset_' + bookType; var booksetInScope = $scope[bookSet]; var query = angular.extend(booksetInScope.query, $scope.order.selected.query); Bookset.displayBooksById(query, bookSet).then(function(data){ gaEcommerce.addImpressions(IMPRESSIONS.BESTSELLERS + ', ' + bookType, data.items); if (bookType === 'nonfiction') { gaEcommerce.sendPageView(); } if (typeof(booksetInScope.items) !== 'undefined' && booksetInScope.items.length > 0 && data.items.length > 0) { booksetInScope.items = booksetInScope.items.concat(data.items); } else { angular.extend(booksetInScope, data); } }, function(error){ $exceptionHandler({message: error.status, stack: error.config}, error); }); }; // set default option $scope.order = { selected: { query: { order: $rootScope.sort_modes.sequential.code, desc: false } } }; // booksets $scope.bookset_fiction = Bookset.getBookset(); $scope.bookset_fiction.title = localize('_Fiction_'); $scope.bookset_fiction.query.count = $rootScope.bestseller.items_count; $scope.bookset_fiction.listType = $rootScope.list_type.simple; $scope.bookset_fiction.limit = $rootScope.bestseller.limit; $scope.bookset_fiction.refresh = function() { $scope.loadBooks('fiction'); }; // We set up the non-fiction books here, but only actually load them when we need to when the tab is selected. $scope.bookset_nonfiction = Bookset.getBookset(); $scope.bookset_nonfiction.title = localize('_Nonfiction_'); $scope.bookset_nonfiction.query.count = $rootScope.bestseller.items_count; $scope.bookset_nonfiction.listType = $rootScope.list_type.simple; $scope.bookset_nonfiction.limit = $rootScope.bestseller.limit; $scope.bookset_nonfiction.refresh = function() { $scope.loadBooks('nonfiction'); }; $scope.sections = [$scope.bookset_fiction, $scope.bookset_nonfiction]; // retrieve the id of the fiction categories and get all the books for each section Catalogue.get({slug: SETTINGS.CURATED_CATEGORIES.BESTSELLERS_FICTION}, 'categories').then(function (response) { if(response.data.items && response.data.items.length > 0){ $scope.bookset_fiction.query.category = response.data.items[0].id; $scope.loadBooks('fiction', true); } }, function (error) { $exceptionHandler({message: error.status, stack: error.config}, error); } ); // set init flag on show var activeWatch = $scope.$watch('active', function() { if($scope.active && $scope.active.title === $scope.bookset_nonfiction.title){ Catalogue.get({slug: SETTINGS.CURATED_CATEGORIES.BESTSELLERS_NON_FICTION}, 'categories').then(function (response) { if(response.data.items && response.data.items.length > 0){ $scope.bookset_nonfiction.query.category = response.data.items[0].id; $scope.loadBooks('nonfiction'); } }, function (error) { $exceptionHandler({message: error.status, stack: error.config}, error); } ); activeWatch(); } }); // sync listType between tabs $scope.$watch('listType', function(){ angular.forEach($scope.sections, function(section){ section.listType = $scope.listType; }); $rootScope.listType = $scope.listType; }); /** * GA - Track scrolling event when user scrolls more than x number of pixels * @see app/scripts/directives/scroll_directive.js * @use scroll-position="scroll" within the view/template */ var scrollListener = $scope.$watch('scroll', function(){ if($scope.scroll > 20) { $rootScope.reportGA($rootScope.GA.BESTSELLERS_PAGE.USER_SCROLL_ACTION); scrollListener(); // remove watcher } }); });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M14.99 3H6c-.8 0-1.52.48-1.83 1.21L.91 11.82C.06 13.8 1.51 16 3.66 16h5.65l-.95 4.58c-.1.5.05 1.01.41 1.37.29.29.67.43 1.05.43s.77-.15 1.06-.44l5.53-5.54c.37-.37.58-.88.58-1.41V5c0-1.1-.9-2-2-2zm-4.33 16.33.61-2.92.5-2.41H3.66c-.47 0-.72-.28-.83-.45-.11-.17-.27-.51-.08-.95L6 5h8.99v9.99l-4.33 4.34zM21 3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2s2-.9 2-2V5c0-1.1-.9-2-2-2z" }), 'ThumbDownOffAltRounded'); exports.default = _default;
// DATA_TEMPLATE: empty_table oTest.fnStart("sPaginationType"); $(document).ready(function () { /* Check the default */ var oTable = $('#example').dataTable({ "bServerSide": true, "sAjaxSource": "../../../examples/server_side/scripts/server_processing.php" }); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Check two button paging is the default", null, function () { return oSettings.sPaginationType == "two_button"; } ); oTest.fnWaitTest( "Check class is applied", null, function () { return $('#example_paginate').hasClass('paging_two_button'); } ); oTest.fnWaitTest( "Two A elements are in the wrapper", null, function () { return $('#example_paginate a').length == 2; } ); oTest.fnWaitTest( "We have the previous button", null, function () { return document.getElementById('example_previous'); } ); oTest.fnWaitTest( "We have the next button", null, function () { return document.getElementById('example_next'); } ); oTest.fnWaitTest( "Previous button is disabled", null, function () { return $('#example_previous').hasClass('paginate_disabled_previous'); } ); oTest.fnWaitTest( "Next button is enabled", null, function () { return $('#example_next').hasClass('paginate_enabled_next'); } ); /* Don't test paging - that's done by the zero config test script. */ /* Two buttons paging */ var bComplete = false; oTest.fnWaitTest( "Can enabled full numbers paging", function () { oSession.fnRestore(); oTable = $('#example').dataTable({ "bServerSide": true, "sAjaxSource": "../../../examples/server_side/scripts/server_processing.php", "sPaginationType": "full_numbers", "fnInitComplete": function () { setTimeout(function () { bComplete = true; }, 500); } }); oSettings = oTable.fnSettings(); }, function () { if (bComplete) return oSettings.sPaginationType == "full_numbers"; else return false; } ); oTest.fnWaitTest( "Check full numbers class is applied", null, function () { return $('#example_paginate').hasClass('paging_full_numbers'); } ); var nFirst, nPrevious, nNext, nLast; oTest.fnWaitTest( "Jump to last page", function () { nFirst = $('div.dataTables_paginate a.first'); nPrevious = $('div.dataTables_paginate a.previous'); nNext = $('div.dataTables_paginate a.next'); nLast = $('div.dataTables_paginate a.last'); nLast.click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 51 to 57 of 57 entries"; } ); oTest.fnWaitTest( "Go to two pages previous", function () { nPrevious.click(); nPrevious.click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 31 to 40 of 57 entries"; } ); oTest.fnWaitTest( "Next (second last) page", function () { nNext.click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 41 to 50 of 57 entries"; } ); oTest.fnWaitTest( "Jump to first page", function () { nFirst.click(); }, function () { return document.getElementById('example_info').innerHTML == "Showing 1 to 10 of 57 entries"; } ); oTest.fnComplete(); });
/* globals google: true */ import Ember from 'ember'; const { later } = Ember.run; const { on, computed, isArray } = Ember; export default Ember.Mixin.create({ // Stores reference to google DrawingManager instance _drawingManager: null, /** * [selectionsDelay time it takes to remove last selection from the map] * @type {Number} */ selectionsDelay: null, // Default to all supported mode selectionsModes: [ 'marker', 'circle', 'polygon', 'polyline', 'rectangle' ], /** * [_gmapSelectionsModes] * @param {String} [observes `selectionsModes` binding options] * @return {[Array]} [Returns array of matched google OverlayType's] */ _gmapSelectionsModes: computed('selectionsModes.[]', function() { const modes = []; if(isArray(this.get('selectionsModes')) === false) { Ember.Logger.error('`selectionsModes` property expects an array'); } const selectionsModes = this.get('selectionsModes').map((dm) => dm.toLowerCase()); if(selectionsModes.indexOf('marker') > -1) { modes.push(google.maps.drawing.OverlayType.MARKER); } if(selectionsModes.indexOf('circle') > -1) { modes.push(google.maps.drawing.OverlayType.CIRCLE); } if(selectionsModes.indexOf('polygon') > -1) { modes.push(google.maps.drawing.OverlayType.POLYGON); } if(selectionsModes.indexOf('polyline') > -1) { modes.push(google.maps.drawing.OverlayType.POLYLINE); } if(selectionsModes.indexOf('rectangle') > -1) { modes.push(google.maps.drawing.OverlayType.RECTANGLE); } return modes; }), // Default to controls on top selectionsPosition: 'top', /** * [_gmapSelectionsPosition ] * @param {String} [observes `selectionsPosition` binding] * @return {[ControlPosition]} [Returns matching google ControlPosition] */ _gmapSelectionsPosition: computed('selectionsPosition', function() { let pos = 'TOP_CENTER'; if(typeof this.get('selectionsPosition') !== 'string') { Ember.Logger.error('`selectionsPosition` property expects a string'); } switch(Ember.String.dasherize(this.get('selectionsPosition').replace('_', '-')).toLowerCase()) { case 'top-left': pos = 'TOP_LEFT'; break; case 'top-right': pos = 'TOP_RIGHT'; break; case 'left-top': pos = 'LEFT_TOP'; break; case 'right-top': pos = 'RIGHT_TOP'; break; case 'left': pos = 'LEFT_CENTER'; break; case 'left-center': pos = 'LEFT_CENTER'; break; case 'right': pos = 'RIGHT_CENTER'; break; case 'right-center': pos = 'RIGHT_CENTER'; break; case 'left-bottom': pos = 'LEFT_BOTTOM'; break; case 'right-bottom': pos = 'RIGHT_BOTTOM'; break; case 'bottom': pos = 'BOTTOM_CENTER'; break; case 'bottom-center': pos = 'BOTTOM_CENTER'; break; case 'bottom-left': pos = 'BOTTOM_LEFT'; break; case 'bottom-right': pos = 'BOTTOM_RIGHT'; break; } return google.maps.ControlPosition[pos]; }), // Default to no active selection tool selectionsMode: '', /** * [_gmapSelectionsMode] * @param {String} [observes `selectionsMode` binding] * @return {[OverlayType|null]} [Returns matching google OverlayType] */ _gmapSelectionsMode: computed('selectionsMode', function() { let mode = ''; if(typeof this.get('selectionsMode') !== 'string') { Ember.Logger.error('`selectionsMode` property expects a string'); } switch(this.get('selectionsMode').toLowerCase()) { case 'marker': mode = 'MARKER'; break; case 'circle': mode = 'CIRCLE'; break; case 'polygon': mode = 'POLYGON'; break; case 'polyline': mode = 'POLYLINE'; break; case 'rectangle': mode = 'RECTANGLE'; break; } return (mode ? google.maps.drawing.OverlayType[mode] : null); }), // Stores reference to `overlaycomplete` event _selectionsEventOverlayComplete: null, /** * [_initSelections runs once per selections instance instantiation] * [Added via `_validateSelections`] * [Observes ('isMapLoaded', 'selections')] */ _initSelections: function() { const continueSetup = ( this.get('isMapLoaded') && this.get('selections') && this.get('googleMapsSupportsDrawingManager') && !this.get('_drawingManager') ); if(!continueSetup) { return; } // Create DrawingManager Instance and store const drawingManager = new google.maps.drawing.DrawingManager(); this.set('_drawingManager', drawingManager); // Watch for changes to selections configuration and inital sync this.addObserver('_drawManagerOptions', this, '_syncDrawingMangagerOptions'); this._syncDrawingMangagerOptions(); // Add the drawing manager to the map drawingManager.setMap(this.get('map').map); let lastSelection; // Bind selection events const overlayListener = google.maps.event.addListener(drawingManager, 'overlaycomplete', (event) => { // Prohibit simultanious selections if(lastSelection && lastSelection.map) { lastSelection.setMap(null); } lastSelection = event.overlay; if (event.type === google.maps.drawing.OverlayType.MARKER) { this.send('selectionsMarker', event.overlay); } else if (event.type === google.maps.drawing.OverlayType.CIRCLE) { this.send('selectionsCircle', event.overlay); } else if(event.type === google.maps.drawing.OverlayType.RECTANGLE) { this.send('selectionsRectangle', event.overlay); } else if(event.type === google.maps.drawing.OverlayType.POLYGON) { this.send('selectionsPolygon', event.overlay); } else if(event.type === google.maps.drawing.OverlayType.POLYLINE) { this.send('selectionsPolyline', event.overlay); } // Remove the last drawing from map later(() => { event.overlay.setMap(null); }, this.get('selectionsDelay') || 400); }); // create reference to event this.set('_selectionsEventOverlayComplete', overlayListener); // Add listener to sync user selection of map drawing controls this.$().on('click', '.gmnoprint > div', Ember.run.bind(this, this._syncDrawingManagerModeControls)); // Remove observers added during `didInsertElement` this.removeObserver('isMapLoaded', this, '_initSelections'); this.removeObserver('selections', this, '_initSelections'); }, /** * [Return the configuration object for the drawingManager] * @param {[Strings]} [Observes all relevant properties on `selections` config] * @return {[Object]} [Drawing Manager Configuration Object] */ _drawManagerOptions: computed( 'selections', '_gmapSelectionsMode', '_gmapSelectionsModes', '_gmapSelectionsPosition', 'selections.{visible,markerOptions,circleOptions,polygonOptions,polylineOptions,rectangleOptions}', function() { const isVisible = this.get('selections.visible'); const markerOptions = this.get('selections.markerOptions'); const circleOptions = this.get('selections.circleOptions'); const polygonOptions = this.get('selections.polygonOptions'); const polylineOptions = this.get('selections.polylineOptions'); const rectangleOptions = this.get('selections.rectangleOptions'); const options = { drawingMode: this.get('_gmapSelectionsMode'), drawingControl: (typeof isVisible === 'boolean' ? isVisible : true), // Shows or hides draw manager drawingControlOptions: { position: this.get('_gmapSelectionsPosition'), drawingModes: this.get('_gmapSelectionsModes') } }; if(markerOptions) { options.markerOptions = markerOptions; } if(circleOptions) { options.circleOptions = circleOptions; } if(polygonOptions) { options.polygonOptions = polygonOptions; } if(polylineOptions) { options.polylineOptions = polylineOptions; } if(rectangleOptions) { options.rectangleOptions = rectangleOptions; } return options; } ), /** * [_syncDrawingMangagerOptions finally sets the options on the drawManager instance] * [Added via `_initSelections`] * [Observes ('_drawManagerOptions')] */ _syncDrawingMangagerOptions: function() { return this.get('_drawingManager').setOptions(this.get('_drawManagerOptions')); }, /** * [_syncDrawingManagerModeControls get active drawingMode and bind to parent, enforces string type if falsey] */ _syncDrawingManagerModeControls: function() { const mode = this.get('_drawingManager').drawingMode || ''; this.set('selectionsMode', mode); }, /** * [googleMapsSupportsDrawingManager returns a boolean indicating if DrawingManager is supported] * @return {[Boolean]} */ googleMapsSupportsDrawingManager: computed(function() { return ( google.maps && google.maps.drawing && google.maps.drawing.DrawingManager ); }), /** * [_validateSelections determines if selections can instantiate, if so adds init observers] * @param {[String]} )[triggered on element insertion] * @return {[Oberservers]} [if valid adds obersvers to init method] */ _validateSelections: on('didInsertElement', function() { if(!this.get('selections')) { return false; } if(!this.get('googleMapsSupportsDrawingManager')) { throw new Error('g-map component requires the "drawing" library included in `config/environment.js`'); } else { // Enable selections setup this.addObserver('isMapLoaded', this, '_initSelections'); this.addObserver('selections', this, '_initSelections'); } }), /** * [_teardownSelections removes the draw manager from the map, clears up memory, and unbinds events] * @param {[String]} [triggered on element destroy] */ _teardownSelections: on('willDestroyElement', function() { const drawingManager = this.get('_drawingManager'); if(drawingManager) { drawingManager.setMap(null); this.set('drawingManager', null); // Remove overlay complete listener this.get('_selectionsEventOverlayComplete').remove(); this.set('_selectionsEventOverlayComplete', null); // Remove select control sync listener this.$().off('click', '.gmnoprint > div'); } }), actions: { selectionsMarker: function(marker) { this.sendAction('selectionsMarker', { marker, lat: marker.position.lat(), lng: marker.position.lng() }); }, selectionsCircle: function(circle) { this.sendAction('selectionsCircle', { circle, radius: circle.getRadius(), lat: circle.center.lat(), lng: circle.center.lng() }); }, selectionsRectangle: function(rectangle) { const ne = rectangle.bounds.getNorthEast(); const sw = rectangle.bounds.getSouthWest(); this.sendAction('selectionsRectangle', { rectangle, bounds: [ { lat: ne.lat(), lng: ne.lng(), location: 'northeast' }, // Northeast { lat: sw.lat(), lng: sw.lng(), location: 'southwest' } // Southwest ] }); }, selectionsPolygon: function(polygon) { let pathTarget = polygon.latLngs.getArray()[0]; if(typeof pathTarget.getArray === 'function') { pathTarget = pathTarget.getArray(); } this.sendAction('selectionsPolygon', { polygon, coords: pathTarget.map((c) => { return { lat: c.lat(), lng: c.lng() }; }) }); }, selectionsPolyline: function(polyline) { let pathTarget = polyline.latLngs.getArray()[0]; if(typeof pathTarget.getArray === 'function') { pathTarget = pathTarget.getArray(); } this.sendAction('selectionsPolyline', { polyline, coords: pathTarget.map((c) => { return { lat: c.lat(), lng: c.lng() }; }) }); } } });
//>>built define({save:"Salvare"});
version https://git-lfs.github.com/spec/v1 oid sha256:3e054bba755bec7f581c9e2cac4eac5c9b3512a85b0ab6b23000e70080d16227 size 7523
version https://git-lfs.github.com/spec/v1 oid sha256:6da85cedae08e0f9ef218782d3e938f808a5e065d84fe860b8a2093cda083eb0 size 2700
import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { Tracker } from 'meteor/tracker'; import { UploadFS } from 'meteor/jalik:ufs'; import { FileUploadBase } from '../../lib/FileUploadBase'; import { Uploads, Avatars } from '../../../models'; new UploadFS.Store({ collection: Uploads.model, name: 'Uploads', }); new UploadFS.Store({ collection: Avatars.model, name: 'Avatars', }); export const fileUploadHandler = (directive, meta, file) => { const store = UploadFS.getStore(directive); if (store) { return new FileUploadBase(store, meta, file); } console.error('Invalid file store', directive); }; Tracker.autorun(function() { if (Meteor.userId()) { document.cookie = `rc_uid=${ escape(Meteor.userId()) }; path=/`; document.cookie = `rc_token=${ escape(Accounts._storedLoginToken()) }; path=/`; } });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)([/*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M12 11h2v2h-2v2h2v2h-2v2h8V9h-8v2zm4 0h2v2h-2v-2zm0 4h2v2h-2v-2z", opacity: ".3" }, "0"), /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M16 15h2v2h-2zm0-4h2v2h-2zm6-4H12V3H2v18h20V7zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10z" }, "1")], 'BusinessTwoTone'); exports.default = _default;
module.exports = [ { name: 'aqua', hex: '#00FFFF' }, { name: 'aliceblue', hex: '#F0F8FF' }, { name: 'antiquewhite', hex: '#FAEBD7' }, { name: 'black', hex: '#000000' }, { name: 'blue', hex: '#0000FF' }, { name: 'cyan', hex: '#00FFFF' }, { name: 'darkblue', hex: '#00008B' }, { name: 'darkcyan', hex: '#008B8B' }, { name: 'darkgreen', hex: '#006400' }, { name: 'darkturquoise', hex: '#00CED1' }, { name: 'deepskyblue', hex: '#00BFFF' }, { name: 'green', hex: '#008000' }, { name: 'lime', hex: '#00FF00' }, { name: 'mediumblue', hex: '#0000CD' }, { name: 'mediumspringgreen', hex: '#00FA9A' }, { name: 'navy', hex: '#000080' }, { name: 'springgreen', hex: '#00FF7F' }, { name: 'teal', hex: '#008080' }, { name: 'midnightblue', hex: '#191970' }, { name: 'dodgerblue', hex: '#1E90FF' }, { name: 'lightseagreen', hex: '#20B2AA' }, { name: 'forestgreen', hex: '#228B22' }, { name: 'seagreen', hex: '#2E8B57' }, { name: 'darkslategray', hex: '#2F4F4F' }, { name: 'darkslategrey', hex: '#2F4F4F' }, { name: 'limegreen', hex: '#32CD32' }, { name: 'mediumseagreen', hex: '#3CB371' }, { name: 'turquoise', hex: '#40E0D0' }, { name: 'royalblue', hex: '#4169E1' }, { name: 'steelblue', hex: '#4682B4' }, { name: 'darkslateblue', hex: '#483D8B' }, { name: 'mediumturquoise', hex: '#48D1CC' }, { name: 'indigo', hex: '#4B0082' }, { name: 'darkolivegreen', hex: '#556B2F' }, { name: 'cadetblue', hex: '#5F9EA0' }, { name: 'cornflowerblue', hex: '#6495ED' }, { name: 'mediumaquamarine', hex: '#66CDAA' }, { name: 'dimgray', hex: '#696969' }, { name: 'dimgrey', hex: '#696969' }, { name: 'slateblue', hex: '#6A5ACD' }, { name: 'olivedrab', hex: '#6B8E23' }, { name: 'slategray', hex: '#708090' }, { name: 'slategrey', hex: '#708090' }, { name: 'lightslategray', hex: '#778899' }, { name: 'lightslategrey', hex: '#778899' }, { name: 'mediumslateblue', hex: '#7B68EE' }, { name: 'lawngreen', hex: '#7CFC00' }, { name: 'aquamarine', hex: '#7FFFD4' }, { name: 'chartreuse', hex: '#7FFF00' }, { name: 'gray', hex: '#808080' }, { name: 'grey', hex: '#808080' }, { name: 'maroon', hex: '#800000' }, { name: 'olive', hex: '#808000' }, { name: 'purple', hex: '#800080' }, { name: 'lightskyblue', hex: '#87CEFA' }, { name: 'skyblue', hex: '#87CEEB' }, { name: 'blueviolet', hex: '#8A2BE2' }, { name: 'darkmagenta', hex: '#8B008B' }, { name: 'darkred', hex: '#8B0000' }, { name: 'saddlebrown', hex: '#8B4513' }, { name: 'darkseagreen', hex: '#8FBC8F' }, { name: 'lightgreen', hex: '#90EE90' }, { name: 'mediumpurple', hex: '#9370DB' }, { name: 'darkviolet', hex: '#9400D3' }, { name: 'palegreen', hex: '#98FB98' }, { name: 'darkorchid', hex: '#9932CC' }, { name: 'yellowgreen', hex: '#9ACD32' }, { name: 'sienna', hex: '#A0522D' }, { name: 'brown', hex: '#A52A2A' }, { name: 'darkgray', hex: '#A9A9A9' }, { name: 'darkgrey', hex: '#A9A9A9' }, { name: 'greenyellow', hex: '#ADFF2F' }, { name: 'lightblue', hex: '#ADD8E6' }, { name: 'paleturquoise', hex: '#AFEEEE' }, { name: 'lightsteelblue', hex: '#B0C4DE' }, { name: 'powderblue', hex: '#B0E0E6' }, { name: 'firebrick', hex: '#B22222' }, { name: 'darkgoldenrod', hex: '#B8860B' }, { name: 'mediumorchid', hex: '#BA55D3' }, { name: 'rosybrown', hex: '#BC8F8F' }, { name: 'darkkhaki', hex: '#BDB76B' }, { name: 'silver', hex: '#C0C0C0' }, { name: 'mediumvioletred', hex: '#C71585' }, { name: 'indianred', hex: '#CD5C5C' }, { name: 'peru', hex: '#CD853F' }, { name: 'chocolate', hex: '#D2691E' }, { name: 'tan', hex: '#D2B48C' }, { name: 'lightgray', hex: '#D3D3D3' }, { name: 'lightgrey', hex: '#D3D3D3' }, { name: 'thistle', hex: '#D8BFD8' }, { name: 'goldenrod', hex: '#DAA520' }, { name: 'orchid', hex: '#DA70D6' }, { name: 'palevioletred', hex: '#DB7093' }, { name: 'crimson', hex: '#DC143C' }, { name: 'gainsboro', hex: '#DCDCDC' }, { name: 'plum', hex: '#DDA0DD' }, { name: 'burlywood', hex: '#DEB887' }, { name: 'lightcyan', hex: '#E0FFFF' }, { name: 'lavender', hex: '#E6E6FA' }, { name: 'darksalmon', hex: '#E9967A' }, { name: 'palegoldenrod', hex: '#EEE8AA' }, { name: 'violet', hex: '#EE82EE' }, { name: 'azure', hex: '#F0FFFF' }, { name: 'honeydew', hex: '#F0FFF0' }, { name: 'khaki', hex: '#F0E68C' }, { name: 'lightcoral', hex: '#F08080' }, { name: 'sandybrown', hex: '#F4A460' }, { name: 'beige', hex: '#F5F5DC' }, { name: 'mintcream', hex: '#F5FFFA' }, { name: 'wheat', hex: '#F5DEB3' }, { name: 'whitesmoke', hex: '#F5F5F5' }, { name: 'ghostwhite', hex: '#F8F8FF' }, { name: 'lightgoldenrodyellow', hex: '#FAFAD2' }, { name: 'linen', hex: '#FAF0E6' }, { name: 'salmon', hex: '#FA8072' }, { name: 'oldlace', hex: '#FDF5E6' }, { name: 'bisque', hex: '#FFE4C4' }, { name: 'blanchedalmond', hex: '#FFEBCD' }, { name: 'coral', hex: '#FF7F50' }, { name: 'cornsilk', hex: '#FFF8DC' }, { name: 'darkorange', hex: '#FF8C00' }, { name: 'deeppink', hex: '#FF1493' }, { name: 'floralwhite', hex: '#FFFAF0' }, { name: 'fuchsia', hex: '#FF00FF' }, { name: 'gold', hex: '#FFD700' }, { name: 'hotpink', hex: '#FF69B4' }, { name: 'ivory', hex: '#FFFFF0' }, { name: 'lavenderblush', hex: '#FFF0F5' }, { name: 'lemonchiffon', hex: '#FFFACD' }, { name: 'lightpink', hex: '#FFB6C1' }, { name: 'lightsalmon', hex: '#FFA07A' }, { name: 'lightyellow', hex: '#FFFFE0' }, { name: 'magenta', hex: '#FF00FF' }, { name: 'mistyrose', hex: '#FFE4E1' }, { name: 'moccasin', hex: '#FFE4B5' }, { name: 'navajowhite', hex: '#FFDEAD' }, { name: 'orange', hex: '#FFA500' }, { name: 'orangered', hex: '#FF4500' }, { name: 'papayawhip', hex: '#FFEFD5' }, { name: 'peachpuff', hex: '#FFDAB9' }, { name: 'pink', hex: '#FFC0CB' }, { name: 'red', hex: '#FF0000' }, { name: 'seashell', hex: '#FFF5EE' }, { name: 'snow', hex: '#FFFAFA' }, { name: 'tomato', hex: '#FF6347' }, { name: 'white', hex: '#FFFFFF' }, { name: 'yellow', hex: '#FFFF00' } ]
'use strict'; // determine native module name let nativeModuleName = null; if (process.platform === 'win32') { nativeModuleName = `${process.platform}-${process.arch}`; } // find module let native = null; try { const _native = require(`./${nativeModuleName}`); native = _native; } catch (e) {} // assign mock object if (native === null) { native = { fetchFileIconAsPng: (path, cb) => { cb([]); }, saveFocus: () => {}, restoreFocus: () => {} }; } function fetchFileIconAsPng(filePath, callback) { try { native.fetchFileIconAsPng(filePath, callback); } catch (e) { console.log(e); } } function saveFocus() { native.saveFocus(); } function restoreFocus() { native.restoreFocus(); } module.exports = { fetchFileIconAsPng, saveFocus, restoreFocus };
'use strict'; var loginMod = angular.module('MMI.login', ['MMI.ajaxService', 'ui.router', 'ngStorage']); loginMod.controller('LoginCtrl', ['$scope', 'ajaxRequest', '$state', '$localStorage', function ($scope, ajaxRequest, $state, $localStorage) { $scope.data = { username: '', password: '' }; if ($localStorage.user) { $state.go('main.dashboard'); } $scope.login = function () { console.log($scope.data); //can do better validation, but not doing it due to time constaint if ($scope.data.username.length > 0 && $scope.data.password.length > 0) { var ajax = ajaxRequest.send('login', $scope.data, true); ajax.then(function (data) { $localStorage.user = $scope.data.username; $state.go('main.dashboard'); //its not returning proper response, thats why doing like this }, function (data) { alert(data.error); }); } else { alert('Please fill up form!'); } }; }]);
'use strict' const path = require('path') const fs = require('fs-extra') const chai = require('chai') const expect = chai.expect const sinonChai = require('sinon-chai') chai.use(sinonChai) chai.should() const AccountTemplate = require('../../lib/models/account-template') const templatePath = path.join(__dirname, '../../default-templates/new-account') const accountPath = path.join(__dirname, '../resources/new-account') describe('AccountTemplate', () => { beforeEach(() => { fs.removeSync(accountPath) }) afterEach(() => { fs.removeSync(accountPath) }) describe('copy()', () => { it('should copy a directory', () => { return AccountTemplate.copyTemplateDir(templatePath, accountPath) .then(() => { let rootAcl = fs.readFileSync(path.join(accountPath, '.acl'), 'utf8') expect(rootAcl).to.exist }) }) }) describe('processAccount()', () => { it('should process all the files in an account', () => { let substitutions = { webId: 'https://alice.example.com/#me', email: 'alice@example.com', name: 'Alice Q.' } let template = new AccountTemplate({ substitutions }) return AccountTemplate.copyTemplateDir(templatePath, accountPath) .then(() => { return template.processAccount(accountPath) }) .then(() => { let profile = fs.readFileSync(path.join(accountPath, '/profile/card'), 'utf8') expect(profile).to.include('"Alice Q."') let rootAcl = fs.readFileSync(path.join(accountPath, '.acl'), 'utf8') expect(rootAcl).to.include('<mailto:alice@') expect(rootAcl).to.include('<https://alice.example.com/#me>') }) }) }) })
/** * bootstrap-multiselect.js * https://github.com/davidstutz/bootstrap-multiselect * * Copyright 2012, 2013 David Stutz * * Dual licensed under the BSD-3-Clause and the Apache License, Version 2.0. */ !function($) { "use strict";// jshint ;_; if (typeof ko !== 'undefined' && ko.bindingHandlers && !ko.bindingHandlers.multiselect) { ko.bindingHandlers.multiselect = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {}, update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var config = ko.utils.unwrapObservable(valueAccessor()); var selectOptions = allBindingsAccessor().options; var ms = $(element).data('multiselect'); if (!ms) { $(element).multiselect(config); } else { ms.updateOriginalOptions(); if (selectOptions && selectOptions().length !== ms.originalOptions.length) { $(element).multiselect('rebuild'); } } } }; } /** * Constructor to create a new multiselect using the given select. * * @param {jQuery} select * @param {Object} options * @returns {Multiselect} */ function Multiselect(select, options) { this.options = this.mergeOptions(options); this.$select = $(select); // Initialization. // We have to clone to create a new reference. this.originalOptions = this.$select.clone()[0].options; this.query = ''; this.searchTimeout = null; this.options.multiple = this.$select.attr('multiple') === "multiple"; this.options.onChange = $.proxy(this.options.onChange, this); this.options.onDropdownShow = $.proxy(this.options.onDropdownShow, this); this.options.onDropdownHide = $.proxy(this.options.onDropdownHide, this); // Build select all if enabled. this.buildContainer(); this.buildButton(); this.buildSelectAll(); this.buildDropdown(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); this.$select.hide().after(this.$container); }; Multiselect.prototype = { defaults: { /** * Default text function will either print 'None selected' in case no * option is selected or a list of the selected options up to a length of 3 selected options. * * @param {jQuery} options * @param {jQuery} select * @returns {String} */ buttonText: function(options, select) { if (options.length === 0) { return this.nonSelectedText + ' <b class="caret"></b>'; } else { if (options.length > this.numberDisplayed) { return options.length + ' ' + this.nSelectedText + ' <b class="caret"></b>'; } else { var selected = ''; options.each(function() { var label = ($(this).attr('label') !== undefined) ? $(this).attr('label') : $(this).html(); selected += label + ', '; }); return selected.substr(0, selected.length - 2) + ' <b class="caret"></b>'; } } }, /** * Updates the title of the button similar to the buttonText function. * @param {jQuery} options * @param {jQuery} select * @returns {@exp;selected@call;substr} */ buttonTitle: function(options, select) { if (options.length === 0) { return this.nonSelectedText; } else { var selected = ''; options.each(function () { selected += $(this).text() + ', '; }); return selected.substr(0, selected.length - 2); } }, /** * Create a label. * * @param {jQuery} element * @returns {String} */ label: function(element){ return $(element).attr('label') || $(element).html(); }, /** * Triggered on change of the multiselect. * Not triggered when selecting/deselecting options manually. * * @param {jQuery} option * @param {Boolean} checked */ onChange : function(option, checked) { }, /** * Triggered when the dropdown is shown. * * @param {jQuery} event */ onDropdownShow: function(event) { }, /** * Triggered when the dropdown is hidden. * * @param {jQuery} event */ onDropdownHide: function(event) { }, buttonClass: 'btn btn-default', dropRight: false, selectedClass: 'active', buttonWidth: 'auto', buttonContainer: '<div class="btn-group" />', // Maximum height of the dropdown menu. // If maximum height is exceeded a scrollbar will be displayed. maxHeight: false, includeSelectAllOption: false, selectAllText: ' Select all', selectAllValue: 'multiselect-all', enableFiltering: false, enableCaseInsensitiveFiltering: false, filterPlaceholder: 'Search', // possible options: 'text', 'value', 'both' filterBehavior: 'text', preventInputChangeEvent: false, nonSelectedText: 'None selected', nSelectedText: 'selected', numberDisplayed: 3 }, templates: { button: '<button type="button" class="multiselect dropdown-toggle" data-toggle="dropdown"></button>', ul: '<ul class="multiselect-container dropdown-menu"></ul>', filter: '<div class="input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-search"></i></span><input class="form-control multiselect-search" type="text"></div>', li: '<li><a href="javascript:void(0);"><label></label></a></li>', divider: '<li class="divider"></li>', liGroup: '<li><label class="multiselect-group"></label></li>' }, constructor: Multiselect, /** * Builds the container of the multiselect. */ buildContainer: function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); }, /** * Builds the button of the multiselect. */ buildButton: function() { this.$button = $(this.templates.button).addClass(this.options.buttonClass); // Adopt active state. if (this.$select.prop('disabled')) { this.disable(); } else { this.enable(); } // Manually add button width if set. if (this.options.buttonWidth && this.options.buttonWidth != 'auto') { this.$button.css({ 'width' : this.options.buttonWidth }); } // Keep the tab index from the select. var tabindex = this.$select.attr('tabindex'); if (tabindex) { this.$button.attr('tabindex', tabindex); } this.$container.prepend(this.$button); }, /** * Builds the ul representing the dropdown menu. */ buildDropdown: function() { // Build ul. this.$ul = $(this.templates.ul); if (this.options.dropRight) { this.$ul.addClass('dropdown-menu-right'); } // Set max height of dropdown menu to activate auto scrollbar. if (this.options.maxHeight) { // TODO: Add a class for this option to move the css declarations. this.$ul.css({ 'max-height': this.options.maxHeight + 'px', 'overflow-y': 'auto', 'overflow-x': 'hidden' }); } this.$container.append(this.$ul); }, /** * Build the dropdown options and binds all nessecary events. * Uses createDivider and createOptionValue to create the necessary options. */ buildDropdownOptions: function() { this.$select.children().each($.proxy(function(index, element) { // Support optgroups and options without a group simultaneously. var tag = $(element).prop('tagName') .toLowerCase(); if (tag === 'optgroup') { this.createOptgroup(element); } else if (tag === 'option') { if ($(element).data('role') === 'divider') { this.createDivider(); } else { this.createOptionValue(element); } } // Other illegal tags will be ignored. }, this)); // Bind the change event on the dropdown elements. $('li input', this.$ul).on('change', $.proxy(function(event) { var checked = $(event.target).prop('checked') || false; var isSelectAllOption = $(event.target).val() === this.options.selectAllValue; // Apply or unapply the configured selected class. if (this.options.selectedClass) { if (checked) { $(event.target).parents('li') .addClass(this.options.selectedClass); } else { $(event.target).parents('li') .removeClass(this.options.selectedClass); } } // Get the corresponding option. var value = $(event.target).val(); var $option = this.getOptionByValue(value); var $optionsNotThis = $('option', this.$select).not($option); var $checkboxesNotThis = $('input', this.$container).not($(event.target)); if (isSelectAllOption) { if (this.$select[0][0].value === this.options.selectAllValue) { var values = []; var options = $('option[value!="' + this.options.selectAllValue + '"]', this.$select); for (var i = 0; i < options.length; i++) { // Additionally check whether the option is visible within the dropcown. if (options[i].value !== this.options.selectAllValue && this.getInputByValue(options[i].value).is(':visible')) { values.push(options[i].value); } } if (checked) { this.select(values); } else { this.deselect(values); } } } if (checked) { $option.prop('selected', true); if (this.options.multiple) { // Simply select additional option. $option.prop('selected', true); } else { // Unselect all other options and corresponding checkboxes. if (this.options.selectedClass) { $($checkboxesNotThis).parents('li').removeClass(this.options.selectedClass); } $($checkboxesNotThis).prop('checked', false); $optionsNotThis.prop('selected', false); // It's a single selection, so close. this.$button.click(); } if (this.options.selectedClass === "active") { $optionsNotThis.parents("a").css("outline", ""); } } else { // Unselect option. $option.prop('selected', false); } this.$select.change(); this.options.onChange($option, checked); this.updateButtonText(); this.updateSelectAll(); if(this.options.preventInputChangeEvent) { return false; } }, this)); $('li a', this.$ul).on('touchstart click', function(event) { event.stopPropagation(); if (event.shiftKey) { var checked = $(event.target).prop('checked') || false; if (checked) { var prev = $(event.target).parents('li:last') .siblings('li[class="active"]:first'); var currentIdx = $(event.target).parents('li') .index(); var prevIdx = prev.index(); if (currentIdx > prevIdx) { $(event.target).parents("li:last").prevUntil(prev).each( function() { $(this).find("input:first").prop("checked", true) .trigger("change"); } ); } else { $(event.target).parents("li:last").nextUntil(prev).each( function() { $(this).find("input:first").prop("checked", true) .trigger("change"); } ); } } } $(event.target).blur(); }); // Keyboard support. this.$container.on('keydown', $.proxy(function(event) { if ($('input[type="text"]', this.$container).is(':focus')) { return; } if ((event.keyCode === 9 || event.keyCode === 27) && this.$container.hasClass('open')) { // Close on tab or escape. this.$button.click(); } else { var $items = $(this.$container).find("li:not(.divider):visible a"); if (!$items.length) { return; } var index = $items.index($items.filter(':focus')); // Navigation up. if (event.keyCode === 38 && index > 0) { index--; } // Navigate down. else if (event.keyCode === 40 && index < $items.length - 1) { index++; } else if (!~index) { index = 0; } var $current = $items.eq(index); $current.focus(); if (event.keyCode === 32 || event.keyCode === 13) { var $checkbox = $current.find('input'); $checkbox.prop("checked", !$checkbox.prop("checked")); $checkbox.change(); } event.stopPropagation(); event.preventDefault(); } }, this)); }, /** * Create an option using the given select option. * * @param {jQuery} element */ createOptionValue: function(element) { if ($(element).is(':selected')) { $(element).prop('selected', true); } // Support the label attribute on options. var label = this.options.label(element); var value = $(element).val(); var inputType = this.options.multiple ? "checkbox" : "radio"; var $li = $(this.templates.li); $('label', $li).addClass(inputType); $('label', $li).append('<input type="' + inputType + '" />'); var selected = $(element).prop('selected') || false; var $checkbox = $('input', $li); $checkbox.val(value); if (value === this.options.selectAllValue) { $checkbox.parent().parent() .addClass('multiselect-all'); } $('label', $li).append(" " + label); this.$ul.append($li); if ($(element).is(':disabled')) { $checkbox.attr('disabled', 'disabled') .prop('disabled', true) .parents('li') .addClass('disabled'); } $checkbox.prop('checked', selected); if (selected && this.options.selectedClass) { $checkbox.parents('li') .addClass(this.options.selectedClass); } }, /** * Creates a divider using the given select option. * * @param {jQuery} element */ createDivider: function(element) { var $divider = $(this.templates.divider); this.$ul.append($divider); }, /** * Creates an optgroup. * * @param {jQuery} group */ createOptgroup: function(group) { var groupName = $(group).prop('label'); // Add a header for the group. var $li = $(this.templates.liGroup); $('label', $li).text(groupName); this.$ul.append($li); // Add the options of the group. $('option', group).each($.proxy(function(index, element) { this.createOptionValue(element); }, this)); }, /** * Build the selct all. * Checks if a select all ahs already been created. */ buildSelectAll: function() { var alreadyHasSelectAll = this.hasSelectAll(); // If options.includeSelectAllOption === true, add the include all checkbox. if (this.options.includeSelectAllOption && this.options.multiple && !alreadyHasSelectAll) { this.$select.prepend('<option value="' + this.options.selectAllValue + '">' + this.options.selectAllText + '</option>'); } }, /** * Builds the filter. */ buildFilter: function() { // Build filter if filtering OR case insensitive filtering is enabled and the number of options exceeds (or equals) enableFilterLength. if (this.options.enableFiltering || this.options.enableCaseInsensitiveFiltering) { var enableFilterLength = Math.max(this.options.enableFiltering, this.options.enableCaseInsensitiveFiltering); if (this.$select.find('option').length >= enableFilterLength) { this.$filter = $(this.templates.filter); $('input', this.$filter).attr('placeholder', this.options.filterPlaceholder); this.$ul.prepend(this.$filter); this.$filter.val(this.query).on('click', function(event) { event.stopPropagation(); }).on('input keydown', $.proxy(function(event) { // This is useful to catch "keydown" events after the browser has updated the control. clearTimeout(this.searchTimeout); this.searchTimeout = this.asyncFunction($.proxy(function() { if (this.query !== event.target.value) { this.query = event.target.value; $.each($('li', this.$ul), $.proxy(function(index, element) { var value = $('input', element).val(); var text = $('label', element).text(); if (value !== this.options.selectAllValue && text) { // by default lets assume that element is not // interesting for this search var showElement = false; var filterCandidate = ''; if ((this.options.filterBehavior === 'text' || this.options.filterBehavior === 'both')) { filterCandidate = text; } if ((this.options.filterBehavior === 'value' || this.options.filterBehavior === 'both')) { filterCandidate = value; } if (this.options.enableCaseInsensitiveFiltering && filterCandidate.toLowerCase().indexOf(this.query.toLowerCase()) > -1) { showElement = true; } else if (filterCandidate.indexOf(this.query) > -1) { showElement = true; } if (showElement) { $(element).show(); } else { $(element).hide(); } } }, this)); } // TODO: check whether select all option needs to be updated. }, this), 300, this); }, this)); } } }, /** * Unbinds the whole plugin. */ destroy: function() { this.$container.remove(); this.$select.show(); }, /** * Refreshs the multiselect based on the selected options of the select. */ refresh: function() { $('option', this.$select).each($.proxy(function(index, element) { var $input = $('li input', this.$ul).filter(function() { return $(this).val() === $(element).val(); }); if ($(element).is(':selected')) { $input.prop('checked', true); if (this.options.selectedClass) { $input.parents('li') .addClass(this.options.selectedClass); } } else { $input.prop('checked', false); if (this.options.selectedClass) { $input.parents('li') .removeClass(this.options.selectedClass); } } if ($(element).is(":disabled")) { $input.attr('disabled', 'disabled') .prop('disabled', true) .parents('li') .addClass('disabled'); } else { $input.prop('disabled', false) .parents('li') .removeClass('disabled'); } }, this)); this.updateButtonText(); this.updateSelectAll(); }, /** * Select all options of the given values. * * @param {Array} selectValues */ select: function(selectValues) { if(selectValues && !$.isArray(selectValues)) { selectValues = [selectValues]; } for (var i = 0; i < selectValues.length; i++) { var value = selectValues[i]; var $option = this.getOptionByValue(value); var $checkbox = this.getInputByValue(value); if (this.options.selectedClass) { $checkbox.parents('li') .addClass(this.options.selectedClass); } $checkbox.prop('checked', true); $option.prop('selected', true); } this.updateButtonText(); }, /** * Deselects all options of the given values. * * @param {Array} deselectValues */ deselect: function(deselectValues) { if(deselectValues && !$.isArray(deselectValues)) { deselectValues = [deselectValues]; } for (var i = 0; i < deselectValues.length; i++) { var value = deselectValues[i]; var $option = this.getOptionByValue(value); var $checkbox = this.getInputByValue(value); if (this.options.selectedClass) { $checkbox.parents('li') .removeClass(this.options.selectedClass); } $checkbox.prop('checked', false); $option.prop('selected', false); } this.updateButtonText(); }, /** * Rebuild the plugin. * Rebuilds the dropdown, the filter and the select all option. */ rebuild: function() { this.$ul.html(''); // Remove select all option in select. $('option[value="' + this.options.selectAllValue + '"]', this.$select).remove(); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); }, /** * The provided data will be used to build the dropdown. * * @param {Array} dataprovider */ dataprovider: function(dataprovider) { var optionDOM = ""; dataprovider.forEach(function (option) { optionDOM += '<option value="' + option.value + '">' + option.label + '</option>'; }); this.$select.html(optionDOM); this.rebuild(); }, /** * Enable the multiselect. */ enable: function() { this.$select.prop('disabled', false); this.$button.prop('disabled', false) .removeClass('disabled'); }, /** * Disable the multiselect. */ disable: function() { this.$select.prop('disabled', true); this.$button.prop('disabled', true) .addClass('disabled'); }, /** * Set the options. * * @param {Array} options */ setOptions: function(options) { this.options = this.mergeOptions(options); }, /** * Merges the given options with the default options. * * @param {Array} options * @returns {Array} */ mergeOptions: function(options) { return $.extend({}, this.defaults, options); }, /** * Checks whether a select all option is present. * * @returns {Boolean} */ hasSelectAll: function() { return this.$select[0][0] ? this.$select[0][0].value === this.options.selectAllValue : false; }, /** * Updates the select all option based on the currently selected options. */ updateSelectAll: function() { if (this.hasSelectAll()) { var selected = this.getSelected(); if (selected.length === $('option', this.$select).length - 1) { this.select(this.options.selectAllValue); } else { this.deselect(this.options.selectAllValue); } } }, /** * Update the button text and its title base don the currenty selected options. */ updateButtonText: function() { var options = this.getSelected(); // First update the displayed button text. $('button', this.$container).html(this.options.buttonText(options, this.$select)); // Now update the title attribute of the button. $('button', this.$container).attr('title', this.options.buttonTitle(options, this.$select)); }, /** * Get all selected options. * * @returns {jQUery} */ getSelected: function() { return $('option[value!="' + this.options.selectAllValue + '"]:selected', this.$select).filter(function() { return $(this).prop('selected'); }); }, /** * Gets a select option by its value. * * @param {String} value * @returns {jQuery} */ getOptionByValue: function(value) { return $('option', this.$select).filter(function() { return $(this).val() === value; }); }, /** * Get the input (radio/checkbox) by its value. * * @param {String} value * @returns {jQuery} */ getInputByValue: function(value) { return $('li input', this.$ul).filter(function() { return $(this).val() === value; }); }, /** * Used for knockout integration. */ updateOriginalOptions: function() { this.originalOptions = this.$select.clone()[0].options; }, asyncFunction: function(callback, timeout, self) { var args = Array.prototype.slice.call(arguments, 3); return setTimeout(function() { callback.apply(self || window, args); }, timeout); } }; $.fn.multiselect = function(option, parameter) { return this.each(function() { var data = $(this).data('multiselect'); var options = typeof option === 'object' && option; // Initialize the multiselect. if (!data) { $(this).data('multiselect', ( data = new Multiselect(this, options))); } // Call multiselect method. if (typeof option === 'string') { data[option](parameter); } }); }; $.fn.multiselect.Constructor = Multiselect; $(function() { $("select[data-role=multiselect]").multiselect(); }); }(window.jQuery);
module.exports={A:{A:{"1":"B","2":"H D G E A JB"},B:{"1":"1 C p J L N I"},C:{"1":"0 2 3 4 5 6 7 8 9 I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z AB CB DB","2":"1 eB EB F K H D G E A B C p J L N cB WB"},D:{"1":"0 1 2 3 4 5 6 7 8 9 F K H D G E A B C p J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z AB CB DB QB gB KB IB LB MB NB OB"},E:{"1":"F K H D G E A B C PB HB RB SB TB UB VB c XB"},F:{"1":"0 4 C J L N I O P Q R S T U V W X Y Z a b d e f g h i j k l m n o M q r s t u v w x y z dB BB","2":"E B YB ZB aB bB c FB"},G:{"1":"G HB fB GB hB iB jB kB lB mB nB oB pB qB rB"},H:{"1":"sB"},I:{"1":"3 EB F tB uB vB wB GB xB yB"},J:{"1":"D A"},K:{"1":"C M BB","2":"A B c FB"},L:{"1":"IB"},M:{"1":"2"},N:{"1":"B","2":"A"},O:{"1":"zB"},P:{"1":"F K 0B 1B"},Q:{"1":"2B"},R:{"1":"3B"}},B:5,C:"Window.devicePixelRatio"};
if (typeof exports === 'undefined') { exports = {}; } exports.config = { "name": "addImgcom", "desc": "新增图片组件", // 线上地址 "url": "http://xxx/addImgcom", // 日常地址 "urlDaily": "http://xxxx/addImgcom", // 预发地址 "urlPrepub": "http://example.com/addImgcom", // 支持的 Method 集合 "method": ['POST'] }; exports.request ={ pageId:'1332edf', //关联 pageid imgcom:ImgComSchema //db的imgcom表; } ; exports.response = { "success": true, // 标记成功 "model": ImgComSchema }; exports.responseError = { "success": false, // 标记失败 "model": { "error": "Error message" } };
'use strict'; const React = require('react'); const classnames = require('classnames'); const baseClasses = { 'mdl-textfield__error': true, }; class TextFieldError extends React.Component { render() { const { children, className, } = this.props; const classes = classnames(baseClasses, className); return ( <span {...this.props} className={classes}> {children} </span> ); } } TextFieldError.propTypes = { className: React.PropTypes.string, children: React.PropTypes.object, }; module.exports = TextFieldError;
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 11.8.3-4 description: > 11.8.3 Less-than-or-equal Operator - Partial left to right order enforced when using Less-than-or-equal operator: toString <= toString includes: [runTestCase.js] ---*/ function testcase() { var accessed = false; var obj1 = { toString: function () { accessed = true; return 3; } }; var obj2 = { toString: function () { if (accessed === true) { return 4; } else { return 2; } } }; return (obj1 <= obj2); } runTestCase(testcase);
/** * funnyText.js 0.3 Beta * https://github.com/alvarotrigo/funnyText.js * MIT licensed * * Copyright (C) 2013 alvarotrigo.com - A project by Alvaro Trigo */ (function($){ $.fn.funnyText = function(options){ // Create some defaults, extending them with any options that were provided options = $.extend({ 'speed': 700, 'borderColor': 'black', 'activeColor': 'white', 'color': 'black', 'fontSize': '7em', 'direction': 'both' }, options); var that = $(this); that.addClass('funnyText'); var original = $(this); var characters = $.trim(original.text()).split(''); var positionsY = ['top', 'bottom']; var positionsX = ['left', 'right']; var activePositionX, activePositionY, normalPositionX, normalPositionY; var previousPosition; //removing the original text original.html(''); //append the CSS styles var style = $('<style>'+that.selector +'.funnyText span.active { color: ' + options.activeColor + '; text-shadow: -1px 0 '+options.borderColor+', 0 1px '+options.borderColor+', 1px 0 '+options.borderColor+', 0 -1px '+options.borderColor+';} '+that.selector +'.funnyText span{color: ' + options.color +'; font-size:' + options.fontSize + ';}</style>') $('html > head').append(style); //for each character for (var i = 0; i < characters.length; i++){ normalPositionY = positionsY[getRandom(0, 100) % 2]; normalPositionX = positionsX[getRandom(0, 100) % 2]; if(characters[i] == ' '){ characters[i] = '&nbsp;'; } var visibleChar = '<span class="normal ' + normalPositionY + ' ' + normalPositionX + '">' + characters[i] + '</span>'; //avoid repeating the same values two consecutive letters do{ activePositionXY = getNewPosition(normalPositionX, normalPositionY); }while(activePositionXY == previousPosition && options.direction == 'both'); previousPosition = activePositionXY; var activeChar = '<span class="active ' + activePositionXY + '">' + characters[i] + '</span>'; var newChar = '<div class="charWrap">' + visibleChar + activeChar + '</div>'; original.append(newChar); }; //setting the width and height of each character to its wrapper that.find('.charWrap').each(function (){ var sizeX = $(this).find('span').width(); var sizeY = $(this).find('span').height(); $(this).css({ 'width': sizeX * 2 + 'px', 'height': sizeY * 2 + 'px' }); //adjusting the wrappers positions setMargin($(this)); //creating the "viewport" for each character. $(this).wrap('<div class="character" style="width:' + sizeX + 'px; height: ' + sizeY + 'px"></div>'); }); /** * Returnsn a random number between two values. */ function getRandom(from, to){ return from + Math.floor(Math.random() * (to +1)); } /** * Gets a new position for the active character in a way it can be scrolled * vertically or horizontally from the position of the original character. * (from top left to botom right wouldn't work, for example) */ function getNewPosition(x, y){ var result; if((getRandom(0, 100) % 2 && options.direction == 'both') || options.direction == 'horizontal') { if(x == "right" && y == "top"){ result = "left top moveLeft"; } else if(x == "right" && y == "bottom"){ result = "left bottom moveLeft"; } else if(x == "left" && y == "top"){ result = "right top moveRight"; } else if(x == "left" && y == "bottom"){ result = "right bottom moveRight"; } }else{ if(x == "right" && y == "top"){ result = "right bottom moveDown"; } else if(x == "right" && y == "bottom"){ result = "right top moveUp"; } else if(x == "left" && y == "top"){ result = "left bottom moveDown"; } else if(x == "left" && y == "bottom"){ result = "left top moveUp"; } } return result; } /** * Sets the margin for the characters container depending on the position * of the characters to show. */ function setMargin(obj){ if(obj.find('.normal').hasClass('bottom')){ obj.css('top', '-' + obj.find('.normal').height() + 'px'); } if(obj.find('.normal').hasClass('right')){ obj.css('left', '-' + obj.find('.normal').width() + 'px'); } } //random movement for the characters of the title setInterval(function (){ var randomTime = getRandom(2, 6); var previousNum = ''; do{ var num = getRandom(0, characters.length - 1); }while(num === previousNum); previousNum = num; setTimer(that.find('.charWrap').eq(num), randomTime); }, 1 * options.speed); /** * Sets a timer for a given character for a given time. */ function setTimer(character, time){ setTimeout(function (){ moveCharacter(character); }, time * options.speed); } $('.charWrap').hover(function (){ if(!$(this).hasClass('moved')){ moveCharacter($(this)); } }); /** * Moves a character to the destination position. * Once reached, it will add a class "moved" as an status indicator. */ function moveCharacter(characterWrap){ var sizeY = characterWrap.height() / 2; var sizeX = characterWrap.width() / 2; var character = characterWrap.find('.active'); if(supportTransitions()){ if(character.hasClass('moveRight')){ if(!characterWrap.hasClass('moved')){ characterWrap.css('left', '-' + sizeX + 'px'); }else{ characterWrap.css('left', '0px'); } } else if(character.hasClass('moveLeft')){ if(!characterWrap.hasClass('moved')){ characterWrap.css('left', '0px'); }else{ characterWrap.css('left', '-' + sizeX + 'px'); } } else if(character.hasClass('moveUp')){ if(!characterWrap.hasClass('moved')){ characterWrap.css('top', '0px'); }else{ characterWrap.css('top', '-' + sizeY + 'px'); } } else if(character.hasClass('moveDown')){ if(!characterWrap.hasClass('moved')){ characterWrap.css('bottom', sizeY + 'px'); }else{ characterWrap.css('bottom', '0px'); } } } //jquery fallback else{ if(character.hasClass('moveRight')){ if(!characterWrap.hasClass('moved')){ characterWrap.animate({ 'left': '-' + sizeX + 'px' }, 400); }else{ characterWrap.animate({ 'left': '0px' },400); } } else if(character.hasClass('moveLeft')){ if(!characterWrap.hasClass('moved')){ characterWrap.animate({ 'left': '0px' },400); }else{ characterWrap.animate({ 'left' : '-' + sizeX + 'px' },400); } } else if(character.hasClass('moveUp')){ if(!characterWrap.hasClass('moved')){ characterWrap.animate({ 'top': '0px' }, 400); }else{ characterWrap.animate({ 'top': '-' + sizeY + 'px' }, 400); } } else if(character.hasClass('moveDown')){ if(!characterWrap.hasClass('moved')){ characterWrap.animate({ 'bottom' : sizeY + 'px' }, 400); }else{ characterWrap.animate({ 'bottom':'0px' },400); } } } characterWrap.toggleClass('moved'); } }; /** * jQuery.support.cssProperty * To verify that a CSS property is supported (or any of its browser-specific implementations) * * * @Author: Axel Jack Fuchs (Cologne, Germany) * @Date: 08-29-2010 18:43 * * Example: $.support.cssProperty('boxShadow'); * Returns: true * * Example: $.support.cssProperty('boxShadow', true); * Returns: 'MozBoxShadow' (On Firefox4 beta4) * Returns: 'WebkitBoxShadow' (On Safari 5) */ function supportTransitions() { var b = document.body || document.documentElement; var s = b.style; var p = 'transition'; if(typeof s[p] == 'string') {return true; } // Tests for vendor specific prop v = ['Moz', 'Webkit', 'Khtml', 'O', 'ms', 'Icab'], p = p.charAt(0).toUpperCase() + p.substr(1); for(var i=0; i<v.length; i++) { if(typeof s[v[i] + p] == 'string') { return true; } } return false; } })(jQuery);
'use strict'; module.exports = { extends: ['@commitlint/config-conventional'] };
// RequireJS configuration /*global requirejs */ requirejs.config({ waitSeconds: 0, packages: [ { name: 'css', location: 'bower-libs/require-css', main: 'css' }, { name: 'less', location: 'bower-libs/require-less', main: 'less' } ], paths: { jquery: 'bower-libs/jquery/jquery', underscore: 'bower-libs/underscore/underscore', crel: 'bower-libs/crel/crel', jgrowl: 'bower-libs/jgrowl/jquery.jgrowl', mousetrap: 'bower-libs/mousetrap/mousetrap', 'mousetrap-record': 'bower-libs/mousetrap/plugins/record/mousetrap-record', toMarkdown: 'bower-libs/to-markdown/src/to-markdown', text: 'bower-libs/requirejs-text/text', mathjax: '../res/bower-libs/MathJax/MathJax.js?config=TeX-AMS_SVG', bootstrap: 'bower-libs/bootstrap/dist/js/bootstrap', requirejs: 'bower-libs/requirejs/require', 'google-code-prettify': 'bower-libs/google-code-prettify/src/prettify', highlightjs: 'libs/highlight/highlight.pack', 'jquery-waitforimages': 'bower-libs/waitForImages/src/jquery.waitforimages', 'jquery-ui': 'bower-libs/jquery-ui/ui/jquery-ui', 'jquery-ui-core': 'bower-libs/jquery-ui/ui/jquery.ui.core', 'jquery-ui-widget': 'bower-libs/jquery-ui/ui/jquery.ui.widget', 'jquery-ui-mouse': 'bower-libs/jquery-ui/ui/jquery.ui.mouse', 'jquery-ui-draggable': 'bower-libs/jquery-ui/ui/jquery.ui.draggable', 'jquery-ui-effect': 'bower-libs/jquery-ui/ui/jquery.ui.effect', 'jquery-ui-effect-slide': 'bower-libs/jquery-ui/ui/jquery.ui.effect-slide', FileSaver: 'bower-libs/FileSaver/FileSaver', stacktrace: 'bower-libs/stacktrace/stacktrace', 'requirejs-text': 'bower-libs/requirejs-text/text', 'bootstrap-tour': 'bower-libs/bootstrap-tour/build/js/bootstrap-tour', css_browser_selector: 'bower-libs/css_browser_selector/css_browser_selector', 'pagedown-extra': 'bower-libs/pagedown-extra/node-pagedown-extra', pagedownExtra: 'bower-libs/pagedown-extra/Markdown.Extra', pagedown: 'libs/Markdown.Editor', 'require-css': 'bower-libs/require-css/css', xregexp: 'bower-libs/xregexp/xregexp-all', yaml: 'bower-libs/yaml.js/bin/yaml', 'yaml.js': 'bower-libs/yaml.js', 'yaml-js': 'bower-libs/yaml.js/bin/yaml', css: 'bower-libs/require-css/css', 'css-builder': 'bower-libs/require-css/css-builder', normalize: 'bower-libs/require-css/normalize', prism: 'bower-libs/prism/prism', 'prism-core': 'bower-libs/prism/components/prism-core', MutationObservers: 'bower-libs/MutationObservers/MutationObserver', WeakMap: 'bower-libs/WeakMap/weakmap', rangy: 'bower-libs/rangy/rangy-core', 'rangy-cssclassapplier': 'bower-libs/rangy/rangy-cssclassapplier', diff_match_patch: 'bower-libs/google-diff-match-patch-js/diff_match_patch', diff_match_patch_uncompressed: 'bower-libs/google-diff-match-patch-js/diff_match_patch_uncompressed', jsondiffpatch: 'bower-libs/jsondiffpatch/build/bundle', hammerjs: 'bower-libs/hammerjs/hammer', Diagram: 'bower-libs/js-sequence-diagrams/src/sequence-diagram', 'diagram-grammar': 'bower-libs/js-sequence-diagrams/build/diagram-grammar', raphael: 'bower-libs/raphael/raphael', 'flow-chart': 'bower-libs/flowchart/release/flowchart.amd-1.3.4.min', flowchart: 'bower-libs/flowchart/release/flowchart-1.3.4.min', monetizejs: 'bower-libs/monetizejs/src/monetize', 'to-markdown': 'bower-libs/to-markdown/src/to-markdown', waitForImages: 'bower-libs/waitForImages/dist/jquery.waitforimages', MathJax: 'bower-libs/MathJax/MathJax', alertify: 'bower-libs/alertify.js/lib/alertify' }, shim: { underscore: { exports: '_' }, mathjax: [ 'libs/mathjax_init' ], jgrowl: { deps: [ 'jquery' ], exports: 'jQuery.jGrowl' }, diff_match_patch_uncompressed: { exports: 'diff_match_patch' }, jsondiffpatch: [ 'diff_match_patch_uncompressed' ], rangy: { exports: 'rangy' }, 'rangy-cssclassapplier': [ 'rangy' ], mousetrap: { exports: 'Mousetrap' }, 'yaml-js': { exports: 'YAML' }, 'prism-core': { exports: 'Prism' }, 'bower-libs/prism/components/prism-markup': [ 'prism-core' ], 'libs/prism-latex': [ 'prism-core' ], 'libs/prism-markdown': [ 'bower-libs/prism/components/prism-markup', 'libs/prism-latex' ], 'bootstrap-record': [ 'mousetrap' ], toMarkdown: { deps: [ 'jquery' ], exports: 'toMarkdown' }, stacktrace: { exports: 'printStackTrace' }, FileSaver: { exports: 'saveAs' }, MutationObservers: [ 'WeakMap' ], highlightjs: { exports: 'hljs' }, 'bootstrap-tour': { deps: [ 'bootstrap' ], exports: 'Tour' }, bootstrap: [ 'jquery' ], 'jquery-waitforimages': [ 'jquery' ], pagedown: [ 'libs/Markdown.Converter' ], pagedownExtra: [ 'libs/Markdown.Converter' ], 'flow-chart': [ 'raphael' ], 'diagram-grammar': [ 'underscore' ], Diagram: [ 'raphael', 'diagram-grammar' ] } }); // Check browser compatibility try { var test = 'seLocalStorageCheck'; localStorage.setItem(test, test); localStorage.removeItem(test); var obj = {}; Object.defineProperty(obj, 'prop', { get: function() { }, set: function() { } }); } catch(e) { alert('Your browser is not supported, sorry!'); throw e; } // Viewer mode is deduced from the body class window.viewerMode = /(^| )viewer($| )/.test(document.body.className); // Keep the theme in a global variable window.theme = localStorage.themeV4 || 'default'; var themeModule = "less!themes/" + window.theme; if(window.baseDir.indexOf('-min') !== -1) { themeModule = "css!themes/" + window.theme; } // RequireJS entry point. By requiring synchronizer, publisher, sharing and // media-importer, we are actually loading all the modules require([ "jquery", "rangy", "core", "eventMgr", "synchronizer", "publisher", "sharing", "mediaImporter", "css", "rangy-cssclassapplier", themeModule ], function($, rangy, core, eventMgr) { if(window.noStart) { return; } $(function() { rangy.init(); // Here, all the modules are loaded and the DOM is ready core.onReady(); // If browser has detected a new application cache. if(window.applicationCache) { window.applicationCache.addEventListener('updateready', function() { if(window.applicationCache.status === window.applicationCache.UPDATEREADY) { window.applicationCache.swapCache(); eventMgr.onMessage('New version available!\nJust refresh the page to upgrade.'); } }, false); } }); });
export NavHeaderComponent from './NavHeader.component'; export default from './NavHeader.container';
angular.module('adminlounge.services', [])
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z" }), 'SearchOutlined');
'use strict'; var Database = require('../../../') , getPrototypeOf = Object.getPrototypeOf; module.exports = function (a) { var db = new Database(), proto = db.Object.prototype, obj = new db.Object() , protoDesc, protoSet, set, item, protoItem; protoDesc = proto.$getOwn('foo'); protoDesc.multiple = true; set = obj.foo; item = set.$getOwn('foo'); protoSet = proto.foo; protoItem = protoSet.$getOwn('foo'); a(getPrototypeOf(item), protoItem, "Item prototype"); a(item._resolveValue_(), undefined, "Initial value"); protoSet.add('foo'); a(item._resolveValue_(), true, "Prototype: Add"); db.Object.prototype.define('dates', { multiple: true, type: db.DateTime }); obj = db.objects.unserialize('Object#/dates*41420070400000'); a(obj.key instanceof db.DateTime, true); db.DateTime.extend('Foo', { step: { value: 1000 * 60 * 60 * 24 }, _validateCreate_: { value: function (value/*[, mth[, d[, h]]]*/) { var l = arguments.length, year, month, day; if (!l) { value = new Date(); year = value.getFullYear(); month = value.getMonth(); day = value.getDate(); value.setUTCFullYear(year); value.setUTCMonth(month); value.setUTCDate(day); } else if (l === 1) { value = new Date(value); } else { value = new Date(Date.UTC(value, arguments[1], (l > 2) ? arguments[2] : 1, (l > 3) ? arguments[3] : 0)); } return [this.database.DateTime.validate.call(this, value)]; } }, normalize: { value: function (value/*, descriptor*/) { var year, month, date; if (!value) return this.database.DateTime.normalize.apply(this, arguments); if (value instanceof this) return this.database.DateTime.normalize.apply(this, arguments); if (Object.prototype.toString.call(value) !== '[object Date]') { return this.database.DateTime.normalize.apply(this, arguments); } year = value.getFullYear(); month = value.getMonth(); date = value.getDate(); value = new Date(value); value.setUTCFullYear(year); value.setUTCMonth(month); value.setUTCDate(date); return this.database.DateTime.normalize.call(this, value, arguments[1]); } }, validate: { value: function (value/*, descriptor*/) { var year, month, date; if (!value) return this.database.DateTime.validate.apply(this, arguments); if (value instanceof this) return this.database.DateTime.validate.apply(this, arguments); if (Object.prototype.toString.call(value) !== '[object Date]') { return this.database.DateTime.validate.apply(this, arguments); } year = value.getFullYear(); month = value.getMonth(); date = value.getDate(); value = new Date(value); value.setUTCFullYear(year); value.setUTCMonth(month); value.setUTCDate(date); return this.database.DateTime.validate.call(this, value, arguments[1]); } } }); db.Object.prototype.define('dates2', { multiple: true, type: db.Foo }); obj = new db.Object(); var date = new Date(2012, 2, 3, 12, 34); obj.dates2.add(date); var createdDate = obj.dates2.first; a.not(date, createdDate); obj.dates2.on('change', function (event) { a(event.value, createdDate); }); obj.dates2.delete(date); a(obj.dates2.size, 0); };
'use strict'; module.exports = { build: ['<%= buildDir %>'] };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M11 16h2v2h-2zm1-14C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm0-14c-2.21 0-4 1.79-4 4h2c0-1.1.9-2 2-2s2 .9 2 2c0 2-3 1.75-3 5h2c0-2.25 3-2.5 3-5 0-2.21-1.79-4-4-4z" }), 'HelpOutlineTwoTone'); exports.default = _default;
module.exports = Lightbox; /** * Lightbox with default configuration to * lightbox all webhook wysiwyg generated * * - Adds a lightbox container to the DOM. * - Adds a new image tag in the lightbox container * for each lightbox image. * - Adds click events for preventing the default * image wrapping anchor tag, and enables the * lightbox instead * * elements on a page. * @param {object} opts * @param {string} opts.decorate Query selector string for all a tags * that contain images to lightbox. * @param {string} opts.appendTo Query selector string of element to * append the lightbox to. */ function Lightbox(opts) { if (!(this instanceof Lightbox)) return new Lightbox(opts); if (typeof opts !== 'object') opts = {}; // console.log('Lightbox initialized.'); // classes this.box = bem('lightbox'); this.viewport = this.box('viewport'); this.image = this.box('image'); this.active = this.box.modifier('active'); this.inactive = this.box.modifier('inactive'); this.noscroll = this.box.modifier('noscroll'); this.decorateQuery = opts.decorate || 'figure[data-type="image"] > a'; var $decorated = this.decorate(this.decorateQuery); this.boxes = this.build(opts.appendTo || 'body'); this.$images = this.addImages(this.boxes.$viewport, $decorated); $decorated.on('click', this.open.bind(this)); this.boxes.$box.on('click', this.close.bind(this)); }; /** * Expects a click event whose target is within the scope of a * $(this.decorateQuery) element to find its lightbox image ID. * With the image ID, update the class list of this.$images * comparing lightbox IDs to reflect active/inactive state. Also * update the box & body state. * * @param {object} event Click event * @return {undefined} */ Lightbox.prototype.open = function (event) { event.preventDefault(); $(event.target).closest(this.decorateQuery).each(lightboxFor.bind(this)); function lightboxFor (index, element) { var imageId = element.dataset.lightboxableImageId; this.$images.each(updateClasslist.bind(this, imageId)); this.boxes.$box .removeClass(this.inactive()) .addClass(this.active()); document.body.classList.add(this.noscroll()); } function updateClasslist (activeId, uindex, uelement) { if (uelement.dataset.lightboxId === activeId) { uelement.classList.add(this.active()); uelement.classList.remove(this.inactive()); } else { uelement.classList.add(this.inactive()); uelement.classList.remove(this.active()); } } } /** * Closes the lightbox. Both the box and body return to their * default state, not active. * * @return {undefined} */ Lightbox.prototype.close = function lightboxClose () { this.boxes.$box .removeClass(this.active()) .addClass(this.inactive()); document.body.classList.remove(this.noscroll()); } /** * Looks through decorated images, and adds a new img tag to the * $viewport with the same source. These are the images that will * load in the lightbox. * * @param {object} $viewport jQuery selector of the parent of the * lightbox images * @param {object} $decorated jQuery selector of images to clone into * the lightbox * @return {object} $this jQuery selector of the lightbox images */ Lightbox.prototype.addImages = function ($viewport, $decorated) { $decorated.each(addem.bind(this)); function addem (index, element) { var img = document.createElement('img'); img.src = srcFor(element); img.dataset.lightboxId = element.dataset.lightboxableImageId; img.classList.add(this.image()); img.classList.add(this.inactive()); $viewport.append(img); } return $viewport.children(); function srcFor (element) { var innerImage = $(element).find('img').get(0); if (innerImage) { if (innerImage.dataset.hasOwnProperty('resizeSrc')) { return innerImage.dataset.resizeSrc + '=s1200'; } else { return element.href; } } } }; /** * Decorate targets with lightbox attributes, to attach lightbox * functionality to thme. * Returns $decorated based on the selector. * * @param {string|object} $query jQuery selector or string of * selector query * @return {object} $decorated */ Lightbox.prototype.decorate = function ($query) { if (typeof $query === 'string') $query = $($query); var $decorated = $query; $decorated.each(function (index, a) { a.dataset.lightboxableImageId = index; }); return $decorated; }; /** * Build the lightbox container. * Returns $viewport, the place where * images will end up going. * * @param {string|object} $query jQuery selector or string of * selector query * @return {object} boxes * @return {object.$box} $box * @return {object.$viewport} $viewport */ Lightbox.prototype.build = function ($query) { if (typeof $query === 'string') $query = $($query); var box = document.createElement('div'); box.classList.add(this.box()); box.classList.add(this.inactive()); var viewport = document.createElement('div'); viewport.classList.add(this.viewport()); box.appendChild(viewport); $query.append(box); return { $viewport: $(viewport), $box: $(box) }; }; /** * bem helper. base__element--modifier. * * base = bem('bs'); * base() * // 'bs' * element = base('el'); * element() * // 'bs__el' * modifier = element('mod'); * modifier(); * // 'bs__el--mod' * baseModifier = base.modifier('bmod'); * // 'bs--bmod' * * @param {string} base The base string * @return {function} */ function bem (base) { function element (element) { if (!element) return base; function modifier (modifier) { var baseElement = [base, element].join('__'); if (!modifier) return baseElement; return function () { return [baseElement, modifier].join('--'); } } return modifier; } element.modifier = function (modifier) { return function () { return [base, modifier].join('--'); } } return element; }
// a key map of allowed keys var allowedKeys = { 67: 'c', 69: 'e', 83: 's', 66: 'b', 73: 'i', 84: 't' }; // the 'official' Konami Code sequence var konamiCode = ['e', 'e', 'c', 's', 'b', 'i', 't']; // a variable to remember the 'position' the user has reached so far. var konamiCodePosition = 0; // add keydown event listener document.addEventListener('keydown', function(e) { // get the value of the key code from the key map var key = allowedKeys[e.keyCode]; // get the value of the required key from the konami code var requiredKey = konamiCode[konamiCodePosition]; // compare the key with the required key if (key == requiredKey) { // move to the next key in the konami code sequence konamiCodePosition++; // if the last key is reached, activate cheats if (konamiCodePosition == konamiCode.length) activateCheats(); } else konamiCodePosition = 0; }); function activateCheats() { document.body.style.backgroundImage = "url('images/james.jpg')"; var audio = new Audio('audio/barbie.mp3'); audio.play(); alert("Throughout this project, Paul and James have constantly made jokes and bits. Here's a picture of James stripping in EECS - Vikram"); }
"use strict"; // utilisation de : http://bl.ocks.org/brattonc/5e5ce9beee483220e2f6#index.html // les données var donneesJardinJoseph = { "printemps": [ {nomProduit: "Racines", poids: 12850}, {nomProduit: "Poids et Haricots", poids: 10934}, {nomProduit: "Choux", poids: 8760}, {nomProduit: "Epinards et Salades", poids: 19851}, {nomProduit: "Courges", poids: 77400}, {nomProduit: "Tomates", poids: 35314}, {nomProduit: "Aromatiques", poids: 1260}, {nomProduit: "Fruits", poids: 11600}, {nomProduit: "Autres", poids: 2400} ], "ete": [ {nomProduit: "Racines", poids: 7200}, {nomProduit: "Poids et Haricots", poids: 5466}, {nomProduit: "Choux", poids: 0}, {nomProduit: "Epinards et Salades", poids: 6671}, {nomProduit: "Courges", poids: 0}, {nomProduit: "Tomates", poids: 88286}, {nomProduit: "Aromatiques", poids: 1267}, {nomProduit: "Fruits", poids: 2695}, {nomProduit: "Autres", poids: 7265} ], "automne": [ {nomProduit: "Racines", poids: 0}, {nomProduit: "Poids et Haricots", poids: 0}, {nomProduit: "Choux", poids: 2920}, {nomProduit: "Epinards et Salades", poids: 0}, {nomProduit: "Courges", poids: 0}, {nomProduit: "Tomates", poids: 0}, {nomProduit: "Aromatiques", poids: 1273}, {nomProduit: "Fruits", poids: 15715}, {nomProduit: "Autres", poids: 2300} ], "hiver": [ {nomProduit: "Racines", poids: 0}, {nomProduit: "Poids et Haricots", poids: 0}, {nomProduit: "Choux", poids: 2920}, {nomProduit: "Epinards et Salades", poids: 13233}, {nomProduit: "Courges", poids: 0}, {nomProduit: "Tomates", poids: 0}, {nomProduit: "Aromatiques", poids: 0}, {nomProduit: "Fruits", poids: 0}, {nomProduit: "Autres", poids: 0} ], "total": [ {nomProduit: "Racines", poids: 20050}, {nomProduit: "Poids et Haricots", poids: 16400}, {nomProduit: "Choux", poids: 14600}, {nomProduit: "Epinards et Salades", poids: 39755}, {nomProduit: "Courges", poids: 77400}, {nomProduit: "Tomates", poids: 123600}, {nomProduit: "Aromatiques", poids: 3800}, {nomProduit: "Fruits", poids: 30010}, {nomProduit: "Autres", poids: 11965} ] }; var infosJardinJoseph = { "Racines": { idJauge: "jauge_racine", couleur: "#f7bd48", maximum: 20050, cheminImage: "./img/joseph/racines.svg" }, "Poids et Haricots": { idJauge: "jauge_haricots", couleur: "#c96d63", maximum: 16400, cheminImage: "./img/joseph/haricots.svg" }, "Choux": { idJauge: "jauge_choux", couleur: "#b5ff9c", maximum: 14600, cheminImage: "./img/joseph/choux.svg" }, "Epinards et Salades": { idJauge: "jauge_salades", couleur: "#c9ff73", maximum: 39755, cheminImage: "./img/joseph/salades.svg" }, "Courges": { idJauge: "jauge_courges", couleur: "#d6ff38", maximum: 77400, cheminImage: "./img/joseph/courges.svg" }, "Tomates": { idJauge: "jauge_tomates", couleur: "#ee7268", maximum: 123600, cheminImage: "./img/joseph/tomates.svg" }, "Aromatiques": { idJauge: "jauge_aromatiques", couleur: "#aef86e", maximum: 3800, cheminImage: "./img/joseph/aromatiques.svg" }, "Fruits": { idJauge: "jauge_fruits", couleur: "#ffa87b", maximum: 30010, cheminImage: "./img/joseph/fruits.svg" }, "Autres": { idJauge: "jauge_autres", couleur: "#f7ff64", maximum: 11965, cheminImage: "./img/joseph/autres.svg" } }; // utilisé pour sauvegarder les Jauge Updater (GaugeUpdater) var jauges = {}; // on récupère les données pour la saison actuelle var saisonActuelle = getSaisonActuelle(); var donneesActuelles = donneesJardinJoseph[saisonActuelle]; // création de la balise contenant le total var total = [ calculerPoidsTotal(donneesActuelles) ]; d3.select("#totalJoseph").selectAll("p").data(total).enter().append("p").text(function(d) { return d; }); // pour chaque produit, on crée une balise donneesActuelles.forEach(function(element, index, tableau) { var infoElement = infosJardinJoseph[element.nomProduit]; var idJauge = infoElement.idJauge; // création de la balise contenant la jauge var baliseJauge = d3.select("#diagrammeJoseph").append("div").attr("class", "baliseJauge"); var svgJauge = baliseJauge.append("svg").attr({ "id": idJauge, "viewBox": "0 0 100 150", //"height": 150, //"width": 100 }); // configuration de la jauge var config = liquidFillGaugeDefaultSettings(); config.minValue = 0; config.maxValue = (infoElement.maximum * 0.001).toFixed(1); config.circleThickness = 0.02; // taille cercle extérieur config.circleFillGap = 0; // espacement entre cercle extérieur et intérieur config.textVertPosition = 1.6; // positionner le texte au dessus de la gauge config.circleColor = "#706f6f"; config.textColor = "#999999"; config.waveColor = infoElement.couleur; //config.waveTextColor = "#6DA398"; config.waveAnimateTime = 5000; config.waveHeight = 0; config.waveAnimate = false; config.waveCount = 2; config.waveOffset = 0.25; config.textSize = 1.2; config.displayPercent = false; var poids = (element.poids * 0.001).toFixed(1); var jauge = loadLiquidFillGauge(idJauge, poids, config); jauges[idJauge] = jauge; // ajout du "kg" au dessus de la jauge svgJauge.select("g").append("text").attr("x", 50).attr("y", -6).attr("class", "liquidFillGaugeText").attr("text-anchor", "middle").style("fill", "#fdbe63").text("kg"); // remettre le groupe à la position (0, 0) (nécessaire car le texte de la jauge sortait de la zone) svgJauge.select("g").attr("transform", "translate(0, 50)"); // ajout de l'image dans la jauge svgJauge.select("g").append("image").attr({ "xlink:href": infoElement.cheminImage, "x": 0, "y": 0, "height": 50, "width": 50, "transform": "translate(25, 25)", }); }); // on pet à jour les données du diagramme avec les données de la saison actuelle updateDiagrammeJoseph(saisonActuelle); // mise à jour du radio sélectionné $("#radioJoseph_" + saisonActuelle).attr("checked", ""); /** * met à jour les données du diagramme de joseph (l'histogramme) en fonction de la saison * @param {string} saison peut prendre 5 valeurs: "printemps", "ete", "automne", "hiver", "total" */ function updateDiagrammeJoseph(saison) { // récupération des données selon la saison var donneesActuelles = donneesJardinJoseph[saison] || []; // mise à jour des colonnes de l'histogramme donneesActuelles.forEach(function(element, index, tableau) { var infosElement = infosJardinJoseph[element.nomProduit]; var jauge = jauges[infosElement.idJauge]; var poids = (element.poids * 0.001).toFixed(1); jauge.update(poids); }); // mise à jour du total var total = [ calculerPoidsTotal(donneesActuelles) ]; var balisesTotal = d3.select("#totalJoseph").selectAll("p").data(total).transition().duration(1000).tween("text", function() { var i = d3.interpolateRound(Number(this.textContent), total[0]); return function(t) { this.textContent = i(t); }; }); // tween permet d'animer la mise à jour d'un nombre // mise à jour de l'image de saison $("#imageSaison").attr("src", "./img/joseph/background_" + saison + ".png"); } /** * retourne le poids total de légumes récoltés pour les données passées en entrées * @param {Array} donnees la liste des produits, chaque produit étant enregistrer dans un objet contenant les attrbuts "nomProduit" et "poids" * @returns {number} le poids total */ function calculerPoidsTotal(donnees) { var total = donnees.reduce(function(prec, elem, indice, tab) { return prec + elem.poids; }, 0); return (total * 0.001).toFixed(1); } /** * retourne la saison actuelle (la saison en fonction de la date actuelle) * @returns {string} la saison actuelle, peut être "printemps", "ete", "automne", "hiver" */ function getSaisonActuelle() { var today = new Date(); var mois = today.getMonth(); var jour = today.getDay(); // janvier: 0, fevrier: 1, ... if(mois >=2 && mois <= 5) { // entre mars et juin if(mois == 2 && jour < 20) return "hiver"; else if(mois == 5 && jour > 20) return "ete"; else return "printemps"; } else if(mois >= 5 && mois <= 8) { // entre juin et septembre if(mois == 5 && jour < 21) return "printemps"; else if(mois == 8 && jour > 22) return "automne"; else return "ete"; } else if(mois >= 8 && mois <= 11) { // entre septemps et decembre if(mois == 8 && jour < 23) return "ete"; else if(mois == 11 && jour > 20) return "hiver"; else return "automne"; } else return "hiver" }
app.factory('loaderService', function($ionicModal, $rootScope) { $ionicModal.fromTemplateUrl('templates/modals/loader.html', { scope: $rootScope }).then(function(modal) { $rootScope.loader = modal; }); return { show: function() { $rootScope.loader.show(); }, hide: function() { $rootScope.loader.hide(); } } });
var searchData= [ ['child',['child',['../classQuadLinkedTrieNode.html#a386e85a2b259728ec9fbe26907823dcf',1,'QuadLinkedTrieNode::child() const '],['../classQuadLinkedTrieNode.html#add46f502e721f5cc00a3972d6cbec709',1,'QuadLinkedTrieNode::child(QuadLinkedTrieNode&lt; T &gt; *pChild)']]] ];
import React from 'react'; import TestUtils from 'react-addons-test-utils'; import { expect } from 'chai'; import { AddPet } from 'client/components/AddPet'; import style from 'client/style.css'; const setup = () => { const renderer = TestUtils.createRenderer(); renderer.render(<AddPet />); const output = renderer.getRenderOutput(); return { output }; }; describe('tests AddPet component', () => { it('renders correctly', () => { const { output } = setup(); expect(output.type).to.eql('div'); expect(output.props.className).to.eql(style.add); }); });
'use strict'; define(["app"], function(app) { app.directive("scrollmanager", ["$timeout", "$rootScope", "Visibility", "ArrayUtils", "Network", function($timeout, $rootScope, $visibility, $arrayUtils, $network) { var userScroll = false, scrollObjects = {}, timeoutsUpdateSinceId = {}; function updateSinceId(referer, msg) { timeoutsUpdateSinceId[referer] = timeoutsUpdateSinceId[referer] || {}; var uidProviderUser = msg.unifiedRequest.uidProviderUser; if(msg.unifiedRequest.args && msg.unifiedRequest.args[0]) { uidProviderUser + msg.unifiedRequest.args[0].value.call;//discriminant server side } if(timeoutsUpdateSinceId[referer][uidProviderUser] != undefined) { $timeout.cancel(timeoutsUpdateSinceId[referer][uidProviderUser]); } timeoutsUpdateSinceId[referer][uidProviderUser] = $timeout(function() { console.log(msg); $network.send({ cmd: "updateSinceId", body: { columnTitle: msg.column, unifiedRequest: msg.unifiedRequest, sinceId: msg.sinceId } }); timeoutsUpdateSinceId[referer][uidProviderUser] = undefined; }, 3000); } return { restrict: 'A', link: function(scope, elmt, attrs) { var element = elmt[0]; var timeout = undefined; if(attrs["scrollmanager"] === "onlyTop") { var scroller = angular.element(element); var unwatch = scope.$watch(attrs["scrolldata"], function(newValue, oldValue) { if(newValue) { var data = newValue.title; console.log(newValue); $rootScope.$on("scrollManagerGoTop", function(evt, column) { if(angular.equals(column.title, data)) { userScroll = false; scroller[0].scrollTop = 0; console.log(scrollObjects[data]); updateSinceId(data, scrollObjects[data][scrollObjects[data].length-1]); $timeout(function() { userScroll = true; }, 100); } }); var scrollMove = function(evt) { if(scrollObjects[data] && userScroll == true) { for (var i = 0; i < scrollObjects[data].length; i++) { var object = scrollObjects[data][i]; if(object.isView === false) { var pos = object.refElement.offsetTop - scroller[0].offsetTop; if(evt.target.scrollTop <= pos) { scrollObjects[data].splice(i, 1); object.isView = true; $visibility.notifyMessageRead(); scope.$apply(); updateSinceId(data, object); } else { //when object post is above scroll we stop //why the fuck insert array isn't ordered ????????? //return; } } } } } scroller.bind('scroll', scrollMove); unwatch(); } }); } else { var scroller = angular.element(element.parentElement.parentElement); var unwatch = scope.$watch(attrs["scrollmanager"], function(newValue, oldValue) { if(newValue) { var object = scope[attrs["scrollmanager"]]; if(object.isView === false) { var referer = scope[attrs["scrolldata"]].title; object.refElement = element; scrollObjects[referer] = scrollObjects[referer] || []; userScroll = false; scroller[0].scrollTop += element.clientHeight; if(timeout != undefined) { $timeout.cancel(timeout); } timeout = $timeout(function() { userScroll = true; timeout = undefined; }, 500); scrollObjects[referer].splice( $arrayUtils.sortedArrayLocationOf(object, scrollObjects[referer], 'createdAt')+1, 0, object); } unwatch(); } }); } } }; }]); })
angular.module('pager') .controller('HeaderCtrl', function($scope, $state) { $scope.image = 'http://agencedianeriel.com/photo/Ostiguy-Jeanne-nouv09.jpg'; $scope.$on('$viewContentLoaded', function() { $scope.view = $state.current.title; }); });
// redeye.js // @author Tim McGowan <dropdownmenu> var fs = require("fs"); var _ = require("underscore"); var path = require("path"); var cs = require("coffee-script"); var coffee = require("js2coffee"); var IGNORE = ["node_modules"]; var convert = function(dir, force, cb) { fs.readdir(dir, function(err, files) { _.each(files, function(file) { if (_.indexOf(IGNORE, file) === -1) { var loc = path.join(dir, file); fs.stat(loc, function(err, stat) { if (stat.isDirectory()) { convert(loc, force, cb); } else { var extension = path.extname(file); if (extension === ".js") { fs.readFile(loc, "utf8", function(err, str) { try { var res = coffee.build(str); var comp; if (force) { // compile up here to avoid multiple try/catch comp = cs.compile(res); } console.log(file); var csFile = file.replace(".js", ".coffee"); fs.writeFile(path.join(dir, csFile), res, "utf8", function(err) { if (err) { console.log("could not convert: " + file); cb(); } else { console.log(path.join(dir, file)); if (force) { fs.writeFile(path.join(dir, file), comp, function(err) { if (err) { console.log('unable to write new js'); } cb(); }); } else { cb(); } } }); } catch (e) { console.log("could not convert: " + file); } }); } } }); } }); }); }; function wrapper(dir, force) { } module.exports = function(startDir, number, force) { var cb = function() { number--; if (number >= 0) { convert(startDir, force, cb); } } convert(startDir, force, cb); }
import ValueCommand from './ValueCommand' export default class RemoveValueCommand extends ValueCommand { execute (params, context) { const { nodeId, propertyName, valueId } = params.commandState context.api.removeItem([nodeId, propertyName], valueId) } }
//@AddComponentMenu("planet/CloudsRotate") //partial class CloudsRotate{ } private var amtx : float = 0.0; private var amty : float = 0.0; private var amtz : float = 0.0; //private var amtx : float = Random.Range(.2,-.2); //private var amtz : float = Random.Range(.2,-.2); private var this_transform : Transform; function Start() { amty = Random.Range(Random.Range(4.0,7.0),-Random.Range(4.0,7.0)); amtx = Random.Range(Random.Range(4.0,7.0),-Random.Range(4.0,8.0)); amty = Random.Range(Random.Range(4.0,7.0),-Random.Range(4.0,8.0)); this_transform = transform; } function Update () { this_transform.Rotate(Time.deltaTime *amtx, Time.deltaTime *amty, Time.deltaTime *amtz); }
module.exports = function(grunt) { grunt.registerTask('compile-html', [ 'assemble', 'bower-dependencies' ]); };
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Business = props => <SvgIcon {...props}> <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z" /> </SvgIcon>; Business = pure(Business); Business.muiName = 'SvgIcon'; export default Business;
/** @type {import("../../../").Configuration} */ module.exports = { mode: "production", entry: "./index", stats: { ids: true, reasons: false, modules: false, chunks: true, chunkRelations: true, chunkModules: true, dependentModules: true, chunkOrigins: true } };
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M20 6h-2.18c.11-.31.18-.65.18-1 0-1.66-1.34-3-3-3-1.05 0-1.96.54-2.5 1.35l-.5.67-.5-.68C10.96 2.54 10.05 2 9 2 7.34 2 6 3.34 6 5c0 .35.07.69.18 1H4c-1.11 0-1.99.89-1.99 2L2 19c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V8c0-1.11-.89-2-2-2zm-5-2c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zM9 4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm11 15H4v-2h16v2zm0-5H4V8h5.08L7 10.83 8.62 12 11 8.76l1-1.36 1 1.36L15.38 12 17 10.83 14.92 8H20v6z" }), 'Redeem'); exports.default = _default;
for (var i = function() { return 10 in [] } in list) process(x);
import { Composer } from '@superguigui/wagner'; import withStore from 'decorators/withStore'; /** * EffectComposer class */ @withStore({ handleResize: ({ viewport }) => ({ width: viewport.width, height: viewport.height }) }) class EffectComposer extends Composer { /** * Constructor function * @param {object} renderer Renderer */ constructor( renderer ) { super( renderer, { useRGBA: true }); } /** * handleResize function * @param {Object} size Viewport size * @param {number} param.width Viewport width * @param {number} param.height Viewport height */ handleResize({ width, height }) { this.setSize( width, height ); } } export default EffectComposer;
var fs = require('fs'); var scripts = require('./sha'); var client; module.exports = { join: join, init: init }; function init(_client) { client = _client; } /** * @param args {Array} name of key table, namespace of hashes, and an optional limit * @param callback {Function} called after the script executes */ function join(args, callback) { var numKeys = ''+args.length; var keys = args[0]; var hashNamespace = args[1]; var limit = args[2]; if(typeof callback !== 'function') { throw new TypeError('moon-bucket requires a callback as the last argument'); } if(client) { fs.readFile('./scripts/join.lua', 'utf8', function(err, script) { console.log(scripts['join']); client.evalsha([scripts['join'], numKeys, keys, hashNamespace, limit], function(err, res) { var reply; if(res) { reply = res.map(function(item) { return reply_to_object(item); }); } return callback(err, reply); }); }); } } /** * Taken from the node redis source. * * Converts a redis reply to a valid JavaScript object. */ function reply_to_object(reply) { var obj = {}, j, jl, key, val; if (reply.length === 0 || !Array.isArray(reply)) { return null; } for (j = 0, jl = reply.length; j < jl; j += 2) { key = reply[j].toString('binary'); val = reply[j + 1]; obj[key] = val; } return obj; }