code
stringlengths
2
1.05M
(function($, UI) { "use strict"; var Animations; UI.component('switcher', { defaults: { connect : false, toggle : ">*", active : 0, animation: false }, init: function() { var $this = this; this.on("click", this.options.toggle, function(e) { e.preventDefault(); $this.show(this); }); if (this.options.connect) { this.connect = $(this.options.connect).find(".uk-active").removeClass(".uk-active").end(); // delegate switch commands within container content if (this.connect.length) { this.connect.on("click", '[data-uk-switcher-item]', function(e) { e.preventDefault(); var item = $(this).data('ukSwitcherItem'); if ($this.index == item) return; switch(item) { case 'next': case 'previous': $this.show($this.index + (item=='next' ? 1:-1)); break; default: $this.show(item); } }); } var toggles = this.find(this.options.toggle), active = toggles.filter(".uk-active"); if (active.length) { this.show(active); } else { active = toggles.eq(this.options.active); this.show(active.length ? active : toggles.eq(0)); } } }, show: function(tab) { tab = isNaN(tab) ? $(tab) : this.find(this.options.toggle).eq(tab); var $this = this, active = tab, animation = Animations[this.options.animation] || Animations['none']; if (active.hasClass("uk-disabled")) return; this.find(this.options.toggle).filter(".uk-active").removeClass("uk-active"); active.addClass("uk-active"); if (this.options.connect && this.connect.length) { this.index = this.find(this.options.toggle).index(active); if (this.index == -1 ) { this.index = 0; } this.connect.each(function() { var container = $(this), children = container.children(), current = children.filter('.uk-active'), next = children.eq($this.index); animation.apply($this, [current, next]).then(function(){ current.removeClass("uk-active"); next.addClass("uk-active"); UI.Utils.checkDisplay(next); }); }); } this.trigger("uk.switcher.show", [active]); } }); Animations = { 'none': function() { var d = $.Deferred(); d.resolve(); return d.promise(); }, 'fade': function(current, next, dir) { var d = $.Deferred(); if (current) { current.removeClass('uk-active'); } next.fadeIn(300, function(){ next.css({opacity:'', display:''}); d.resolve(); }); return d.promise(); } }; // init code UI.ready(function(context) { $("[data-uk-switcher]", context).each(function() { var switcher = $(this); if (!switcher.data("switcher")) { var obj = UI.switcher(switcher, UI.Utils.options(switcher.attr("data-uk-switcher"))); } }); }); })(jQuery, jQuery.UIkit);
import { getCurrentEnvironment } from './getCurrentEnvironment'; export function Environment(Builder) { return class Wrapped extends Builder { constructor(...args) { super(...args); this._environments = new Set(); } inEnvironment(environment) { this._environments.add(environment); return this; } get inDev() { return this.inEnvironment('development'); } get inProd() { return this.inEnvironment('production'); } build(...args) { if (this._environments.size && !this._environments.has(getCurrentEnvironment())) { return; } return super.build(...args); } }; }
/* */ "format global"; "use strict"; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj["default"] : obj; }; exports.UnaryExpression = UnaryExpression; exports.DoExpression = DoExpression; exports.UpdateExpression = UpdateExpression; exports.ConditionalExpression = ConditionalExpression; exports.NewExpression = NewExpression; exports.SequenceExpression = SequenceExpression; exports.ThisExpression = ThisExpression; exports.Super = Super; exports.Decorator = Decorator; exports.CallExpression = CallExpression; exports.EmptyStatement = EmptyStatement; exports.ExpressionStatement = ExpressionStatement; exports.AssignmentExpression = AssignmentExpression; exports.MemberExpression = MemberExpression; exports.MetaProperty = MetaProperty; exports.__esModule = true; var isInteger = _interopRequire(require("is-integer")); var isNumber = _interopRequire(require("lodash/lang/isNumber")); var t = _interopRequireWildcard(require("../../types")); function UnaryExpression(node, print) { var hasSpace = /[a-z]$/.test(node.operator); var arg = node.argument; if (t.isUpdateExpression(arg) || t.isUnaryExpression(arg)) { hasSpace = true; } if (t.isUnaryExpression(arg) && arg.operator === "!") { hasSpace = false; } this.push(node.operator); if (hasSpace) this.push(" "); print(node.argument); } function DoExpression(node, print) { this.push("do"); this.space(); print(node.body); } function UpdateExpression(node, print) { if (node.prefix) { this.push(node.operator); print(node.argument); } else { print(node.argument); this.push(node.operator); } } function ConditionalExpression(node, print) { print(node.test); this.space(); this.push("?"); this.space(); print(node.consequent); this.space(); this.push(":"); this.space(); print(node.alternate); } function NewExpression(node, print) { this.push("new "); print(node.callee); this.push("("); print.list(node.arguments); this.push(")"); } function SequenceExpression(node, print) { print.list(node.expressions); } function ThisExpression() { this.push("this"); } function Super() { this.push("super"); } function Decorator(node, print) { this.push("@"); print(node.expression); } function CallExpression(node, print) { print(node.callee); this.push("("); var separator = ","; if (node._prettyCall) { separator += "\n"; this.newline(); this.indent(); } else { separator += " "; } print.list(node.arguments, { separator: separator }); if (node._prettyCall) { this.newline(); this.dedent(); } this.push(")"); } var buildYieldAwait = function buildYieldAwait(keyword) { return function (node, print) { this.push(keyword); if (node.delegate || node.all) { this.push("*"); } if (node.argument) { this.space(); print(node.argument); } }; }; var YieldExpression = buildYieldAwait("yield"); exports.YieldExpression = YieldExpression; var AwaitExpression = buildYieldAwait("await"); exports.AwaitExpression = AwaitExpression; function EmptyStatement() { this.semicolon(); } function ExpressionStatement(node, print) { print(node.expression); this.semicolon(); } function AssignmentExpression(node, print) { // todo: add cases where the spaces can be dropped when in compact mode print(node.left); this.push(" "); this.push(node.operator); this.push(" "); print(node.right); } exports.BinaryExpression = AssignmentExpression; exports.LogicalExpression = AssignmentExpression; exports.AssignmentPattern = AssignmentExpression; var SCIENTIFIC_NOTATION = /e/i; function MemberExpression(node, print) { var obj = node.object; print(obj); if (!node.computed && t.isMemberExpression(node.property)) { throw new TypeError("Got a MemberExpression for MemberExpression property"); } var computed = node.computed; if (t.isLiteral(node.property) && isNumber(node.property.value)) { computed = true; } if (computed) { this.push("["); print(node.property); this.push("]"); } else { // 5..toFixed(2); if (t.isLiteral(obj) && isInteger(obj.value) && !SCIENTIFIC_NOTATION.test(obj.value.toString())) { this.push("."); } this.push("."); print(node.property); } } function MetaProperty(node, print) { print(node.meta); this.push("."); print(node.property); }
//rollup.config.ts import alias from 'rollup-plugin-alias'; import resolve from 'rollup-plugin-node-resolve'; import typescript from 'rollup-plugin-typescript2'; import angular from 'rollup-plugin-angular-aot'; export default { input: 'tmp/esm5/main.js', output: { format: 'es', file: 'dist/esm5/angular2-tree.es5.js', name: 'angular2tree', sourcemap: false, globals: {} }, context: 'this', plugins: [ angular(), typescript(), alias({ rxjs: __dirname + '/node_modules/rxjs-es' }), resolve({ jsnext: true, main: true, browser: true, modulesOnly: true }) ], external: [ '@angular/animations', '@angular/animations/browser', '@angular/cdk', '@angular/core', '@angular/common', '@angular/common/http', '@angular/compiler', '@angular/core', '@angular/core/testing', '@angular/http', '@angular/forms', '@angular/platform-browser', '@angular/platform-browser/animations', '@angular/platform-browser-dynamic', '@angular/router', '@angular/router-deprecated', '@ngrx/core', '@ngrx/store', '@ngrx/store/src/selector', '@ngrx/effects', '@ngrx/store-devtools', 'lodash.isequal', 'ng2-translate', 'ng2-dnd', 'rxjs/add/observable/empty', 'rxjs/add/observable/of', 'rxjs/add/observable/combineLatest', 'rxjs/add/operator/do', 'rxjs/add/operator/withLatestFrom', 'rxjs/add/observable/merge', 'rxjs/operators', 'rxjs/operator/map', 'rxjs/operator/filter', 'rxjs/BehaviorSubject', 'rxjs/Subject', 'rxjs/Observable', 'rxjs/Subscription', 'ngx-contextmenu' ], }
/* * CheckRegPage Messages * * This contains all the text for the CheckRegPage component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.containers.CheckRegPage.header', defaultMessage: 'Are you registered to vote?', }, apiErr: 'Error connecting to our servers', });
/** * Constructing and interpreting flat frames representation * The representation is similar to * [ANF](https://en.wikipedia.org/wiki/A-normal_form) */ import * as Kit from "./kit"; import { Tag, invariant } from "./kit"; import * as Block from "./block"; import * as Ctrl from "./control"; import * as Coerce from "./coerce"; import * as Loop from "./loops"; import * as Bind from "./bind"; import * as State from "./state"; import { ifDefunct } from "./options"; import * as Except from "./exceptions"; import * as Policy from "./policy"; import * as Defunct from "./defunct"; import * as Gens from "./generators"; import * as Inline from "./inline"; import * as Par from "./par"; import * as Opt from "./optimization"; function byNumFst(a, b) { return a[0].num - b[0].num; } const emptyArr = []; /** temporal marker of all frames inside finally block */ const finallyBlock = Kit.symbol("finally.block"); /** temporal marker of all frames inside catchBlock */ const catchBlock = Kit.symbol("catch.block"); /** temporal marker delimiting handler block for both catch and finally */ const handleBlock = Kit.symbol("try.handle"); const scopeSym = Kit.sysId("scope"); function unboundTempVar(root, name) { const res = Bind.tempVarSym(root, name); res.bound = false; return res; } function addArg(args, lhs, rhs) { for (const [l, r] of args) { if (r === lhs) { args.set(l, rhs); return; } } args.set(lhs, rhs); } /** * convers to a flat stracture (without nested frames) * type ExitVal = JumpVal | LetStmtVal * type ExitVal = ExitVal & { * ref: FrameVal, * goto?: FrameVal * } */ export const convert = Kit.pipe( /** * removes redundant lets to simplify next step * this pass is actually workaround of not very nice output * from the former passes, they were designed for now abandoned nested mode */ function convertPrepare(si) { const s = Kit.auto(si); const root = s.first.value; root.rootName = ((!s.opts.shortFrameNames || s.opts.topLevel) && root.funcId && root.funcId.name) || ""; function* walk() { let res = false; for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Tag.ReturnStatement: const cur = s.curLev(); if (cur && cur.value.eff) { cur.value.result = true; yield* Kit.reposOne(s.sub(), i.pos); } else if (cur || s.opts.keepLastPure) { yield s.enter(i.pos, Block.pure, { result: true }); yield* Kit.reposOne(s.sub(), Tag.push); yield* s.leave(); } s.close(i); continue; case Loop.repeat: case Ctrl.jump: case Block.choice: case Block.frame: res = true; break; case Block.letStmt: i.value.result = i.value.sym && i.value.sym.bound && i.value.sym.result; if (i.value.eff) { res = true; const inner = []; if (Kit.result(walk(), inner)) { yield* Kit.reposOneArr(inner, i.pos); s.close(i); } else { yield i; yield* inner; yield s.close(i); } continue; } if (i.value.result) { /** last not-eff letStmt must be turned into explicit return */ yield s.enter(i.pos, Block.pure); if (s.curLev()) yield* Kit.reposOne(s.sub(), Tag.push); yield* s.leave(); s.close(i); continue; } break; } } yield i; } return res; } return walk(); }, function* convert(si) { const s = Kit.auto(si); const needNextErrCont = !s.opts.defunct && !s.opts.inlineErrorContAssign; const needNextResCont = !s.opts.defunct && !s.opts.inlineResultContAssign && s.opts.storeResultCont; const frames = []; function setGoto(jumps, value) { for (const i of jumps) if (i.goto == null) i.goto = value; } function* _convert(sw, cur, chain) { for (const i of sw) { if (i.enter) { switch (i.type) { case Tag.IfStatement: yield i; yield* s.one(); invariant(!cur.length); cur.push(...(yield* _convert(s.one(), [], chain))); if (s.curLev() != null) cur.push(...(yield* _convert(s.one(), [], chain))); yield s.close(i); continue; case Block.chain: { const fl = frames.length; const lab = s.label(); if (i.pos !== Tag.push || i.value.directives) { yield s.enter(i.pos, Tag.BlockStatement); if (i.value.directives) yield* i.value.directives; yield s.enter(Tag.body, Tag.Array); } cur = yield* _convert(s.sub(), cur, i.value); const goto = frames.length > fl ? frames[fl][0].value : null; yield s.tok(Tag.push, Ctrl.jump, { goto }); yield* lab(); if (i.value.brkRefs) for (const j of i.value.brkRefs) { cur.push(j); } s.close(i); } continue; case Block.frame: setGoto(cur, i.value); i.value.repeat = []; /** the frame should be present in final output */ i.value.noInline = false; i.value.chain = chain; i.value.declSym = Kit.scope.newSym("_"); const inner = [i]; frames.push(inner); cur = Kit.result( Kit.repos(_convert(s.sub(), [], chain), Tag.push), inner ); if (!i.value.eff && inner[inner.length - 1].type !== Ctrl.jump) { const j = s.tok(Tag.push, Ctrl.jump); inner.push(j); cur.push(j.value); } inner.push(s.close(i)); continue; case Block.app: if (i.value.eff) { invariant(!cur.length); let fl = frames.length; const bodyJumps = yield* _convert(s.one(), cur, chain); const j = s.curLev(); let params; if (j.pos === Tag.params) { const j = s.take(); params = [...s.one()]; s.close(j); } const hl = frames.length; const hjumps = Kit.skip(_convert(s.one(), [], chain)); const bodyOpen = frames[fl][0].value; const bodyClose = frames[hl - 1][0].value; const handle = frames[hl][0].value; const onOpen = bodyOpen.onOpen || (bodyOpen.onOpen = []); const onClose = bodyClose.onClose || (bodyClose.onClose = []); handle.tryBody = frames[fl][0].value; switch (i.value.sym) { case Except.handleId: const errSym = params.length && params[0].value.sym; onOpen.unshift( s.enter(Tag.push, catchBlock, { handle: handle, errSym }) ); onClose.push(...s.leave()); cur = bodyJumps.concat(hjumps); break; case Except.finallyId: const finJump = { declSym: unboundTempVar(s.first.value, "fc"), catchContRedir: needNextErrCont && { declSym: unboundTempVar(s.first.value, "fe") }, resultContRedir: needNextResCont && { declSym: unboundTempVar(s.first.value, "fr") }, dynamicJump: true, instances: new Set(), handle, defaultJumps: bodyJumps }; handle.contArg = finJump; onOpen.unshift(s.enter(Tag.push, finallyBlock, { handle })); onClose.push(...s.leave()); setGoto(hjumps, finJump); cur = bodyJumps; break; default: throw s.error(`unsupported "app" ${i.value.node.name}`); } s.close(i); const handleClose = frames[frames.length - 1][0].value; (handle.onOpen || (handle.onOpen = [])).unshift( s.enter(Tag.push, handleBlock, {}) ); (handleClose.onClose || (handleClose.onClose = [])).push( ...s.leave() ); cur.push((handle.frameAfterTry = { close: handleClose })); continue; } break; case Block.pure: const pj = s.enter(i.pos, Ctrl.jump, { result: i.value.result }); yield pj; if (!i.leave) { yield* s.sub(); s.close(i); } cur.push(pj.value); yield* s.leave(); continue; case Block.letStmt: const j = s.curLev(); if ( j != null && j.type === Block.pure && (!i.value.bindName || i.value.bindName === s.opts.bindName) ) { s.take(); i.value.eff = false; i.value.bindName = i.value.opSym = void 0; yield s.enter(i.pos, Ctrl.jump, i.value); if (!j.leave) yield* s.sub(); yield* s.leave(); s.close(j); s.close(i); cur.push(i.value); continue; } yield* s.copy(i); if (i.value.eff) cur.push(i.value); continue; case Loop.repeat: const fl = frames.length; const ncur = yield* _convert(s.sub(), cur, chain); const nfl = frames.length; if (nfl > fl) { const k = frames[fl][0].value; for (const l of ncur) if (l.goto == null) l.goto = k; } cur = []; s.close(i); continue; } } yield i; } return cur; } for (const i of s) { switch (i.type) { case Block.chain: if (i.enter) { yield Kit.setPos(i, Tag.body); yield* _convert(s.sub(), [], i.value); for (const j of frames) { const v = j[0].value; if (v.onOpen) { yield* v.onOpen; v.onOpen = null; } yield* j; if (v.onClose) { yield* v.onClose; v.onClose = null; } } yield Kit.setPos(s.close(i), Tag.body); continue; } break; default: yield i; } } }, Policy.stage("rawConvert"), Kit.toArray, // sets a few useful fields function postproc(sa) { const s = Kit.auto(sa); const bindName = s.opts.bindName || "chain"; _postproc(); return sa; function _postproc() { for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Block.frame: for (const j of s.sub()) { if (j.enter) { switch (j.type) { case Block.bindPat: break; case Block.letStmt: if (!j.value.eff) { j.value.ref = i.value; break; } if (j.value.bindName == null) j.value.bindName = bindName; j.value.suspending = j.value.bindName !== bindName; case Ctrl.jump: const bindJump = j.type === Block.letStmt; j.value.bindJump = bindJump; // avoiding inlining of some frame after for-of j.value.ref = i.value; } } } } } } } }, /** wraps chain with extra frames for exiting the function */ function* wrapChain(sa) { const s = Kit.auto(sa); const root = s.first.value; root.pureExitFrame = { declSym: s.opts.defunct ? Defunct.pureFrameSym : root.pureId, last: true, enters: new Set(), exits: new Set(), frameParamsClos: new Set() }; let first = sa.find(i => i.type === Block.frame); if (!first) return s; first = first.value; let chain; for (const i of s) { yield i; if (i.enter && i.type === Block.chain) { chain = i.value; break; } } const j = s.cur(); function* ctrlFrames() { const sym = (root.resSym = unboundTempVar(root, "r")); sym.optional = true; const psym = Kit.scope.newSym("r"); const fr = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("retv"), root, errSym: psym, last: true }); /** # a frame returning its argument */ root.resFrameRedir = fr.value; yield fr; yield s.enter(j.pos, Block.app, { sym: root.pureId, insideCtx: true }); yield s.tok(Tag.push, Tag.Identifier, { sym: psym }); yield* s.leave(); yield* s.leave(); const esym = Kit.scope.newSym("e"); // Bind.tempVarSym(root) const er = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("errv"), root, errSym: esym }); yield er; root.errFrameRedir = er.value; yield s.enter(j.pos, Block.app, { sym: root.raiseId, insideCtx: true }); yield s.tok(Tag.push, Tag.Identifier, { sym: esym }); yield* s.leave(); yield* s.leave(); /** a frame returning `resSym` */ const f = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("ret"), root, last: true, chain }); f.value.resultRedir = { errSym: psym, redir: fr.value }; root.resFrame = f.value; yield f; yield s.enter(Tag.push, Ctrl.jump, { goto: fr.value, ref: f.value, eff: true, op: null, opSym: null, bindJump: false, init: false }); yield s.tok(Tag.push, Tag.Identifier, { sym, lhs: false, rhs: true, decl: false }); yield* s.leave(); yield* s.leave(); return [sym, f.value, fr.value, er.value]; } const frame = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("_"), root, result: false }); yield frame; if (root.opts.scopePrefix) { const name = root.opts.scopePrefix.substr ? root.opts.scopePrefix : "scope"; yield s.enter(Tag.push, Block.letStmt, { goto: first, ref: frame.value, eff: true, op: null, opSym: Kit.sysId(name), bindName: name, bindJump: true, init: true }); } else { yield s.enter(Tag.push, Ctrl.jump, { goto: first, ref: frame.value, eff: true, op: null, opSym: scopeSym, bindJump: false, init: true }); } yield* s.leave(); yield* s.leave(); const resFrameCont = Kit.toArray(ctrlFrames()); yield* s.sub(); // needs to be in the end so `cleanup` pass can remove them if needed yield* resFrameCont; yield* s; }, /** * for each frame and jump adds * finally continuations: * - preCompose: FrameVal[] * catch continuations for frames: * - catchCont - { * // finally frames to execute on exit * preCompose:FrameVal[], * errSym:Sym, * // handler * goto:FrameVal, * // stack of `catch`/`finally` handlers for this frame * stack: FrameVal[] * // stack of `catch`/`finally` handler frames * hstack: FrameVal[] * } */ Kit.toArray, function preComposeTryCatch(si) { const s = Kit.auto(si); const root = s.first.value; const { resFrame } = root; const preCompose = root.preCompose || []; preCompose.unshift(resFrame); const errPreCompose = []; const errSym = unboundTempVar(root, "err"); return Kit.toArray( walk({ goto: null, errSym, preCompose: [], stack: [], hstack: [] }) ); function* walk(cc) { for (const i of s.sub()) { if (i.enter) { switch (i.type) { case finallyBlock: const cont = i.value.handle.contArg; preCompose.unshift(i.value.handle); errPreCompose.unshift(i.value.handle); const errSym = unboundTempVar(root, "err"); yield* walk({ goto: cc.goto, errSym, preCompose: [...errPreCompose], stack: [...cc.stack, i.value.handle], hstack: cc.hstack }); preCompose.shift(); errPreCompose.shift(); s.close(i); const fh = s.take(); invariant(fh.type === handleBlock); const args = cont.args || (cont.args = new Map()); addArg(args, cc.errSym, errSym); yield* walk({ goto: cc.goto, errSym: cc.errSym, preCompose: cc.preCompose, stack: cc.stack, hstack: [...cc.hstack, i.value.handle] }); s.close(fh); continue; case catchBlock: yield* walk({ goto: i.value.handle, errSym: i.value.errSym, preCompose: [...cc.preCompose], stack: [...cc.stack, i.value.handle], hstack: cc.hstack }); s.close(i); const ch = s.take(); invariant(ch.type === handleBlock); yield* walk({ goto: cc.goto, errSym: cc.errSym, preCompose: cc.preCompose, stack: cc.stack, hstack: [...cc.hstack, i.value.handle] }); s.close(ch); continue; case Block.letStmt: if (!i.value.eff) break; case Ctrl.jump: if (i.value.goto) { if (i.value.goto.handle) i.value.goto.preCompose = i.value.goto.handle.preCompose; } i.value.preCompose = [...preCompose]; break; case Block.frame: i.value.catchCont = cc; /** collects chain of finally blocks to be executed here */ i.value.preCompose = [...preCompose]; i.value.errPreCompose = [...errPreCompose]; break; } } yield i; } } }, Kit.toArray, /** * for try-finally (without catch) statements generates a frame for throwing * catched exception again */ function* addReThrowFrames(si) { const s = Kit.auto(si); const root = s.first.value; const termFrames = []; const errFrames = new Map(); function* makeErrFrame(catchCont) { const lab = s.label(); const sym = catchCont.errSym; const res = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("throw_"), root, eff: true, throwSym: sym, insideCtx: true }); yield res; yield s.enter(Tag.push, Block.app, { sym: root.raiseId, insideCtx: true, last: true }); yield s.tok(Tag.push, Tag.Identifier, { sym, lhs: false, rhs: true, decl: false }); yield* lab(); return res.value; } for (const i of s) { yield i; if (i.type === Block.chain) break; } for (const i of s.sub()) { yield i; if (i.enter && i.type === Block.frame) { const { catchCont } = i.value; if (!catchCont.goto) { let frame = errFrames.get(catchCont.errSym); if (!frame) { const content = Kit.toArray(makeErrFrame(catchCont)); frame = content[0].value; termFrames.push(...content); errFrames.set(catchCont.errSym, frame); } catchCont.goto = frame; } } } yield* termFrames; yield* s; }, /** * emits auxiliary frames if there are jumps through several finally blocks */ function* composeFinallyBlocks(si) { const s = Kit.auto(si); const root = s.first.value; const { resFrame, resSym, errFrameRedir } = root; const storeResultCont = root.opts.storeResultCont || root.opts.defunct; const redirFrames = []; for (const i of s) { yield i; if (i.type === Block.chain) break; } for (const i of s.sub()) { if (i.enter && i.type === Block.frame) { yield* frame(i); continue; } yield i; } yield* redirFrames; yield* s; function cutChain(jump, dstChain) { let res = jump.preCompose || emptyArr; if (!res.length) return res; res = [...res]; const dst = jump.goto; if (!dst) return res; if (!dstChain) return res; for (const i of Kit.reverse(dstChain)) { if (i === res[res.length - 1]) res.pop(); else break; } return res; } function preComposeFrame(jump, chain) { const len = chain.length; jump.preCompose = null; if (len) { const indirJumps = (jump.indirJumps = new Map()); for (let i = 0; ; ) { const step = chain[i++]; const cont = step.contArg; if (i < len) { const next = chain[i]; indirJumps.set(next, cont); cont.instances.add(next); } else { if (jump.goto) { if (cont) { indirJumps.set(jump.goto, cont); cont.instances.add(jump.goto); } } else { if (jump.result) { resSym.bound = true; (jump.frameArgs || (jump.frameArgs = new Map())).set( resSym, Block.argSym ); } } break; } } jump.indirGoto = jump.goto; jump.goto = chain[0]; } } function* makeRedir(cont) { if (cont.goto && cont.goto.throwSym) { cont.redir = errFrameRedir; return; } const sym = Kit.scope.newSym(); const redir = s.enter(Tag.push, Block.frame, { declSym: Kit.scope.newSym("ce_"), root, errSym: sym, savedDecls: new Map() }); cont.redir = redir.value; yield redir; const args = new Map(cont.frameArgs); yield s.tok(Tag.push, Ctrl.jump, { goto: cont.goto, ref: redir.value, indirJumps: cont.indirJumps, frameArgs: args }); if (cont.errSym) { cont.errSym.bound = true; args.set(cont.errSym, sym); } yield* s.leave(); } function* frame(i) { const frame = i.value; let { catchCont } = i.value; function getResCont() { if (frame.resultCont) return frame.resultCont; const result = (frame.preCompose && frame.preCompose[0]) || resFrame; if (result.resultRedir) return (frame.resultCont = result.resultRedir); const resCont = (frame.resultCont = result.resultRedir = { errSym: resSym }); preComposeFrame(resCont, frame.preCompose); redirFrames.push(...makeRedir(resCont)); if (resCont.goto) resCont.goto.noInline = true; return resCont; } if (catchCont) { if (!catchCont.composed) { const chain = cutChain( catchCont, catchCont.goto && catchCont.goto.errPreCompose ); preComposeFrame(catchCont, chain); redirFrames.push(...makeRedir(catchCont)); catchCont.composed = true; } i.value.catchContRedir = catchCont.redir; if (catchCont.goto) catchCont.goto.noInline = true; } else i.value.catchContRedir = errFrameRedir; yield i; if (catchCont && !catchCont.goto) catchCont = null; if (!frame.savedDecls) frame.savedDecls = new Map(); for (const j of s.sub()) { if (j.enter) { if (storeResultCont) getResCont(); switch (j.type) { case Block.letStmt: if (!j.value.eff) break; case Ctrl.jump: if (frame === resFrame) break; preComposeFrame( j.value, cutChain( j.value, (j.value.goto && j.value.goto.preCompose) || emptyArr ) ); if ( j.type === Block.letStmt && j.value.goto === resFrame && j.value.result ) { const resultCont = getResCont(); j.value.goto = resultCont.goto; j.value.sym = resultCont.errSym; } break; } } yield j; } if (frame.resultCont) frame.resultContRedir = frame.resultCont.redir; yield s.close(i); } }, Inline.throwStatements, Kit.toArray, function cfgPostProc(sa) { const root = sa[0].value; Ctrl.convolveFrames(sa); let cfg = root.cfg; cfg = Opt.removeUnreachable(cfg); Ctrl.instantiateJumps(cfg); Ctrl.resetEnters(cfg); for (const i of cfg) { if (i.throwSym) i.throwSym.bound = true; for (const j of i.exits) jumpArgs(j); if (i.catchCont) jumpArgs(i.catchCont); } return Block.cleanup(sa); }, Opt.removeSingleJumps, Kit.toArray ); /** converts indirect jumps into symbol arguments */ function jumpArgs(j) { if (j.indirJumps) { const args = j.frameArgs || (j.frameArgs = new Map()); for (const [dest, cont] of j.indirJumps) { if (!cont.reachable) continue; args.set(cont.declSym, dest.declSym); cont.declSym.bound = true; if (cont.resultContRedir && dest.resultContRedir) { args.set(cont.resultContRedir.declSym, dest.resultContRedir.declSym); cont.resultContRedir.declSym.bound = true; dest.resultContRedir.required = true; cont.resultContRedir.required = true; } if (cont.catchContRedir && dest.catchContRedir) { args.set(cont.catchContRedir.declSym, dest.catchContRedir.declSym); cont.catchContRedir.required = true; dest.catchContRedir.required = true; cont.catchContRedir.declSym.bound = true; } } } } /** generates local copies of variables used in each frame */ function* copyFrameVars(si) { const s = Kit.auto(si); const frame = yield* s.till(i => i.enter && i.type === Block.frame); const root = s.first.value; if (!root.savedDecls) root.savedDecls = new Map(); const reuseTemps = s.opts.reuseTempVars !== false; const commonPatSym = root.commonPatSym; yield* frameContent(frame.value); for (const i of s) { yield i; if (i.enter && i.type === Block.frame) yield* frameContent(i.value); } function isRef(sym) { return sym.interpr === Bind.ctxField || sym.interpr === Bind.closureVar; } function* frameContent(frame) { const first = frame === root.first; const decls = frame.savedDecls; const sw = frame.stateVars; const vars = new Set(); if (sw) { sw.w.forEach(vars.add, vars); sw.r.forEach(vars.add, vars); } const patSym = frame.errSym || frame.patSym; let patCopy; /** optimizing expressions like `v = await e` */ if (patSym && isRef(patSym) && patSym.extBind) { patCopy = commonPatSym || Kit.scope.newSym(); yield s.enter(Tag.push, Tag.AssignmentExpression, { node: { operator: "=" } }); let patOrig = patSym; if (patSym.assignedAt) { const { assignPat } = patSym.assignedAt; if (!assignPat.parCopy && assignPat.interpr) { patOrig = assignPat; patSym.removed = patSym.assignedAt.removed = true; } } yield s.tok(Tag.left, Tag.Identifier, { sym: patOrig }); yield s.tok(Tag.right, Tag.Identifier, { sym: patCopy }); yield* s.leave(); } else if (commonPatSym) { patCopy = commonPatSym; } if (patCopy) { if (frame.errSym) { // for (const i of frame.enters) // if (i.sym === frame.errSym) i.sym = patCopy; frame.errSym = patCopy; } else frame.patSym = patCopy; } const tempVars = []; const substPatSym = commonPatSym && patSym ? function*() { for (const i of s.sub()) { if ( i.enter && (i.type === Block.bindPat || i.type === Tag.Identifier) && i.value.sym === patSym ) i.value.sym = commonPatSym; yield i; } } : function() { return s.sub(); }; for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Block.bindPat: case Tag.Identifier: const { sym } = i.value; if (sym) { if (commonPatSym && sym === patSym) i.value.sym = commonPatSym; else if (sym.interpr === Bind.ctxField) i.value.insideCtx = !frame.first; } break; case Tag.AssignmentExpression: if (i.value.removed) { Kit.skip(s.copy(i)); continue; } break; case Block.letStmt: if (!i.value.eff) break; case Ctrl.jump: if (!i.value.gotoDests.length) break; const { goto } = i.value; let gotoSym, catchContSym, resultContSym; if (goto) { const { catchContRedir: cc, resultContRedir: rc } = goto; gotoSym = goto && goto.declSym; catchContSym = cc && !cc.removed && cc.declSym; resultContSym = rc && !rc.removed && rc.declSym; } const del = new Set(); const args = i.value.frameArgs; let assignArg; const assign = []; if (args) { for (let [left, right] of args) { if (isRef(left)) { if (right === Block.argSym) assignArg = left; else { if (commonPatSym && patSym && right === patSym) right = commonPatSym; assign.push([ left, [s.tok(Tag.right, Tag.Identifier, { sym: right })] ]); } } } } if (!first && !i.value.reflected && s.opts.cleanupFrameVars) { const nextList = []; for (const j of i.value.gotoDests) nextList.push(...j.frameParamsClos); const next = new Set(nextList); for (const i of vars) { if (i.removed) continue; if (!next.has(i) && !i.closCapt && isRef(i)) del.add(i); } } assign.sort(byNumFst); let inner = i.leave ? null : Kit.toArray(substPatSym()); if (assignArg && inner && inner.length) { assign.push([assignArg, Kit.reposOneArr(inner, Tag.right)]); inner = null; } if (del.size) { const delList = []; const subst = new Map(); let tmpVarNum = 0; function getCopy(sym) { let copy = subst.get(sym); if (!copy) { if (!reuseTemps || !(copy = tempVars[tmpVarNum++])) { copy = Kit.scope.newSym(); if (reuseTemps) tempVars.push(copy); decls.set(copy, { raw: null }); } assign.push([ copy, [s.tok(Tag.right, Tag.Identifier, { sym })] ]); subst.set(sym, copy); } return copy; } if (inner) { for (const j of inner) { let sym; if (j.enter) { switch (j.type) { case Block.bindPat: if (commonPatSym && patSym && j.value.sym === patSym) { j.value.sym = commonPatSym; break; } case Tag.Identifier: if ((sym = j.value.sym) && del.has(sym)) j.value.sym = getCopy(sym); } } } } if (gotoSym && del.has(gotoSym)) gotoSym = getCopy(gotoSym); if (catchContSym && del.has(catchContSym)) catchContSym = getCopy(catchContSym); if (resultContSym && del.has(resultContSym)) resultContSym = getCopy(resultContSym); for (const i of del) delList.push([i, [s.tok(Tag.right, Tag.NullLiteral)]]); delList.sort(byNumFst); assign.push(...delList); } const lab = s.label(); invariant(i.pos === Tag.push); i.value.gotoSym = gotoSym; i.value.catchContSym = catchContSym; i.value.resultContSym = resultContSym; if (assign.length) { yield s.enter(Tag.push, Tag.SequenceExpression); yield s.enter(Tag.expressions, Tag.Array); for (const [sym, init] of assign) { yield s.enter(Tag.push, Tag.AssignmentExpression, { node: { operator: "=" } }); yield s.tok(Tag.left, Tag.Identifier, { sym }); yield* init; yield* s.leave(); } yield* lab(); } yield s.peel(i); if (inner && inner.length) yield* Kit.reposOneArr(inner, Tag.push); yield* lab(); continue; } } yield i; } } } export function interpretFrames(si) { const s = Kit.auto(si); const root = s.first.value; const rootName = root.rootName; const top = !!s.opts.topLevel; if (top) root.module.hasTop = true; let paramPrefix = function*() {}; const ctxSym = s.first.value.contextSym; if (ctxSym && ctxSym.bound && s.opts.contextBy === "parameter") { paramPrefix = function*() { yield s.tok(Tag.push, Tag.Identifier, { sym: ctxSym }); }; } const byThis = ctxSym && s.opts.contextBy === "this"; let num = 0; function* walk() { for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Block.chain: yield s.enter(i.pos, Tag.BlockStatement); if (i.value.directives) yield* i.value.directives; yield s.enter(Tag.body, Tag.Array); yield* walk(); yield* s.leave(); yield* s.leave(); s.close(i); continue; case Block.bindPat: yield s.tok(i.pos, Tag.Identifier, i.value); s.close(i); continue; case Block.frame: const fn = num++; i.value.moveToTop = top; const flab = s.label(); if (fn !== 0) { i.value.declSym.orig = `${rootName}_${fn}`; if (byThis) (i.value.savedDecls || (i.value.savedDecls = new Map())).set( ctxSym, { raw: null, init: [s.tok(Tag.init, Tag.ThisExpression)] } ); i.value.func = true; yield s.enter(Tag.push, Tag.FunctionDeclaration, i.value); yield s.tok(Tag.id, Tag.Identifier, { sym: i.value.declSym, decl: true }); const paramLab = s.label(); yield s.enter(Tag.params, Tag.Array); yield* paramPrefix(i.value); if (i.value.ctrlParam) yield s.tok(Tag.push, Tag.Identifier, { sym: i.value.ctrlParam }); const patSym = i.value.errSym || i.value.patSym; if (patSym && !patSym.dummy) yield s.tok(Tag.push, Tag.Identifier, { sym: patSym }); yield* paramLab(); yield s.enter(Tag.body, Tag.BlockStatement); yield s.enter(Tag.body, Tag.Array); } else { // first frame is erased, so copying its vars here const { savedDecls } = root; for (const [j, v] of i.value.savedDecls) if (!savedDecls.has(j)) savedDecls.set(j, v); } yield* walk(); yield* flab(); s.close(i); continue; } } yield i; } } return walk(); } /** converts `letStmt` and `jump` into JS expressions*/ export function interpretJumps(si) { const s = Kit.auto(si); const { bindName, pureBindName } = s.opts; const root = s.first.value; const passCont = !s.opts.inlineContAssign; const passCatchCont = !s.opts.defunct && !s.opts.inlineErrorContAssign; const passResultCont = !s.opts.defunct && !s.opts.inlineResultContAssign; const { markRepeat, keepLastPure } = s.opts; return _interpretJumps(); function* _interpretJumps() { for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Block.letStmt: if (!i.value.eff) break; case Ctrl.jump: const frame = i.value.ref; const pure = i.type === Ctrl.jump; const insideCtx = !frame.first; const lab = s.label(); const { goto, gotoDests, delegateCtx } = i.value; let rec = pure && markRepeat && i.value.rec; const pos = i.pos; const defaultName = pure ? pureBindName : bindName; let name = i.value.bindName || defaultName; const st = s.opts.static || !s.opts.methodOps[name]; if ( (!gotoDests.length && name === defaultName) || (!keepLastPure && pure && goto === root.pureExitFrame) ) { yield pure ? s.enter(pos, Block.app, { sym: root.pureId, insideCtx, delegateCtx, reflected: i.value.reflected, tmpVar: i.value.tmpVar }) : s.enter(pos, Block.effExpr, { reflected: i.value.reflected, tmpVar: i.value.tmpVar }); if (!i.leave) yield* _interpretJumps(); } else { let catchCont, resCont; if (goto) { if (passCatchCont && i.value.catchContSym) catchCont = i.value.catchContSym; if (passResultCont && i.value.resultContSym) resCont = i.value.resultContSym; } const appVal = { fam: Kit.sysId(name), static: st, insideCtx: !i.value.ref.first, delegateCtx, passCont, goto: i.value.gotoSym, result: name === "scope", reflected: i.value.reflected, tmpVar: i.value.tmpVar, cloneCtx: i.value.cloneCtx }; if (s.curLev()) { if (s.opts.markBindValue !== false) name += "B"; appVal.hasBindVal = true; } else if ( i.type === Ctrl.jump && s.opts.markBindValue === false ) { appVal.hasBindVal = true; } if (rec) { name += "R"; appVal.noInline = true; } if (catchCont && passCatchCont) { if (s.opts.markErrorCont !== false) name += "H"; appVal.hasErrorCont = true; } if (resCont && passResultCont) { if (s.opts.markResultCont !== false) name += "F"; appVal.hasResultCont = true; } appVal.sym = Kit.sysId(name); if (passCont) appVal.hasCont = true; yield s.enter(pos, Block.app, appVal); invariant(goto); if (s.curLev()) yield* _interpretJumps(); else if (appVal.hasBindVal) yield s.tok(Tag.push, Tag.Identifier, { sym: Kit.scope.undefinedSym }); if (passCont) yield s.tok(Tag.push, Tag.Identifier, { sym: i.value.gotoSym }); if (catchCont && passCatchCont) yield s.tok(Tag.push, Tag.Identifier, { sym: catchCont }); if (resCont && passResultCont) yield s.tok(Tag.push, Tag.Identifier, { sym: resCont }); if (i.value.params) for (const sym of i.value.params) yield s.tok(Tag.push, Tag.Identifier, { sym }); } yield* lab(); s.close(i); continue; } } yield i; } } } /** calculates `patSym` field */ function calcPatSym(cfg) { for (const i of cfg) { if (!i.errSym && !(i.patSym && !i.patSym.dummy)) { const { enters } = i; if (enters && enters.size > 0) { [{ sym: i.patSym }] = enters; } } } } /** * calculate inter-frame dependecies * - `frameLocals: Set<Symbol>`: used or written by the frame but not read: * - `frameParams: Set<Symbol>`: needed by the frame * - `framePat: Set<Symbol>`: received from bound effectful value * - `frameParamsClos: Set<Symbol>`: needed by the frame or some next frame */ function calcVarDeps(si) { let sa = Kit.toArray(si); const root = sa[0].value; Ctrl.convolveFrames(sa); sa = Kit.toArray(cleanup(sa)); State.calcFlatCfg(root.cfg, sa); // if (!root.opts.keep return sa; } /** * For all symbols which are still in the programm setting `bound: true` */ function markBound(si) { const sa = Kit.toArray(si); for (const i of sa) { if ( i.enter && (i.type === Tag.Identifier || i.type === Block.bindPat) && i.value.sym && !i.value.sym.optional ) { i.value.sym.bound = true; } } return sa; } /** * if bind variable is used only in the frame where it is bound * we can avoid tracking it, also calculates `assignedAt` and `assignPat` * fields for each assignment expression with bindPat RHS */ function localizeBinds(sa) { let s = Kit.auto(sa); const forseBind = s.opts.markBindValue === false || s.opts.defunct; const rootDecls = s.first.value.savedDecls; const bindVars = new Set(); if (s.opts.optBindAssign !== false) { for (const i of s) { switch (i.type) { case Tag.AssignmentExpression: if ( i.value.node.operator === "=" && s.cur().type === Tag.Identifier ) { i.value.assignPat = s.cur().value.sym; Kit.skip(s.one()); if (s.cur().type === Block.bindPat) s.cur().value.sym.assignedAt = i.value; } break; } } s = Kit.auto(sa); } const bindExprs = []; for (const i of s) { if (i.enter && i.type === Block.frame) { if (i.value.patSym && !i.value.patSym.dummy) { i.value.patSym.boundAt = i.value; bindVars.add(i.value.patSym); i.value.patSym.extBind = false; } for (const j of s.sub()) { if (j.enter) { switch (j.type) { case Block.letStmt: if (!j.value.eff) { if (j.value.sym) { j.value.sym.boundAt = i.value; bindVars.add(j.value.sym); j.value.sym.extBind = false; } break; } case Ctrl.jump: if (forseBind && j.value.gotoDests) { for (const k of j.value.gotoDests) { if (!k.patSym && !k.errSym) { const sym = Kit.scope.newSym(); sym.dummy = true; k.patSym = sym; } } } break; case Block.bindPat: j.value.ref = i.value; bindExprs.push(j.value); break; } } } } } for (const i of bindExprs) { if (i.sym.boundAt !== i.ref) { i.sym.extBind = true; } } for (const i of bindVars) { if (!i.extBind) { i.interpr = null; rootDecls.delete(i); if (i.bound && i.boundAt.patSym !== i) i.boundAt.savedDecls.set(i, { raw: null }); } } } /** * removes a few useless items from resulting code * - result/exception frames if they are not used * - not bound identifiers */ function cleanup(si) { const sa = Kit.toArray(si); localizeBinds(sa); const s = Kit.auto(sa); const root = s.first.value; const { resFrame, resFrameRedir, errFrameRedir, resSym, savedDecls, contextSym } = root; const needResultCont = s.opts.keepLastPure || s.opts.storeResultCont; const needErrorCont = s.opts.keepLastRaise || s.opts.storeErrorCont; if (contextSym.bound === false) root.contextSym = null; const ns = s.opts.contextMethodOps && root.contextSym; for (const i of savedDecls.keys()) if (i.bound === false) savedDecls.delete(i); const res = Kit.toArray(walk()); for (const i of root.cfg) i.removed = true; root.cfg[0].removed = false; for (const i of root.cfg) { if (i.required) i.removed = false; for (const j of i.exits) markGoto(j); markGoto(i.catchCont); markGoto(i.resultCont); if (i.catchContRedir) i.catchContRedir.removed = false; if (i.resultContRedir) i.resultContRedir.removed = false; } return Block.cleanup(res); function markGoto(value) { if (!value) return; if (value.frameArgs) { for (const i of value.frameArgs.keys()) { if (!i.bound) value.frameArgs.delete(i); } } if (value.goto) { value.goto.removed = false; if (value.goto.dynamicJump) { for (const i of value.goto.instances) i.removed = false; } } if (value.indirJumps) { for (const i of value.indirJumps.keys()) i.removed = false; } if (value.redir) value.redir.removed = false; } function* writeResult(j) { yield s.enter(j.pos, Block.app, { sym: root.pureId, insideCtx: !j.value.ref.first }); const args = j.value.frameArgs; let sym; if ((sym = args && args.get(resSym))) { if (sym === Block.argSym) yield* inner(); else yield s.tok(Tag.push, Tag.Identifier, { sym, lhs: false, rhs: true, decl: false }); } else if (s.curLev()) { yield* inner(); } else if (resSym.bound) yield s.tok(Tag.push, Tag.Identifier, { sym: resSym, lhs: false, rhs: true, decl: false }); yield* s.leave(); s.close(j); } function* writeError(j) { const lab = s.label(); const errSym = j.value.goto.throwSym; const sym = (errSym && j.value.frameArgs && j.value.frameArgs.get(errSym)) || errSym; yield s.enter(j.pos, Tag.CallExpression, { result: true }); yield s.tok(Tag.callee, Tag.Identifier, { sym: root.raiseId, ns }); yield s.enter(Tag.arguments, Tag.Array); yield s.tok(Tag.push, Tag.Identifier, { sym, lhs: false, rhs: true, decl: false }); yield* lab(); s.close(j); } function* inner() { for (const i of s.sub()) { if ( i.enter && i.type === Tag.Identifier && i.value.sym && i.value.sym.bound === false ) { Kit.skip(s.copy(i)); } else yield i; } } function* walk() { for (const i of s.sub()) { if (i.enter) { switch (i.type) { case Tag.ThrowStatement: if (i.pos === Tag.push) { yield i; if (!i.leave) { yield* inner(); yield s.close(i); } Kit.skip(s.sub()); continue; } break; case Block.frame: if (i.value.patSym && i.value.patSym.bound === false) i.value.patSym = null; if (i.value.errSym && i.value.errSym.bound === false) i.value.errSym = null; if ( i.value.patSym && i.value.patSym.interpr && !i.value.patSym.bound ) { i.value.patSym.interpr = null; i.value.patSym.dummy = true; } if (i.value.catchContRedir) { if ( i.value.catchContRedir === errFrameRedir && !needErrorCont && !( i.value.catchCont && i.value.catchCont.indirJumps && i.value.catchCont.indirJumps.size ) ) { i.value.catchContRedir = null; i.value.catchCont = null; } } if (i.value.resultContRedir) { if (!needResultCont) { i.value.resultContRedir = null; i.value.resultCont = null; } } if (i.value === resFrame) { yield i; for (const i of s.sub()) { if ( (i.type === Tag.Identifier || i.type === Block.bindPat) && i.value.sym && !i.value.sym.bound ) continue; yield i; } continue; } break; case Block.letStmt: if (i.value.sym && !i.value.sym.bound) i.value.sym = null; if (!i.value.eff) break; case Ctrl.jump: const args = i.value.frameArgs; if (args) { for (const j of args.keys()) if (j.bound === false) args.delete(j); } if (i.value.goto === resFrameRedir && !needResultCont) { yield s.enter(i.pos, Block.effExpr, { result: i.value.result }); yield* inner(); yield* s.leave(); s.close(i); continue; } if (i.value.goto === resFrame) { if (i.type === Ctrl.jump) { const [exit] = resFrame.exits; i.value.goto = exit && exit.goto; yield* writeResult(i); resFrame.enters.delete(i.value); continue; } } else if (i.value.goto && i.value.goto.throwSym) { if (i.type === Ctrl.jump) { const [exit] = i.value.goto.exits; yield* writeError(i); i.value.goto.enters.delete(i.value); i.value.goto = exit && exit.goto; continue; } } } } yield i; } } } /** * calcualtes transitive closure of frames' control flow graph if needed * * type RootVal = RootVal & { cfg: FrameVal[] } * * type FrameVal = FrameVal & { * -- frames after this frame in control flow * framesAfter: Set<FrameVal>, * framesBefore: Set<FrameVal> * } * * type JumpLetVal = JumpLetVal & { * // the jump is recursive * rec: boolean * } * * assumes the frames are topologically sorted */ function prepareCfg(sa) { const root = sa[0].value; const opts = root.opts; Ctrl.convolveFrames(sa); const cfg = root.cfg; calcPatSym(cfg); const needsTransClos = opts.par; const needsRec = opts.par || opts.markRepeat; root.pureExitFrame.framesAfter = new Map(); if (!needsRec) return sa; if (needsRec) for (const i of cfg) i.calcBranchesVisited = false; if (needsTransClos) for (const i of cfg) { i.framesAfter = new Set(); i.framesBefore = new Set(); } if (needsRec) for (const i of cfg) { i.calcBranchesVisited = true; for (const j of i.exits) { const goto = j.indirGoto || j.goto; if (goto.calcBranchesVisited) { j.rec = true; } } } return sa; } /** conferts flat structure to JS expressions */ export const interpret = Kit.pipe( Inline.markSimpleRedir, markBound, prepareCfg, Par.convert, Policy.stage("flat-interpret-opt"), Opt.removeSingleJumps, Opt.inlineFrames, Policy.stage("flat-interpret-vars"), calcVarDeps, ifDefunct(Defunct.init), Par.postproc, Opt.inlinePureCont, Inline.storeContinuations, ifDefunct(Defunct.prepare), Gens.functionSentAssign, Bind.interpretPureLet, copyFrameVars, Policy.stage("interpretFrames"), ifDefunct(Defunct.convert), Policy.stage("clean-jumps"), Coerce.cleanPureJumps, Policy.stage("defunctFrames"), Inline.jumps, interpretJumps, Policy.stage("flat-interpret-3"), Inline.control, interpretFrames, Kit.toArray, ifDefunct(Defunct.substSymConsts) );
// @flow strict import { useStaticQuery, graphql } from 'gatsby'; const useSiteMetadata = () => { const { site } = useStaticQuery( graphql` query SiteMetaData { site { siteMetadata { author { name bio photo contacts { email telegram github } } menu { label path } url title subtitle copyright disqusShortname } } } ` ); return site.siteMetadata; }; export default useSiteMetadata;
describe('Atm', function() { it('should send value to server', function() { browser.get('http://localhost:8080/withdrawal'); element(by.model('vm.withdrawalValue')).sendKeys('200'); // Find the first (and only) button on the page and click it element(by.id("withdrawal")).click(); function eventual(expectedCondition) { return browser.wait(expectedCondition, 2000).then(function() { return true; }, function() { return false; }); } var EC = protractor.ExpectedConditions; var e = element(by.id('msg')); expect(eventual(EC.presenceOf(e))).toBe(true); expect(e.isPresent()).toBeTruthy(); }); it('should have msg', function() { function eventual(expectedCondition) { return browser.wait(expectedCondition, 2000).then(function() { return true; }, function() { return false; }); } var EC = protractor.ExpectedConditions; var e = element(by.id('msg')); expect(eventual(EC.presenceOf(e))).toBe(true); expect(e.getText()).toEqual("Vocรช sacou 200 reais!"); }); });
const enums = { PlayerBan: 'player.bans', PlayerKick: 'player.kicks', PlayerMute: 'player.mutes', PlayerNote: 'player.notes', PlayerWarning: 'player.warnings' } module.exports = (type) => enums[type]
import moment from 'moment'; export class WeekCalcer { constructor(matches, currentWeek, includeFreeMatches = false) { this.includeFreeMatches = includeFreeMatches; this.matches = matches.sort((a, b) => a.date - b.date); this.setCurrentWeeks(currentWeek); } getMatches() { const week = this.getWeek(); // TODO: the includeFreeMatches is broken because this.weeks needs a weekSorta and weekVttl prop... // const matchFilter = match => match.date.isBetween(week.start, week.end) || (this.includeFreeMatches && match.week === this.currentWeek); const matchFilter = match => match.date.isBetween(week.start, week.end); return this.matches.filter(matchFilter); } getWeek() { return this.weeks[this.currentWeek - 1]; } setCurrentWeeks(currentWeek) { this.currentWeek = currentWeek; if (!this.matches.size) { this.firstWeek = 1; this.currentWeek = 1; this.lastWeek = 22; this.weeks = [{start: moment().startOf('week'), end: moment().endOf('week')}]; return; } this.weeks = this.matches.reduce((acc, next) => { const date = next.date.clone().startOf('week'); if (!acc.length || !acc[acc.length -1].start.isSame(date, 'day')) { acc.push({start: date, end: next.date.clone().endOf('week')}); } return acc; }, []); //console.log('weekz', this.weeks.map(x => x.start.toString() + " -> " + x.end.toString())); this.firstWeek = 1; this.lastWeek = this.weeks.length; if (!this.currentWeek) { let testWeek = moment().startOf('week'); const indexFinder = w => w.start.isSame(testWeek, 'day'); while (!this.currentWeek) { this.currentWeek = this.weeks.findIndex(indexFinder) + 1; testWeek = testWeek.add(1, 'week'); if (testWeek.isAfter(this.weeks[this.weeks.length - 1].end)) { this.currentWeek = this.lastWeek; break; } } } } }
/* Copyright (c) 2009, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.7.0 */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; /** * @module editor * @description <p>Creates a rich custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar</p> * @class ToolbarButtonAdvanced * @namespace YAHOO.widget * @requires yahoo, dom, element, event, container_core, menu, button * * Provides a toolbar button based on the button and menu widgets. * @constructor * @class ToolbarButtonAdvanced * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ if (YAHOO.widget.Button) { YAHOO.widget.ToolbarButtonAdvanced = YAHOO.widget.Button; /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ YAHOO.widget.ToolbarButtonAdvanced.prototype.buttonType = 'rich'; /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ YAHOO.widget.ToolbarButtonAdvanced.prototype.checkValue = function(value) { var _menuItems = this.getMenu().getItems(); if (_menuItems.length === 0) { this.getMenu()._onBeforeShow(); _menuItems = this.getMenu().getItems(); } for (var i = 0; i < _menuItems.length; i++) { _menuItems[i].cfg.setProperty('checked', false); if (_menuItems[i].value == value) { _menuItems[i].cfg.setProperty('checked', true); } } }; } else { YAHOO.widget.ToolbarButtonAdvanced = function() {}; } /** * @description <p>Creates a basic custom Toolbar Button. Primarily used with the Rich Text Editor's Toolbar</p><p>Provides a toolbar button based on the button and menu widgets, &lt;select&gt; elements are used in place of menu's.</p> * @class ToolbarButton * @namespace YAHOO.widget * @requires yahoo, dom, element, event * @extends YAHOO.util.Element * * * @constructor * @param {String/HTMLElement} el The element to turn into a button. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.ToolbarButton = function(el, attrs) { YAHOO.log('ToolbarButton Initalizing', 'info', 'ToolbarButton'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = (attrs || {}); var oConfig = { element: null, attributes: local_attrs }; if (!oConfig.attributes.type) { oConfig.attributes.type = 'push'; } oConfig.element = document.createElement('span'); oConfig.element.setAttribute('unselectable', 'on'); oConfig.element.className = 'yui-button yui-' + oConfig.attributes.type + '-button'; oConfig.element.innerHTML = '<span class="first-child"><a href="#">LABEL</a></span>'; oConfig.element.firstChild.firstChild.tabIndex = '-1'; oConfig.attributes.id = (oConfig.attributes.id || Dom.generateId()); oConfig.element.id = oConfig.attributes.id; YAHOO.widget.ToolbarButton.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.ToolbarButton, YAHOO.util.Element, { /** * @property buttonType * @private * @description Tells if the Button is a Rich Button or a Simple Button */ buttonType: 'normal', /** * @method _handleMouseOver * @private * @description Adds classes to the button elements on mouseover (hover) */ _handleMouseOver: function() { if (!this.get('disabled')) { this.addClass('yui-button-hover'); this.addClass('yui-' + this.get('type') + '-button-hover'); } }, /** * @method _handleMouseOut * @private * @description Removes classes from the button elements on mouseout (hover) */ _handleMouseOut: function() { this.removeClass('yui-button-hover'); this.removeClass('yui-' + this.get('type') + '-button-hover'); }, /** * @method checkValue * @param {String} value The value of the option that we want to mark as selected * @description Select an option by value */ checkValue: function(value) { if (this.get('type') == 'menu') { var opts = this._button.options; for (var i = 0; i < opts.length; i++) { if (opts[i].value == value) { opts.selectedIndex = i; } } } }, /** * @method init * @description The ToolbarButton class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.ToolbarButton.superclass.init.call(this, p_oElement, p_oAttributes); this.on('mouseover', this._handleMouseOver, this, true); this.on('mouseout', this._handleMouseOut, this, true); this.on('click', function(ev) { Event.stopEvent(ev); return false; }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.ToolbarButton.superclass.initAttributes.call(this, attr); /** * @attribute value * @description The value of the button * @type String */ this.setAttributeConfig('value', { value: attr.value }); /** * @attribute menu * @description The menu attribute, see YAHOO.widget.Button * @type Object */ this.setAttributeConfig('menu', { value: attr.menu || false }); /** * @attribute type * @description The type of button to create: push, menu, color, select, spin * @type String */ this.setAttributeConfig('type', { value: attr.type, writeOnce: true, method: function(type) { var el, opt; if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } switch (type) { case 'select': case 'menu': el = document.createElement('select'); var menu = this.get('menu'); for (var i = 0; i < menu.length; i++) { opt = document.createElement('option'); opt.innerHTML = menu[i].text; opt.value = menu[i].value; if (menu[i].checked) { opt.selected = true; } el.appendChild(opt); } this._button.parentNode.replaceChild(el, this._button); Event.on(el, 'change', this._handleSelect, this, true); this._button = el; break; } } }); /** * @attribute disabled * @description Set the button into a disabled state * @type String */ this.setAttributeConfig('disabled', { value: attr.disabled || false, method: function(disabled) { if (disabled) { this.addClass('yui-button-disabled'); this.addClass('yui-' + this.get('type') + '-button-disabled'); } else { this.removeClass('yui-button-disabled'); this.removeClass('yui-' + this.get('type') + '-button-disabled'); } if (this.get('type') == 'menu') { this._button.disabled = disabled; } } }); /** * @attribute label * @description The text label for the button * @type String */ this.setAttributeConfig('label', { value: attr.label, method: function(label) { if (!this._button) { this._button = this.get('element').getElementsByTagName('a')[0]; } if (this.get('type') == 'push') { this._button.innerHTML = label; } } }); /** * @attribute title * @description The title of the button * @type String */ this.setAttributeConfig('title', { value: attr.title }); /** * @config container * @description The container that the button is rendered to, handled by Toolbar * @type String */ this.setAttributeConfig('container', { value: null, writeOnce: true, method: function(cont) { this.appendTo(cont); } }); }, /** * @private * @method _handleSelect * @description The event fired when a change event gets fired on a select element * @param {Event} ev The change event. */ _handleSelect: function(ev) { var tar = Event.getTarget(ev); var value = tar.options[tar.selectedIndex].value; this.fireEvent('change', {type: 'change', value: value }); }, /** * @method getMenu * @description A stub function to mimic YAHOO.widget.Button's getMenu method */ getMenu: function() { return this.get('menu'); }, /** * @method destroy * @description Destroy the button */ destroy: function() { Event.purgeElement(this.get('element'), true); this.get('element').parentNode.removeChild(this.get('element')); //Brutal Object Destroy for (var i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } }, /** * @method fireEvent * @description Overridden fireEvent method to prevent DOM events from firing if the button is disabled. */ fireEvent: function(p_sType, p_aArgs) { // Disabled buttons should not respond to DOM events if (this.DOM_EVENTS[p_sType] && this.get('disabled')) { Event.stopEvent(p_aArgs); return; } YAHOO.widget.ToolbarButton.superclass.fireEvent.call(this, p_sType, p_aArgs); }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'ToolbarButton (' + this.get('id') + ')'; } }); })(); /** * @module editor * @description <p>Creates a rich Toolbar widget based on Button. Primarily used with the Rich Text Editor</p> * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbarbutton * @optional container_core, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang; var getButton = function(id) { var button = id; if (Lang.isString(id)) { button = this.getButtonById(id); } if (Lang.isNumber(id)) { button = this.getButtonByIndex(id); } if ((!(button instanceof YAHOO.widget.ToolbarButton)) && (!(button instanceof YAHOO.widget.ToolbarButtonAdvanced))) { button = this.getButtonByValue(id); } if ((button instanceof YAHOO.widget.ToolbarButton) || (button instanceof YAHOO.widget.ToolbarButtonAdvanced)) { return button; } return false; }; /** * Provides a rich toolbar widget based on the button and menu widgets * @constructor * @class Toolbar * @extends YAHOO.util.Element * @param {String/HTMLElement} el The element to turn into a toolbar. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.Toolbar = function(el, attrs) { YAHOO.log('Toolbar Initalizing', 'info', 'Toolbar'); YAHOO.log(arguments.length + ' arguments passed to constructor', 'info', 'Toolbar'); if (Lang.isObject(arguments[0]) && !Dom.get(el).nodeType) { attrs = el; } var local_attrs = {}; if (attrs) { Lang.augmentObject(local_attrs, attrs); //Break the config reference } var oConfig = { element: null, attributes: local_attrs }; if (Lang.isString(el) && Dom.get(el)) { oConfig.element = Dom.get(el); } else if (Lang.isObject(el) && Dom.get(el) && Dom.get(el).nodeType) { oConfig.element = Dom.get(el); } if (!oConfig.element) { YAHOO.log('No element defined, creating toolbar container', 'warn', 'Toolbar'); oConfig.element = document.createElement('DIV'); oConfig.element.id = Dom.generateId(); if (local_attrs.container && Dom.get(local_attrs.container)) { YAHOO.log('Container found in config appending to it (' + Dom.get(local_attrs.container).id + ')', 'info', 'Toolbar'); Dom.get(local_attrs.container).appendChild(oConfig.element); } } if (!oConfig.element.id) { oConfig.element.id = ((Lang.isString(el)) ? el : Dom.generateId()); YAHOO.log('No element ID defined for toolbar container, creating..', 'warn', 'Toolbar'); } YAHOO.log('Initing toolbar with id: ' + oConfig.element.id, 'info', 'Toolbar'); var fs = document.createElement('fieldset'); var lg = document.createElement('legend'); lg.innerHTML = 'Toolbar'; fs.appendChild(lg); var cont = document.createElement('DIV'); oConfig.attributes.cont = cont; Dom.addClass(cont, 'yui-toolbar-subcont'); fs.appendChild(cont); oConfig.element.appendChild(fs); oConfig.element.tabIndex = -1; oConfig.attributes.element = oConfig.element; oConfig.attributes.id = oConfig.element.id; YAHOO.widget.Toolbar.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.Toolbar, YAHOO.util.Element, { /** * @method _addMenuClasses * @private * @description This method is called from Menu's renderEvent to add a few more classes to the menu items * @param {String} ev The event that fired. * @param {Array} na Array of event information. * @param {Object} o Button config object. */ _addMenuClasses: function(ev, na, o) { Dom.addClass(this.element, 'yui-toolbar-' + o.get('value') + '-menu'); if (Dom.hasClass(o._button.parentNode.parentNode, 'yui-toolbar-select')) { Dom.addClass(this.element, 'yui-toolbar-select-menu'); } var items = this.getItems(); for (var i = 0; i < items.length; i++) { Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-').toLowerCase() : items[i]._oText.nodeValue.replace(/ /g, '-').toLowerCase())); Dom.addClass(items[i].element, 'yui-toolbar-' + o.get('value') + '-' + ((items[i].value) ? items[i].value.replace(/ /g, '-') : items[i]._oText.nodeValue.replace(/ /g, '-'))); } }, /** * @property buttonType * @description The default button to use * @type Object */ buttonType: YAHOO.widget.ToolbarButton, /** * @property dd * @description The DragDrop instance associated with the Toolbar * @type Object */ dd: null, /** * @property _colorData * @description Object reference containing colors hex and text values. * @type Object */ _colorData: { /* {{{ _colorData */ '#111111': 'Obsidian', '#2D2D2D': 'Dark Gray', '#434343': 'Shale', '#5B5B5B': 'Flint', '#737373': 'Gray', '#8B8B8B': 'Concrete', '#A2A2A2': 'Gray', '#B9B9B9': 'Titanium', '#000000': 'Black', '#D0D0D0': 'Light Gray', '#E6E6E6': 'Silver', '#FFFFFF': 'White', '#BFBF00': 'Pumpkin', '#FFFF00': 'Yellow', '#FFFF40': 'Banana', '#FFFF80': 'Pale Yellow', '#FFFFBF': 'Butter', '#525330': 'Raw Siena', '#898A49': 'Mildew', '#AEA945': 'Olive', '#7F7F00': 'Paprika', '#C3BE71': 'Earth', '#E0DCAA': 'Khaki', '#FCFAE1': 'Cream', '#60BF00': 'Cactus', '#80FF00': 'Chartreuse', '#A0FF40': 'Green', '#C0FF80': 'Pale Lime', '#DFFFBF': 'Light Mint', '#3B5738': 'Green', '#668F5A': 'Lime Gray', '#7F9757': 'Yellow', '#407F00': 'Clover', '#8A9B55': 'Pistachio', '#B7C296': 'Light Jade', '#E6EBD5': 'Breakwater', '#00BF00': 'Spring Frost', '#00FF80': 'Pastel Green', '#40FFA0': 'Light Emerald', '#80FFC0': 'Sea Foam', '#BFFFDF': 'Sea Mist', '#033D21': 'Dark Forrest', '#438059': 'Moss', '#7FA37C': 'Medium Green', '#007F40': 'Pine', '#8DAE94': 'Yellow Gray Green', '#ACC6B5': 'Aqua Lung', '#DDEBE2': 'Sea Vapor', '#00BFBF': 'Fog', '#00FFFF': 'Cyan', '#40FFFF': 'Turquoise Blue', '#80FFFF': 'Light Aqua', '#BFFFFF': 'Pale Cyan', '#033D3D': 'Dark Teal', '#347D7E': 'Gray Turquoise', '#609A9F': 'Green Blue', '#007F7F': 'Seaweed', '#96BDC4': 'Green Gray', '#B5D1D7': 'Soapstone', '#E2F1F4': 'Light Turquoise', '#0060BF': 'Summer Sky', '#0080FF': 'Sky Blue', '#40A0FF': 'Electric Blue', '#80C0FF': 'Light Azure', '#BFDFFF': 'Ice Blue', '#1B2C48': 'Navy', '#385376': 'Biscay', '#57708F': 'Dusty Blue', '#00407F': 'Sea Blue', '#7792AC': 'Sky Blue Gray', '#A8BED1': 'Morning Sky', '#DEEBF6': 'Vapor', '#0000BF': 'Deep Blue', '#0000FF': 'Blue', '#4040FF': 'Cerulean Blue', '#8080FF': 'Evening Blue', '#BFBFFF': 'Light Blue', '#212143': 'Deep Indigo', '#373E68': 'Sea Blue', '#444F75': 'Night Blue', '#00007F': 'Indigo Blue', '#585E82': 'Dockside', '#8687A4': 'Blue Gray', '#D2D1E1': 'Light Blue Gray', '#6000BF': 'Neon Violet', '#8000FF': 'Blue Violet', '#A040FF': 'Violet Purple', '#C080FF': 'Violet Dusk', '#DFBFFF': 'Pale Lavender', '#302449': 'Cool Shale', '#54466F': 'Dark Indigo', '#655A7F': 'Dark Violet', '#40007F': 'Violet', '#726284': 'Smoky Violet', '#9E8FA9': 'Slate Gray', '#DCD1DF': 'Violet White', '#BF00BF': 'Royal Violet', '#FF00FF': 'Fuchsia', '#FF40FF': 'Magenta', '#FF80FF': 'Orchid', '#FFBFFF': 'Pale Magenta', '#4A234A': 'Dark Purple', '#794A72': 'Medium Purple', '#936386': 'Cool Granite', '#7F007F': 'Purple', '#9D7292': 'Purple Moon', '#C0A0B6': 'Pale Purple', '#ECDAE5': 'Pink Cloud', '#BF005F': 'Hot Pink', '#FF007F': 'Deep Pink', '#FF409F': 'Grape', '#FF80BF': 'Electric Pink', '#FFBFDF': 'Pink', '#451528': 'Purple Red', '#823857': 'Purple Dino', '#A94A76': 'Purple Gray', '#7F003F': 'Rose', '#BC6F95': 'Antique Mauve', '#D8A5BB': 'Cool Marble', '#F7DDE9': 'Pink Granite', '#C00000': 'Apple', '#FF0000': 'Fire Truck', '#FF4040': 'Pale Red', '#FF8080': 'Salmon', '#FFC0C0': 'Warm Pink', '#441415': 'Sepia', '#82393C': 'Rust', '#AA4D4E': 'Brick', '#800000': 'Brick Red', '#BC6E6E': 'Mauve', '#D8A3A4': 'Shrimp Pink', '#F8DDDD': 'Shell Pink', '#BF5F00': 'Dark Orange', '#FF7F00': 'Orange', '#FF9F40': 'Grapefruit', '#FFBF80': 'Canteloupe', '#FFDFBF': 'Wax', '#482C1B': 'Dark Brick', '#855A40': 'Dirt', '#B27C51': 'Tan', '#7F3F00': 'Nutmeg', '#C49B71': 'Mustard', '#E1C4A8': 'Pale Tan', '#FDEEE0': 'Marble' /* }}} */ }, /** * @property _colorPicker * @description The HTML Element containing the colorPicker * @type HTMLElement */ _colorPicker: null, /** * @property STR_COLLAPSE * @description String for Toolbar Collapse Button * @type String */ STR_COLLAPSE: 'Collapse Toolbar', /** * @property STR_SPIN_LABEL * @description String for spinbutton dynamic label. Note the {VALUE} will be replaced with YAHOO.lang.substitute * @type String */ STR_SPIN_LABEL: 'Spin Button with value {VALUE}. Use Control Shift Up Arrow and Control Shift Down arrow keys to increase or decrease the value.', /** * @property STR_SPIN_UP * @description String for spinbutton up * @type String */ STR_SPIN_UP: 'Click to increase the value of this input', /** * @property STR_SPIN_DOWN * @description String for spinbutton down * @type String */ STR_SPIN_DOWN: 'Click to decrease the value of this input', /** * @property _titlebar * @description Object reference to the titlebar * @type HTMLElement */ _titlebar: null, /** * @property browser * @description Standard browser detection * @type Object */ browser: YAHOO.env.ua, /** * @protected * @property _buttonList * @description Internal property list of current buttons in the toolbar * @type Array */ _buttonList: null, /** * @protected * @property _buttonGroupList * @description Internal property list of current button groups in the toolbar * @type Array */ _buttonGroupList: null, /** * @protected * @property _sep * @description Internal reference to the separator HTML Element for cloning * @type HTMLElement */ _sep: null, /** * @protected * @property _sepCount * @description Internal refernce for counting separators, so we can give them a useful class name for styling * @type Number */ _sepCount: null, /** * @protected * @property draghandle * @type HTMLElement */ _dragHandle: null, /** * @protected * @property _toolbarConfigs * @type Object */ _toolbarConfigs: { renderer: true }, /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the toolbar container element * @type String */ CLASS_CONTAINER: 'yui-toolbar-container', /** * @protected * @property CLASS_DRAGHANDLE * @description Default CSS class to apply to the toolbar's drag handle element * @type String */ CLASS_DRAGHANDLE: 'yui-toolbar-draghandle', /** * @protected * @property CLASS_SEPARATOR * @description Default CSS class to apply to all separators in the toolbar * @type String */ CLASS_SEPARATOR: 'yui-toolbar-separator', /** * @protected * @property CLASS_DISABLED * @description Default CSS class to apply when the toolbar is disabled * @type String */ CLASS_DISABLED: 'yui-toolbar-disabled', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-toolbar', /** * @method init * @description The Toolbar class's initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.widget.Toolbar.superclass.init.call(this, p_oElement, p_oAttributes); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the toolbar. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the toolbar. */ initAttributes: function(attr) { YAHOO.widget.Toolbar.superclass.initAttributes.call(this, attr); this.addClass(this.CLASS_CONTAINER); /** * @attribute buttonType * @description The buttonType to use (advanced or basic) * @type String */ this.setAttributeConfig('buttonType', { value: attr.buttonType || 'basic', writeOnce: true, validator: function(type) { switch (type) { case 'advanced': case 'basic': return true; } return false; }, method: function(type) { if (type == 'advanced') { if (YAHOO.widget.Button) { this.buttonType = YAHOO.widget.ToolbarButtonAdvanced; } else { YAHOO.log('Can not find YAHOO.widget.Button', 'error', 'Toolbar'); this.buttonType = YAHOO.widget.ToolbarButton; } } else { this.buttonType = YAHOO.widget.ToolbarButton; } } }); /** * @attribute buttons * @description Object specifying the buttons to include in the toolbar * Example: * <code><pre> * { * { id: 'b3', type: 'button', label: 'Underline', value: 'underline' }, * { type: 'separator' }, * { id: 'b4', type: 'menu', label: 'Align', value: 'align', * menu: [ * { text: "Left", value: 'alignleft' }, * { text: "Center", value: 'aligncenter' }, * { text: "Right", value: 'alignright' } * ] * } * } * </pre></code> * @type Array */ this.setAttributeConfig('buttons', { value: [], writeOnce: true, method: function(data) { for (var i in data) { if (Lang.hasOwnProperty(data, i)) { if (data[i].type == 'separator') { this.addSeparator(); } else if (data[i].group !== undefined) { this.addButtonGroup(data[i]); } else { this.addButton(data[i]); } } } } }); /** * @attribute disabled * @description Boolean indicating if the toolbar should be disabled. It will also disable the draggable attribute if it is on. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this.get('disabled') === disabled) { return false; } if (disabled) { this.addClass(this.CLASS_DISABLED); this.set('draggable', false); this.disableAllButtons(); } else { this.removeClass(this.CLASS_DISABLED); if (this._configs.draggable._initialConfig.value) { //Draggable by default, set it back this.set('draggable', true); } this.resetAllButtons(); } } }); /** * @config cont * @description The container for the toolbar. * @type HTMLElement */ this.setAttributeConfig('cont', { value: attr.cont, readOnly: true }); /** * @attribute grouplabels * @description Boolean indicating if the toolbar should show the group label's text string. * @default true * @type Boolean */ this.setAttributeConfig('grouplabels', { value: ((attr.grouplabels === false) ? false : true), method: function(grouplabels) { if (grouplabels) { Dom.removeClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } else { Dom.addClass(this.get('cont'), (this.CLASS_PREFIX + '-nogrouplabels')); } } }); /** * @attribute titlebar * @description Boolean indicating if the toolbar should have a titlebar. If * passed a string, it will use that as the titlebar text * @default false * @type Boolean or String */ this.setAttributeConfig('titlebar', { value: false, method: function(titlebar) { if (titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } this._titlebar = document.createElement('DIV'); this._titlebar.tabIndex = '-1'; Event.on(this._titlebar, 'focus', function() { this._handleFocus(); }, this, true); Dom.addClass(this._titlebar, this.CLASS_PREFIX + '-titlebar'); if (Lang.isString(titlebar)) { var h2 = document.createElement('h2'); h2.tabIndex = '-1'; h2.innerHTML = '<a href="#" tabIndex="0">' + titlebar + '</a>'; this._titlebar.appendChild(h2); Event.on(h2.firstChild, 'click', function(ev) { Event.stopEvent(ev); }); Event.on([h2, h2.firstChild], 'focus', function() { this._handleFocus(); }, this, true); } if (this.get('firstChild')) { this.insertBefore(this._titlebar, this.get('firstChild')); } else { this.appendChild(this._titlebar); } if (this.get('collapse')) { this.set('collapse', true); } } else if (this._titlebar) { if (this._titlebar && this._titlebar.parentNode) { this._titlebar.parentNode.removeChild(this._titlebar); } } } }); /** * @attribute collapse * @description Boolean indicating if the the titlebar should have a collapse button. * The collapse button will not remove the toolbar, it will minimize it to the titlebar * @default false * @type Boolean */ this.setAttributeConfig('collapse', { value: false, method: function(collapse) { if (this._titlebar) { var collapseEl = null; var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse) { if (el.length > 0) { //There is already a collapse button return true; } collapseEl = document.createElement('SPAN'); collapseEl.innerHTML = 'X'; collapseEl.title = this.STR_COLLAPSE; Dom.addClass(collapseEl, 'collapse'); this._titlebar.appendChild(collapseEl); Event.addListener(collapseEl, 'click', function() { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { this.collapse(false); //Expand Toolbar } else { this.collapse(); //Collapse Toolbar } }, this, true); } else { collapseEl = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapseEl[0]) { if (Dom.hasClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed')) { //We are closed, reopen the titlebar.. this.collapse(false); //Expand Toolbar } collapseEl[0].parentNode.removeChild(collapseEl[0]); } } } } }); /** * @attribute draggable * @description Boolean indicating if the toolbar should be draggable. * @default false * @type Boolean */ this.setAttributeConfig('draggable', { value: (attr.draggable || false), method: function(draggable) { if (draggable && !this.get('titlebar')) { YAHOO.log('Dragging enabled', 'info', 'Toolbar'); if (!this._dragHandle) { this._dragHandle = document.createElement('SPAN'); this._dragHandle.innerHTML = '|'; this._dragHandle.setAttribute('title', 'Click to drag the toolbar'); this._dragHandle.id = this.get('id') + '_draghandle'; Dom.addClass(this._dragHandle, this.CLASS_DRAGHANDLE); if (this.get('cont').hasChildNodes()) { this.get('cont').insertBefore(this._dragHandle, this.get('cont').firstChild); } else { this.get('cont').appendChild(this._dragHandle); } this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._dragHandle.id); } } else { YAHOO.log('Dragging disabled', 'info', 'Toolbar'); if (this._dragHandle) { this._dragHandle.parentNode.removeChild(this._dragHandle); this._dragHandle = null; this.dd = null; } } if (this._titlebar) { if (draggable) { this.dd = new YAHOO.util.DD(this.get('id')); this.dd.setHandleElId(this._titlebar); Dom.addClass(this._titlebar, 'draggable'); } else { Dom.removeClass(this._titlebar, 'draggable'); if (this.dd) { this.dd.unreg(); this.dd = null; } } } }, validator: function(value) { var ret = true; if (!YAHOO.util.DD) { ret = false; } return ret; } }); }, /** * @method addButtonGroup * @description Add a new button group to the toolbar. (uses addButton) * @param {Object} oGroup Object literal reference to the Groups Config (contains an array of button configs as well as the group label) */ addButtonGroup: function(oGroup) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButtonGroup', arguments]; return false; } if (!this.hasClass(this.CLASS_PREFIX + '-grouped')) { this.addClass(this.CLASS_PREFIX + '-grouped'); } var div = document.createElement('DIV'); Dom.addClass(div, this.CLASS_PREFIX + '-group'); Dom.addClass(div, this.CLASS_PREFIX + '-group-' + oGroup.group); if (oGroup.label) { var label = document.createElement('h3'); label.innerHTML = oGroup.label; div.appendChild(label); } if (!this.get('grouplabels')) { Dom.addClass(this.get('cont'), this.CLASS_PREFIX, '-nogrouplabels'); } this.get('cont').appendChild(div); //For accessibility, let's put all of the group buttons in an Unordered List var ul = document.createElement('ul'); div.appendChild(ul); if (!this._buttonGroupList) { this._buttonGroupList = {}; } this._buttonGroupList[oGroup.group] = ul; for (var i = 0; i < oGroup.buttons.length; i++) { var li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; ul.appendChild(li); if ((oGroup.buttons[i].type !== undefined) && oGroup.buttons[i].type == 'separator') { this.addSeparator(li); } else { oGroup.buttons[i].container = li; this.addButton(oGroup.buttons[i]); } } }, /** * @method addButtonToGroup * @description Add a new button to a toolbar group. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {String} group The Group identifier passed into the initial config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButtonToGroup: function(oButton, group, after) { var groupCont = this._buttonGroupList[group]; var li = document.createElement('li'); li.className = this.CLASS_PREFIX + '-groupitem'; oButton.container = li; this.addButton(oButton, after); groupCont.appendChild(li); }, /** * @method addButton * @description Add a new button to the toolbar. Buttons supported: * push, split, menu, select, color, spin * @param {Object} oButton Object literal reference to the Button's Config * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addButton: function(oButton, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addButton', arguments]; return false; } if (!this._buttonList) { this._buttonList = []; } YAHOO.log('Adding button of type: ' + oButton.type, 'info', 'Toolbar'); if (!oButton.container) { oButton.container = this.get('cont'); } if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { for (var i in oButton.menu) { if (Lang.hasOwnProperty(oButton.menu, i)) { var funcObject = { fn: function(ev, x, oMenu) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); }, scope: this }; oButton.menu[i].onclick = funcObject; } } } } var _oButton = {}, skip = false; for (var o in oButton) { if (Lang.hasOwnProperty(oButton, o)) { if (!this._toolbarConfigs[o]) { _oButton[o] = oButton[o]; } } } if (oButton.type == 'select') { _oButton.type = 'menu'; } if (oButton.type == 'spin') { _oButton.type = 'push'; } if (_oButton.type == 'color') { if (YAHOO.widget.Overlay) { _oButton = this._makeColorButton(_oButton); } else { skip = true; } } if (_oButton.menu) { if ((YAHOO.widget.Overlay) && (oButton.menu instanceof YAHOO.widget.Overlay)) { oButton.menu.showEvent.subscribe(function() { this._button = _oButton; }); } else { for (var m = 0; m < _oButton.menu.length; m++) { if (!_oButton.menu[m].value) { _oButton.menu[m].value = _oButton.menu[m].text; } } if (this.browser.webkit) { _oButton.focusmenu = false; } } } if (skip) { oButton = false; } else { //Add to .get('buttons') manually this._configs.buttons.value[this._configs.buttons.value.length] = oButton; var tmp = new this.buttonType(_oButton); tmp.get('element').tabIndex = '-1'; tmp.get('element').setAttribute('role', 'button'); tmp._selected = true; if (this.get('disabled')) { //Toolbar is disabled, disable the new button too! tmp.set('disabled', true); } if (!oButton.id) { oButton.id = tmp.get('id'); } YAHOO.log('Button created (' + oButton.type + ')', 'info', 'Toolbar'); if (after) { var el = tmp.get('element'); var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } if (nextSib) { nextSib.parentNode.insertBefore(el, nextSib); } } tmp.addClass(this.CLASS_PREFIX + '-' + tmp.get('value')); var icon = document.createElement('span'); icon.className = this.CLASS_PREFIX + '-icon'; tmp.get('element').insertBefore(icon, tmp.get('firstChild')); if (tmp._button.tagName.toLowerCase() == 'button') { tmp.get('element').setAttribute('unselectable', 'on'); //Replace the Button HTML Element with an a href if it exists var a = document.createElement('a'); a.innerHTML = tmp._button.innerHTML; a.href = '#'; a.tabIndex = '-1'; Event.on(a, 'click', function(ev) { Event.stopEvent(ev); }); tmp._button.parentNode.replaceChild(a, tmp._button); tmp._button = a; } if (oButton.type == 'select') { if (tmp._button.tagName.toLowerCase() == 'select') { icon.parentNode.removeChild(icon); var iel = tmp._button; var parEl = tmp.get('element'); parEl.parentNode.replaceChild(iel, parEl); } else { //Don't put a class on it if it's a real select element tmp.addClass(this.CLASS_PREFIX + '-select'); } } if (oButton.type == 'spin') { if (!Lang.isArray(oButton.range)) { oButton.range = [ 10, 100 ]; } this._makeSpinButton(tmp, oButton); } tmp.get('element').setAttribute('title', tmp.get('label')); if (oButton.type != 'spin') { if ((YAHOO.widget.Overlay) && (_oButton.menu instanceof YAHOO.widget.Overlay)) { var showPicker = function(ev) { var exec = true; if (ev.keyCode && (ev.keyCode == 9)) { exec = false; } if (exec) { if (this._colorPicker) { this._colorPicker._button = oButton.value; } var menuEL = tmp.getMenu().element; if (Dom.getStyle(menuEL, 'visibility') == 'hidden') { tmp.getMenu().show(); } else { tmp.getMenu().hide(); } } YAHOO.util.Event.stopEvent(ev); }; tmp.on('mousedown', showPicker, oButton, this); tmp.on('keydown', showPicker, oButton, this); } else if ((oButton.type != 'menu') && (oButton.type != 'select')) { tmp.on('keypress', this._buttonClick, oButton, this); tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); this._buttonClick(ev, oButton); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('change', function(ev) { if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ev.value; this._buttonClick(ev, oButton); }, this, true); var self = this; //Hijack the mousedown event in the menu and make it fire a button click.. tmp.on('appendTo', function() { var tmp = this; if (tmp.getMenu() && tmp.getMenu().mouseDownEvent) { tmp.getMenu().mouseDownEvent.subscribe(function(ev, args) { YAHOO.log('mouseDownEvent', 'warn', 'Toolbar'); var oMenu = args[1]; YAHOO.util.Event.stopEvent(args[0]); tmp._onMenuClick(args[0], tmp); if (!oButton.menucmd) { oButton.menucmd = oButton.value; } oButton.value = ((oMenu.value) ? oMenu.value : oMenu._oText.nodeValue); self._buttonClick.call(self, args[1], oButton); tmp._hideMenu(); return false; }); tmp.getMenu().clickEvent.subscribe(function(ev, args) { YAHOO.log('clickEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); tmp.getMenu().mouseUpEvent.subscribe(function(ev, args) { YAHOO.log('mouseUpEvent', 'warn', 'Toolbar'); YAHOO.util.Event.stopEvent(args[0]); }); } }); } } else { //Stop the mousedown event so we can trap the selection in the editor! tmp.on('mousedown', function(ev) { YAHOO.util.Event.stopEvent(ev); }); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }); } if (this.browser.ie) { /* //Add a couple of new events for IE tmp.DOM_EVENTS.focusin = true; tmp.DOM_EVENTS.focusout = true; //Stop them so we don't loose focus in the Editor tmp.on('focusin', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('focusout', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); tmp.on('click', function(ev) { YAHOO.util.Event.stopEvent(ev); }, oButton, this); */ } if (this.browser.webkit) { //This will keep the document from gaining focus and the editor from loosing it.. //Forcefully remove the focus calls in button! tmp.hasFocus = function() { return true; }; } this._buttonList[this._buttonList.length] = tmp; if ((oButton.type == 'menu') || (oButton.type == 'split') || (oButton.type == 'select')) { if (Lang.isArray(oButton.menu)) { YAHOO.log('Button type is (' + oButton.type + '), doing extra renderer work.', 'info', 'Toolbar'); var menu = tmp.getMenu(); if (menu && menu.renderEvent) { menu.renderEvent.subscribe(this._addMenuClasses, tmp); if (oButton.renderer) { menu.renderEvent.subscribe(oButton.renderer, tmp); } } } } } return oButton; }, /** * @method addSeparator * @description Add a new button separator to the toolbar. * @param {HTMLElement} cont Optional HTML element to insert this button into. * @param {HTMLElement} after Optional HTML element to insert this button after in the DOM. */ addSeparator: function(cont, after) { if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } var sepCont = ((cont) ? cont : this.get('cont')); if (!this.get('element')) { this._queue[this._queue.length] = ['addSeparator', arguments]; return false; } if (this._sepCount === null) { this._sepCount = 0; } if (!this._sep) { YAHOO.log('Separator does not yet exist, creating', 'info', 'Toolbar'); this._sep = document.createElement('SPAN'); Dom.addClass(this._sep, this.CLASS_SEPARATOR); this._sep.innerHTML = '|'; } YAHOO.log('Separator does exist, cloning', 'info', 'Toolbar'); var _sep = this._sep.cloneNode(true); this._sepCount++; Dom.addClass(_sep, this.CLASS_SEPARATOR + '-' + this._sepCount); if (after) { var nextSib = null; if (after.get) { nextSib = after.get('element').nextSibling; } else if (after.nextSibling) { nextSib = after.nextSibling; } else { nextSib = after; } if (nextSib) { if (nextSib == after) { nextSib.parentNode.appendChild(_sep); } else { nextSib.parentNode.insertBefore(_sep, nextSib); } } } else { sepCont.appendChild(_sep); } return _sep; }, /** * @method _createColorPicker * @private * @description Creates the core DOM reference to the color picker menu item. * @param {String} id the id of the toolbar to prefix this DOM container with. */ _createColorPicker: function(id) { if (Dom.get(id + '_colors')) { Dom.get(id + '_colors').parentNode.removeChild(Dom.get(id + '_colors')); } var picker = document.createElement('div'); picker.className = 'yui-toolbar-colors'; picker.id = id + '_colors'; picker.style.display = 'none'; Event.on(window, 'load', function() { document.body.appendChild(picker); }, this, true); this._colorPicker = picker; var html = ''; for (var i in this._colorData) { if (Lang.hasOwnProperty(this._colorData, i)) { html += '<a style="background-color: ' + i + '" href="#">' + i.replace('#', '') + '</a>'; } } html += '<span><em>X</em><strong></strong></span>'; window.setTimeout(function() { picker.innerHTML = html; }, 0); Event.on(picker, 'mouseover', function(ev) { var picker = this._colorPicker; var em = picker.getElementsByTagName('em')[0]; var strong = picker.getElementsByTagName('strong')[0]; var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { em.style.backgroundColor = tar.style.backgroundColor; strong.innerHTML = this._colorData['#' + tar.innerHTML] + '<br>' + tar.innerHTML; } }, this, true); Event.on(picker, 'focus', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'click', function(ev) { Event.stopEvent(ev); }); Event.on(picker, 'mousedown', function(ev) { Event.stopEvent(ev); var tar = Event.getTarget(ev); if (tar.tagName.toLowerCase() == 'a') { var retVal = this.fireEvent('colorPickerClicked', { type: 'colorPickerClicked', target: this, button: this._colorPicker._button, color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML] } ); if (retVal !== false) { var info = { color: tar.innerHTML, colorName: this._colorData['#' + tar.innerHTML], value: this._colorPicker._button }; this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } this.getButtonByValue(this._colorPicker._button).getMenu().hide(); } }, this, true); }, /** * @method _resetColorPicker * @private * @description Clears the currently selected color or mouseover color in the color picker. */ _resetColorPicker: function() { var em = this._colorPicker.getElementsByTagName('em')[0]; var strong = this._colorPicker.getElementsByTagName('strong')[0]; em.style.backgroundColor = 'transparent'; strong.innerHTML = ''; }, /** * @method _makeColorButton * @private * @description Called to turn a "color" button into a menu button with an Overlay for the menu. * @param {Object} _oButton <a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> reference */ _makeColorButton: function(_oButton) { if (!this._colorPicker) { this._createColorPicker(this.get('id')); } _oButton.type = 'color'; _oButton.menu = new YAHOO.widget.Overlay(this.get('id') + '_' + _oButton.value + '_menu', { visible: false, position: 'absolute', iframe: true }); _oButton.menu.setBody(''); _oButton.menu.render(this.get('cont')); Dom.addClass(_oButton.menu.element, 'yui-button-menu'); Dom.addClass(_oButton.menu.element, 'yui-color-button-menu'); _oButton.menu.beforeShowEvent.subscribe(function() { _oButton.menu.cfg.setProperty('zindex', 5); //Re Adjust the overlays zIndex.. not sure why. _oButton.menu.cfg.setProperty('context', [this.getButtonById(_oButton.id).get('element'), 'tl', 'bl']); //Re Adjust the overlay.. not sure why. //Move the DOM reference of the color picker to the Overlay that we are about to show. this._resetColorPicker(); var _p = this._colorPicker; if (_p.parentNode) { _p.parentNode.removeChild(_p); } _oButton.menu.setBody(''); _oButton.menu.appendToBody(_p); this._colorPicker.style.display = 'block'; }, this, true); return _oButton; }, /** * @private * @method _makeSpinButton * @description Create a button similar to an OS Spin button.. It has an up/down arrow combo to scroll through a range of int values. * @param {Object} _button <a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> reference * @param {Object} oButton Object literal containing the buttons initial config */ _makeSpinButton: function(_button, oButton) { _button.addClass(this.CLASS_PREFIX + '-spinbutton'); var self = this, _par = _button._button.parentNode.parentNode, //parentNode of Button Element for appending child range = oButton.range, _b1 = document.createElement('a'), _b2 = document.createElement('a'); _b1.href = '#'; _b2.href = '#'; _b1.tabIndex = '-1'; _b2.tabIndex = '-1'; //Setup the up and down arrows _b1.className = 'up'; _b1.title = this.STR_SPIN_UP; _b1.innerHTML = this.STR_SPIN_UP; _b2.className = 'down'; _b2.title = this.STR_SPIN_DOWN; _b2.innerHTML = this.STR_SPIN_DOWN; //Append them to the container _par.appendChild(_b1); _par.appendChild(_b2); var label = YAHOO.lang.substitute(this.STR_SPIN_LABEL, { VALUE: _button.get('label') }); _button.set('title', label); var cleanVal = function(value) { value = ((value < range[0]) ? range[0] : value); value = ((value > range[1]) ? range[1] : value); return value; }; var br = this.browser; var tbar = false; var strLabel = this.STR_SPIN_LABEL; if (this._titlebar && this._titlebar.firstChild) { tbar = this._titlebar.firstChild; } var _intUp = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value++; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intDown = function(ev) { YAHOO.util.Event.stopEvent(ev); if (!_button.get('disabled') && (ev.keyCode != 9)) { var value = parseInt(_button.get('label'), 10); value--; value = cleanVal(value); _button.set('label', ''+value); var label = YAHOO.lang.substitute(strLabel, { VALUE: _button.get('label') }); _button.set('title', label); if (!br.webkit && tbar) { //tbar.focus(); //We do this for accessibility, on the re-focus of the element, a screen reader will re-read the title that was just changed //_button.focus(); } self._buttonClick(ev, oButton); } }; var _intKeyUp = function(ev) { if (ev.keyCode == 38) { _intUp(ev); } else if (ev.keyCode == 40) { _intDown(ev); } else if (ev.keyCode == 107 && ev.shiftKey) { //Plus Key _intUp(ev); } else if (ev.keyCode == 109 && ev.shiftKey) { //Minus Key _intDown(ev); } }; //Handle arrow keys.. _button.on('keydown', _intKeyUp, this, true); //Listen for the click on the up button and act on it //Listen for the click on the down button and act on it Event.on(_b1, 'mousedown',function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b2, 'mousedown', function(ev) { Event.stopEvent(ev); }, this, true); Event.on(_b1, 'click', _intUp, this, true); Event.on(_b2, 'click', _intDown, this, true); }, /** * @protected * @method _buttonClick * @description Click handler for all buttons in the toolbar. * @param {String} ev The event that was passed in. * @param {Object} info Object literal of information about the button that was clicked. */ _buttonClick: function(ev, info) { var doEvent = true; if (ev && ev.type == 'keypress') { if (ev.keyCode == 9) { doEvent = false; } else if ((ev.keyCode === 13) || (ev.keyCode === 0) || (ev.keyCode === 32)) { } else { doEvent = false; } } if (doEvent) { var fireNextEvent = true, retValue = false; info.isSelected = this.isSelected(info.id); if (info.value) { YAHOO.log('fireEvent::' + info.value + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.value + 'Click', { type: info.value + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (info.menucmd && fireNextEvent) { YAHOO.log('fireEvent::' + info.menucmd + 'Click', 'info', 'Toolbar'); retValue = this.fireEvent(info.menucmd + 'Click', { type: info.menucmd + 'Click', target: this.get('element'), button: info }); if (retValue === false) { fireNextEvent = false; } } if (fireNextEvent) { YAHOO.log('fireEvent::buttonClick', 'info', 'Toolbar'); this.fireEvent('buttonClick', { type: 'buttonClick', target: this.get('element'), button: info }); } if (info.type == 'select') { var button = this.getButtonById(info.id); if (button.buttonType == 'rich') { var txt = info.value; for (var i = 0; i < info.menu.length; i++) { if (info.menu[i].value == info.value) { txt = info.menu[i].text; break; } } button.set('label', '<span class="yui-toolbar-' + info.menucmd + '-' + (info.value).replace(/ /g, '-').toLowerCase() + '">' + txt + '</span>'); var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value.toLowerCase() == info.value.toLowerCase()) { _items[m].cfg.setProperty('checked', true); } else { _items[m].cfg.setProperty('checked', false); } } } } if (ev) { Event.stopEvent(ev); } } }, /** * @private * @property _keyNav * @description Flag to determine if the arrow nav listeners have been attached * @type Boolean */ _keyNav: null, /** * @private * @property _navCounter * @description Internal counter for walking the buttons in the toolbar with the arrow keys * @type Number */ _navCounter: null, /** * @private * @method _navigateButtons * @description Handles the navigation/focus of toolbar buttons with the Arrow Keys * @param {Event} ev The Key Event */ _navigateButtons: function(ev) { switch (ev.keyCode) { case 37: case 39: if (ev.keyCode == 37) { this._navCounter--; } else { this._navCounter++; } if (this._navCounter > (this._buttonList.length - 1)) { this._navCounter = 0; } if (this._navCounter < 0) { this._navCounter = (this._buttonList.length - 1); } if (this._buttonList[this._navCounter]) { var el = this._buttonList[this._navCounter].get('element'); if (this.browser.ie) { el = this._buttonList[this._navCounter].get('element').getElementsByTagName('a')[0]; } if (this._buttonList[this._navCounter].get('disabled')) { this._navigateButtons(ev); } else { el.focus(); } } break; } }, /** * @private * @method _handleFocus * @description Sets up the listeners for the arrow key navigation */ _handleFocus: function() { if (!this._keyNav) { var ev = 'keypress'; if (this.browser.ie) { ev = 'keydown'; } Event.on(this.get('element'), ev, this._navigateButtons, this, true); this._keyNav = true; this._navCounter = -1; } }, /** * @method getButtonById * @description Gets a button instance from the toolbar by is Dom id. * @param {String} id The Dom id to query for. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a>} */ getButtonById: function(id) { var len = this._buttonList.length; for (var i = 0; i < len; i++) { if (this._buttonList[i] && this._buttonList[i].get('id') == id) { return this._buttonList[i]; } } return false; }, /** * @method getButtonByValue * @description Gets a button instance or a menuitem instance from the toolbar by it's value. * @param {String} value The button value to query for. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a> or <a href="YAHOO.widget.MenuItem.html">YAHOO.widget.MenuItem</a>} */ getButtonByValue: function(value) { var _buttons = this.get('buttons'); var len = _buttons.length; for (var i = 0; i < len; i++) { if (_buttons[i].group !== undefined) { for (var m = 0; m < _buttons[i].buttons.length; m++) { if ((_buttons[i].buttons[m].value == value) || (_buttons[i].buttons[m].menucmd == value)) { return this.getButtonById(_buttons[i].buttons[m].id); } if (_buttons[i].buttons[m].menu) { //Menu Button, loop through the values for (var s = 0; s < _buttons[i].buttons[m].menu.length; s++) { if (_buttons[i].buttons[m].menu[s].value == value) { return this.getButtonById(_buttons[i].buttons[m].id); } } } } } else { if ((_buttons[i].value == value) || (_buttons[i].menucmd == value)) { return this.getButtonById(_buttons[i].id); } if (_buttons[i].menu) { //Menu Button, loop through the values for (var j = 0; j < _buttons[i].menu.length; j++) { if (_buttons[i].menu[j].value == value) { return this.getButtonById(_buttons[i].id); } } } } } return false; }, /** * @method getButtonByIndex * @description Gets a button instance from the toolbar by is index in _buttonList. * @param {Number} index The index of the button in _buttonList. * @return {<a href="YAHOO.widget.ToolbarButton.html">YAHOO.widget.ToolbarButton</a>} */ getButtonByIndex: function(index) { if (this._buttonList[index]) { return this._buttonList[index]; } else { return false; } }, /** * @method getButtons * @description Returns an array of buttons in the current toolbar * @return {Array} */ getButtons: function() { return this._buttonList; }, /** * @method disableButton * @description Disables a button in the toolbar. * @param {String/Number} id Disable a button by it's id, index or value. * @return {Boolean} */ disableButton: function(id) { var button = getButton.call(this, id); if (button) { button.set('disabled', true); } else { return false; } }, /** * @method enableButton * @description Enables a button in the toolbar. * @param {String/Number} id Enable a button by it's id, index or value. * @return {Boolean} */ enableButton: function(id) { if (this.get('disabled')) { return false; } var button = getButton.call(this, id); if (button) { if (button.get('disabled')) { button.set('disabled', false); } } else { return false; } }, /** * @method isSelected * @description Tells if a button is selected or not. * @param {String/Number} id A button by it's id, index or value. * @return {Boolean} */ isSelected: function(id) { var button = getButton.call(this, id); if (button) { return button._selected; } return false; }, /** * @method selectButton * @description Selects a button in the toolbar. * @param {String/Number} id Select a button by it's id, index or value. * @param {String} value If this is a Menu Button, check this item in the menu * @return {Boolean} */ selectButton: function(id, value) { var button = getButton.call(this, id); if (button) { button.addClass('yui-button-selected'); button.addClass('yui-button-' + button.get('value') + '-selected'); button._selected = true; if (value) { if (button.buttonType == 'rich') { var _items = button.getMenu().getItems(); for (var m = 0; m < _items.length; m++) { if (_items[m].value == value) { _items[m].cfg.setProperty('checked', true); button.set('label', '<span class="yui-toolbar-' + button.get('value') + '-' + (value).replace(/ /g, '-').toLowerCase() + '">' + _items[m]._oText.nodeValue + '</span>'); } else { _items[m].cfg.setProperty('checked', false); } } } } } else { return false; } }, /** * @method deselectButton * @description Deselects a button in the toolbar. * @param {String/Number} id Deselect a button by it's id, index or value. * @return {Boolean} */ deselectButton: function(id) { var button = getButton.call(this, id); if (button) { button.removeClass('yui-button-selected'); button.removeClass('yui-button-' + button.get('value') + '-selected'); button.removeClass('yui-button-hover'); button._selected = false; } else { return false; } }, /** * @method deselectAllButtons * @description Deselects all buttons in the toolbar. * @return {Boolean} */ deselectAllButtons: function() { var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.deselectButton(this._buttonList[i]); } }, /** * @method disableAllButtons * @description Disables all buttons in the toolbar. * @return {Boolean} */ disableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.disableButton(this._buttonList[i]); } }, /** * @method enableAllButtons * @description Enables all buttons in the toolbar. * @return {Boolean} */ enableAllButtons: function() { if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { this.enableButton(this._buttonList[i]); } }, /** * @method resetAllButtons * @description Resets all buttons to their initial state. * @param {Object} _ex Except these buttons * @return {Boolean} */ resetAllButtons: function(_ex) { if (!Lang.isObject(_ex)) { _ex = {}; } if (this.get('disabled')) { return false; } var len = this._buttonList.length; for (var i = 0; i < len; i++) { var _button = this._buttonList[i]; if (_button) { var disabled = _button._configs.disabled._initialConfig.value; if (_ex[_button.get('id')]) { this.enableButton(_button); this.selectButton(_button); } else { if (disabled) { this.disableButton(_button); } else { this.enableButton(_button); } this.deselectButton(_button); } } } }, /** * @method destroyButton * @description Destroy a button in the toolbar. * @param {String/Number} id Destroy a button by it's id or index. * @return {Boolean} */ destroyButton: function(id) { var button = getButton.call(this, id); if (button) { var thisID = button.get('id'); button.destroy(); var len = this._buttonList.length; for (var i = 0; i < len; i++) { if (this._buttonList[i] && this._buttonList[i].get('id') == thisID) { this._buttonList[i] = null; } } } else { return false; } }, /** * @method destroy * @description Destroys the toolbar, all of it's elements and objects. * @return {Boolean} */ destroy: function() { this.get('element').innerHTML = ''; this.get('element').className = ''; //Brutal Object Destroy for (var i in this) { if (Lang.hasOwnProperty(this, i)) { this[i] = null; } } return true; }, /** * @method collapse * @description Programatically collapse the toolbar. * @param {Boolean} collapse True to collapse, false to expand. */ collapse: function(collapse) { var el = Dom.getElementsByClassName('collapse', 'span', this._titlebar); if (collapse === false) { Dom.removeClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); if (el[0]) { Dom.removeClass(el[0], 'collapsed'); } this.fireEvent('toolbarExpanded', { type: 'toolbarExpanded', target: this }); } else { if (el[0]) { Dom.addClass(el[0], 'collapsed'); } Dom.addClass(this.get('cont').parentNode, 'yui-toolbar-container-collapsed'); this.fireEvent('toolbarCollapsed', { type: 'toolbarCollapsed', target: this }); } }, /** * @method toString * @description Returns a string representing the toolbar. * @return {String} */ toString: function() { return 'Toolbar (#' + this.get('element').id + ') with ' + this._buttonList.length + ' buttons.'; } }); /** * @event buttonClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description Fires when any botton receives a click event. Passes back a single object representing the buttons config object. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event valueClick * @param {Object} o The object passed to this handler is the button config used to create the button. * @description This is a special dynamic event that is created and dispatched based on the value property * of the button config. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * Example: * <code><pre> * buttons : [ * { type: 'button', value: 'test', value: 'testButton' } * ]</pre> * </code> * With the valueClick event you could subscribe to this buttons click event with this: * tbar.in('testButtonClick', function() { alert('test button clicked'); }) * @type YAHOO.util.CustomEvent */ /** * @event toolbarExpanded * @description Fires when the toolbar is expanded via the collapse button. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event toolbarCollapsed * @description Fires when the toolbar is collapsed via the collapse button. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ })(); /** * @module editor * @description <p>The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization.</p> * @namespace YAHOO.widget * @requires yahoo, dom, element, event, toolbar * @optional animation, container_core, resize, dragdrop */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Toolbar = YAHOO.widget.Toolbar; /** * The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization. * @constructor * @class SimpleEditor * @extends YAHOO.util.Element * @param {String/HTMLElement} el The textarea element to turn into an editor. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.SimpleEditor = function(el, attrs) { YAHOO.log('SimpleEditor Initalizing', 'info', 'SimpleEditor'); var o = {}; if (Lang.isObject(el) && (!el.tagName) && !attrs) { Lang.augmentObject(o, el); //Break the config reference el = document.createElement('textarea'); this.DOMReady = true; if (o.container) { var c = Dom.get(o.container); c.appendChild(el); } else { document.body.appendChild(el); } } else { if (attrs) { Lang.augmentObject(o, attrs); //Break the config reference } } var oConfig = { element: null, attributes: o }, id = null; if (Lang.isString(el)) { id = el; } else { if (oConfig.attributes.id) { id = oConfig.attributes.id; } else { this.DOMReady = true; id = Dom.generateId(el); } } oConfig.element = el; var element_cont = document.createElement('DIV'); oConfig.attributes.element_cont = new YAHOO.util.Element(element_cont, { id: id + '_container' }); var div = document.createElement('div'); Dom.addClass(div, 'first-child'); oConfig.attributes.element_cont.appendChild(div); if (!oConfig.attributes.toolbar_cont) { oConfig.attributes.toolbar_cont = document.createElement('DIV'); oConfig.attributes.toolbar_cont.id = id + '_toolbar'; div.appendChild(oConfig.attributes.toolbar_cont); } var editorWrapper = document.createElement('DIV'); div.appendChild(editorWrapper); oConfig.attributes.editor_wrapper = editorWrapper; YAHOO.widget.SimpleEditor.superclass.constructor.call(this, oConfig.element, oConfig.attributes); }; YAHOO.extend(YAHOO.widget.SimpleEditor, YAHOO.util.Element, { /** * @private * @property _resizeConfig * @description The default config for the Resize Utility */ _resizeConfig: { handles: ['br'], autoRatio: true, status: true, proxy: true, useShim: true, setSize: false }, /** * @private * @method _setupResize * @description Creates the Resize instance and binds its events. */ _setupResize: function() { if (!YAHOO.util.DD || !YAHOO.util.Resize) { return false; } if (this.get('resize')) { var config = {}; Lang.augmentObject(config, this._resizeConfig); //Break the config reference this.resize = new YAHOO.util.Resize(this.get('element_cont').get('element'), config); this.resize.on('resize', function(args) { var anim = this.get('animate'); this.set('animate', false); this.set('width', args.width + 'px'); var h = args.height, th = (this.toolbar.get('element').clientHeight + 2), dh = 0; if (this.dompath) { dh = (this.dompath.clientHeight + 1); //It has a 1px top border.. } var newH = (h - th - dh); this.set('height', newH + 'px'); this.get('element_cont').setStyle('height', ''); this.set('animate', anim); }, this, true); } }, /** * @property resize * @description A reference to the Resize object * @type YAHOO.util.Resize */ resize: null, /** * @private * @method _setupDD * @description Sets up the DD instance used from the 'drag' config option. */ _setupDD: function() { if (!YAHOO.util.DD) { return false; } if (this.get('drag')) { YAHOO.log('Attaching DD instance to Editor', 'info', 'SimpleEditor'); var d = this.get('drag'), dd = YAHOO.util.DD; if (d === 'proxy') { dd = YAHOO.util.DDProxy; } this.dd = new dd(this.get('element_cont').get('element')); this.toolbar.addClass('draggable'); this.dd.setHandleElId(this.toolbar._titlebar); } }, /** * @property dd * @description A reference to the DragDrop object. * @type YAHOO.util.DD/YAHOO.util.DDProxy */ dd: null, /** * @private * @property _lastCommand * @description A cache of the last execCommand (used for Undo/Redo so they don't mark an undo level) * @type String */ _lastCommand: null, _undoNodeChange: function() {}, _storeUndo: function() {}, /** * @private * @method _checkKey * @description Checks a keyMap entry against a key event * @param {Object} k The _keyMap object * @param {Event} e The Mouse Event * @return {Boolean} */ _checkKey: function(k, e) { var ret = false; if ((e.keyCode === k.key)) { if (k.mods && (k.mods.length > 0)) { var val = 0; for (var i = 0; i < k.mods.length; i++) { if (this.browser.mac) { if (k.mods[i] == 'ctrl') { k.mods[i] = 'meta'; } } if (e[k.mods[i] + 'Key'] === true) { val++; } } if (val === k.mods.length) { ret = true; } } else { ret = true; } } //YAHOO.log('Shortcut Key Check: (' + k.key + ') return: ' + ret, 'info', 'SimpleEditor'); return ret; }, /** * @private * @property _keyMap * @description Named key maps for various actions in the Editor. Example: <code>CLOSE_WINDOW: { key: 87, mods: ['shift', 'ctrl'] }</code>. * This entry shows that when key 87 (W) is found with the modifiers of shift and control, the window will close. You can customize this object to tweak keyboard shortcuts. * @type {Object/Mixed} */ _keyMap: { SELECT_ALL: { key: 65, //A key mods: ['ctrl'] }, CLOSE_WINDOW: { key: 87, //W key mods: ['shift', 'ctrl'] }, FOCUS_TOOLBAR: { key: 27, mods: ['shift'] }, FOCUS_AFTER: { key: 27 }, FONT_SIZE_UP: { key: 38, mods: ['shift', 'ctrl'] }, FONT_SIZE_DOWN: { key: 40, mods: ['shift', 'ctrl'] }, CREATE_LINK: { key: 76, mods: ['shift', 'ctrl'] }, BOLD: { key: 66, mods: ['shift', 'ctrl'] }, ITALIC: { key: 73, mods: ['shift', 'ctrl'] }, UNDERLINE: { key: 85, mods: ['shift', 'ctrl'] }, UNDO: { key: 90, mods: ['ctrl'] }, REDO: { key: 90, mods: ['shift', 'ctrl'] }, JUSTIFY_LEFT: { key: 219, mods: ['shift', 'ctrl'] }, JUSTIFY_CENTER: { key: 220, mods: ['shift', 'ctrl'] }, JUSTIFY_RIGHT: { key: 221, mods: ['shift', 'ctrl'] } }, /** * @private * @method _cleanClassName * @description Makes a useable classname from dynamic data, by dropping it to lowercase and replacing spaces with -'s. * @param {String} str The classname to clean up * @return {String} */ _cleanClassName: function(str) { return str.replace(/ /g, '-').toLowerCase(); }, /** * @property _textarea * @description Flag to determine if we are using a textarea or an HTML Node. * @type Boolean */ _textarea: null, /** * @property _docType * @description The DOCTYPE to use in the editable container. * @type String */ _docType: '<!DOCTYPE HTML PUBLIC "-/'+'/W3C/'+'/DTD HTML 4.01/'+'/EN" "http:/'+'/www.w3.org/TR/html4/strict.dtd">', /** * @property editorDirty * @description This flag will be set when certain things in the Editor happen. It is to be used by the developer to check to see if content has changed. * @type Boolean */ editorDirty: null, /** * @property _defaultCSS * @description The default CSS used in the config for 'css'. This way you can add to the config like this: { css: YAHOO.widget.SimpleEditor.prototype._defaultCSS + 'ADD MYY CSS HERE' } * @type String */ _defaultCSS: 'html { height: 95%; } body { padding: 7px; background-color: #fff; font: 13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a, a:visited, a:hover { color: blue !important; text-decoration: underline !important; cursor: text !important; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } body.ptags.webkit div.yui-wk-p { margin: 11px 0; } body.ptags.webkit div.yui-wk-div { margin: 0; }', /** * @property _defaultToolbar * @private * @description Default toolbar config. * @type Object */ _defaultToolbar: null, /** * @property _lastButton * @private * @description The last button pressed, so we don't disable it. * @type Object */ _lastButton: null, /** * @property _baseHREF * @private * @description The base location of the editable page (this page) so that relative paths for image work. * @type String */ _baseHREF: function() { var href = document.location.href; if (href.indexOf('?') !== -1) { //Remove the query string href = href.substring(0, href.indexOf('?')); } href = href.substring(0, href.lastIndexOf('/')) + '/'; return href; }(), /** * @property _lastImage * @private * @description Safari reference for the last image selected (for styling as selected). * @type HTMLElement */ _lastImage: null, /** * @property _blankImageLoaded * @private * @description Don't load the blank image more than once.. * @type Boolean */ _blankImageLoaded: null, /** * @property _fixNodesTimer * @private * @description Holder for the fixNodes timer * @type Date */ _fixNodesTimer: null, /** * @property _nodeChangeTimer * @private * @description Holds a reference to the nodeChange setTimeout call * @type Number */ _nodeChangeTimer: null, /** * @property _lastNodeChangeEvent * @private * @description Flag to determine the last event that fired a node change * @type Event */ _lastNodeChangeEvent: null, /** * @property _lastNodeChange * @private * @description Flag to determine when the last node change was fired * @type Date */ _lastNodeChange: 0, /** * @property _rendered * @private * @description Flag to determine if editor has been rendered or not * @type Boolean */ _rendered: null, /** * @property DOMReady * @private * @description Flag to determine if DOM is ready or not * @type Boolean */ DOMReady: null, /** * @property _selection * @private * @description Holder for caching iframe selections * @type Object */ _selection: null, /** * @property _mask * @private * @description DOM Element holder for the editor Mask when disabled * @type Object */ _mask: null, /** * @property _showingHiddenElements * @private * @description Status of the hidden elements button * @type Boolean */ _showingHiddenElements: null, /** * @property currentWindow * @description A reference to the currently open EditorWindow * @type Object */ currentWindow: null, /** * @property currentEvent * @description A reference to the current editor event * @type Event */ currentEvent: null, /** * @property operaEvent * @private * @description setTimeout holder for Opera and Image DoubleClick event.. * @type Object */ operaEvent: null, /** * @property currentFont * @description A reference to the last font selected from the Toolbar * @type HTMLElement */ currentFont: null, /** * @property currentElement * @description A reference to the current working element in the editor * @type Array */ currentElement: null, /** * @property dompath * @description A reference to the dompath container for writing the current working dom path to. * @type HTMLElement */ dompath: null, /** * @property beforeElement * @description A reference to the H2 placed before the editor for Accessibilty. * @type HTMLElement */ beforeElement: null, /** * @property afterElement * @description A reference to the H2 placed after the editor for Accessibilty. * @type HTMLElement */ afterElement: null, /** * @property invalidHTML * @description Contains a list of HTML elements that are invalid inside the editor. They will be removed when they are found. If you set the value of a key to "{ keepContents: true }", then the element will be replaced with a yui-non span to be filtered out when cleanHTML is called. The only tag that is ignored here is the span tag as it will force the Editor into a loop and freeze the browser. However.. all of these tags will be removed in the cleanHTML routine. * @type Object */ invalidHTML: { form: true, input: true, button: true, select: true, link: true, html: true, body: true, iframe: true, script: true, style: true, textarea: true }, /** * @property toolbar * @description Local property containing the <a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a> instance * @type <a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a> */ toolbar: null, /** * @private * @property _contentTimer * @description setTimeout holder for documentReady check */ _contentTimer: null, /** * @private * @property _contentTimerCounter * @description Counter to check the number of times the body is polled for before giving up * @type Number */ _contentTimerCounter: 0, /** * @private * @property _disabled * @description The Toolbar items that should be disabled if there is no selection present in the editor. * @type Array */ _disabled: [ 'createlink', 'fontname', 'fontsize', 'forecolor', 'backcolor' ], /** * @private * @property _alwaysDisabled * @description The Toolbar items that should ALWAYS be disabled event if there is a selection present in the editor. * @type Object */ _alwaysDisabled: { undo: true, redo: true }, /** * @private * @property _alwaysEnabled * @description The Toolbar items that should ALWAYS be enabled event if there isn't a selection present in the editor. * @type Object */ _alwaysEnabled: { }, /** * @private * @property _semantic * @description The Toolbar commands that we should attempt to make tags out of instead of using styles. * @type Object */ _semantic: { 'bold': true, 'italic' : true, 'underline' : true }, /** * @private * @property _tag2cmd * @description A tag map of HTML tags to convert to the different types of commands so we can select the proper toolbar button. * @type Object */ _tag2cmd: { 'b': 'bold', 'strong': 'bold', 'i': 'italic', 'em': 'italic', 'u': 'underline', 'sup': 'superscript', 'sub': 'subscript', 'img': 'insertimage', 'a' : 'createlink', 'ul' : 'insertunorderedlist', 'ol' : 'insertorderedlist' }, /** * @private _createIframe * @description Creates the DOM and YUI Element for the iFrame editor area. * @param {String} id The string ID to prefix the iframe with * @return {Object} iFrame object */ _createIframe: function() { var ifrmDom = document.createElement('iframe'); ifrmDom.id = this.get('id') + '_editor'; var config = { border: '0', frameBorder: '0', marginWidth: '0', marginHeight: '0', leftMargin: '0', topMargin: '0', allowTransparency: 'true', width: '100%' }; if (this.get('autoHeight')) { config.scrolling = 'no'; } for (var i in config) { if (Lang.hasOwnProperty(config, i)) { ifrmDom.setAttribute(i, config[i]); } } var isrc = 'javascript:;'; if (this.browser.ie) { //isrc = 'about:blank'; //TODO - Check this, I have changed it before.. isrc = 'javascript:false;'; } ifrmDom.setAttribute('src', isrc); var ifrm = new YAHOO.util.Element(ifrmDom); ifrm.setStyle('visibility', 'hidden'); return ifrm; }, /** * @private _isElement * @description Checks to see if an Element reference is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return {Boolean} */ _isElement: function(el, tag) { if (el && el.tagName && (el.tagName.toLowerCase() == tag)) { return true; } if (el && el.getAttribute && (el.getAttribute('tag') == tag)) { return true; } return false; }, /** * @private _hasParent * @description Checks to see if an Element reference or one of it's parents is a valid one and has a certain tag type * @param {HTMLElement} el The element to check * @param {String} tag The tag that the element needs to be * @return HTMLElement */ _hasParent: function(el, tag) { if (!el || !el.parentNode) { return false; } while (el.parentNode) { if (this._isElement(el, tag)) { return el; } if (el.parentNode) { el = el.parentNode; } else { return false; } } return false; }, /** * @private * @method _getDoc * @description Get the Document of the IFRAME * @return {Object} */ _getDoc: function() { var value = false; if (this.get) { if (this.get('iframe')) { if (this.get('iframe').get) { if (this.get('iframe').get('element')) { try { if (this.get('iframe').get('element').contentWindow) { if (this.get('iframe').get('element').contentWindow.document) { value = this.get('iframe').get('element').contentWindow.document; return value; } } } catch (e) {} } } } } return false; }, /** * @private * @method _getWindow * @description Get the Window of the IFRAME * @return {Object} */ _getWindow: function() { return this.get('iframe').get('element').contentWindow; }, /** * @method focus * @description Attempt to set the focus of the iframes window. */ focus: function() { this._getWindow().focus(); }, /** * @private * @depreciated - This should not be used, moved to this.focus(); * @method _focusWindow * @description Attempt to set the focus of the iframes window. */ _focusWindow: function() { YAHOO.log('_focusWindow: depreciated in favor of this.focus()', 'warn', 'Editor'); this.focus(); }, /** * @private * @method _hasSelection * @description Determines if there is a selection in the editor document. * @return {Boolean} */ _hasSelection: function() { var sel = this._getSelection(); var range = this._getRange(); var hasSel = false; if (!sel || !range) { return hasSel; } //Internet Explorer if (this.browser.ie || this.browser.opera) { if (range.text) { hasSel = true; } if (range.html) { hasSel = true; } } else { if (this.browser.webkit) { if (sel+'' !== '') { hasSel = true; } } else { if (sel && (sel.toString() !== '') && (sel !== undefined)) { hasSel = true; } } } return hasSel; }, /** * @private * @method _getSelection * @description Handles the different selection objects across the A-Grade list. * @return {Object} Selection Object */ _getSelection: function() { var _sel = null; if (this._getDoc() && this._getWindow()) { if (this._getDoc().selection) { _sel = this._getDoc().selection; } else { _sel = this._getWindow().getSelection(); } //Handle Safari's lack of Selection Object if (this.browser.webkit) { if (_sel.baseNode) { this._selection = {}; this._selection.baseNode = _sel.baseNode; this._selection.baseOffset = _sel.baseOffset; this._selection.extentNode = _sel.extentNode; this._selection.extentOffset = _sel.extentOffset; } else if (this._selection !== null) { _sel = this._getWindow().getSelection(); _sel.setBaseAndExtent( this._selection.baseNode, this._selection.baseOffset, this._selection.extentNode, this._selection.extentOffset); this._selection = null; } } } return _sel; }, /** * @private * @method _selectNode * @description Places the highlight around a given node * @param {HTMLElement} node The node to select */ _selectNode: function(node, collapse) { if (!node) { return false; } var sel = this._getSelection(), range = null; if (this.browser.ie) { try { //IE freaks out here sometimes.. range = this._getDoc().body.createTextRange(); range.moveToElementText(node); range.select(); } catch (e) { YAHOO.log('IE failed to select element: ' + node.tagName, 'warn', 'SimpleEditor'); } } else if (this.browser.webkit) { if (collapse) { sel.setBaseAndExtent(node, 1, node, node.innerText.length); } else { sel.setBaseAndExtent(node, 0, node, node.innerText.length); } } else if (this.browser.opera) { sel = this._getWindow().getSelection(); range = this._getDoc().createRange(); range.selectNode(node); sel.removeAllRanges(); sel.addRange(range); } else { range = this._getDoc().createRange(); range.selectNodeContents(node); sel.removeAllRanges(); sel.addRange(range); } //TODO - Check Performance this.nodeChange(); }, /** * @private * @method _getRange * @description Handles the different range objects across the A-Grade list. * @return {Object} Range Object */ _getRange: function() { var sel = this._getSelection(); if (sel === null) { return null; } if (this.browser.webkit && !sel.getRangeAt) { var _range = this._getDoc().createRange(); try { _range.setStart(sel.anchorNode, sel.anchorOffset); _range.setEnd(sel.focusNode, sel.focusOffset); } catch (e) { _range = this._getWindow().getSelection()+''; } return _range; } if (this.browser.ie || this.browser.opera) { try { return sel.createRange(); } catch (e2) { return null; } } if (sel.rangeCount > 0) { return sel.getRangeAt(0); } return null; }, /** * @private * @method _setDesignMode * @description Sets the designMode of the iFrame document. * @param {String} state This should be either on or off */ _setDesignMode: function(state) { try { var set = true; //SourceForge Bug #1807057 if (this.browser.ie && (state.toLowerCase() == 'off')) { set = false; } if (set) { this._getDoc().designMode = state; } } catch(e) { } }, /** * @private * @method _toggleDesignMode * @description Toggles the designMode of the iFrame document on and off. * @return {String} The state that it was set to. */ _toggleDesignMode: function() { var _dMode = this._getDoc().designMode.toLowerCase(), _state = 'on'; if (_dMode == 'on') { _state = 'off'; } this._setDesignMode(_state); return _state; }, /** * @private * @property _focused * @description Holder for trapping focus/blur state and prevent double events * @type Boolean */ _focused: null, /** * @private * @method _handleFocus * @description Handles the focus of the iframe. Note, this is window focus event, not an Editor focus event. * @param {Event} e The DOM Event */ _handleFocus: function(e) { if (!this._focused) { YAHOO.log('Editor Window Focused', 'info', 'SimpleEditor'); this._focused = true; this.fireEvent('editorWindowFocus', { type: 'editorWindowFocus', target: this }); } }, /** * @private * @method _handleBlur * @description Handles the blur of the iframe. Note, this is window blur event, not an Editor blur event. * @param {Event} e The DOM Event */ _handleBlur: function(e) { if (this._focused) { YAHOO.log('Editor Window Blurred', 'info', 'SimpleEditor'); this._focused = false; this.fireEvent('editorWindowBlur', { type: 'editorWindowBlur', target: this }); } }, /** * @private * @method _initEditorEvents * @description This method sets up the listeners on the Editors document. */ _initEditorEvents: function() { //Setup Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.on(doc, 'mouseup', this._handleMouseUp, this, true); Event.on(doc, 'mousedown', this._handleMouseDown, this, true); Event.on(doc, 'click', this._handleClick, this, true); Event.on(doc, 'dblclick', this._handleDoubleClick, this, true); Event.on(doc, 'keypress', this._handleKeyPress, this, true); Event.on(doc, 'keyup', this._handleKeyUp, this, true); Event.on(doc, 'keydown', this._handleKeyDown, this, true); /* TODO -- Everyone but Opera works here.. Event.on(doc, 'paste', function() { YAHOO.log('PASTE', 'info', 'SimpleEditor'); }, this, true); */ //Focus and blur.. Event.on(win, 'focus', this._handleFocus, this, true); Event.on(win, 'blur', this._handleBlur, this, true); }, /** * @private * @method _removeEditorEvents * @description This method removes the listeners on the Editors document (for disabling). */ _removeEditorEvents: function() { //Remove Listeners on iFrame var doc = this._getDoc(), win = this._getWindow(); Event.removeListener(doc, 'mouseup', this._handleMouseUp, this, true); Event.removeListener(doc, 'mousedown', this._handleMouseDown, this, true); Event.removeListener(doc, 'click', this._handleClick, this, true); Event.removeListener(doc, 'dblclick', this._handleDoubleClick, this, true); Event.removeListener(doc, 'keypress', this._handleKeyPress, this, true); Event.removeListener(doc, 'keyup', this._handleKeyUp, this, true); Event.removeListener(doc, 'keydown', this._handleKeyDown, this, true); //Focus and blur.. Event.removeListener(win, 'focus', this._handleFocus, this, true); Event.removeListener(win, 'blur', this._handleBlur, this, true); }, _fixWebkitDivs: function() { if (this.browser.webkit) { var divs = this._getDoc().body.getElementsByTagName('div'); Dom.addClass(divs, 'yui-wk-div'); } }, /** * @private * @method _initEditor * @description This method is fired from _checkLoaded when the document is ready. It turns on designMode and set's up the listeners. */ _initEditor: function() { if (this.browser.ie) { this._getDoc().body.style.margin = '0'; } if (!this.get('disabled')) { if (this._getDoc().designMode.toLowerCase() != 'on') { this._setDesignMode('on'); this._contentTimerCounter = 0; } } if (!this._getDoc().body) { YAHOO.log('Body is null, check again', 'error', 'SimpleEditor'); this._contentTimerCounter = 0; this._checkLoaded(); return false; } YAHOO.log('editorLoaded', 'info', 'SimpleEditor'); this.toolbar.on('buttonClick', this._handleToolbarClick, this, true); if (!this.get('disabled')) { this._initEditorEvents(); this.toolbar.set('disabled', false); } this.fireEvent('editorContentLoaded', { type: 'editorLoaded', target: this }); this._fixWebkitDivs(); if (this.get('dompath')) { YAHOO.log('Delayed DomPath write', 'info', 'SimpleEditor'); var self = this; setTimeout(function() { self._writeDomPath.call(self); self._setupResize.call(self); }, 150); } var br = []; for (var i in this.browser) { if (this.browser[i]) { br.push(i); } } if (this.get('ptags')) { br.push('ptags'); } Dom.addClass(this._getDoc().body, br.join(' ')); this.nodeChange(true); }, /** * @private * @method _checkLoaded * @description Called from a setTimeout loop to check if the iframes body.onload event has fired, then it will init the editor. */ _checkLoaded: function() { this._contentTimerCounter++; if (this._contentTimer) { clearTimeout(this._contentTimer); } if (this._contentTimerCounter > 500) { YAHOO.log('ERROR: Body Did Not load', 'error', 'SimpleEditor'); return false; } var init = false; try { if (this._getDoc() && this._getDoc().body) { if (this.browser.ie) { if (this._getDoc().body.readyState == 'complete') { init = true; } } else { if (this._getDoc().body._rteLoaded === true) { init = true; } } } } catch (e) { init = false; YAHOO.log('checking body (e)' + e, 'error', 'SimpleEditor'); } if (init === true) { //The onload event has fired, clean up after ourselves and fire the _initEditor method YAHOO.log('Firing _initEditor', 'info', 'SimpleEditor'); this._initEditor(); } else { var self = this; this._contentTimer = setTimeout(function() { self._checkLoaded.call(self); }, 20); } }, /** * @private * @method _setInitialContent * @description This method will open the iframes content document and write the textareas value into it, then start the body.onload checking. */ _setInitialContent: function() { YAHOO.log('Populating editor body with contents of the text area', 'info', 'SimpleEditor'); var value = ((this._textarea) ? this.get('element').value : this.get('element').innerHTML), doc = null; if ((value === '') && this.browser.gecko) { //It seems that Gecko doesn't like an empty body so we have to give it something.. value = '<br>'; } var html = Lang.substitute(this.get('html'), { TITLE: this.STR_TITLE, CONTENT: this._cleanIncomingHTML(value), CSS: this.get('css'), HIDDEN_CSS: ((this.get('hiddencss')) ? this.get('hiddencss') : '/* No Hidden CSS */'), EXTRA_CSS: ((this.get('extracss')) ? this.get('extracss') : '/* No Extra CSS */') }), check = true; if (document.compatMode != 'BackCompat') { YAHOO.log('Adding Doctype to editable area', 'info', 'SimpleEditor'); html = this._docType + "\n" + html; } else { YAHOO.log('DocType skipped because we are in BackCompat Mode.', 'warn', 'SimpleEditor'); } if (this.browser.ie || this.browser.webkit || this.browser.opera || (navigator.userAgent.indexOf('Firefox/1.5') != -1)) { //Firefox 1.5 doesn't like setting designMode on an document created with a data url try { //Adobe AIR Code if (this.browser.air) { doc = this._getDoc().implementation.createHTMLDocument(); var origDoc = this._getDoc(); origDoc.open(); origDoc.close(); doc.open(); doc.write(html); doc.close(); var node = origDoc.importNode(doc.getElementsByTagName("html")[0], true); origDoc.replaceChild(node, origDoc.getElementsByTagName("html")[0]); origDoc.body._rteLoaded = true; } else { doc = this._getDoc(); doc.open(); doc.write(html); doc.close(); } } catch (e) { YAHOO.log('Setting doc failed.. (_setInitialContent)', 'error', 'SimpleEditor'); //Safari will only be here if we are hidden check = false; } } else { //This keeps Firefox 2 from writing the iframe to history preserving the back buttons functionality this.get('iframe').get('element').src = 'data:text/html;charset=utf-8,' + encodeURIComponent(html); } this.get('iframe').setStyle('visibility', ''); if (check) { this._checkLoaded(); } }, /** * @private * @method _setMarkupType * @param {String} action The action to take. Possible values are: css, default or semantic * @description This method will turn on/off the useCSS execCommand. */ _setMarkupType: function(action) { switch (this.get('markup')) { case 'css': this._setEditorStyle(true); break; case 'default': this._setEditorStyle(false); break; case 'semantic': case 'xhtml': if (this._semantic[action]) { this._setEditorStyle(false); } else { this._setEditorStyle(true); } break; } }, /** * Set the editor to use CSS instead of HTML * @param {Booleen} stat True/False */ _setEditorStyle: function(stat) { try { this._getDoc().execCommand('useCSS', false, !stat); } catch (ex) { } }, /** * @private * @method _getSelectedElement * @description This method will attempt to locate the element that was last interacted with, either via selection, location or event. * @return {HTMLElement} The currently selected element. */ _getSelectedElement: function() { var doc = this._getDoc(), range = null, sel = null, elm = null, check = true; if (this.browser.ie) { this.currentEvent = this._getWindow().event; //Event utility assumes window.event, so we need to reset it to this._getWindow().event; range = this._getRange(); if (range) { elm = range.item ? range.item(0) : range.parentElement(); if (this._hasSelection()) { //TODO //WTF.. Why can't I get an element reference here?!??! } if (elm === doc.body) { elm = null; } } if ((this.currentEvent !== null) && (this.currentEvent.keyCode === 0)) { elm = Event.getTarget(this.currentEvent); } } else { sel = this._getSelection(); range = this._getRange(); if (!sel || !range) { return null; } //TODO if (!this._hasSelection() && this.browser.webkit3) { //check = false; } if (this.browser.gecko) { //Added in 2.6.0 if (range.startContainer) { if (range.startContainer.nodeType === 3) { elm = range.startContainer.parentNode; } else if (range.startContainer.nodeType === 1) { elm = range.startContainer; } //Added in 2.7.0 if (this.currentEvent) { var tar = Event.getTarget(this.currentEvent); if (!this._isElement(tar, 'html')) { if (elm !== tar) { elm = tar; } } } } } if (check) { if (sel.anchorNode && (sel.anchorNode.nodeType == 3)) { if (sel.anchorNode.parentNode) { //next check parentNode elm = sel.anchorNode.parentNode; } if (sel.anchorNode.nextSibling != sel.focusNode.nextSibling) { elm = sel.anchorNode.nextSibling; } } if (this._isElement(elm, 'br')) { elm = null; } if (!elm) { elm = range.commonAncestorContainer; if (!range.collapsed) { if (range.startContainer == range.endContainer) { if (range.startOffset - range.endOffset < 2) { if (range.startContainer.hasChildNodes()) { elm = range.startContainer.childNodes[range.startOffset]; } } } } } } } if (this.currentEvent !== null) { try { switch (this.currentEvent.type) { case 'click': case 'mousedown': case 'mouseup': if (this.browser.webkit) { elm = Event.getTarget(this.currentEvent); } break; default: //Do nothing break; } } catch (e) { YAHOO.log('Firefox 1.5 errors here: ' + e, 'error', 'SimpleEditor'); } } else if ((this.currentElement && this.currentElement[0]) && (!this.browser.ie)) { //TODO is this still needed? //elm = this.currentElement[0]; } if (this.browser.opera || this.browser.webkit) { if (this.currentEvent && !elm) { elm = YAHOO.util.Event.getTarget(this.currentEvent); } } if (!elm || !elm.tagName) { elm = doc.body; } if (this._isElement(elm, 'html')) { //Safari sometimes gives us the HTML node back.. elm = doc.body; } if (this._isElement(elm, 'body')) { //make sure that body means this body not the parent.. elm = doc.body; } if (elm && !elm.parentNode) { //Not in document elm = doc.body; } if (elm === undefined) { elm = null; } return elm; }, /** * @private * @method _getDomPath * @description This method will attempt to build the DOM path from the currently selected element. * @param HTMLElement el The element to start with, if not provided _getSelectedElement is used * @return {Array} An array of node references that will create the DOM Path. */ _getDomPath: function(el) { if (!el) { el = this._getSelectedElement(); } var domPath = []; while (el !== null) { if (el.ownerDocument != this._getDoc()) { el = null; break; } //Check to see if we get el.nodeName and nodeType if (el.nodeName && el.nodeType && (el.nodeType == 1)) { domPath[domPath.length] = el; } if (this._isElement(el, 'body')) { break; } el = el.parentNode; } if (domPath.length === 0) { if (this._getDoc() && this._getDoc().body) { domPath[0] = this._getDoc().body; } } return domPath.reverse(); }, /** * @private * @method _writeDomPath * @description Write the current DOM path out to the dompath container below the editor. */ _writeDomPath: function() { var path = this._getDomPath(), pathArr = [], classPath = '', pathStr = ''; for (var i = 0; i < path.length; i++) { var tag = path[i].tagName.toLowerCase(); if ((tag == 'ol') && (path[i].type)) { tag += ':' + path[i].type; } if (Dom.hasClass(path[i], 'yui-tag')) { tag = path[i].getAttribute('tag'); } if ((this.get('markup') == 'semantic') || (this.get('markup') == 'xhtml')) { switch (tag) { case 'b': tag = 'strong'; break; case 'i': tag = 'em'; break; } } if (!Dom.hasClass(path[i], 'yui-non')) { if (Dom.hasClass(path[i], 'yui-tag')) { pathStr = tag; } else { classPath = ((path[i].className !== '') ? '.' + path[i].className.replace(/ /g, '.') : ''); if ((classPath.indexOf('yui') != -1) || (classPath.toLowerCase().indexOf('apple-style-span') != -1)) { classPath = ''; } pathStr = tag + ((path[i].id) ? '#' + path[i].id : '') + classPath; } switch (tag) { case 'body': pathStr = 'body'; break; case 'a': if (path[i].getAttribute('href', 2)) { pathStr += ':' + path[i].getAttribute('href', 2).replace('mailto:', '').replace('http:/'+'/', '').replace('https:/'+'/', ''); //May need to add others here ftp } break; case 'img': var h = path[i].height; var w = path[i].width; if (path[i].style.height) { h = parseInt(path[i].style.height, 10); } if (path[i].style.width) { w = parseInt(path[i].style.width, 10); } pathStr += '(' + w + 'x' + h + ')'; break; } if (pathStr.length > 10) { pathStr = '<span title="' + pathStr + '">' + pathStr.substring(0, 10) + '...' + '</span>'; } else { pathStr = '<span title="' + pathStr + '">' + pathStr + '</span>'; } pathArr[pathArr.length] = pathStr; } } var str = pathArr.join(' ' + this.SEP_DOMPATH + ' '); //Prevent flickering if (this.dompath.innerHTML != str) { this.dompath.innerHTML = str; } }, /** * @private * @method _fixNodes * @description Fix href and imgs as well as remove invalid HTML. */ _fixNodes: function() { var doc = this._getDoc(), els = []; for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (v.toLowerCase() != 'span') { var tags = doc.body.getElementsByTagName(v); if (tags.length) { for (var i = 0; i < tags.length; i++) { els.push(tags[i]); } } } } } for (var h = 0; h < els.length; h++) { if (els[h].parentNode) { if (Lang.isObject(this.invalidHTML[els[h].tagName.toLowerCase()]) && this.invalidHTML[els[h].tagName.toLowerCase()].keepContents) { this._swapEl(els[h], 'span', function(el) { el.className = 'yui-non'; }); } else { els[h].parentNode.removeChild(els[h]); } } } var imgs = this._getDoc().getElementsByTagName('img'); Dom.addClass(imgs, 'yui-img'); }, /** * @private * @method _isNonEditable * @param Event ev The Dom event being checked * @description Method is called at the beginning of all event handlers to check if this element or a parent element has the class yui-noedit (this.CLASS_NOEDIT) applied. * If it does, then this method will stop the event and return true. The event handlers will then return false and stop the nodeChange from occuring. This method will also * disable and enable the Editor's toolbar based on the noedit state. * @return Boolean */ _isNonEditable: function(ev) { if (this.get('allowNoEdit')) { var el = Event.getTarget(ev); if (this._isElement(el, 'html')) { el = null; } var path = this._getDomPath(el); for (var i = (path.length - 1); i > -1; i--) { if (Dom.hasClass(path[i], this.CLASS_NOEDIT)) { //if (this.toolbar.get('disabled') === false) { // this.toolbar.set('disabled', true); //} try { this._getDoc().execCommand('enableObjectResizing', false, 'false'); } catch (e) {} this.nodeChange(); Event.stopEvent(ev); YAHOO.log('CLASS_NOEDIT found in DOM Path, stopping event', 'info', 'SimpleEditor'); return true; } } //if (this.toolbar.get('disabled') === true) { //Should only happen once.. //this.toolbar.set('disabled', false); try { this._getDoc().execCommand('enableObjectResizing', false, 'true'); } catch (e2) {} //} } return false; }, /** * @private * @method _setCurrentEvent * @param {Event} ev The event to cache * @description Sets the current event property */ _setCurrentEvent: function(ev) { this.currentEvent = ev; }, /** * @private * @method _handleClick * @param {Event} ev The event we are working on. * @description Handles all click events inside the iFrame document. */ _handleClick: function(ev) { var ret = this.fireEvent('beforeEditorClick', { type: 'beforeEditorClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } if (this.browser.webkit) { var tar =Event.getTarget(ev); if (this._isElement(tar, 'a') || this._isElement(tar.parentNode, 'a')) { Event.stopEvent(ev); this.nodeChange(); } } else { this.nodeChange(); } this.fireEvent('editorClick', { type: 'editorClick', target: this, ev: ev }); }, /** * @private * @method _handleMouseUp * @param {Event} ev The event we are working on. * @description Handles all mouseup events inside the iFrame document. */ _handleMouseUp: function(ev) { var ret = this.fireEvent('beforeEditorMouseUp', { type: 'beforeEditorMouseUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } //Don't set current event for mouseup. //It get's fired after a menu is closed and gives up a bogus event to work with //this._setCurrentEvent(ev); var self = this; if (this.browser.opera) { /* * @knownissue Opera appears to stop the MouseDown, Click and DoubleClick events on an image inside of a document with designMode on.. * @browser Opera * @description This work around traps the MouseUp event and sets a timer to check if another MouseUp event fires in so many seconds. If another event is fired, they we internally fire the DoubleClick event. */ var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.nodeChange(); if (this.operaEvent) { clearTimeout(this.operaEvent); this.operaEvent = null; this._handleDoubleClick(ev); } else { this.operaEvent = window.setTimeout(function() { self.operaEvent = false; }, 700); } } } //This will stop Safari from selecting the entire document if you select all the text in the editor if (this.browser.webkit || this.browser.opera) { if (this.browser.webkit) { Event.stopEvent(ev); } } this.nodeChange(); this.fireEvent('editorMouseUp', { type: 'editorMouseUp', target: this, ev: ev }); }, /** * @private * @method _handleMouseDown * @param {Event} ev The event we are working on. * @description Handles all mousedown events inside the iFrame document. */ _handleMouseDown: function(ev) { var ret = this.fireEvent('beforeEditorMouseDown', { type: 'beforeEditorMouseDown', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this.browser.webkit && this._hasSelection()) { var _sel = this._getSelection(); if (!this.browser.webkit3) { _sel.collapse(true); } else { _sel.collapseToStart(); } } if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } if (this._isElement(sel, 'img') || this._isElement(sel, 'a')) { if (this.browser.webkit) { Event.stopEvent(ev); if (this._isElement(sel, 'img')) { Dom.addClass(sel, 'selected'); this._lastImage = sel; } } if (this.currentWindow) { this.closeWindow(); } this.nodeChange(); } this.fireEvent('editorMouseDown', { type: 'editorMouseDown', target: this, ev: ev }); }, /** * @private * @method _handleDoubleClick * @param {Event} ev The event we are working on. * @description Handles all doubleclick events inside the iFrame document. */ _handleDoubleClick: function(ev) { var ret = this.fireEvent('beforeEditorDoubleClick', { type: 'beforeEditorDoubleClick', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); var sel = Event.getTarget(ev); if (this._isElement(sel, 'img')) { this.currentElement[0] = sel; this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } else if (this._hasParent(sel, 'a')) { //Handle elements inside an a this.currentElement[0] = this._hasParent(sel, 'a'); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); } this.nodeChange(); this.fireEvent('editorDoubleClick', { type: 'editorDoubleClick', target: this, ev: ev }); }, /** * @private * @method _handleKeyUp * @param {Event} ev The event we are working on. * @description Handles all keyup events inside the iFrame document. */ _handleKeyUp: function(ev) { var ret = this.fireEvent('beforeEditorKeyUp', { type: 'beforeEditorKeyUp', target: this, ev: ev }); if (ret === false) { return false; } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); switch (ev.keyCode) { case this._keyMap.SELECT_ALL.key: if (this._checkKey(this._keyMap.SELECT_ALL, ev)) { this.nodeChange(); } break; case 32: //Space Bar case 35: //End case 36: //Home case 37: //Left Arrow case 38: //Up Arrow case 39: //Right Arrow case 40: //Down Arrow case 46: //Forward Delete case 8: //Delete case this._keyMap.CLOSE_WINDOW.key: //W key if window is open if ((ev.keyCode == this._keyMap.CLOSE_WINDOW.key) && this.currentWindow) { if (this._checkKey(this._keyMap.CLOSE_WINDOW, ev)) { this.closeWindow(); } } else { if (!this.browser.ie) { if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); } var self = this; this._nodeChangeTimer = setTimeout(function() { self._nodeChangeTimer = null; self.nodeChange.call(self); }, 100); } else { this.nodeChange(); } this.editorDirty = true; } break; } this.fireEvent('editorKeyUp', { type: 'editorKeyUp', target: this, ev: ev }); this._storeUndo(); }, /** * @private * @method _handleKeyPress * @param {Event} ev The event we are working on. * @description Handles all keypress events inside the iFrame document. */ _handleKeyPress: function(ev) { var ret = this.fireEvent('beforeEditorKeyPress', { type: 'beforeEditorKeyPress', target: this, ev: ev }); if (ret === false) { return false; } if (this.get('allowNoEdit')) { //if (ev && ev.keyCode && ((ev.keyCode == 46) || ev.keyCode == 63272)) { if (ev && ev.keyCode && (ev.keyCode == 63272)) { //Forward delete key YAHOO.log('allowNoEdit is set, forward delete key has been disabled', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.browser.opera) { if (ev.keyCode === 13) { var tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { this.execCommand('inserthtml', '<br>'); Event.stopEvent(ev); } } } if (this.browser.webkit) { if (!this.browser.webkit3) { if (ev.keyCode && (ev.keyCode == 122) && (ev.metaKey)) { //This is CMD + z (for undo) if (this._hasParent(this._getSelectedElement(), 'li')) { YAHOO.log('We are in an LI and we found CMD + z, stopping the event', 'warn', 'SimpleEditor'); Event.stopEvent(ev); } } } this._listFix(ev); } this.fireEvent('editorKeyPress', { type: 'editorKeyPress', target: this, ev: ev }); }, /** * @private * @method _handleKeyDown * @param {Event} ev The event we are working on. * @description Handles all keydown events inside the iFrame document. */ _handleKeyDown: function(ev) { var ret = this.fireEvent('beforeEditorKeyDown', { type: 'beforeEditorKeyDown', target: this, ev: ev }); if (ret === false) { return false; } var tar = null, _range = null; if (this._isNonEditable(ev)) { return false; } this._setCurrentEvent(ev); if (this.currentWindow) { this.closeWindow(); } if (this.currentWindow) { this.closeWindow(); } var doExec = false, action = null, value = null, exec = false; //YAHOO.log('keyCode: ' + ev.keyCode, 'info', 'SimpleEditor'); switch (ev.keyCode) { case this._keyMap.FOCUS_TOOLBAR.key: if (this._checkKey(this._keyMap.FOCUS_TOOLBAR, ev)) { var h = this.toolbar.getElementsByTagName('h2')[0]; if (h && h.firstChild) { h.firstChild.focus(); } } else if (this._checkKey(this._keyMap.FOCUS_AFTER, ev)) { //Focus After Element - Esc this.afterElement.focus(); } Event.stopEvent(ev); doExec = false; break; //case 76: //L case this._keyMap.CREATE_LINK.key: //L if (this._hasSelection()) { if (this._checkKey(this._keyMap.CREATE_LINK, ev)) { var makeLink = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); makeLink = false; } } if (makeLink) { this.execCommand('createlink', ''); this.toolbar.fireEvent('createlinkClick', { type: 'createlinkClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); doExec = false; } } } break; //case 90: //Z case this._keyMap.UNDO.key: case this._keyMap.REDO.key: if (this._checkKey(this._keyMap.REDO, ev)) { action = 'redo'; doExec = true; } else if (this._checkKey(this._keyMap.UNDO, ev)) { action = 'undo'; doExec = true; } break; //case 66: //B case this._keyMap.BOLD.key: if (this._checkKey(this._keyMap.BOLD, ev)) { action = 'bold'; doExec = true; } break; case this._keyMap.FONT_SIZE_UP.key: case this._keyMap.FONT_SIZE_DOWN.key: var uk = false, dk = false; if (this._checkKey(this._keyMap.FONT_SIZE_UP, ev)) { uk = true; } if (this._checkKey(this._keyMap.FONT_SIZE_DOWN, ev)) { dk = true; } if (uk || dk) { var fs_button = this.toolbar.getButtonByValue('fontsize'), label = parseInt(fs_button.get('label'), 10), newValue = (label + 1); if (dk) { newValue = (label - 1); } action = 'fontsize'; value = newValue + 'px'; doExec = true; } break; //case 73: //I case this._keyMap.ITALIC.key: if (this._checkKey(this._keyMap.ITALIC, ev)) { action = 'italic'; doExec = true; } break; //case 85: //U case this._keyMap.UNDERLINE.key: if (this._checkKey(this._keyMap.UNDERLINE, ev)) { action = 'underline'; doExec = true; } break; case 9: if (this.browser.ie) { //Insert a tab in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('&nbsp;&nbsp;&nbsp;&nbsp;'); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } //Firefox 3 code if (this.browser.gecko > 1.8) { tar = this._getSelectedElement(); if (this._isElement(tar, 'li')) { if (ev.shiftKey) { this._getDoc().execCommand('outdent', null, ''); } else { this._getDoc().execCommand('indent', null, ''); } } else if (!this._hasSelection()) { this.execCommand('inserthtml', '&nbsp;&nbsp;&nbsp;&nbsp;'); } Event.stopEvent(ev); } break; case 13: var p = null, i = 0; if (this.get('ptags') && !ev.shiftKey) { if (this.browser.gecko) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { if (this._hasParent(tar, 'p')) { p = this._getDoc().createElement('p'); p.innerHTML = '&nbsp;'; Dom.insertAfter(p, tar); this._selectNode(p.firstChild); } else if (this._isElement(tar, 'body')) { this.execCommand('insertparagraph', null); var ps = this._getDoc().body.getElementsByTagName('p'); for (i = 0; i < ps.length; i++) { if (ps[i].getAttribute('_moz_dirty') !== null) { p = this._getDoc().createElement('p'); p.innerHTML = '&nbsp;'; Dom.insertAfter(p, ps[i]); this._selectNode(p.firstChild); ps[i].removeAttribute('_moz_dirty'); } } } else { YAHOO.log('Something went wrong with paragraphs, please file a bug!!', 'error', 'SimpleEditor'); doExec = true; action = 'insertparagraph'; } Event.stopEvent(ev); } } if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { this.execCommand('insertparagraph', null); var divs = this._getDoc().body.getElementsByTagName('div'); for (i = 0; i < divs.length; i++) { if (!Dom.hasClass(divs[i], 'yui-wk-div')) { Dom.addClass(divs[i], 'yui-wk-p'); } } Event.stopEvent(ev); } } } else { if (this.browser.webkit) { tar = this._getSelectedElement(); if (!this._hasParent(tar, 'li')) { this.execCommand('inserthtml', '<var id="yui-br"></var>'); var holder = this._getDoc().getElementById('yui-br'), br = this._getDoc().createElement('br'), caret = this._getDoc().createElement('span'); holder.parentNode.replaceChild(br, holder); caret.className = 'yui-non'; caret.innerHTML = '&nbsp;'; Dom.insertAfter(caret, br); this._selectNode(caret); Event.stopEvent(ev); } } if (this.browser.ie) { YAHOO.log('Stopping P tags', 'info', 'SimpleEditor'); //Insert a <br> instead of a <p></p> in Internet Explorer _range = this._getRange(); tar = this._getSelectedElement(); if (!this._isElement(tar, 'li')) { if (_range) { _range.pasteHTML('<br>'); _range.collapse(false); _range.select(); } Event.stopEvent(ev); } } } break; } if (this.browser.ie) { this._listFix(ev); } if (doExec && action) { this.execCommand(action, value); Event.stopEvent(ev); this.nodeChange(); } this.fireEvent('editorKeyDown', { type: 'editorKeyDown', target: this, ev: ev }); }, /** * @private * @method _listFix * @param {Event} ev The event we are working on. * @description Handles the Enter key, Tab Key and Shift + Tab keys for List Items. */ _listFix: function(ev) { //YAHOO.log('Lists Fix (' + ev.keyCode + ')', 'info', 'SimpleEditor'); var testLi = null, par = null, preContent = false, range = null; //Enter Key if (this.browser.webkit) { if (ev.keyCode && (ev.keyCode == 13)) { if (this._hasParent(this._getSelectedElement(), 'li')) { var tar = this._hasParent(this._getSelectedElement(), 'li'); if (tar.previousSibling) { if (tar.firstChild && (tar.firstChild.length == 1)) { this._selectNode(tar); } } } } } //Shift + Tab Key if (ev.keyCode && ((!this.browser.webkit3 && (ev.keyCode == 25)) || ((this.browser.webkit3 || !this.browser.webkit) && ((ev.keyCode == 9) && ev.shiftKey)))) { testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { testLi = this._hasParent(testLi, 'li'); YAHOO.log('We have a SHIFT tab in an LI, reverse it..', 'info', 'SimpleEditor'); if (this._hasParent(testLi, 'ul') || this._hasParent(testLi, 'ol')) { YAHOO.log('We have a double parent, move up a level', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'ul'); if (!par) { par = this._hasParent(testLi, 'ol'); } //YAHOO.log(par.previousSibling + ' :: ' + par.previousSibling.innerHTML); if (this._isElement(par.previousSibling, 'li')) { par.removeChild(testLi); par.parentNode.insertBefore(testLi, par.nextSibling); if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(testLi); range.collapse(false); range.select(); } if (this.browser.webkit) { this._selectNode(testLi.firstChild); } Event.stopEvent(ev); } } } } //Tab Key if (ev.keyCode && ((ev.keyCode == 9) && (!ev.shiftKey))) { YAHOO.log('List Fix - Tab', 'info', 'SimpleEditor'); var preLi = this._getSelectedElement(); if (this._hasParent(preLi, 'li')) { preContent = this._hasParent(preLi, 'li').innerHTML; } //YAHOO.log('preLI: ' + preLi.tagName + ' :: ' + preLi.innerHTML); if (this.browser.webkit) { this._getDoc().execCommand('inserttext', false, '\t'); } testLi = this._getSelectedElement(); if (this._hasParent(testLi, 'li')) { YAHOO.log('We have a tab in an LI', 'info', 'SimpleEditor'); par = this._hasParent(testLi, 'li'); YAHOO.log('parLI: ' + par.tagName + ' :: ' + par.innerHTML); var newUl = this._getDoc().createElement(par.parentNode.tagName.toLowerCase()); if (this.browser.webkit) { var span = Dom.getElementsByClassName('Apple-tab-span', 'span', par); //Remove the span element that Safari puts in if (span[0]) { par.removeChild(span[0]); par.innerHTML = Lang.trim(par.innerHTML); //Put the HTML from the LI into this new LI if (preContent) { par.innerHTML = '<span class="yui-non">' + preContent + '</span>&nbsp;'; } else { par.innerHTML = '<span class="yui-non">&nbsp;</span>&nbsp;'; } } } else { if (preContent) { par.innerHTML = preContent + '&nbsp;'; } else { par.innerHTML = '&nbsp;'; } } par.parentNode.replaceChild(newUl, par); newUl.appendChild(par); if (this.browser.webkit) { this._getSelection().setBaseAndExtent(par.firstChild, 1, par.firstChild, par.firstChild.innerText.length); if (!this.browser.webkit3) { par.parentNode.parentNode.style.display = 'list-item'; setTimeout(function() { par.parentNode.parentNode.style.display = 'block'; }, 1); } } else if (this.browser.ie) { range = this._getDoc().body.createTextRange(); range.moveToElementText(par); range.collapse(false); range.select(); } else { this._selectNode(par); } Event.stopEvent(ev); } if (this.browser.webkit) { Event.stopEvent(ev); } this.nodeChange(); } }, /** * @method nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Handles setting up the toolbar buttons, getting the Dom path, fixing nodes. */ nodeChange: function(force) { var NCself = this; this._storeUndo(); if (this.get('nodeChangeDelay')) { window.setTimeout(function() { NCself._nodeChange.apply(NCself, arguments); }, 0); } else { this._nodeChange(); } }, /** * @private * @method _nodeChange * @param {Boolean} force Optional paramenter to skip the threshold counter * @description Fired from nodeChange in a setTimeout. */ _nodeChange: function(force) { var threshold = parseInt(this.get('nodeChangeThreshold'), 10), thisNodeChange = Math.round(new Date().getTime() / 1000), self = this; if (force === true) { this._lastNodeChange = 0; } if ((this._lastNodeChange + threshold) < thisNodeChange) { if (this._fixNodesTimer === null) { this._fixNodesTimer = window.setTimeout(function() { self._fixNodes.call(self); self._fixNodesTimer = null; }, 0); } } this._lastNodeChange = thisNodeChange; if (this.currentEvent) { try { this._lastNodeChangeEvent = this.currentEvent.type; } catch (e) {} } var beforeNodeChange = this.fireEvent('beforeNodeChange', { type: 'beforeNodeChange', target: this }); if (beforeNodeChange === false) { return false; } if (this.get('dompath')) { window.setTimeout(function() { self._writeDomPath.call(self); }, 0); } //Check to see if we are disabled before continuing if (!this.get('disabled')) { if (this.STOP_NODE_CHANGE) { //Reset this var for next action this.STOP_NODE_CHANGE = false; return false; } else { var sel = this._getSelection(), range = this._getRange(), el = this._getSelectedElement(), fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), undo_button = this.toolbar.getButtonByValue('undo'), redo_button = this.toolbar.getButtonByValue('redo'); //Handle updating the toolbar with active buttons var _ex = {}; if (this._lastButton) { _ex[this._lastButton.id] = true; //this._lastButton = null; } if (!this._isElement(el, 'body')) { if (fn_button) { _ex[fn_button.get('id')] = true; } if (fs_button) { _ex[fs_button.get('id')] = true; } } if (redo_button) { delete _ex[redo_button.get('id')]; } this.toolbar.resetAllButtons(_ex); //Handle disabled buttons for (var d = 0; d < this._disabled.length; d++) { var _button = this.toolbar.getButtonByValue(this._disabled[d]); if (_button && _button.get) { if (this._lastButton && (_button.get('id') === this._lastButton.id)) { //Skip } else { if (!this._hasSelection() && !this.get('insert')) { switch (this._disabled[d]) { case 'fontname': case 'fontsize': break; default: //No Selection - disable this.toolbar.disableButton(_button); } } else { if (!this._alwaysDisabled[this._disabled[d]]) { this.toolbar.enableButton(_button); } } if (!this._alwaysEnabled[this._disabled[d]]) { this.toolbar.deselectButton(_button); } } } } var path = this._getDomPath(); var tag = null, cmd = null; for (var i = 0; i < path.length; i++) { tag = path[i].tagName.toLowerCase(); if (path[i].getAttribute('tag')) { tag = path[i].getAttribute('tag').toLowerCase(); } cmd = this._tag2cmd[tag]; if (cmd === undefined) { cmd = []; } if (!Lang.isArray(cmd)) { cmd = [cmd]; } //Bold and Italic styles if (path[i].style.fontWeight.toLowerCase() == 'bold') { cmd[cmd.length] = 'bold'; } if (path[i].style.fontStyle.toLowerCase() == 'italic') { cmd[cmd.length] = 'italic'; } if (path[i].style.textDecoration.toLowerCase() == 'underline') { cmd[cmd.length] = 'underline'; } if (path[i].style.textDecoration.toLowerCase() == 'line-through') { cmd[cmd.length] = 'strikethrough'; } if (cmd.length > 0) { for (var j = 0; j < cmd.length; j++) { this.toolbar.selectButton(cmd[j]); this.toolbar.enableButton(cmd[j]); } } //Handle Alignment switch (path[i].style.textAlign.toLowerCase()) { case 'left': case 'right': case 'center': case 'justify': var alignType = path[i].style.textAlign.toLowerCase(); if (path[i].style.textAlign.toLowerCase() == 'justify') { alignType = 'full'; } this.toolbar.selectButton('justify' + alignType); this.toolbar.enableButton('justify' + alignType); break; } } //After for loop //Reset Font Family and Size to the inital configs if (fn_button) { var family = fn_button._configs.label._initialConfig.value; fn_button.set('label', '<span class="yui-toolbar-fontname-' + this._cleanClassName(family) + '">' + family + '</span>'); this._updateMenuChecked('fontname', family); } if (fs_button) { fs_button.set('label', fs_button._configs.label._initialConfig.value); } var hd_button = this.toolbar.getButtonByValue('heading'); if (hd_button) { hd_button.set('label', hd_button._configs.label._initialConfig.value); this._updateMenuChecked('heading', 'none'); } var img_button = this.toolbar.getButtonByValue('insertimage'); if (img_button && this.currentWindow && (this.currentWindow.name == 'insertimage')) { this.toolbar.disableButton(img_button); } if (this._lastButton && this._lastButton.isSelected) { this.toolbar.deselectButton(this._lastButton.id); } this._undoNodeChange(); } } this.fireEvent('afterNodeChange', { type: 'afterNodeChange', target: this }); }, /** * @private * @method _updateMenuChecked * @param {Object} button The command identifier of the button you want to check * @param {String} value The value of the menu item you want to check * @param {<a href="YAHOO.widget.Toolbar.html">YAHOO.widget.Toolbar</a>} The Toolbar instance the button belongs to (defaults to this.toolbar) * @description Gets the menu from a button instance, if the menu is not rendered it will render it. It will then search the menu for the specified value, unchecking all other items and checking the specified on. */ _updateMenuChecked: function(button, value, tbar) { if (!tbar) { tbar = this.toolbar; } var _button = tbar.getButtonByValue(button); _button.checkValue(value); }, /** * @private * @method _handleToolbarClick * @param {Event} ev The event that triggered the button click * @description This is an event handler attached to the Toolbar's buttonClick event. It will fire execCommand with the command identifier from the Toolbar Button. */ _handleToolbarClick: function(ev) { var value = ''; var str = ''; var cmd = ev.button.value; if (ev.button.menucmd) { value = cmd; cmd = ev.button.menucmd; } this._lastButton = ev.button; if (this.STOP_EXEC_COMMAND) { YAHOO.log('execCommand skipped because we found the STOP_EXEC_COMMAND flag set to true', 'warn', 'SimpleEditor'); YAHOO.log('NOEXEC::execCommand::(' + cmd + '), (' + value + ')', 'warn', 'SimpleEditor'); this.STOP_EXEC_COMMAND = false; return false; } else { this.execCommand(cmd, value); if (!this.browser.webkit) { var Fself = this; setTimeout(function() { Fself.focus.call(Fself); }, 5); } } Event.stopEvent(ev); }, /** * @private * @method _setupAfterElement * @description Creates the accessibility h2 header and places it after the iframe in the Dom for navigation. */ _setupAfterElement: function() { if (!this.beforeElement) { this.beforeElement = document.createElement('h2'); this.beforeElement.className = 'yui-editor-skipheader'; this.beforeElement.tabIndex = '-1'; this.beforeElement.innerHTML = this.STR_BEFORE_EDITOR; this.get('element_cont').get('firstChild').insertBefore(this.beforeElement, this.toolbar.get('nextSibling')); } if (!this.afterElement) { this.afterElement = document.createElement('h2'); this.afterElement.className = 'yui-editor-skipheader'; this.afterElement.tabIndex = '-1'; this.afterElement.innerHTML = this.STR_LEAVE_EDITOR; this.get('element_cont').get('firstChild').appendChild(this.afterElement); } }, /** * @private * @method _disableEditor * @param {Boolean} disabled Pass true to disable, false to enable * @description Creates a mask to place over the Editor. */ _disableEditor: function(disabled) { if (disabled) { this._removeEditorEvents(); if (!this._mask) { if (!!this.browser.ie) { this._setDesignMode('off'); } if (this.toolbar) { this.toolbar.set('disabled', true); } this._mask = document.createElement('DIV'); Dom.addClass(this._mask, 'yui-editor-masked'); this.get('iframe').get('parentNode').appendChild(this._mask); } } else { this._initEditorEvents(); if (this._mask) { this._mask.parentNode.removeChild(this._mask); this._mask = null; if (this.toolbar) { this.toolbar.set('disabled', false); } this._setDesignMode('on'); this.focus(); var self = this; window.setTimeout(function() { self.nodeChange.call(self); }, 100); } } }, /** * @property SEP_DOMPATH * @description The value to place in between the Dom path items * @type String */ SEP_DOMPATH: '<', /** * @property STR_LEAVE_EDITOR * @description The accessibility string for the element after the iFrame * @type String */ STR_LEAVE_EDITOR: 'You have left the Rich Text Editor.', /** * @property STR_BEFORE_EDITOR * @description The accessibility string for the element before the iFrame * @type String */ STR_BEFORE_EDITOR: 'This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Shift + Escape to place focus on the toolbar and navigate between options with your arrow keys. To exit this text editor use the Escape key and continue tabbing. <h4>Common formatting keyboard shortcuts:</h4><ul><li>Control Shift B sets text to bold</li> <li>Control Shift I sets text to italic</li> <li>Control Shift U underlines text</li> <li>Control Shift L adds an HTML link</li></ul>', /** * @property STR_TITLE * @description The Title of the HTML document that is created in the iFrame * @type String */ STR_TITLE: 'Rich Text Area.', /** * @property STR_IMAGE_HERE * @description The text to place in the URL textbox when using the blankimage. * @type String */ STR_IMAGE_HERE: 'Image URL Here', /** * @property STR_IMAGE_URL * @description The label string for Image URL * @type String */ STR_IMAGE_URL: 'Image URL', /** * @property STR_LINK_URL * @description The label string for the Link URL. * @type String */ STR_LINK_URL: 'Link URL', /** * @protected * @property STOP_EXEC_COMMAND * @description Set to true when you want the default execCommand function to not process anything * @type Boolean */ STOP_EXEC_COMMAND: false, /** * @protected * @property STOP_NODE_CHANGE * @description Set to true when you want the default nodeChange function to not process anything * @type Boolean */ STOP_NODE_CHANGE: false, /** * @protected * @property CLASS_NOEDIT * @description CSS class applied to elements that are not editable. * @type String */ CLASS_NOEDIT: 'yui-noedit', /** * @protected * @property CLASS_CONTAINER * @description Default CSS class to apply to the editors container element * @type String */ CLASS_CONTAINER: 'yui-editor-container', /** * @protected * @property CLASS_EDITABLE * @description Default CSS class to apply to the editors iframe element * @type String */ CLASS_EDITABLE: 'yui-editor-editable', /** * @protected * @property CLASS_EDITABLE_CONT * @description Default CSS class to apply to the editors iframe's parent element * @type String */ CLASS_EDITABLE_CONT: 'yui-editor-editable-container', /** * @protected * @property CLASS_PREFIX * @description Default prefix for dynamically created class names * @type String */ CLASS_PREFIX: 'yui-editor', /** * @property browser * @description Standard browser detection * @type Object */ browser: function() { var br = YAHOO.env.ua; //Check for webkit3 if (br.webkit >= 420) { br.webkit3 = br.webkit; } else { br.webkit3 = 0; } br.mac = false; //Check for Mac if (navigator.userAgent.indexOf('Macintosh') !== -1) { br.mac = true; } return br; }(), /** * @method init * @description The Editor class' initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.log('init', 'info', 'SimpleEditor'); if (!this._defaultToolbar) { this._defaultToolbar = { collapse: true, titlebar: 'Text Editing Tools', draggable: false, buttons: [ { group: 'fontstyle', label: 'Font Name and Size', buttons: [ { type: 'select', label: 'Arial', value: 'fontname', disabled: true, menu: [ { text: 'Arial', checked: true }, { text: 'Arial Black' }, { text: 'Comic Sans MS' }, { text: 'Courier New' }, { text: 'Lucida Console' }, { text: 'Tahoma' }, { text: 'Times New Roman' }, { text: 'Trebuchet MS' }, { text: 'Verdana' } ] }, { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true } ] }, { type: 'separator' }, { group: 'textstyle', label: 'Font Style', buttons: [ { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' }, { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' }, { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' }, { type: 'push', label: 'Strike Through', value: 'strikethrough' }, { type: 'separator' }, { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true }, { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true } ] }, { type: 'separator' }, { group: 'indentlist', label: 'Lists', buttons: [ { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }, { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' } ] }, { type: 'separator' }, { group: 'insertitem', label: 'Insert Item', buttons: [ { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }, { type: 'push', label: 'Insert Image', value: 'insertimage' } ] } ] }; } YAHOO.widget.SimpleEditor.superclass.init.call(this, p_oElement, p_oAttributes); YAHOO.widget.EditorInfo._instances[this.get('id')] = this; this.currentElement = []; this.on('contentReady', function() { this.DOMReady = true; this.fireQueue(); }, this, true); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the editor. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the editor. */ initAttributes: function(attr) { YAHOO.widget.SimpleEditor.superclass.initAttributes.call(this, attr); var self = this; /** * @config nodeChangeDelay * @description Do we wrap the nodeChange method in a timeout for performance, default: true. * @default true * @type Number */ this.setAttributeConfig('nodeChangeDelay', { value: ((attr.nodeChangeDelay === false) ? false : true) }); /** * @config maxUndo * @description The max number of undo levels to store. * @default 30 * @type Number */ this.setAttributeConfig('maxUndo', { writeOnce: true, value: attr.maxUndo || 30 }); /** * @config ptags * @description If true, the editor uses &lt;P&gt; tags instead of &lt;br&gt; tags. (Use Shift + Enter to get a &lt;br&gt;) * @default false * @type Boolean */ this.setAttributeConfig('ptags', { writeOnce: true, value: attr.ptags || false }); /** * @config insert * @description If true, selection is not required for: fontname, fontsize, forecolor, backcolor. * @default false * @type Boolean */ this.setAttributeConfig('insert', { writeOnce: true, value: attr.insert || false, method: function(insert) { if (insert) { var buttons = { fontname: true, fontsize: true, forecolor: true, backcolor: true }; var tmp = this._defaultToolbar.buttons; for (var i = 0; i < tmp.length; i++) { if (tmp[i].buttons) { for (var a = 0; a < tmp[i].buttons.length; a++) { if (tmp[i].buttons[a].value) { if (buttons[tmp[i].buttons[a].value]) { delete tmp[i].buttons[a].disabled; } } } } } } } }); /** * @config container * @description Used when dynamically creating the Editor from Javascript with no default textarea. * We will create one and place it in this container. If no container is passed we will append to document.body. * @default false * @type HTMLElement */ this.setAttributeConfig('container', { writeOnce: true, value: attr.container || false }); /** * @config plainText * @description Process the inital textarea data as if it was plain text. Accounting for spaces, tabs and line feeds. * @default false * @type Boolean */ this.setAttributeConfig('plainText', { writeOnce: true, value: attr.plainText || false }); /** * @private * @config iframe * @description Internal config for holding the iframe element. * @default null * @type HTMLElement */ this.setAttributeConfig('iframe', { value: null }); /** * @private * @depreciated - No longer used, should use this.get('element') * @config textarea * @description Internal config for holding the textarea element (replaced with element). * @default null * @type HTMLElement */ this.setAttributeConfig('textarea', { value: null, writeOnce: true }); /** * @config nodeChangeThreshold * @description The number of seconds that need to be in between nodeChange processing * @default 3 * @type Number */ this.setAttributeConfig('nodeChangeThreshold', { value: attr.nodeChangeThreshold || 3, validator: YAHOO.lang.isNumber }); /** * @config allowNoEdit * @description Should the editor check for non-edit fields. It should be noted that this technique is not perfect. If the user does the right things, they will still be able to make changes. * Such as highlighting an element below and above the content and hitting a toolbar button or a shortcut key. * @default false * @type Boolean */ this.setAttributeConfig('allowNoEdit', { value: attr.allowNoEdit || false, validator: YAHOO.lang.isBoolean }); /** * @config limitCommands * @description Should the Editor limit the allowed execCommands to the ones available in the toolbar. If true, then execCommand and keyboard shortcuts will fail if they are not defined in the toolbar. * @default false * @type Boolean */ this.setAttributeConfig('limitCommands', { value: attr.limitCommands || false, validator: YAHOO.lang.isBoolean }); /** * @config element_cont * @description Internal config for the editors container * @default false * @type HTMLElement */ this.setAttributeConfig('element_cont', { value: attr.element_cont }); /** * @private * @config editor_wrapper * @description The outter wrapper for the entire editor. * @default null * @type HTMLElement */ this.setAttributeConfig('editor_wrapper', { value: attr.editor_wrapper || null, writeOnce: true }); /** * @attribute height * @description The height of the editor iframe container, not including the toolbar.. * @default Best guessed size of the textarea, for best results use CSS to style the height of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('height', { value: attr.height || Dom.getStyle(self.get('element'), 'height'), method: function(height) { if (this._rendered) { //We have been rendered, change the height if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('iframe').get('parentNode'), { height: { to: parseInt(height, 10) } }, 0.5); anim.animate(); } else { Dom.setStyle(this.get('iframe').get('parentNode'), 'height', height); } } } }); /** * @config autoHeight * @description Remove the scrollbars from the edit area and resize it to fit the content. It will not go any lower than the current config height. * @default false * @type Boolean || Number */ this.setAttributeConfig('autoHeight', { value: attr.autoHeight || false, method: function(a) { if (a) { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'no'); } this.on('afterNodeChange', this._handleAutoHeight, this, true); this.on('editorKeyDown', this._handleAutoHeight, this, true); this.on('editorKeyPress', this._handleAutoHeight, this, true); } else { if (this.get('iframe')) { this.get('iframe').get('element').setAttribute('scrolling', 'auto'); } this.unsubscribe('afterNodeChange', this._handleAutoHeight); this.unsubscribe('editorKeyDown', this._handleAutoHeight); this.unsubscribe('editorKeyPress', this._handleAutoHeight); } } }); /** * @attribute width * @description The width of the editor container. * @default Best guessed size of the textarea, for best results use CSS to style the width of the textarea or pass it in as an argument * @type String */ this.setAttributeConfig('width', { value: attr.width || Dom.getStyle(this.get('element'), 'width'), method: function(width) { if (this._rendered) { //We have been rendered, change the width if (this.get('animate')) { var anim = new YAHOO.util.Anim(this.get('element_cont').get('element'), { width: { to: parseInt(width, 10) } }, 0.5); anim.animate(); } else { this.get('element_cont').setStyle('width', width); } } } }); /** * @attribute blankimage * @description The URL for the image placeholder to put in when inserting an image. * @default The yahooapis.com address for the current release + 'assets/blankimage.png' * @type String */ this.setAttributeConfig('blankimage', { value: attr.blankimage || this._getBlankImage() }); /** * @attribute css * @description The Base CSS used to format the content of the editor * @default <code><pre>html { height: 95%; } body { height: 100%; padding: 7px; background-color: #fff; font:13px/1.22 arial,helvetica,clean,sans-serif;*font-size:small;*font:x-small; } a { color: blue; text-decoration: underline; cursor: pointer; } .warning-localfile { border-bottom: 1px dashed red !important; } .yui-busy { cursor: wait !important; } img.selected { //Safari image selection border: 2px dotted #808080; } img { cursor: pointer !important; border: none; } </pre></code> * @type String */ this.setAttributeConfig('css', { value: attr.css || this._defaultCSS, writeOnce: true }); /** * @attribute html * @description The default HTML to be written to the iframe document before the contents are loaded (Note that the DOCTYPE attr will be added at render item) * @default This HTML requires a few things if you are to override: <p><code>{TITLE}, {CSS}, {HIDDEN_CSS}, {EXTRA_CSS}</code> and <code>{CONTENT}</code> need to be there, they are passed to YAHOO.lang.substitute to be replace with other strings.<p> <p><code>onload="document.body._rteLoaded = true;"</code> : the onload statement must be there or the editor will not finish loading.</p> <code> <pre> &lt;html&gt; &lt;head&gt; &lt;title&gt;{TITLE}&lt;/title&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; &lt;style&gt; {CSS} &lt;/style&gt; &lt;style&gt; {HIDDEN_CSS} &lt;/style&gt; &lt;style&gt; {EXTRA_CSS} &lt;/style&gt; &lt;/head&gt; &lt;body onload="document.body._rteLoaded = true;"&gt; {CONTENT} &lt;/body&gt; &lt;/html&gt; </pre> </code> * @type String */ this.setAttributeConfig('html', { value: attr.html || '<html><head><title>{TITLE}</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><base href="' + this._baseHREF + '"><style>{CSS}</style><style>{HIDDEN_CSS}</style><style>{EXTRA_CSS}</style></head><body onload="document.body._rteLoaded = true;">{CONTENT}</body></html>', writeOnce: true }); /** * @attribute extracss * @description Extra user defined css to load after the default SimpleEditor CSS * @default '' * @type String */ this.setAttributeConfig('extracss', { value: attr.extracss || '', writeOnce: true }); /** * @attribute handleSubmit * @description Config handles if the editor will attach itself to the textareas parent form's submit handler. If it is set to true, the editor will attempt to attach a submit listener to the textareas parent form. Then it will trigger the editors save handler and place the new content back into the text area before the form is submitted. * @default false * @type Boolean */ this.setAttributeConfig('handleSubmit', { value: attr.handleSubmit || false, method: function(exec) { if (this.get('element').form) { if (!this._formButtons) { this._formButtons = []; } if (exec) { Event.on(this.get('element').form, 'submit', this._handleFormSubmit, this, true); var i = this.get('element').form.getElementsByTagName('input'); for (var s = 0; s < i.length; s++) { var type = i[s].getAttribute('type'); if (type && (type.toLowerCase() == 'submit')) { Event.on(i[s], 'click', this._handleFormButtonClick, this, true); this._formButtons[this._formButtons.length] = i[s]; } } } else { Event.removeListener(this.get('element').form, 'submit', this._handleFormSubmit); if (this._formButtons) { Event.removeListener(this._formButtons, 'click', this._handleFormButtonClick); } } } } }); /** * @attribute disabled * @description This will toggle the editor's disabled state. When the editor is disabled, designMode is turned off and a mask is placed over the iframe so no interaction can take place. All Toolbar buttons are also disabled so they cannot be used. * @default false * @type Boolean */ this.setAttributeConfig('disabled', { value: false, method: function(disabled) { if (this._rendered) { this._disableEditor(disabled); } } }); /** * @config saveEl * @description When save HTML is called, this element will be updated as well as the source of data. * @default element * @type HTMLElement */ this.setAttributeConfig('saveEl', { value: this.get('element') }); /** * @config toolbar_cont * @description Internal config for the toolbars container * @default false * @type Boolean */ this.setAttributeConfig('toolbar_cont', { value: null, writeOnce: true }); /** * @attribute toolbar * @description The default toolbar config. * @type Object */ this.setAttributeConfig('toolbar', { value: attr.toolbar || this._defaultToolbar, writeOnce: true, method: function(toolbar) { if (!toolbar.buttonType) { toolbar.buttonType = this._defaultToolbar.buttonType; } this._defaultToolbar = toolbar; } }); /** * @attribute animate * @description Should the editor animate window movements * @default false unless Animation is found, then true * @type Boolean */ this.setAttributeConfig('animate', { value: ((attr.animate) ? ((YAHOO.util.Anim) ? true : false) : false), validator: function(value) { var ret = true; if (!YAHOO.util.Anim) { ret = false; } return ret; } }); /** * @config panel * @description A reference to the panel we are using for windows. * @default false * @type Boolean */ this.setAttributeConfig('panel', { value: null, writeOnce: true, validator: function(value) { var ret = true; if (!YAHOO.widget.Overlay) { ret = false; } return ret; } }); /** * @attribute focusAtStart * @description Should we focus the window when the content is ready? * @default false * @type Boolean */ this.setAttributeConfig('focusAtStart', { value: attr.focusAtStart || false, writeOnce: true, method: function(fs) { if (fs) { this.on('editorContentLoaded', function() { var self = this; setTimeout(function() { self.focus.call(self); self.editorDirty = false; }, 400); }, this, true); } } }); /** * @attribute dompath * @description Toggle the display of the current Dom path below the editor * @default false * @type Boolean */ this.setAttributeConfig('dompath', { value: attr.dompath || false, method: function(dompath) { if (dompath && !this.dompath) { this.dompath = document.createElement('DIV'); this.dompath.id = this.get('id') + '_dompath'; Dom.addClass(this.dompath, 'dompath'); this.get('element_cont').get('firstChild').appendChild(this.dompath); if (this.get('iframe')) { this._writeDomPath(); } } else if (!dompath && this.dompath) { this.dompath.parentNode.removeChild(this.dompath); this.dompath = null; } } }); /** * @attribute markup * @description Should we try to adjust the markup for the following types: semantic, css, default or xhtml * @default "semantic" * @type String */ this.setAttributeConfig('markup', { value: attr.markup || 'semantic', validator: function(markup) { switch (markup.toLowerCase()) { case 'semantic': case 'css': case 'default': case 'xhtml': return true; } return false; } }); /** * @attribute removeLineBreaks * @description Should we remove linebreaks and extra spaces on cleanup * @default false * @type Boolean */ this.setAttributeConfig('removeLineBreaks', { value: attr.removeLineBreaks || false, validator: YAHOO.lang.isBoolean }); /** * @config drag * @description Set this config to make the Editor draggable, pass 'proxy' to make use YAHOO.util.DDProxy. * @type {Boolean/String} */ this.setAttributeConfig('drag', { writeOnce: true, value: attr.drag || false }); /** * @config resize * @description Set this to true to make the Editor Resizable with YAHOO.util.Resize. The default config is available: myEditor._resizeConfig * Animation will be ignored while performing this resize to allow for the dynamic change in size of the toolbar. * @type Boolean */ this.setAttributeConfig('resize', { writeOnce: true, value: attr.resize || false }); /** * @config filterWord * @description Attempt to filter out MS Word HTML from the Editor's output. * @type Boolean */ this.setAttributeConfig('filterWord', { value: attr.filterWord || false, validator: YAHOO.lang.isBoolean }); }, /** * @private * @method _getBlankImage * @description Retrieves the full url of the image to use as the blank image. * @return {String} The URL to the blank image */ _getBlankImage: function() { if (!this.DOMReady) { this._queue[this._queue.length] = ['_getBlankImage', arguments]; return ''; } var img = ''; if (!this._blankImageLoaded) { if (YAHOO.widget.EditorInfo.blankImage) { this.set('blankimage', YAHOO.widget.EditorInfo.blankImage); this._blankImageLoaded = true; } else { var div = document.createElement('div'); div.style.position = 'absolute'; div.style.top = '-9999px'; div.style.left = '-9999px'; div.className = this.CLASS_PREFIX + '-blankimage'; document.body.appendChild(div); img = YAHOO.util.Dom.getStyle(div, 'background-image'); img = img.replace('url(', '').replace(')', '').replace(/"/g, ''); //Adobe AIR Code img = img.replace('app:/', ''); this.set('blankimage', img); this._blankImageLoaded = true; div.parentNode.removeChild(div); YAHOO.widget.EditorInfo.blankImage = img; } } else { img = this.get('blankimage'); } return img; }, /** * @private * @method _handleAutoHeight * @description Handles resizing the editor's height based on the content */ _handleAutoHeight: function() { var doc = this._getDoc(), body = doc.body, docEl = doc.documentElement; var height = parseInt(Dom.getStyle(this.get('editor_wrapper'), 'height'), 10); var newHeight = body.scrollHeight; if (this.browser.webkit) { newHeight = docEl.scrollHeight; } if (newHeight < parseInt(this.get('height'), 10)) { newHeight = parseInt(this.get('height'), 10); } if ((height != newHeight) && (newHeight >= parseInt(this.get('height'), 10))) { var anim = this.get('animate'); this.set('animate', false); this.set('height', newHeight + 'px'); this.set('animate', anim); if (this.browser.ie) { //Internet Explorer needs this this.get('iframe').setStyle('height', '99%'); this.get('iframe').setStyle('zoom', '1'); var self = this; window.setTimeout(function() { self.get('iframe').setStyle('height', '100%'); }, 1); } } }, /** * @private * @property _formButtons * @description Array of buttons that are in the Editor's parent form (for handleSubmit) * @type Array */ _formButtons: null, /** * @private * @property _formButtonClicked * @description The form button that was clicked to submit the form. * @type HTMLElement */ _formButtonClicked: null, /** * @private * @method _handleFormButtonClick * @description The click listener assigned to each submit button in the Editor's parent form. * @param {Event} ev The click event */ _handleFormButtonClick: function(ev) { var tar = Event.getTarget(ev); this._formButtonClicked = tar; }, /** * @private * @method _handleFormSubmit * @description Handles the form submission. * @param {Object} ev The Form Submit Event */ _handleFormSubmit: function(ev) { this.saveHTML(); var form = this.get('element').form, tar = this._formButtonClicked || false; Event.removeListener(form, 'submit', this._handleFormSubmit); if (YAHOO.env.ua.ie) { //form.fireEvent("onsubmit"); if (tar && !tar.disabled) { tar.click(); } } else { // Gecko, Opera, and Safari if (tar && !tar.disabled) { tar.click(); } var oEvent = document.createEvent("HTMLEvents"); oEvent.initEvent("submit", true, true); form.dispatchEvent(oEvent); if (YAHOO.env.ua.webkit) { if (YAHOO.lang.isFunction(form.submit)) { form.submit(); } } } //2.6.0 //Removed this, not need since removing Safari 2.x //Event.stopEvent(ev); }, /** * @private * @method _handleFontSize * @description Handles the font size button in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleFontSize: function(o) { var button = this.toolbar.getButtonById(o.button.id); var value = button.get('label') + 'px'; this.execCommand('fontsize', value); return false; }, /** * @private * @description Handles the colorpicker buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleColorPicker: function(o) { var cmd = o.button; var value = '#' + o.color; if ((cmd == 'forecolor') || (cmd == 'backcolor')) { this.execCommand(cmd, value); } }, /** * @private * @method _handleAlign * @description Handles the alignment buttons in the toolbar. * @param {Object} o Object returned from Toolbar's buttonClick Event */ _handleAlign: function(o) { var cmd = null; for (var i = 0; i < o.button.menu.length; i++) { if (o.button.menu[i].value == o.button.value) { cmd = o.button.menu[i].value; } } var value = this._getSelection(); this.execCommand(cmd, value); return false; }, /** * @private * @method _handleAfterNodeChange * @description Fires after a nodeChange happens to setup the things that where reset on the node change (button state). */ _handleAfterNodeChange: function() { var path = this._getDomPath(), elm = null, family = null, fontsize = null, validFont = false, fn_button = this.toolbar.getButtonByValue('fontname'), fs_button = this.toolbar.getButtonByValue('fontsize'), hd_button = this.toolbar.getButtonByValue('heading'); for (var i = 0; i < path.length; i++) { elm = path[i]; var tag = elm.tagName.toLowerCase(); if (elm.getAttribute('tag')) { tag = elm.getAttribute('tag'); } family = elm.getAttribute('face'); if (Dom.getStyle(elm, 'font-family')) { family = Dom.getStyle(elm, 'font-family'); //Adobe AIR Code family = family.replace(/'/g, ''); } if (tag.substring(0, 1) == 'h') { if (hd_button) { for (var h = 0; h < hd_button._configs.menu.value.length; h++) { if (hd_button._configs.menu.value[h].value.toLowerCase() == tag) { hd_button.set('label', hd_button._configs.menu.value[h].text); } } this._updateMenuChecked('heading', tag); } } } if (fn_button) { for (var b = 0; b < fn_button._configs.menu.value.length; b++) { if (family && fn_button._configs.menu.value[b].text.toLowerCase() == family.toLowerCase()) { validFont = true; family = fn_button._configs.menu.value[b].text; //Put the proper menu name in the button } } if (!validFont) { family = fn_button._configs.label._initialConfig.value; } var familyLabel = '<span class="yui-toolbar-fontname-' + this._cleanClassName(family) + '">' + family + '</span>'; if (fn_button.get('label') != familyLabel) { fn_button.set('label', familyLabel); this._updateMenuChecked('fontname', family); } } if (fs_button) { fontsize = parseInt(Dom.getStyle(elm, 'fontSize'), 10); if ((fontsize === null) || isNaN(fontsize)) { fontsize = fs_button._configs.label._initialConfig.value; } fs_button.set('label', ''+fontsize); } if (!this._isElement(elm, 'body') && !this._isElement(elm, 'img')) { this.toolbar.enableButton(fn_button); this.toolbar.enableButton(fs_button); this.toolbar.enableButton('forecolor'); this.toolbar.enableButton('backcolor'); } if (this._isElement(elm, 'img')) { if (YAHOO.widget.Overlay) { this.toolbar.enableButton('createlink'); } } if (this._hasParent(elm, 'blockquote')) { this.toolbar.selectButton('indent'); this.toolbar.disableButton('indent'); this.toolbar.enableButton('outdent'); } if (this._hasParent(elm, 'ol') || this._hasParent(elm, 'ul')) { this.toolbar.disableButton('indent'); } this._lastButton = null; }, /** * @private * @method _handleInsertImageClick * @description Opens the Image Properties Window when the insert Image button is clicked or an Image is Double Clicked. */ _handleInsertImageClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('insertimage')) { YAHOO.log('Toolbar Button for (insertimage) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], src = 'http://'; if (!el) { el = this._getSelectedElement(); } if (el) { if (el.getAttribute('src')) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { src = this.STR_IMAGE_HERE; } } } var str = prompt(this.STR_IMAGE_URL + ': ', src); if ((str !== '') && (str !== null)) { el.setAttribute('src', str); } else if (str === '') { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } else if ((str === null)) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { el.parentNode.removeChild(el); this.currentElement = []; this.nodeChange(); } } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this, true); }, /** * @private * @method _handleInsertImageWindowClose * @description Handles the closing of the Image Properties Window. */ _handleInsertImageWindowClose: function() { this.nodeChange(); }, /** * @private * @method _isLocalFile * @param {String} url THe url/string to check * @description Checks to see if a string (href or img src) is possibly a local file reference.. */ _isLocalFile: function(url) { if ((url) && (url !== '') && ((url.indexOf('file:/') != -1) || (url.indexOf(':\\') != -1))) { return true; } return false; }, /** * @private * @method _handleCreateLinkClick * @description Handles the opening of the Link Properties Window when the Create Link button is clicked or an href is doubleclicked. */ _handleCreateLinkClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'SimpleEditor'); return false; } } this.toolbar.set('disabled', true); //Disable the toolbar when the prompt is showing var _handleAEC = function() { var el = this.currentElement[0], url = ''; if (el) { if (el.getAttribute('href', 2) !== null) { url = el.getAttribute('href', 2); } } var str = prompt(this.STR_LINK_URL + ': ', url); if ((str !== '') && (str !== null)) { var urlValue = str; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { /* :// not found adding */ if (urlValue.substring(0, 1) != '#') { //urlValue = 'http:/'+'/' + urlValue; } } } el.setAttribute('href', urlValue); } else if (str !== null) { var _span = this._getDoc().createElement('span'); _span.innerHTML = el.innerHTML; Dom.addClass(_span, 'yui-non'); el.parentNode.replaceChild(_span, el); } this.closeWindow(); this.toolbar.set('disabled', false); this.unsubscribe('afterExecCommand', _handleAEC, this, true); }; this.on('afterExecCommand', _handleAEC, this); }, /** * @private * @method _handleCreateLinkWindowClose * @description Handles the closing of the Link Properties Window. */ _handleCreateLinkWindowClose: function() { this.nodeChange(); this.currentElement = []; }, /** * @method render * @description Calls the private method _render in a setTimeout to allow for other things on the page to continue to load. */ render: function() { if (this._rendered) { return false; } YAHOO.log('Render', 'info', 'SimpleEditor'); if (!this.DOMReady) { YAHOO.log('!DOMReady', 'info', 'SimpleEditor'); this._queue[this._queue.length] = ['render', arguments]; return false; } if (this.get('element')) { if (this.get('element').tagName) { this._textarea = true; if (this.get('element').tagName.toLowerCase() !== 'textarea') { this._textarea = false; } } else { YAHOO.log('No Valid Element', 'error', 'SimpleEditor'); return false; } } else { YAHOO.log('No Element', 'error', 'SimpleEditor'); return false; } this._rendered = true; var self = this; window.setTimeout(function() { self._render.call(self); }, 4); }, /** * @private * @method _render * @description Causes the toolbar and the editor to render and replace the textarea. */ _render: function() { var self = this; this.set('textarea', this.get('element')); this.get('element_cont').setStyle('display', 'none'); this.get('element_cont').addClass(this.CLASS_CONTAINER); this.set('iframe', this._createIframe()); window.setTimeout(function() { self._setInitialContent.call(self); }, 10); this.get('editor_wrapper').appendChild(this.get('iframe').get('element')); if (this.get('disabled')) { this._disableEditor(true); } var tbarConf = this.get('toolbar'); //Create Toolbar instance if (tbarConf instanceof Toolbar) { this.toolbar = tbarConf; //Set the toolbar to disabled until content is loaded this.toolbar.set('disabled', true); } else { //Set the toolbar to disabled until content is loaded tbarConf.disabled = true; this.toolbar = new Toolbar(this.get('toolbar_cont'), tbarConf); } YAHOO.log('fireEvent::toolbarLoaded', 'info', 'SimpleEditor'); this.fireEvent('toolbarLoaded', { type: 'toolbarLoaded', target: this.toolbar }); this.toolbar.on('toolbarCollapsed', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('toolbarExpanded', function() { if (this.currentWindow) { this.moveWindow(); } }, this, true); this.toolbar.on('fontsizeClick', this._handleFontSize, this, true); this.toolbar.on('colorPickerClicked', function(o) { this._handleColorPicker(o); return false; //Stop the buttonClick event }, this, true); this.toolbar.on('alignClick', this._handleAlign, this, true); this.on('afterNodeChange', this._handleAfterNodeChange, this, true); this.toolbar.on('insertimageClick', this._handleInsertImageClick, this, true); this.on('windowinsertimageClose', this._handleInsertImageWindowClose, this, true); this.toolbar.on('createlinkClick', this._handleCreateLinkClick, this, true); this.on('windowcreatelinkClose', this._handleCreateLinkWindowClose, this, true); //Replace Textarea with editable area this.get('parentNode').replaceChild(this.get('element_cont').get('element'), this.get('element')); this.setStyle('visibility', 'hidden'); this.setStyle('position', 'absolute'); this.setStyle('top', '-9999px'); this.setStyle('left', '-9999px'); this.get('element_cont').appendChild(this.get('element')); this.get('element_cont').setStyle('display', 'block'); Dom.addClass(this.get('iframe').get('parentNode'), this.CLASS_EDITABLE_CONT); this.get('iframe').addClass(this.CLASS_EDITABLE); //Set height and width of editor container this.get('element_cont').setStyle('width', this.get('width')); Dom.setStyle(this.get('iframe').get('parentNode'), 'height', this.get('height')); this.get('iframe').setStyle('width', '100%'); //WIDTH this.get('iframe').setStyle('height', '100%'); this._setupDD(); window.setTimeout(function() { self._setupAfterElement.call(self); }, 0); this.fireEvent('afterRender', { type: 'afterRender', target: this }); }, /** * @method execCommand * @param {String} action The "execCommand" action to try to execute (Example: bold, insertimage, inserthtml) * @param {String} value (optional) The value for a given action such as action: fontname value: 'Verdana' * @description This method attempts to try and level the differences in the various browsers and their support for execCommand actions */ execCommand: function(action, value) { var beforeExec = this.fireEvent('beforeExecCommand', { type: 'beforeExecCommand', target: this, args: arguments }); if ((beforeExec === false) || (this.STOP_EXEC_COMMAND)) { this.STOP_EXEC_COMMAND = false; return false; } this._lastCommand = action; this._setMarkupType(action); if (this.browser.ie) { this._getWindow().focus(); } var exec = true; if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue(action)) { YAHOO.log('Toolbar Button for (' + action + ') was not found, skipping exec.', 'info', 'SimpleEditor'); exec = false; } } this.editorDirty = true; if ((typeof this['cmd_' + action.toLowerCase()] == 'function') && exec) { YAHOO.log('Found execCommand override method: (cmd_' + action.toLowerCase() + ')', 'info', 'SimpleEditor'); var retValue = this['cmd_' + action.toLowerCase()](value); exec = retValue[0]; if (retValue[1]) { action = retValue[1]; } if (retValue[2]) { value = retValue[2]; } } if (exec) { YAHOO.log('execCommand::(' + action + '), (' + value + ')', 'info', 'SimpleEditor'); try { this._getDoc().execCommand(action, false, value); } catch(e) { YAHOO.log('execCommand Failed', 'error', 'SimpleEditor'); } } else { YAHOO.log('OVERRIDE::execCommand::(' + action + '),(' + value + ') skipped', 'warn', 'SimpleEditor'); } this.on('afterExecCommand', function() { this.unsubscribeAll('afterExecCommand'); this.nodeChange(); }, this, true); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); }, /* {{{ Command Overrides */ /** * @method cmd_bold * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('bold') is used. */ cmd_bold: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontWeight == 'bold') { el.style.fontWeight = ''; var b = this._getDoc().createElement('b'), par = el.parentNode; par.replaceChild(b, el); b.appendChild(el); } } } return [true]; }, /** * @method cmd_italic * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('italic') is used. */ cmd_italic: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span') && this._hasSelection()) { if (el.style.fontStyle == 'italic') { el.style.fontStyle = ''; var i = this._getDoc().createElement('i'), par = el.parentNode; par.replaceChild(i, el); i.appendChild(el); } } } return [true]; }, /** * @method cmd_underline * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('underline') is used. */ cmd_underline: function(value) { if (!this.browser.webkit) { var el = this._getSelectedElement(); if (el && this._isElement(el, 'span')) { if (el.style.textDecoration == 'underline') { el.style.textDecoration = 'none'; } else { el.style.textDecoration = 'underline'; } return [false]; } } return [true]; }, /** * @method cmd_backcolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('backcolor') is used. */ cmd_backcolor: function(value) { var exec = true, el = this._getSelectedElement(), action = 'backcolor'; if (this.browser.gecko || this.browser.opera) { this._setEditorStyle(true); action = 'hilitecolor'; } if (!this._isElement(el, 'body') && !this._hasSelection()) { el.style.backgroundColor = value; this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ backgroundColor: value }); } else { this._createCurrentElement('span', { backgroundColor: value, color: el.style.color, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec, action]; }, /** * @method cmd_forecolor * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('forecolor') is used. */ cmd_forecolor: function(value) { var exec = true, el = this._getSelectedElement(); if (!this._isElement(el, 'body') && !this._hasSelection()) { Dom.setStyle(el, 'color', value); this._selectNode(el); exec = false; } else { if (this.get('insert')) { el = this._createInsertElement({ color: value }); } else { this._createCurrentElement('span', { color: value, fontSize: el.style.fontSize, fontFamily: el.style.fontFamily, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } exec = false; } return [exec]; }, /** * @method cmd_unlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('unlink') is used. */ cmd_unlink: function(value) { this._swapEl(this.currentElement[0], 'span', function(el) { el.className = 'yui-non'; }); return [false]; }, /** * @method cmd_createlink * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('createlink') is used. */ cmd_createlink: function(value) { var el = this._getSelectedElement(), _a = null; if (this._hasParent(el, 'a')) { this.currentElement[0] = this._hasParent(el, 'a'); } else if (this._isElement(el, 'li')) { _a = this._getDoc().createElement('a'); _a.innerHTML = el.innerHTML; el.innerHTML = ''; el.appendChild(_a); this.currentElement[0] = _a; } else if (!this._isElement(el, 'a')) { this._createCurrentElement('a'); _a = this._swapEl(this.currentElement[0], 'a'); this.currentElement[0] = _a; } else { this.currentElement[0] = el; } return [false]; }, /** * @method cmd_insertimage * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertimage') is used. */ cmd_insertimage: function(value) { var exec = true, _img = null, action = 'insertimage', el = this._getSelectedElement(); if (value === '') { value = this.get('blankimage'); } /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ YAHOO.log('InsertImage: ' + el.tagName, 'info', 'SimpleEditor'); if (this._isElement(el, 'img')) { this.currentElement[0] = el; exec = false; } else { if (this._getDoc().queryCommandEnabled(action)) { this._getDoc().execCommand('insertimage', false, value); var imgs = this._getDoc().getElementsByTagName('img'); for (var i = 0; i < imgs.length; i++) { if (!YAHOO.util.Dom.hasClass(imgs[i], 'yui-img')) { YAHOO.util.Dom.addClass(imgs[i], 'yui-img'); this.currentElement[0] = imgs[i]; } } exec = false; } else { if (el == this._getDoc().body) { _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this._getDoc().body.appendChild(_img); } else { this._createCurrentElement('img'); _img = this._getDoc().createElement('img'); _img.setAttribute('src', value); YAHOO.util.Dom.addClass(_img, 'yui-img'); this.currentElement[0].parentNode.replaceChild(_img, this.currentElement[0]); } this.currentElement[0] = _img; exec = false; } } return [exec]; }, /** * @method cmd_inserthtml * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('inserthtml') is used. */ cmd_inserthtml: function(value) { var exec = true, action = 'inserthtml', _span = null, _range = null; /* * @knownissue Safari cursor position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ if (this.browser.webkit && !this._getDoc().queryCommandEnabled(action)) { YAHOO.log('More Safari DOM tricks (inserthtml)', 'info', 'EditorSafari'); this._createCurrentElement('img'); _span = this._getDoc().createElement('span'); _span.innerHTML = value; this.currentElement[0].parentNode.replaceChild(_span, this.currentElement[0]); exec = false; } else if (this.browser.ie) { _range = this._getRange(); if (_range.item) { _range.item(0).outerHTML = value; } else { _range.pasteHTML(value); } exec = false; } return [exec]; }, /** * @method cmd_list * @param tag The tag of the list you want to create (eg, ul or ol) * @description This is a combined execCommand override method. It is called from the cmd_insertorderedlist and cmd_insertunorderedlist methods. */ cmd_list: function(tag) { var exec = true, list = null, li = 0, el = null, str = '', selEl = this._getSelectedElement(), action = 'insertorderedlist'; if (tag == 'ul') { action = 'insertunorderedlist'; } /* * @knownissue Safari 2.+ doesn't support ordered and unordered lists * @browser Safari 2.x * The issue with this workaround is that when applied to a set of text * that has BR's in it, Safari may or may not pick up the individual items as * list items. This is fixed in WebKit (Safari 3) * 2.6.0: Seems there are still some issues with List Creation and Safari 3, reverting to previously working Safari 2.x code */ //if ((this.browser.webkit && !this._getDoc().queryCommandEnabled(action))) { if (this.browser.webkit) { if (this._isElement(selEl, 'li') && this._isElement(selEl.parentNode, tag)) { YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); el = selEl.parentNode; list = this._getDoc().createElement('span'); YAHOO.util.Dom.addClass(list, 'yui-non'); str = ''; var lis = el.getElementsByTagName('li'); for (li = 0; li < lis.length; li++) { str += '<div>' + lis[li].innerHTML + '</div>'; } list.innerHTML = str; this.currentElement[0] = el; this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); } else { YAHOO.log('Create list item', 'info', 'SimpleEditor'); this._createCurrentElement(tag.toLowerCase()); list = this._getDoc().createElement(tag); for (li = 0; li < this.currentElement.length; li++) { var newli = this._getDoc().createElement('li'); newli.innerHTML = this.currentElement[li].innerHTML + '<span class="yui-non">&nbsp;</span>&nbsp;'; list.appendChild(newli); if (li > 0) { this.currentElement[li].parentNode.removeChild(this.currentElement[li]); } } var items = list.firstChild.innerHTML.split('<br>'); if (items.length > 0) { list.innerHTML = ''; for (var i = 0; i < items.length; i++) { var item = this._getDoc().createElement('li'); item.innerHTML = items[i]; list.appendChild(item); } } this.currentElement[0].parentNode.replaceChild(list, this.currentElement[0]); this.currentElement[0] = list; var _h = this.currentElement[0].firstChild; _h = Dom.getElementsByClassName('yui-non', 'span', _h)[0]; this._getSelection().setBaseAndExtent(_h, 1, _h, _h.innerText.length); } exec = false; } else { el = this._getSelectedElement(); YAHOO.log(el.tagName); if (this._isElement(el, 'li') && this._isElement(el.parentNode, tag) || (this.browser.ie && this._isElement(this._getRange().parentElement, 'li')) || (this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { //we are in a list.. YAHOO.log('We already have a list, undo it', 'info', 'SimpleEditor'); if (this.browser.ie) { if ((this.browser.ie && this._isElement(el, 'ul')) || (this.browser.ie && this._isElement(el, 'ol'))) { el = el.getElementsByTagName('li')[0]; } YAHOO.log('Undo IE', 'info', 'SimpleEditor'); str = ''; var lis2 = el.parentNode.getElementsByTagName('li'); for (var j = 0; j < lis2.length; j++) { str += lis2[j].innerHTML + '<br>'; } var newEl = this._getDoc().createElement('span'); newEl.innerHTML = str; el.parentNode.parentNode.replaceChild(newEl, el.parentNode); } else { this.nodeChange(); this._getDoc().execCommand(action, '', el.parentNode); this.nodeChange(); } exec = false; } if (this.browser.opera) { var self = this; window.setTimeout(function() { var liso = self._getDoc().getElementsByTagName('li'); for (var i = 0; i < liso.length; i++) { if (liso[i].innerHTML.toLowerCase() == '<br>') { liso[i].parentNode.parentNode.removeChild(liso[i].parentNode); } } },30); } if (this.browser.ie && exec) { var html = ''; if (this._getRange().html) { html = '<li>' + this._getRange().html+ '</li>'; } else { var t = this._getRange().text.split('\n'); if (t.length > 1) { html = ''; for (var ie = 0; ie < t.length; ie++) { html += '<li>' + t[ie] + '</li>'; } } else { var txt = this._getRange().text; if (txt === '') { html = '<li id="new_list_item">' + txt + '</li>'; } else { html = '<li>' + txt + '</li>'; } } } this._getRange().pasteHTML('<' + tag + '>' + html + '</' + tag + '>'); var new_item = this._getDoc().getElementById('new_list_item'); if (new_item) { var range = this._getDoc().body.createTextRange(); range.moveToElementText(new_item); range.collapse(false); range.select(); new_item.id = ''; } exec = false; } } return exec; }, /** * @method cmd_insertorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertorderedlist ') is used. */ cmd_insertorderedlist: function(value) { return [this.cmd_list('ol')]; }, /** * @method cmd_insertunorderedlist * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('insertunorderedlist') is used. */ cmd_insertunorderedlist: function(value) { return [this.cmd_list('ul')]; }, /** * @method cmd_fontname * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontname') is used. */ cmd_fontname: function(value) { var exec = true, selEl = this._getSelectedElement(); this.currentFont = value; if (selEl && selEl.tagName && !this._hasSelection() && !this._isElement(selEl, 'body') && !this.get('insert')) { YAHOO.util.Dom.setStyle(selEl, 'font-family', value); exec = false; } else if (this.get('insert') && !this._hasSelection()) { YAHOO.log('No selection and no selected element and we are in insert mode', 'info', 'SimpleEditor'); var el = this._createInsertElement({ fontFamily: value }); exec = false; } return [exec]; }, /** * @method cmd_fontsize * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('fontsize') is used. */ cmd_fontsize: function(value) { var el = null, go = true; el = this._getSelectedElement(); if (this.browser.webkit) { if (this.currentElement[0]) { if (el == this.currentElement[0]) { go = false; YAHOO.util.Dom.setStyle(el, 'fontSize', value); this._selectNode(el); this.currentElement[0] = el; } } } if (go) { if (!this._isElement(this._getSelectedElement(), 'body') && (!this._hasSelection())) { el = this._getSelectedElement(); YAHOO.util.Dom.setStyle(el, 'fontSize', value); if (this.get('insert') && this.browser.ie) { var r = this._getRange(); r.collapse(false); r.select(); } else { this._selectNode(el); } } else if (this.currentElement && (this.currentElement.length > 0) && (!this._hasSelection()) && (!this.get('insert'))) { YAHOO.util.Dom.setStyle(this.currentElement, 'fontSize', value); } else { if (this.get('insert') && !this._hasSelection()) { el = this._createInsertElement({ fontSize: value }); this.currentElement[0] = el; this._selectNode(this.currentElement[0]); } else { this._createCurrentElement('span', {'fontSize': value, fontFamily: el.style.fontFamily, color: el.style.color, backgroundColor: el.style.backgroundColor }); this._selectNode(this.currentElement[0]); } } } return [false]; }, /* }}} */ /** * @private * @method _swapEl * @param {HTMLElement} el The element to swap with * @param {String} tagName The tagname of the element that you wish to create * @param {Function} callback (optional) A function to run on the element after it is created, but before it is replaced. An element reference is passed to this function. * @description This function will create a new element in the DOM and populate it with the contents of another element. Then it will assume it's place. */ _swapEl: function(el, tagName, callback) { var _el = this._getDoc().createElement(tagName); if (el) { _el.innerHTML = el.innerHTML; } if (typeof callback == 'function') { callback.call(this, _el); } if (el) { el.parentNode.replaceChild(_el, el); } return _el; }, /** * @private * @method _createInsertElement * @description Creates a new "currentElement" then adds some text (and other things) to make it selectable and stylable. Then the user can continue typing. * @param {Object} css (optional) Object literal containing styles to apply to the new element. * @return {HTMLElement} */ _createInsertElement: function(css) { this._createCurrentElement('span', css); var el = this.currentElement[0]; if (this.browser.webkit) { //Little Safari Hackery here.. el.innerHTML = '<span class="yui-non">&nbsp;</span>'; el = el.firstChild; this._getSelection().setBaseAndExtent(el, 1, el, el.innerText.length); } else if (this.browser.ie || this.browser.opera) { el.innerHTML = '&nbsp;'; } this.focus(); this._selectNode(el, true); return el; }, /** * @private * @method _createCurrentElement * @param {String} tagName (optional defaults to a) The tagname of the element that you wish to create * @param {Object} tagStyle (optional) Object literal containing styles to apply to the new element. * @description This is a work around for the various browser issues with execCommand. This method will run <code>execCommand('fontname', false, 'yui-tmp')</code> on the given selection. * It will then search the document for an element with the font-family set to <strong>yui-tmp</strong> and replace that with another span that has other information in it, then assign the new span to the * <code>this.currentElement</code> array, so we now have element references to the elements that were just modified. At this point we can use standard DOM manipulation to change them as we see fit. */ _createCurrentElement: function(tagName, tagStyle) { tagName = ((tagName) ? tagName : 'a'); var tar = null, el = [], _doc = this._getDoc(); if (this.currentFont) { if (!tagStyle) { tagStyle = {}; } tagStyle.fontFamily = this.currentFont; this.currentFont = null; } this.currentElement = []; var _elCreate = function(tagName, tagStyle) { var el = null; tagName = ((tagName) ? tagName : 'span'); tagName = tagName.toLowerCase(); switch (tagName) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': el = _doc.createElement(tagName); break; default: el = _doc.createElement(tagName); if (tagName === 'span') { YAHOO.util.Dom.addClass(el, 'yui-tag-' + tagName); YAHOO.util.Dom.addClass(el, 'yui-tag'); el.setAttribute('tag', tagName); } for (var k in tagStyle) { if (YAHOO.lang.hasOwnProperty(tagStyle, k)) { el.style[k] = tagStyle[k]; } } break; } return el; }; if (!this._hasSelection()) { if (this._getDoc().queryCommandEnabled('insertimage')) { this._getDoc().execCommand('insertimage', false, 'yui-tmp-img'); var imgs = this._getDoc().getElementsByTagName('img'); for (var j = 0; j < imgs.length; j++) { if (imgs[j].getAttribute('src', 2) == 'yui-tmp-img') { el = _elCreate(tagName, tagStyle); imgs[j].parentNode.replaceChild(el, imgs[j]); this.currentElement[this.currentElement.length] = el; } } } else { if (this.currentEvent) { tar = YAHOO.util.Event.getTarget(this.currentEvent); } else { //For Safari.. tar = this._getDoc().body; } } if (tar) { /* * @knownissue Safari Cursor Position * @browser Safari 2.x * @description The issue here is that we have no way of knowing where the cursor position is * inside of the iframe, so we have to place the newly inserted data in the best place that we can. */ el = _elCreate(tagName, tagStyle); if (this._isElement(tar, 'body') || this._isElement(tar, 'html')) { if (this._isElement(tar, 'html')) { tar = this._getDoc().body; } tar.appendChild(el); } else if (tar.nextSibling) { tar.parentNode.insertBefore(el, tar.nextSibling); } else { tar.parentNode.appendChild(el); } //this.currentElement = el; this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } } } else { //Force CSS Styling for this action... this._setEditorStyle(true); this._getDoc().execCommand('fontname', false, 'yui-tmp'); var _tmp = [], __tmp, __els = ['font', 'span', 'i', 'b', 'u']; if (!this._isElement(this._getSelectedElement(), 'body')) { __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().tagName); __els[__els.length] = this._getDoc().getElementsByTagName(this._getSelectedElement().parentNode.tagName); } for (var _els = 0; _els < __els.length; _els++) { var _tmp1 = this._getDoc().getElementsByTagName(__els[_els]); for (var e = 0; e < _tmp1.length; e++) { _tmp[_tmp.length] = _tmp1[e]; } } for (var i = 0; i < _tmp.length; i++) { if ((YAHOO.util.Dom.getStyle(_tmp[i], 'font-family') == 'yui-tmp') || (_tmp[i].face && (_tmp[i].face == 'yui-tmp'))) { if (tagName !== 'span') { el = _elCreate(tagName, tagStyle); } else { el = _elCreate(_tmp[i].tagName, tagStyle); } el.innerHTML = _tmp[i].innerHTML; if (this._isElement(_tmp[i], 'ol') || (this._isElement(_tmp[i], 'ul'))) { var fc = _tmp[i].getElementsByTagName('li')[0]; _tmp[i].style.fontFamily = 'inherit'; fc.style.fontFamily = 'inherit'; el.innerHTML = fc.innerHTML; fc.innerHTML = ''; fc.appendChild(el); this.currentElement[this.currentElement.length] = el; } else if (this._isElement(_tmp[i], 'li')) { _tmp[i].innerHTML = ''; _tmp[i].appendChild(el); _tmp[i].style.fontFamily = 'inherit'; this.currentElement[this.currentElement.length] = el; } else { if (_tmp[i].parentNode) { _tmp[i].parentNode.replaceChild(el, _tmp[i]); this.currentElement[this.currentElement.length] = el; this.currentEvent = null; if (this.browser.webkit) { //Force Safari to focus the new element this._getSelection().setBaseAndExtent(el, 0, el, 0); if (this.browser.webkit3) { this._getSelection().collapseToStart(); } else { this._getSelection().collapse(true); } } if (this.browser.ie && tagStyle && tagStyle.fontSize) { this._getSelection().empty(); } if (this.browser.gecko) { this._getSelection().collapseToStart(); } } } } } var len = this.currentElement.length; for (var o = 0; o < len; o++) { if ((o + 1) != len) { //Skip the last one in the list if (this.currentElement[o] && this.currentElement[o].nextSibling) { if (this._isElement(this.currentElement[o], 'br')) { this.currentElement[this.currentElement.length] = this.currentElement[o].nextSibling; } } } } } }, /** * @method saveHTML * @description Cleans the HTML with the cleanHTML method then places that string back into the textarea. * @return String */ saveHTML: function() { var html = this.cleanHTML(); if (this._textarea) { this.get('element').value = html; } else { this.get('element').innerHTML = html; } if (this.get('saveEl') !== this.get('element')) { var out = this.get('saveEl'); if (Lang.isString(out)) { out = Dom.get(out); } if (out) { if (out.tagName.toLowerCase() === 'textarea') { out.value = html; } else { out.innerHTML = html; } } } return html; }, /** * @method setEditorHTML * @param {String} incomingHTML The html content to load into the editor * @description Loads HTML into the editors body */ setEditorHTML: function(incomingHTML) { var html = this._cleanIncomingHTML(incomingHTML); this._getDoc().body.innerHTML = html; this.nodeChange(); }, /** * @method getEditorHTML * @description Gets the unprocessed/unfiltered HTML from the editor */ getEditorHTML: function() { var b = this._getDoc().body; if (b === null) { YAHOO.log('Body is null, returning null.', 'error', 'SimpleEditor'); return null; } return this._getDoc().body.innerHTML; }, /** * @method show * @description This method needs to be called if the Editor was hidden (like in a TabView or Panel). It is used to reset the editor after being in a container that was set to display none. */ show: function() { if (this.browser.gecko) { this._setDesignMode('on'); this.focus(); } if (this.browser.webkit) { var self = this; window.setTimeout(function() { self._setInitialContent.call(self); }, 10); } //Adding this will close all other Editor window's when showing this one. if (this.currentWindow) { this.closeWindow(); } //Put the iframe back in place this.get('iframe').setStyle('position', 'static'); this.get('iframe').setStyle('left', ''); }, /** * @method hide * @description This method needs to be called if the Editor is to be hidden (like in a TabView or Panel). It should be called to clear timeouts and close open editor windows. */ hide: function() { //Adding this will close all other Editor window's. if (this.currentWindow) { this.closeWindow(); } if (this._fixNodesTimer) { clearTimeout(this._fixNodesTimer); this._fixNodesTimer = null; } if (this._nodeChangeTimer) { clearTimeout(this._nodeChangeTimer); this._nodeChangeTimer = null; } this._lastNodeChange = 0; //Move the iframe off of the screen, so that in containers with visiblity hidden, IE will not cover other elements. this.get('iframe').setStyle('position', 'absolute'); this.get('iframe').setStyle('left', '-9999px'); }, /** * @method _cleanIncomingHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the input * @return {String} The filtered HTML */ _cleanIncomingHTML: function(html) { html = html.replace(/<strong([^>]*)>/gi, '<b$1>'); html = html.replace(/<\/strong>/gi, '</b>'); //replace embed before em check html = html.replace(/<embed([^>]*)>/gi, '<YUI_EMBED$1>'); html = html.replace(/<\/embed>/gi, '</YUI_EMBED>'); html = html.replace(/<em([^>]*)>/gi, '<i$1>'); html = html.replace(/<\/em>/gi, '</i>'); html = html.replace(/_moz_dirty=""/gi, ''); //Put embed tags back in.. html = html.replace(/<YUI_EMBED([^>]*)>/gi, '<embed$1>'); html = html.replace(/<\/YUI_EMBED>/gi, '</embed>'); if (this.get('plainText')) { YAHOO.log('Filtering as plain text', 'info', 'SimpleEditor'); html = html.replace(/\n/g, '<br>').replace(/\r/g, '<br>'); html = html.replace(/ /gi, '&nbsp;&nbsp;'); //Replace all double spaces html = html.replace(/\t/gi, '&nbsp;&nbsp;&nbsp;&nbsp;'); //Replace all tabs } //Removing Script Tags from the Editor html = html.replace(/<script([^>]*)>/gi, '<bad>'); html = html.replace(/<\/script([^>]*)>/gi, '</bad>'); html = html.replace(/&lt;script([^>]*)&gt;/gi, '<bad>'); html = html.replace(/&lt;\/script([^>]*)&gt;/gi, '</bad>'); //Replace the line feeds html = html.replace(/\r\n/g, '<YUI_LF>').replace(/\n/g, '<YUI_LF>').replace(/\r/g, '<YUI_LF>'); //Remove Bad HTML elements (used to be script nodes) html = html.replace(new RegExp('<bad([^>]*)>(.*?)<\/bad>', 'gi'), ''); //Replace the lines feeds html = html.replace(/<YUI_LF>/g, '\n'); return html; }, /** * @method cleanHTML * @param {String} html The unfiltered HTML * @description Process the HTML with a few regexes to clean it up and stabilize the output * @return {String} The filtered HTML */ cleanHTML: function(html) { //Start Filtering Output //Begin RegExs.. if (!html) { html = this.getEditorHTML(); } var markup = this.get('markup'); //Make some backups... html = this.pre_filter_linebreaks(html, markup); //Filter MS Word html = this.filter_msword(html); html = html.replace(/<img([^>]*)\/>/gi, '<YUI_IMG$1>'); html = html.replace(/<img([^>]*)>/gi, '<YUI_IMG$1>'); html = html.replace(/<input([^>]*)\/>/gi, '<YUI_INPUT$1>'); html = html.replace(/<input([^>]*)>/gi, '<YUI_INPUT$1>'); html = html.replace(/<ul([^>]*)>/gi, '<YUI_UL$1>'); html = html.replace(/<\/ul>/gi, '<\/YUI_UL>'); html = html.replace(/<blockquote([^>]*)>/gi, '<YUI_BQ$1>'); html = html.replace(/<\/blockquote>/gi, '<\/YUI_BQ>'); html = html.replace(/<embed([^>]*)>/gi, '<YUI_EMBED$1>'); html = html.replace(/<\/embed>/gi, '<\/YUI_EMBED>'); //Convert b and i tags to strong and em tags if ((markup == 'semantic') || (markup == 'xhtml')) { html = html.replace(/<i(\s+[^>]*)?>/gi, '<em$1>'); html = html.replace(/<\/i>/gi, '</em>'); html = html.replace(/<b(\s+[^>]*)?>/gi, '<strong$1>'); html = html.replace(/<\/b>/gi, '</strong>'); } html = html.replace(/_moz_dirty=""/gi, ''); //normalize strikethrough html = html.replace(/<strike/gi, '<span style="text-decoration: line-through;"'); html = html.replace(/\/strike>/gi, '/span>'); //Case Changing if (this.browser.ie) { html = html.replace(/text-decoration/gi, 'text-decoration'); html = html.replace(/font-weight/gi, 'font-weight'); html = html.replace(/_width="([^>]*)"/gi, ''); html = html.replace(/_height="([^>]*)"/gi, ''); //Cleanup Image URL's var url = this._baseHREF.replace(/\//gi, '\\/'), re = new RegExp('src="' + url, 'gi'); html = html.replace(re, 'src="'); } html = html.replace(/<font/gi, '<font'); html = html.replace(/<\/font>/gi, '</font>'); html = html.replace(/<span/gi, '<span'); html = html.replace(/<\/span>/gi, '</span>'); if ((markup == 'semantic') || (markup == 'xhtml') || (markup == 'css')) { html = html.replace(new RegExp('<font([^>]*)face="([^>]*)">(.*?)<\/font>', 'gi'), '<span $1 style="font-family: $2;">$3</span>'); html = html.replace(/<u/gi, '<span style="text-decoration: underline;"'); if (this.browser.webkit) { html = html.replace(new RegExp('<span class="Apple-style-span" style="font-weight: bold;">([^>]*)<\/span>', 'gi'), '<strong>$1</strong>'); html = html.replace(new RegExp('<span class="Apple-style-span" style="font-style: italic;">([^>]*)<\/span>', 'gi'), '<em>$1</em>'); } html = html.replace(/\/u>/gi, '/span>'); if (markup == 'css') { html = html.replace(/<em([^>]*)>/gi, '<i$1>'); html = html.replace(/<\/em>/gi, '</i>'); html = html.replace(/<strong([^>]*)>/gi, '<b$1>'); html = html.replace(/<\/strong>/gi, '</b>'); html = html.replace(/<b/gi, '<span style="font-weight: bold;"'); html = html.replace(/\/b>/gi, '/span>'); html = html.replace(/<i/gi, '<span style="font-style: italic;"'); html = html.replace(/\/i>/gi, '/span>'); } html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } else { html = html.replace(/<u/gi, '<u'); html = html.replace(/\/u>/gi, '/u>'); } html = html.replace(/<ol([^>]*)>/gi, '<ol$1>'); html = html.replace(/\/ol>/gi, '/ol>'); html = html.replace(/<li/gi, '<li'); html = html.replace(/\/li>/gi, '/li>'); html = this.filter_safari(html); html = this.filter_internals(html); html = this.filter_all_rgb(html); //Replace our backups with the real thing html = this.post_filter_linebreaks(html, markup); if (markup == 'xhtml') { html = html.replace(/<YUI_IMG([^>]*)>/g, '<img $1 />'); html = html.replace(/<YUI_INPUT([^>]*)>/g, '<input $1 />'); } else { html = html.replace(/<YUI_IMG([^>]*)>/g, '<img $1>'); html = html.replace(/<YUI_INPUT([^>]*)>/g, '<input $1>'); } html = html.replace(/<YUI_UL([^>]*)>/g, '<ul$1>'); html = html.replace(/<\/YUI_UL>/g, '<\/ul>'); html = this.filter_invalid_lists(html); html = html.replace(/<YUI_BQ([^>]*)>/g, '<blockquote$1>'); html = html.replace(/<\/YUI_BQ>/g, '<\/blockquote>'); html = html.replace(/<YUI_EMBED([^>]*)>/g, '<embed$1>'); html = html.replace(/<\/YUI_EMBED>/g, '<\/embed>'); //This should fix &amp;s in URL's html = html.replace(/ &amp; /gi, 'YUI_AMP'); html = html.replace(/&amp;/gi, '&'); html = html.replace(/YUI_AMP/gi, ' &amp; '); //Trim the output, removing whitespace from the beginning and end html = YAHOO.lang.trim(html); if (this.get('removeLineBreaks')) { html = html.replace(/\n/g, '').replace(/\r/g, ''); html = html.replace(/ /gi, ' '); //Replace all double spaces and replace with a single } //First empty span if (html.substring(0, 6).toLowerCase() == '<span>') { html = html.substring(6); //Last empty span if (html.substring(html.length - 7, html.length).toLowerCase() == '</span>') { html = html.substring(0, html.length - 7); } } for (var v in this.invalidHTML) { if (YAHOO.lang.hasOwnProperty(this.invalidHTML, v)) { if (Lang.isObject(v) && v.keepContents) { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), '$1'); } else { html = html.replace(new RegExp('<' + v + '([^>]*)>(.*?)<\/' + v + '>', 'gi'), ''); } } } this.fireEvent('cleanHTML', { type: 'cleanHTML', target: this, html: html }); return html; }, /** * @method filter_msword * @param String html The HTML string to filter * @description Filters out msword html attributes and other junk. Activate with filterWord: true in config */ filter_msword: function(html) { if (!this.get('filterWord')) { return html; } //Remove the ms o: tags html = html.replace(/<o:p>\s*<\/o:p>/g, ''); html = html.replace(/<o:p>[\s\S]*?<\/o:p>/g, '&nbsp;'); //Remove the ms w: tags html = html.replace( /<w:[^>]*>[\s\S]*?<\/w:[^>]*>/gi, ''); //Remove mso-? styles. html = html.replace( /\s*mso-[^:]+:[^;"]+;?/gi, ''); //Remove more bogus MS styles. html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*;/gi, ''); html = html.replace( /\s*MARGIN: 0cm 0cm 0pt\s*"/gi, "\""); html = html.replace( /\s*TEXT-INDENT: 0cm\s*;/gi, ''); html = html.replace( /\s*TEXT-INDENT: 0cm\s*"/gi, "\""); html = html.replace( /\s*PAGE-BREAK-BEFORE: [^\s;]+;?"/gi, "\""); html = html.replace( /\s*FONT-VARIANT: [^\s;]+;?"/gi, "\"" ); html = html.replace( /\s*tab-stops:[^;"]*;?/gi, ''); html = html.replace( /\s*tab-stops:[^"]*/gi, ''); //Remove XML declarations html = html.replace(/<\\?\?xml[^>]*>/gi, ''); //Remove lang html = html.replace(/<(\w[^>]*) lang=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove language tags html = html.replace( /<(\w[^>]*) language=([^ |>]*)([^>]*)/gi, "<$1$3"); //Remove onmouseover and onmouseout events (from MS Word comments effect) html = html.replace( /<(\w[^>]*) onmouseover="([^\"]*)"([^>]*)/gi, "<$1$3"); html = html.replace( /<(\w[^>]*) onmouseout="([^\"]*)"([^>]*)/gi, "<$1$3"); return html; }, /** * @method filter_invalid_lists * @param String html The HTML string to filter * @description Filters invalid ol and ul list markup, converts this: <li></li><ol>..</ol> to this: <li></li><li><ol>..</ol></li> */ filter_invalid_lists: function(html) { html = html.replace(/<\/li>\n/gi, '</li>'); html = html.replace(/<\/li><ol>/gi, '</li><li><ol>'); html = html.replace(/<\/ol>/gi, '</ol></li>'); html = html.replace(/<\/ol><\/li>\n/gi, "</ol>"); html = html.replace(/<\/li><ul>/gi, '</li><li><ul>'); html = html.replace(/<\/ul>/gi, '</ul></li>'); html = html.replace(/<\/ul><\/li>\n?/gi, "</ul>"); html = html.replace(/<\/li>/gi, "</li>"); html = html.replace(/<\/ol>/gi, "</ol>"); html = html.replace(/<ol>/gi, "<ol>"); html = html.replace(/<ul>/gi, "<ul>"); return html; }, /** * @method filter_safari * @param String html The HTML string to filter * @description Filters strings specific to Safari * @return String */ filter_safari: function(html) { if (this.browser.webkit) { //<span class="Apple-tab-span" style="white-space:pre"> </span> html = html.replace(/<span class="Apple-tab-span" style="white-space:pre">([^>])<\/span>/gi, '&nbsp;&nbsp;&nbsp;&nbsp;'); html = html.replace(/Apple-style-span/gi, ''); html = html.replace(/style="line-height: normal;"/gi, ''); html = html.replace(/yui-wk-div/gi, ''); html = html.replace(/yui-wk-p/gi, ''); //Remove bogus LI's html = html.replace(/<li><\/li>/gi, ''); html = html.replace(/<li> <\/li>/gi, ''); html = html.replace(/<li> <\/li>/gi, ''); //Remove bogus DIV's - updated from just removing the div's to replacing /div with a break if (this.get('ptags')) { html = html.replace(/<div([^>]*)>/g, '<p$1>'); html = html.replace(/<\/div>/gi, '</p>'); } else { html = html.replace(/<div>/gi, '<br>'); html = html.replace(/<\/div>/gi, ''); } } return html; }, /** * @method filter_internals * @param String html The HTML string to filter * @description Filters internal RTE strings and bogus attrs we don't want * @return String */ filter_internals: function(html) { html = html.replace(/\r/g, ''); //Fix stuff we don't want html = html.replace(/<\/?(body|head|html)[^>]*>/gi, ''); //Fix last BR in LI html = html.replace(/<YUI_BR><\/li>/gi, '</li>'); html = html.replace(/yui-tag-span/gi, ''); html = html.replace(/yui-tag/gi, ''); html = html.replace(/yui-non/gi, ''); html = html.replace(/yui-img/gi, ''); html = html.replace(/ tag="span"/gi, ''); html = html.replace(/ class=""/gi, ''); html = html.replace(/ style=""/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ class=" "/gi, ''); html = html.replace(/ target=""/gi, ''); html = html.replace(/ title=""/gi, ''); if (this.browser.ie) { html = html.replace(/ class= /gi, ''); html = html.replace(/ class= >/gi, ''); } return html; }, /** * @method filter_all_rgb * @param String str The HTML string to filter * @description Converts all RGB color strings found in passed string to a hex color, example: style="color: rgb(0, 255, 0)" converts to style="color: #00ff00" * @return String */ filter_all_rgb: function(str) { var exp = new RegExp("rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)", "gi"); var arr = str.match(exp); if (Lang.isArray(arr)) { for (var i = 0; i < arr.length; i++) { var color = this.filter_rgb(arr[i]); str = str.replace(arr[i].toString(), color); } } return str; }, /** * @method filter_rgb * @param String css The CSS string containing rgb(#,#,#); * @description Converts an RGB color string to a hex color, example: rgb(0, 255, 0) converts to #00ff00 * @return String */ filter_rgb: function(css) { if (css.toLowerCase().indexOf('rgb') != -1) { var exp = new RegExp("(.*?)rgb\\s*?\\(\\s*?([0-9]+).*?,\\s*?([0-9]+).*?,\\s*?([0-9]+).*?\\)(.*?)", "gi"); var rgb = css.replace(exp, "$1,$2,$3,$4,$5").split(','); if (rgb.length == 5) { var r = parseInt(rgb[1], 10).toString(16); var g = parseInt(rgb[2], 10).toString(16); var b = parseInt(rgb[3], 10).toString(16); r = r.length == 1 ? '0' + r : r; g = g.length == 1 ? '0' + g : g; b = b.length == 1 ? '0' + b : b; css = "#" + r + g + b; } } return css; }, /** * @method pre_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ pre_filter_linebreaks: function(html, markup) { if (this.browser.webkit) { html = html.replace(/<br class="khtml-block-placeholder">/gi, '<YUI_BR>'); html = html.replace(/<br class="webkit-block-placeholder">/gi, '<YUI_BR>'); } html = html.replace(/<br>/gi, '<YUI_BR>'); html = html.replace(/<br (.*?)>/gi, '<YUI_BR>'); html = html.replace(/<br\/>/gi, '<YUI_BR>'); html = html.replace(/<br \/>/gi, '<YUI_BR>'); html = html.replace(/<div><YUI_BR><\/div>/gi, '<YUI_BR>'); html = html.replace(/<p>(&nbsp;|&#160;)<\/p>/g, '<YUI_BR>'); html = html.replace(/<p><br>&nbsp;<\/p>/gi, '<YUI_BR>'); html = html.replace(/<p>&nbsp;<\/p>/gi, '<YUI_BR>'); //Fix last BR html = html.replace(/<YUI_BR>$/, ''); //Fix last BR in P html = html.replace(/<YUI_BR><\/p>/g, '</p>'); if (this.browser.ie) { html = html.replace(/&nbsp;&nbsp;&nbsp;&nbsp;/g, '\t'); } return html; }, /** * @method post_filter_linebreaks * @param String html The HTML to filter * @param String markup The markup type to filter to * @description HTML Pre Filter * @return String */ post_filter_linebreaks: function(html, markup) { if (markup == 'xhtml') { html = html.replace(/<YUI_BR>/g, '<br />'); } else { html = html.replace(/<YUI_BR>/g, '<br>'); } return html; }, /** * @method clearEditorDoc * @description Clear the doc of the Editor */ clearEditorDoc: function() { this._getDoc().body.innerHTML = '&nbsp;'; }, /** * @method openWindow * @description Override Method for Advanced Editor */ openWindow: function(win) { }, /** * @method moveWindow * @description Override Method for Advanced Editor */ moveWindow: function() { }, /** * @private * @method _closeWindow * @description Override Method for Advanced Editor */ _closeWindow: function() { }, /** * @method closeWindow * @description Override Method for Advanced Editor */ closeWindow: function() { //this.unsubscribeAll('afterExecCommand'); this.toolbar.resetAllButtons(); this.focus(); }, /** * @method destroy * @description Destroys the editor, all of it's elements and objects. * @return {Boolean} */ destroy: function() { YAHOO.log('Destroying Editor', 'warn', 'SimpleEditor'); if (this.resize) { YAHOO.log('Destroying Resize', 'warn', 'SimpleEditor'); this.resize.destroy(); } if (this.dd) { YAHOO.log('Unreg DragDrop Instance', 'warn', 'SimpleEditor'); this.dd.unreg(); } if (this.get('panel')) { YAHOO.log('Destroying Editor Panel', 'warn', 'SimpleEditor'); this.get('panel').destroy(); } this.saveHTML(); this.toolbar.destroy(); YAHOO.log('Restoring TextArea', 'info', 'SimpleEditor'); this.setStyle('visibility', 'visible'); this.setStyle('position', 'static'); this.setStyle('top', ''); this.setStyle('left', ''); var textArea = this.get('element'); this.get('element_cont').get('parentNode').replaceChild(textArea, this.get('element_cont').get('element')); this.get('element_cont').get('element').innerHTML = ''; this.set('handleSubmit', false); //Remove the submit handler return true; }, /** * @method toString * @description Returns a string representing the editor. * @return {String} */ toString: function() { var str = 'SimpleEditor'; if (this.get && this.get('element_cont')) { str = 'SimpleEditor (#' + this.get('element_cont').get('id') + ')' + ((this.get('disabled') ? ' Disabled' : '')); } return str; } }); /** * @event toolbarLoaded * @description Event is fired during the render process directly after the Toolbar is loaded. Allowing you to attach events to the toolbar. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event cleanHTML * @description Event is fired after the cleanHTML method is called. * @type YAHOO.util.CustomEvent */ /** * @event afterRender * @description Event is fired after the render process finishes. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorContentLoaded * @description Event is fired after the editor iframe's document fully loads and fires it's onload event. From here you can start injecting your own things into the document. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeNodeChange * @description Event fires at the beginning of the nodeChange process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterNodeChange * @description Event fires at the end of the nodeChange process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeExecCommand * @description Event fires at the beginning of the execCommand process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterExecCommand * @description Event fires at the end of the execCommand process. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorMouseDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorDoubleClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorClick * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyUp * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyPress * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event editorKeyDown * @param {Event} ev The DOM Event that occured * @description Passed through HTML Event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorMouseDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorDoubleClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorClick * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyUp * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyPress * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event beforeEditorKeyDown * @param {Event} ev The DOM Event that occured * @description Fires before editor event, returning false will stop the internal processing. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowFocus * @description Fires when the iframe is focused. Note, this is window focus event, not an Editor focus event. * @type YAHOO.util.CustomEvent */ /** * @event editorWindowBlur * @description Fires when the iframe is blurred. Note, this is window blur event, not an Editor blur event. * @type YAHOO.util.CustomEvent */ /** * @description Singleton object used to track the open window objects and panels across the various open editors * @class EditorInfo * @static */ YAHOO.widget.EditorInfo = { /** * @private * @property _instances * @description A reference to all editors on the page. * @type Object */ _instances: {}, /** * @private * @property blankImage * @description A reference to the blankImage url * @type String */ blankImage: '', /** * @private * @property window * @description A reference to the currently open window object in any editor on the page. * @type Object <a href="YAHOO.widget.EditorWindow.html">YAHOO.widget.EditorWindow</a> */ window: {}, /** * @private * @property panel * @description A reference to the currently open panel in any editor on the page. * @type Object <a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a> */ panel: null, /** * @method getEditorById * @description Returns a reference to the Editor object associated with the given textarea * @param {String/HTMLElement} id The id or reference of the textarea to return the Editor instance of * @return Object <a href="YAHOO.widget.Editor.html">YAHOO.widget.Editor</a> */ getEditorById: function(id) { if (!YAHOO.lang.isString(id)) { //Not a string, assume a node Reference id = id.id; } if (this._instances[id]) { return this._instances[id]; } return false; }, /** * @method toString * @description Returns a string representing the EditorInfo. * @return {String} */ toString: function() { var len = 0; for (var i in this._instances) { if (Lang.hasOwnProperty(this._instances, i)) { len++; } } return 'Editor Info (' + len + ' registered intance' + ((len > 1) ? 's' : '') + ')'; } }; })(); /** * @module editor * @description <p>The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization.</p> * @namespace YAHOO.widget * @requires yahoo, dom, element, event, container_core, simpleeditor * @optional dragdrop, animation, menu, button, resize */ (function() { var Dom = YAHOO.util.Dom, Event = YAHOO.util.Event, Lang = YAHOO.lang, Toolbar = YAHOO.widget.Toolbar; /** * The Rich Text Editor is a UI control that replaces a standard HTML textarea; it allows for the rich formatting of text content, including common structural treatments like lists, formatting treatments like bold and italic text, and drag-and-drop inclusion and sizing of images. The Rich Text Editor's toolbar is extensible via a plugin architecture so that advanced implementations can achieve a high degree of customization. * @constructor * @class Editor * @extends YAHOO.widget.SimpleEditor * @param {String/HTMLElement} el The textarea element to turn into an editor. * @param {Object} attrs Object liternal containing configuration parameters. */ YAHOO.widget.Editor = function(el, attrs) { YAHOO.log('Editor Initalizing', 'info', 'Editor'); YAHOO.widget.Editor.superclass.constructor.call(this, el, attrs); }; YAHOO.extend(YAHOO.widget.Editor, YAHOO.widget.SimpleEditor, { /** * @private * @property _undoCache * @description An Array hash of the Undo Levels. * @type Array */ _undoCache: null, /** * @private * @property _undoLevel * @description The index of the current undo state. * @type Number */ _undoLevel: null, /** * @private * @method _hasUndoLevel * @description Checks to see if we have an undo level available * @return Boolean */ _hasUndoLevel: function() { return ((this._undoCache.length > 1) && this._undoLevel); }, /** * @private * @method _undoNodeChange * @description nodeChange listener for undo processing */ _undoNodeChange: function() { var undo_button = this.toolbar.getButtonByValue('undo'), redo_button = this.toolbar.getButtonByValue('redo'); if (undo_button && redo_button) { if (this._hasUndoLevel()) { this.toolbar.enableButton(undo_button); } if (this._undoLevel < this._undoCache.length) { this.toolbar.enableButton(redo_button); } } this._lastCommand = null; }, /** * @private * @method _checkUndo * @description Prunes the undo cache when it reaches the maxUndo config */ _checkUndo: function() { var len = this._undoCache.length, tmp = []; if (len >= this.get('maxUndo')) { //YAHOO.log('Undo cache too large (' + len + '), pruning..', 'info', 'SimpleEditor'); for (var i = (len - this.get('maxUndo')); i < len; i++) { tmp.push(this._undoCache[i]); } this._undoCache = tmp; } }, /** * @private * @method _putUndo * @description Puts the content of the Editor into the _undoCache. * //TODO Convert the hash to a series of TEXTAREAS to store state in. * @param {String} str The content of the Editor */ _putUndo: function(str) { this._undoCache.push(str); }, /** * @private * @method _getUndo * @description Get's a level from the undo cache. * @param {Number} index The index of the undo level we want to get. * @return {String} */ _getUndo: function(index) { return this._undoCache[index]; }, /** * @private * @method _storeUndo * @description Method to call when you want to store an undo state. Currently called from nodeChange and _handleKeyUp */ _storeUndo: function() { if (this._lastCommand === 'undo' || this._lastCommand === 'redo') { return false; } if (!this._undoCache) { this._undoCache = []; } this._checkUndo(); var str = this.getEditorHTML(); var last = this._undoCache[this._undoCache.length - 1]; if (last) { if (str !== last) { //YAHOO.log('Storing Undo', 'info', 'SimpleEditor'); this._putUndo(str); } } else { //YAHOO.log('Storing Undo', 'info', 'SimpleEditor'); this._putUndo(str); } this._undoLevel = this._undoCache.length; this._undoNodeChange(); }, /** * @property STR_BEFORE_EDITOR * @description The accessibility string for the element before the iFrame * @type String */ STR_BEFORE_EDITOR: 'This text field can contain stylized text and graphics. To cycle through all formatting options, use the keyboard shortcut Control + Shift + T to place focus on the toolbar and navigate between option heading names. <h4>Common formatting keyboard shortcuts:</h4><ul><li>Control Shift B sets text to bold</li> <li>Control Shift I sets text to italic</li> <li>Control Shift U underlines text</li> <li>Control Shift [ aligns text left</li> <li>Control Shift | centers text</li> <li>Control Shift ] aligns text right</li> <li>Control Shift L adds an HTML link</li> <li>To exit this text editor use the keyboard shortcut Control + Shift + ESC.</li></ul>', /** * @property STR_CLOSE_WINDOW * @description The Title of the close button in the Editor Window * @type String */ STR_CLOSE_WINDOW: 'Close Window', /** * @property STR_CLOSE_WINDOW_NOTE * @description A note appearing in the Editor Window to tell the user that the Escape key will close the window * @type String */ STR_CLOSE_WINDOW_NOTE: 'To close this window use the Control + Shift + W key', /** * @property STR_IMAGE_PROP_TITLE * @description The title for the Image Property Editor Window * @type String */ STR_IMAGE_PROP_TITLE: 'Image Options', /** * @property STR_IMAGE_TITLE * @description The label string for Image Description * @type String */ STR_IMAGE_TITLE: 'Description', /** * @property STR_IMAGE_SIZE * @description The label string for Image Size * @type String */ STR_IMAGE_SIZE: 'Size', /** * @property STR_IMAGE_ORIG_SIZE * @description The label string for Original Image Size * @type String */ STR_IMAGE_ORIG_SIZE: 'Original Size', /** * @property STR_IMAGE_COPY * @description The label string for the image copy and paste message for Opera and Safari * @type String */ STR_IMAGE_COPY: '<span class="tip"><span class="icon icon-info"></span><strong>Note:</strong>To move this image just highlight it, cut, and paste where ever you\'d like.</span>', /** * @property STR_IMAGE_PADDING * @description The label string for the image padding. * @type String */ STR_IMAGE_PADDING: 'Padding', /** * @property STR_IMAGE_BORDER * @description The label string for the image border. * @type String */ STR_IMAGE_BORDER: 'Border', /** * @property STR_IMAGE_BORDER_SIZE * @description The label string for the image border size. * @type String */ STR_IMAGE_BORDER_SIZE: 'Border Size', /** * @property STR_IMAGE_BORDER_TYPE * @description The label string for the image border type. * @type String */ STR_IMAGE_BORDER_TYPE: 'Border Type', /** * @property STR_IMAGE_TEXTFLOW * @description The label string for the image text flow. * @type String */ STR_IMAGE_TEXTFLOW: 'Text Flow', /** * @property STR_LOCAL_FILE_WARNING * @description The label string for the local file warning. * @type String */ STR_LOCAL_FILE_WARNING: '<span class="tip"><span class="icon icon-warn"></span><strong>Note:</strong>This image/link points to a file on your computer and will not be accessible to others on the internet.</span>', /** * @property STR_LINK_PROP_TITLE * @description The label string for the Link Property Editor Window. * @type String */ STR_LINK_PROP_TITLE: 'Link Options', /** * @property STR_LINK_PROP_REMOVE * @description The label string for the Remove link from text link inside the property editor. * @type String */ STR_LINK_PROP_REMOVE: 'Remove link from text', /** * @property STR_LINK_NEW_WINDOW * @description The string for the open in a new window label. * @type String */ STR_LINK_NEW_WINDOW: 'Open in a new window.', /** * @property STR_LINK_TITLE * @description The string for the link description. * @type String */ STR_LINK_TITLE: 'Description', /** * @property STR_NONE * @description The string for the word none. * @type String */ STR_NONE: 'none', /** * @protected * @property CLASS_LOCAL_FILE * @description CSS class applied to an element when it's found to have a local url. * @type String */ CLASS_LOCAL_FILE: 'warning-localfile', /** * @protected * @property CLASS_HIDDEN * @description CSS class applied to the body when the hiddenelements button is pressed. * @type String */ CLASS_HIDDEN: 'yui-hidden', /** * @method init * @description The Editor class' initialization method */ init: function(p_oElement, p_oAttributes) { YAHOO.log('init', 'info', 'Editor'); this._windows = {}; this._defaultToolbar = { collapse: true, titlebar: 'Text Editing Tools', draggable: false, buttonType: 'advanced', buttons: [ { group: 'fontstyle', label: 'Font Name and Size', buttons: [ { type: 'select', label: 'Arial', value: 'fontname', disabled: true, menu: [ { text: 'Arial', checked: true }, { text: 'Arial Black' }, { text: 'Comic Sans MS' }, { text: 'Courier New' }, { text: 'Lucida Console' }, { text: 'Tahoma' }, { text: 'Times New Roman' }, { text: 'Trebuchet MS' }, { text: 'Verdana' } ] }, { type: 'spin', label: '13', value: 'fontsize', range: [ 9, 75 ], disabled: true } ] }, { type: 'separator' }, { group: 'textstyle', label: 'Font Style', buttons: [ { type: 'push', label: 'Bold CTRL + SHIFT + B', value: 'bold' }, { type: 'push', label: 'Italic CTRL + SHIFT + I', value: 'italic' }, { type: 'push', label: 'Underline CTRL + SHIFT + U', value: 'underline' }, { type: 'separator' }, { type: 'push', label: 'Subscript', value: 'subscript', disabled: true }, { type: 'push', label: 'Superscript', value: 'superscript', disabled: true } ] }, { type: 'separator' }, { group: 'textstyle2', label: '&nbsp;', buttons: [ { type: 'color', label: 'Font Color', value: 'forecolor', disabled: true }, { type: 'color', label: 'Background Color', value: 'backcolor', disabled: true }, { type: 'separator' }, { type: 'push', label: 'Remove Formatting', value: 'removeformat', disabled: true }, { type: 'push', label: 'Show/Hide Hidden Elements', value: 'hiddenelements' } ] }, { type: 'separator' }, { group: 'undoredo', label: 'Undo/Redo', buttons: [ { type: 'push', label: 'Undo', value: 'undo', disabled: true }, { type: 'push', label: 'Redo', value: 'redo', disabled: true } ] }, { type: 'separator' }, { group: 'alignment', label: 'Alignment', buttons: [ { type: 'push', label: 'Align Left CTRL + SHIFT + [', value: 'justifyleft' }, { type: 'push', label: 'Align Center CTRL + SHIFT + |', value: 'justifycenter' }, { type: 'push', label: 'Align Right CTRL + SHIFT + ]', value: 'justifyright' }, { type: 'push', label: 'Justify', value: 'justifyfull' } ] }, { type: 'separator' }, { group: 'parastyle', label: 'Paragraph Style', buttons: [ { type: 'select', label: 'Normal', value: 'heading', disabled: true, menu: [ { text: 'Normal', value: 'none', checked: true }, { text: 'Header 1', value: 'h1' }, { text: 'Header 2', value: 'h2' }, { text: 'Header 3', value: 'h3' }, { text: 'Header 4', value: 'h4' }, { text: 'Header 5', value: 'h5' }, { text: 'Header 6', value: 'h6' } ] } ] }, { type: 'separator' }, { group: 'indentlist2', label: 'Indenting and Lists', buttons: [ { type: 'push', label: 'Indent', value: 'indent', disabled: true }, { type: 'push', label: 'Outdent', value: 'outdent', disabled: true }, { type: 'push', label: 'Create an Unordered List', value: 'insertunorderedlist' }, { type: 'push', label: 'Create an Ordered List', value: 'insertorderedlist' } ] }, { type: 'separator' }, { group: 'insertitem', label: 'Insert Item', buttons: [ { type: 'push', label: 'HTML Link CTRL + SHIFT + L', value: 'createlink', disabled: true }, { type: 'push', label: 'Insert Image', value: 'insertimage' } ] } ] }; this._defaultImageToolbarConfig = { buttonType: this._defaultToolbar.buttonType, buttons: [ { group: 'textflow', label: this.STR_IMAGE_TEXTFLOW + ':', buttons: [ { type: 'push', label: 'Left', value: 'left' }, { type: 'push', label: 'Inline', value: 'inline' }, { type: 'push', label: 'Block', value: 'block' }, { type: 'push', label: 'Right', value: 'right' } ] }, { type: 'separator' }, { group: 'padding', label: this.STR_IMAGE_PADDING + ':', buttons: [ { type: 'spin', label: '0', value: 'padding', range: [0, 50] } ] }, { type: 'separator' }, { group: 'border', label: this.STR_IMAGE_BORDER + ':', buttons: [ { type: 'select', label: this.STR_IMAGE_BORDER_SIZE, value: 'bordersize', menu: [ { text: 'none', value: '0', checked: true }, { text: '1px', value: '1' }, { text: '2px', value: '2' }, { text: '3px', value: '3' }, { text: '4px', value: '4' }, { text: '5px', value: '5' } ] }, { type: 'select', label: this.STR_IMAGE_BORDER_TYPE, value: 'bordertype', disabled: true, menu: [ { text: 'Solid', value: 'solid', checked: true }, { text: 'Dashed', value: 'dashed' }, { text: 'Dotted', value: 'dotted' } ] }, { type: 'color', label: 'Border Color', value: 'bordercolor', disabled: true } ] } ] }; YAHOO.widget.Editor.superclass.init.call(this, p_oElement, p_oAttributes); }, _render: function() { YAHOO.widget.Editor.superclass._render.apply(this, arguments); var self = this; //Render the panel in another thread and delay it a little.. window.setTimeout(function() { self._renderPanel.call(self); }, 800); }, /** * @method initAttributes * @description Initializes all of the configuration attributes used to create * the editor. * @param {Object} attr Object literal specifying a set of * configuration attributes used to create the editor. */ initAttributes: function(attr) { YAHOO.widget.Editor.superclass.initAttributes.call(this, attr); /** * @attribute localFileWarning * @description Should we throw the warning if we detect a file that is local to their machine? * @default true * @type Boolean */ this.setAttributeConfig('localFileWarning', { value: attr.locaFileWarning || true }); /** * @attribute hiddencss * @description The CSS used to show/hide hidden elements on the page, these rules must be prefixed with the class provided in <code>this.CLASS_HIDDEN</code> * @default <code><pre> .yui-hidden font, .yui-hidden strong, .yui-hidden b, .yui-hidden em, .yui-hidden i, .yui-hidden u, .yui-hidden div, .yui-hidden p, .yui-hidden span, .yui-hidden img, .yui-hidden ul, .yui-hidden ol, .yui-hidden li, .yui-hidden table { border: 1px dotted #ccc; } .yui-hidden .yui-non { border: none; } .yui-hidden img { padding: 2px; }</pre></code> * @type String */ this.setAttributeConfig('hiddencss', { value: attr.hiddencss || '.yui-hidden font, .yui-hidden strong, .yui-hidden b, .yui-hidden em, .yui-hidden i, .yui-hidden u, .yui-hidden div,.yui-hidden p,.yui-hidden span,.yui-hidden img, .yui-hidden ul, .yui-hidden ol, .yui-hidden li, .yui-hidden table { border: 1px dotted #ccc; } .yui-hidden .yui-non { border: none; } .yui-hidden img { padding: 2px; }', writeOnce: true }); }, /** * @private * @method _windows * @description A reference to the HTML elements used for the body of Editor Windows. */ _windows: null, /** * @private * @method _defaultImageToolbar * @description A reference to the Toolbar Object inside Image Editor Window. */ _defaultImageToolbar: null, /** * @private * @method _defaultImageToolbarConfig * @description Config to be used for the default Image Editor Window. */ _defaultImageToolbarConfig: null, /** * @private * @method _fixNodes * @description Fix href and imgs as well as remove invalid HTML. */ _fixNodes: function() { YAHOO.widget.Editor.superclass._fixNodes.call(this); var url = ''; var imgs = this._getDoc().getElementsByTagName('img'); for (var im = 0; im < imgs.length; im++) { if (imgs[im].getAttribute('href', 2)) { url = imgs[im].getAttribute('src', 2); if (this._isLocalFile(url)) { Dom.addClass(imgs[im], this.CLASS_LOCAL_FILE); } else { Dom.removeClass(imgs[im], this.CLASS_LOCAL_FILE); } } } var fakeAs = this._getDoc().body.getElementsByTagName('a'); for (var a = 0; a < fakeAs.length; a++) { if (fakeAs[a].getAttribute('href', 2)) { url = fakeAs[a].getAttribute('href', 2); if (this._isLocalFile(url)) { Dom.addClass(fakeAs[a], this.CLASS_LOCAL_FILE); } else { Dom.removeClass(fakeAs[a], this.CLASS_LOCAL_FILE); } } } }, /** * @private * @property _disabled * @description The Toolbar items that should be disabled if there is no selection present in the editor. * @type Array */ _disabled: [ 'createlink', 'forecolor', 'backcolor', 'fontname', 'fontsize', 'superscript', 'subscript', 'removeformat', 'heading', 'indent' ], /** * @private * @property _alwaysDisabled * @description The Toolbar items that should ALWAYS be disabled event if there is a selection present in the editor. * @type Object */ _alwaysDisabled: { 'outdent': true }, /** * @private * @property _alwaysEnabled * @description The Toolbar items that should ALWAYS be enabled event if there isn't a selection present in the editor. * @type Object */ _alwaysEnabled: { hiddenelements: true }, /** * @private * @method _handleKeyDown * @param {Event} ev The event we are working on. * @description Override method that handles some new keydown events inside the iFrame document. */ _handleKeyDown: function(ev) { YAHOO.widget.Editor.superclass._handleKeyDown.call(this, ev); var doExec = false, action = null, exec = false; switch (ev.keyCode) { //case 219: //Left case this._keyMap.JUSTIFY_LEFT.key: //Left if (this._checkKey(this._keyMap.JUSTIFY_LEFT, ev)) { action = 'justifyleft'; doExec = true; } break; //case 220: //Center case this._keyMap.JUSTIFY_CENTER.key: if (this._checkKey(this._keyMap.JUSTIFY_CENTER, ev)) { action = 'justifycenter'; doExec = true; } break; case 221: //Right case this._keyMap.JUSTIFY_RIGHT.key: if (this._checkKey(this._keyMap.JUSTIFY_RIGHT, ev)) { action = 'justifyright'; doExec = true; } break; } if (doExec && action) { this.execCommand(action, null); Event.stopEvent(ev); this.nodeChange(); } }, /** * @private * @method _renderCreateLinkWindow * @description Pre renders the CreateLink window so we get faster window opening. */ _renderCreateLinkWindow: function() { var str = '<label for="' + this.get('id') + '_createlink_url"><strong>' + this.STR_LINK_URL + ':</strong> <input type="text" name="' + this.get('id') + '_createlink_url" id="' + this.get('id') + '_createlink_url" value=""></label>'; str += '<label for="' + this.get('id') + '_createlink_target"><strong>&nbsp;</strong><input type="checkbox" name="' + this.get('id') + '_createlink_target" id="' + this.get('id') + '_createlink_target" value="_blank" class="createlink_target"> ' + this.STR_LINK_NEW_WINDOW + '</label>'; str += '<label for="' + this.get('id') + '_createlink_title"><strong>' + this.STR_LINK_TITLE + ':</strong> <input type="text" name="' + this.get('id') + '_createlink_title" id="' + this.get('id') + '_createlink_title" value=""></label>'; var body = document.createElement('div'); body.innerHTML = str; var unlinkCont = document.createElement('div'); unlinkCont.className = 'removeLink'; var unlink = document.createElement('a'); unlink.href = '#'; unlink.innerHTML = this.STR_LINK_PROP_REMOVE; unlink.title = this.STR_LINK_PROP_REMOVE; Event.on(unlink, 'click', function(ev) { Event.stopEvent(ev); this.unsubscribeAll('afterExecCommand'); this.execCommand('unlink'); this.closeWindow(); }, this, true); unlinkCont.appendChild(unlink); body.appendChild(unlinkCont); this._windows.createlink = {}; this._windows.createlink.body = body; //body.style.display = 'none'; Event.on(body, 'keyup', function(e) { Event.stopPropagation(e); }); this.get('panel').editor_form.appendChild(body); this.fireEvent('windowCreateLinkRender', { type: 'windowCreateLinkRender', panel: this.get('panel'), body: body }); return body; }, _handleCreateLinkClick: function() { var el = this._getSelectedElement(); if (this._isElement(el, 'img')) { this.STOP_EXEC_COMMAND = true; this.currentElement[0] = el; this.toolbar.fireEvent('insertimageClick', { type: 'insertimageClick', target: this.toolbar }); this.fireEvent('afterExecCommand', { type: 'afterExecCommand', target: this }); return false; } if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('createlink')) { YAHOO.log('Toolbar Button for (createlink) was not found, skipping exec.', 'info', 'Editor'); return false; } } this.on('afterExecCommand', function() { var win = new YAHOO.widget.EditorWindow('createlink', { width: '350px' }); var el = this.currentElement[0], url = '', title = '', target = '', localFile = false; if (el) { win.el = el; if (el.getAttribute('href', 2) !== null) { url = el.getAttribute('href', 2); if (this._isLocalFile(url)) { //Local File throw Warning YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor'); win.setFooter(this.STR_LOCAL_FILE_WARNING); localFile = true; } else { win.setFooter(' '); } } if (el.getAttribute('title') !== null) { title = el.getAttribute('title'); } if (el.getAttribute('target') !== null) { target = el.getAttribute('target'); } } var body = null; if (this._windows.createlink && this._windows.createlink.body) { body = this._windows.createlink.body; } else { body = this._renderCreateLinkWindow(); } win.setHeader(this.STR_LINK_PROP_TITLE); win.setBody(body); Event.purgeElement(this.get('id') + '_createlink_url'); Dom.get(this.get('id') + '_createlink_url').value = url; Dom.get(this.get('id') + '_createlink_title').value = title; Dom.get(this.get('id') + '_createlink_target').checked = ((target) ? true : false); Event.onAvailable(this.get('id') + '_createlink_url', function() { var id = this.get('id'); window.setTimeout(function() { try { YAHOO.util.Dom.get(id + '_createlink_url').focus(); } catch (e) {} }, 50); if (this._isLocalFile(url)) { //Local File throw Warning Dom.addClass(this.get('id') + '_createlink_url', 'warning'); YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor'); this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING); } else { Dom.removeClass(this.get('id') + '_createlink_url', 'warning'); this.get('panel').setFooter(' '); } Event.on(this.get('id') + '_createlink_url', 'blur', function() { var url = Dom.get(this.get('id') + '_createlink_url'); if (this._isLocalFile(url.value)) { //Local File throw Warning Dom.addClass(url, 'warning'); YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor'); this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING); } else { Dom.removeClass(url, 'warning'); this.get('panel').setFooter(' '); } }, this, true); }, this, true); this.openWindow(win); }); }, /** * @private * @method _handleCreateLinkWindowClose * @description Handles the closing of the Link Properties Window. */ _handleCreateLinkWindowClose: function() { var url = Dom.get(this.get('id') + '_createlink_url'), target = Dom.get(this.get('id') + '_createlink_target'), title = Dom.get(this.get('id') + '_createlink_title'), el = arguments[0].win.el, a = el; if (url && url.value) { var urlValue = url.value; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { // :// not found adding if (urlValue.substring(0, 1) != '#') { urlValue = 'http:/'+'/' + urlValue; } } } el.setAttribute('href', urlValue); if (target.checked) { el.setAttribute('target', target.value); } else { el.setAttribute('target', ''); } el.setAttribute('title', ((title.value) ? title.value : '')); } else { var _span = this._getDoc().createElement('span'); _span.innerHTML = el.innerHTML; Dom.addClass(_span, 'yui-non'); el.parentNode.replaceChild(_span, el); } Dom.removeClass(url, 'warning'); Dom.get(this.get('id') + '_createlink_url').value = ''; Dom.get(this.get('id') + '_createlink_title').value = ''; Dom.get(this.get('id') + '_createlink_target').checked = false; this.nodeChange(); this.currentElement = []; }, /** * @private * @method _renderInsertImageWindow * @description Pre renders the InsertImage window so we get faster window opening. */ _renderInsertImageWindow: function() { var el = this.currentElement[0]; var str = '<label for="' + this.get('id') + '_insertimage_url"><strong>' + this.STR_IMAGE_URL + ':</strong> <input type="text" id="' + this.get('id') + '_insertimage_url" value="" size="40"></label>'; var body = document.createElement('div'); body.innerHTML = str; var tbarCont = document.createElement('div'); tbarCont.id = this.get('id') + '_img_toolbar'; body.appendChild(tbarCont); var str2 = '<label for="' + this.get('id') + '_insertimage_title"><strong>' + this.STR_IMAGE_TITLE + ':</strong> <input type="text" id="' + this.get('id') + '_insertimage_title" value="" size="40"></label>'; str2 += '<label for="' + this.get('id') + '_insertimage_link"><strong>' + this.STR_LINK_URL + ':</strong> <input type="text" name="' + this.get('id') + '_insertimage_link" id="' + this.get('id') + '_insertimage_link" value=""></label>'; str2 += '<label for="' + this.get('id') + '_insertimage_target"><strong>&nbsp;</strong><input type="checkbox" name="' + this.get('id') + '_insertimage_target_" id="' + this.get('id') + '_insertimage_target" value="_blank" class="insertimage_target"> ' + this.STR_LINK_NEW_WINDOW + '</label>'; var div = document.createElement('div'); div.innerHTML = str2; body.appendChild(div); var o = {}; Lang.augmentObject(o, this._defaultImageToolbarConfig); //Break the config reference var tbar = new YAHOO.widget.Toolbar(tbarCont, o); tbar.editor_el = el; this._defaultImageToolbar = tbar; var cont = tbar.get('cont'); var hw = document.createElement('div'); hw.className = 'yui-toolbar-group yui-toolbar-group-height-width height-width'; hw.innerHTML = '<h3>' + this.STR_IMAGE_SIZE + ':</h3>'; /* var orgSize = ''; if ((height != oheight) || (width != owidth)) { orgSize = '<span class="info">' + this.STR_IMAGE_ORIG_SIZE + '<br>'+ owidth +' x ' + oheight + '</span>'; } */ hw.innerHTML += '<span tabIndex="-1"><input type="text" size="3" value="" id="' + this.get('id') + '_insertimage_width"> x <input type="text" size="3" value="" id="' + this.get('id') + '_insertimage_height"></span>'; cont.insertBefore(hw, cont.firstChild); Event.onAvailable(this.get('id') + '_insertimage_width', function() { Event.on(this.get('id') + '_insertimage_width', 'blur', function() { var value = parseInt(Dom.get(this.get('id') + '_insertimage_width').value, 10); if (value > 5) { this._defaultImageToolbar.editor_el.style.width = value + 'px'; //Removed moveWindow call so the window doesn't jump //this.moveWindow(); } }, this, true); }, this, true); Event.onAvailable(this.get('id') + '_insertimage_height', function() { Event.on(this.get('id') + '_insertimage_height', 'blur', function() { var value = parseInt(Dom.get(this.get('id') + '_insertimage_height').value, 10); if (value > 5) { this._defaultImageToolbar.editor_el.style.height = value + 'px'; //Removed moveWindow call so the window doesn't jump //this.moveWindow(); } }, this, true); }, this, true); tbar.on('colorPickerClicked', function(o) { var size = '1', type = 'solid', color = 'black', el = this._defaultImageToolbar.editor_el; if (el.style.borderLeftWidth) { size = parseInt(el.style.borderLeftWidth, 10); } if (el.style.borderLeftStyle) { type = el.style.borderLeftStyle; } if (el.style.borderLeftColor) { color = el.style.borderLeftColor; } var borderString = size + 'px ' + type + ' #' + o.color; el.style.border = borderString; }, this, true); tbar.on('buttonClick', function(o) { var value = o.button.value, el = this._defaultImageToolbar.editor_el, borderString = ''; if (o.button.menucmd) { value = o.button.menucmd; } var size = '1', type = 'solid', color = 'black'; /* All border calcs are done on the left border since our default interface only supports one border size/type and color */ if (el.style.borderLeftWidth) { size = parseInt(el.style.borderLeftWidth, 10); } if (el.style.borderLeftStyle) { type = el.style.borderLeftStyle; } if (el.style.borderLeftColor) { color = el.style.borderLeftColor; } switch(value) { case 'bordersize': if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } borderString = parseInt(o.button.value, 10) + 'px ' + type + ' ' + color; el.style.border = borderString; if (parseInt(o.button.value, 10) > 0) { tbar.enableButton('bordertype'); tbar.enableButton('bordercolor'); } else { tbar.disableButton('bordertype'); tbar.disableButton('bordercolor'); } break; case 'bordertype': if (this.browser.webkit && this._lastImage) { Dom.removeClass(this._lastImage, 'selected'); this._lastImage = null; } borderString = size + 'px ' + o.button.value + ' ' + color; el.style.border = borderString; break; case 'right': case 'left': tbar.deselectAllButtons(); el.style.display = ''; el.align = o.button.value; break; case 'inline': tbar.deselectAllButtons(); el.style.display = ''; el.align = ''; break; case 'block': tbar.deselectAllButtons(); el.style.display = 'block'; el.align = 'center'; break; case 'padding': var _button = tbar.getButtonById(o.button.id); el.style.margin = _button.get('label') + 'px'; break; } tbar.selectButton(o.button.value); if (value !== 'padding') { this.moveWindow(); } }, this, true); if (this.get('localFileWarning')) { Event.on(this.get('id') + '_insertimage_link', 'blur', function() { var url = Dom.get(this.get('id') + '_insertimage_link'); if (this._isLocalFile(url.value)) { //Local File throw Warning Dom.addClass(url, 'warning'); YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor'); this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING); } else { Dom.removeClass(url, 'warning'); this.get('panel').setFooter(' '); //Adobe AIR Code if ((this.browser.webkit && !this.browser.webkit3 || this.browser.air) || this.browser.opera) { this.get('panel').setFooter(this.STR_IMAGE_COPY); } } }, this, true); } Event.on(this.get('id') + '_insertimage_url', 'blur', function() { var url = Dom.get(this.get('id') + '_insertimage_url'); if (url.value && el) { if (url.value == el.getAttribute('src', 2)) { YAHOO.log('Images are the same, bail on blur handler', 'info', 'Editor'); return false; } } YAHOO.log('Images are different, process blur handler', 'info', 'Editor'); if (this._isLocalFile(url.value)) { //Local File throw Warning Dom.addClass(url, 'warning'); YAHOO.log('Local file reference found, show local warning', 'warn', 'Editor'); this.get('panel').setFooter(this.STR_LOCAL_FILE_WARNING); } else if (this.currentElement[0]) { Dom.removeClass(url, 'warning'); this.get('panel').setFooter(' '); //Adobe AIR Code if ((this.browser.webkit && !this.browser.webkit3 || this.browser.air) || this.browser.opera) { this.get('panel').setFooter(this.STR_IMAGE_COPY); } if (url && url.value && (url.value != this.STR_IMAGE_HERE)) { this.currentElement[0].setAttribute('src', url.value); var self = this, img = new Image(); img.onerror = function() { url.value = self.STR_IMAGE_HERE; img.setAttribute('src', self.get('blankimage')); self.currentElement[0].setAttribute('src', self.get('blankimage')); YAHOO.util.Dom.get(self.get('id') + '_insertimage_height').value = img.height; YAHOO.util.Dom.get(self.get('id') + '_insertimage_width').value = img.width; }; var id = this.get('id'); window.setTimeout(function() { YAHOO.util.Dom.get(id + '_insertimage_height').value = img.height; YAHOO.util.Dom.get(id + '_insertimage_width').value = img.width; if (self.currentElement && self.currentElement[0]) { if (!self.currentElement[0]._height) { self.currentElement[0]._height = img.height; } if (!self.currentElement[0]._width) { self.currentElement[0]._width = img.width; } } //Removed moveWindow call so the window doesn't jump //self.moveWindow(); }, 800); //Bumped the timeout up to account for larger images.. if (url.value != this.STR_IMAGE_HERE) { img.src = url.value; } } } }, this, true); this._windows.insertimage = {}; this._windows.insertimage.body = body; //body.style.display = 'none'; this.get('panel').editor_form.appendChild(body); this.fireEvent('windowInsertImageRender', { type: 'windowInsertImageRender', panel: this.get('panel'), body: body, toolbar: tbar }); return body; }, /** * @private * @method _handleInsertImageClick * @description Opens the Image Properties Window when the insert Image button is clicked or an Image is Double Clicked. */ _handleInsertImageClick: function() { if (this.get('limitCommands')) { if (!this.toolbar.getButtonByValue('insertimage')) { YAHOO.log('Toolbar Button for (insertimage) was not found, skipping exec.', 'info', 'Editor'); return false; } } this.on('afterExecCommand', function() { YAHOO.log('afterExecCommand :: _handleInsertImageClick', 'info', 'Editor'); var el = this.currentElement[0], body = null, link = '', target = '', tbar = null, title = '', src = '', align = '', height = 75, width = 75, padding = 0, oheight = 0, owidth = 0, blankimage = false, win = new YAHOO.widget.EditorWindow('insertimage', { width: '415px' }); if (!el) { el = this._getSelectedElement(); } if (el) { win.el = el; if (el.getAttribute('src')) { src = el.getAttribute('src', 2); if (src.indexOf(this.get('blankimage')) != -1) { src = this.STR_IMAGE_HERE; blankimage = true; } } if (el.getAttribute('alt', 2)) { title = el.getAttribute('alt', 2); } if (el.getAttribute('title', 2)) { title = el.getAttribute('title', 2); } if (el.parentNode && this._isElement(el.parentNode, 'a')) { link = el.parentNode.getAttribute('href', 2); if (el.parentNode.getAttribute('target') !== null) { target = el.parentNode.getAttribute('target'); } } height = parseInt(el.height, 10); width = parseInt(el.width, 10); if (el.style.height) { height = parseInt(el.style.height, 10); } if (el.style.width) { width = parseInt(el.style.width, 10); } if (el.style.margin) { padding = parseInt(el.style.margin, 10); } if (!el._height) { el._height = height; } if (!el._width) { el._width = width; } oheight = el._height; owidth = el._width; } if (this._windows.insertimage && this._windows.insertimage.body) { body = this._windows.insertimage.body; this._defaultImageToolbar.resetAllButtons(); } else { body = this._renderInsertImageWindow(); } tbar = this._defaultImageToolbar; tbar.editor_el = el; var bsize = '0', btype = 'solid'; if (el.style.borderLeftWidth) { bsize = parseInt(el.style.borderLeftWidth, 10); } if (el.style.borderLeftStyle) { btype = el.style.borderLeftStyle; } var bs_button = tbar.getButtonByValue('bordersize'), bSizeStr = ((parseInt(bsize, 10) > 0) ? '' : this.STR_NONE); bs_button.set('label', '<span class="yui-toolbar-bordersize-' + bsize + '">' + bSizeStr + '</span>'); this._updateMenuChecked('bordersize', bsize, tbar); var bt_button = tbar.getButtonByValue('bordertype'); bt_button.set('label', '<span class="yui-toolbar-bordertype-' + btype + '">asdfa</span>'); this._updateMenuChecked('bordertype', btype, tbar); if (parseInt(bsize, 10) > 0) { tbar.enableButton(bt_button); tbar.enableButton(bs_button); tbar.enableButton('bordercolor'); } if ((el.align == 'right') || (el.align == 'left')) { tbar.selectButton(el.align); } else if (el.style.display == 'block') { tbar.selectButton('block'); } else { tbar.selectButton('inline'); } if (parseInt(el.style.marginLeft, 10) > 0) { tbar.getButtonByValue('padding').set('label', ''+parseInt(el.style.marginLeft, 10)); } if (el.style.borderSize) { tbar.selectButton('bordersize'); tbar.selectButton(parseInt(el.style.borderSize, 10)); } tbar.getButtonByValue('padding').set('label', ''+padding); win.setHeader(this.STR_IMAGE_PROP_TITLE); win.setBody(body); //Adobe AIR Code if ((this.browser.webkit && !this.browser.webkit3 || this.browser.air) || this.browser.opera) { win.setFooter(this.STR_IMAGE_COPY); } this.openWindow(win); Dom.get(this.get('id') + '_insertimage_url').value = src; Dom.get(this.get('id') + '_insertimage_title').value = title; Dom.get(this.get('id') + '_insertimage_link').value = link; Dom.get(this.get('id') + '_insertimage_target').checked = ((target) ? true : false); Dom.get(this.get('id') + '_insertimage_width').value = width; Dom.get(this.get('id') + '_insertimage_height').value = height; var orgSize = ''; if ((height != oheight) || (width != owidth)) { var s = document.createElement('span'); s.className = 'info'; s.innerHTML = this.STR_IMAGE_ORIG_SIZE + ': ('+ owidth +' x ' + oheight + ')'; if (Dom.get(this.get('id') + '_insertimage_height').nextSibling) { var old = Dom.get(this.get('id') + '_insertimage_height').nextSibling; old.parentNode.removeChild(old); } Dom.get(this.get('id') + '_insertimage_height').parentNode.appendChild(s); } this.toolbar.selectButton('insertimage'); var id = this.get('id'); window.setTimeout(function() { try { YAHOO.util.Dom.get(id + '_insertimage_url').focus(); if (blankimage) { YAHOO.util.Dom.get(id + '_insertimage_url').select(); } } catch (e) {} }, 50); }); }, /** * @private * @method _handleInsertImageWindowClose * @description Handles the closing of the Image Properties Window. */ _handleInsertImageWindowClose: function() { var url = Dom.get(this.get('id') + '_insertimage_url'), title = Dom.get(this.get('id') + '_insertimage_title'), link = Dom.get(this.get('id') + '_insertimage_link'), target = Dom.get(this.get('id') + '_insertimage_target'), el = arguments[0].win.el; if (url && url.value && (url.value != this.STR_IMAGE_HERE)) { el.setAttribute('src', url.value); el.setAttribute('title', title.value); el.setAttribute('alt', title.value); var par = el.parentNode; if (link.value) { var urlValue = link.value; if ((urlValue.indexOf(':/'+'/') == -1) && (urlValue.substring(0,1) != '/') && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { if ((urlValue.indexOf('@') != -1) && (urlValue.substring(0, 6).toLowerCase() != 'mailto')) { //Found an @ sign, prefix with mailto: urlValue = 'mailto:' + urlValue; } else { // :// not found adding urlValue = 'http:/'+'/' + urlValue; } } if (par && this._isElement(par, 'a')) { par.setAttribute('href', urlValue); if (target.checked) { par.setAttribute('target', target.value); } else { par.setAttribute('target', ''); } } else { var _a = this._getDoc().createElement('a'); _a.setAttribute('href', urlValue); if (target.checked) { _a.setAttribute('target', target.value); } else { _a.setAttribute('target', ''); } el.parentNode.replaceChild(_a, el); _a.appendChild(el); } } else { if (par && this._isElement(par, 'a')) { par.parentNode.replaceChild(el, par); } } } else { //No url/src given, remove the node from the document el.parentNode.removeChild(el); } Dom.get(this.get('id') + '_insertimage_url').value = ''; Dom.get(this.get('id') + '_insertimage_title').value = ''; Dom.get(this.get('id') + '_insertimage_link').value = ''; Dom.get(this.get('id') + '_insertimage_target').checked = false; Dom.get(this.get('id') + '_insertimage_width').value = 0; Dom.get(this.get('id') + '_insertimage_height').value = 0; this._defaultImageToolbar.resetAllButtons(); this.currentElement = []; this.nodeChange(); }, /** * @property EDITOR_PANEL_ID * @description HTML id to give the properties window in the DOM. * @type String */ EDITOR_PANEL_ID: '-panel', /** * @private * @method _renderPanel * @description Renders the panel used for Editor Windows to the document so we can start using it.. * @return {<a href="YAHOO.widget.Overlay.html">YAHOO.widget.Overlay</a>} */ _renderPanel: function() { var panelEl = document.createElement('div'); Dom.addClass(panelEl, 'yui-editor-panel'); panelEl.id = this.get('id') + this.EDITOR_PANEL_ID; panelEl.style.position = 'absolute'; panelEl.style.top = '-9999px'; panelEl.style.left = '-9999px'; document.body.appendChild(panelEl); this.get('element_cont').insertBefore(panelEl, this.get('element_cont').get('firstChild')); var panel = new YAHOO.widget.Overlay(this.get('id') + this.EDITOR_PANEL_ID, { width: '300px', iframe: true, visible: false, underlay: 'none', draggable: false, close: false }); this.set('panel', panel); panel.setBody('---'); panel.setHeader(' '); panel.setFooter(' '); var body = document.createElement('div'); body.className = this.CLASS_PREFIX + '-body-cont'; for (var b in this.browser) { if (this.browser[b]) { Dom.addClass(body, b); break; } } Dom.addClass(body, ((YAHOO.widget.Button && (this._defaultToolbar.buttonType == 'advanced')) ? 'good-button' : 'no-button')); var _note = document.createElement('h3'); _note.className = 'yui-editor-skipheader'; _note.innerHTML = this.STR_CLOSE_WINDOW_NOTE; body.appendChild(_note); var form = document.createElement('fieldset'); panel.editor_form = form; body.appendChild(form); var _close = document.createElement('span'); _close.innerHTML = 'X'; _close.title = this.STR_CLOSE_WINDOW; _close.className = 'close'; Event.on(_close, 'click', this.closeWindow, this, true); var _knob = document.createElement('span'); _knob.innerHTML = '^'; _knob.className = 'knob'; panel.editor_knob = _knob; var _header = document.createElement('h3'); panel.editor_header = _header; _header.innerHTML = '<span></span>'; panel.setHeader(' '); //Clear the current header panel.appendToHeader(_header); _header.appendChild(_close); _header.appendChild(_knob); panel.setBody(' '); //Clear the current body panel.setFooter(' '); //Clear the current footer panel.appendToBody(body); //Append the new DOM node to it Event.on(panel.element, 'click', function(ev) { Event.stopPropagation(ev); }); var fireShowEvent = function() { panel.bringToTop(); YAHOO.util.Dom.setStyle(this.element, 'display', 'block'); this._handleWindowInputs(false); }; panel.showEvent.subscribe(fireShowEvent, this, true); panel.hideEvent.subscribe(function() { this._handleWindowInputs(true); }, this, true); panel.renderEvent.subscribe(function() { this._renderInsertImageWindow(); this._renderCreateLinkWindow(); this.fireEvent('windowRender', { type: 'windowRender', panel: panel }); this._handleWindowInputs(true); }, this, true); if (this.DOMReady) { this.get('panel').render(); } else { Event.onDOMReady(function() { this.get('panel').render(); }, this, true); } return this.get('panel'); }, /** * @method _handleWindowInputs * @param {Boolean} disable The state to set all inputs in all Editor windows to. Defaults to: false. * @description Disables/Enables all fields inside Editor windows. Used in show/hide events to keep window fields from submitting when the parent form is submitted. */ _handleWindowInputs: function(disable) { if (!Lang.isBoolean(disable)) { disable = false; } var inputs = this.get('panel').element.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i++) { try { inputs[i].disabled = disable; } catch (e) {} } }, /** * @method openWindow * @param {<a href="YAHOO.widget.EditorWindow.html">YAHOO.widget.EditorWindow</a>} win A <a href="YAHOO.widget.EditorWindow.html">YAHOO.widget.EditorWindow</a> instance * @description Opens a new "window/panel" */ openWindow: function(win) { YAHOO.log('openWindow: ' + win.name, 'info', 'Editor'); var self = this; window.setTimeout(function() { self.toolbar.set('disabled', true); //Disable the toolbar when an editor window is open.. }, 10); Event.on(document, 'keydown', this._closeWindow, this, true); if (this.currentWindow) { this.closeWindow(); } var xy = Dom.getXY(this.currentElement[0]), elXY = Dom.getXY(this.get('iframe').get('element')), panel = this.get('panel'), newXY = [(xy[0] + elXY[0] - 20), (xy[1] + elXY[1] + 10)], wWidth = (parseInt(win.attrs.width, 10) / 2), align = 'center', body = null; this.fireEvent('beforeOpenWindow', { type: 'beforeOpenWindow', win: win, panel: panel }); var form = panel.editor_form; var wins = this._windows; for (var b in wins) { if (Lang.hasOwnProperty(wins, b)) { if (wins[b] && wins[b].body) { if (b == win.name) { Dom.setStyle(wins[b].body, 'display', 'block'); } else { Dom.setStyle(wins[b].body, 'display', 'none'); } } } } if (this._windows[win.name].body) { Dom.setStyle(this._windows[win.name].body, 'display', 'block'); form.appendChild(this._windows[win.name].body); } else { if (Lang.isObject(win.body)) { //Assume it's a reference form.appendChild(win.body); } else { //Assume it's a string var _tmp = document.createElement('div'); _tmp.innerHTML = win.body; form.appendChild(_tmp); } } panel.editor_header.firstChild.innerHTML = win.header; if (win.footer !== null) { panel.setFooter(win.footer); Dom.addClass(panel.footer, 'open'); } else { Dom.removeClass(panel.footer, 'open'); } panel.cfg.setProperty('width', win.attrs.width); this.currentWindow = win; this.moveWindow(true); panel.show(); this.fireEvent('afterOpenWindow', { type: 'afterOpenWindow', win: win, panel: panel }); }, /** * @method moveWindow * @param {Boolean} force Boolean to tell it to move but not use any animation (Usually done the first time the window is loaded.) * @description Realign the window with the currentElement and reposition the knob above the panel. */ moveWindow: function(force) { if (!this.currentWindow) { return false; } var win = this.currentWindow, xy = Dom.getXY(this.currentElement[0]), elXY = Dom.getXY(this.get('iframe').get('element')), panel = this.get('panel'), //newXY = [(xy[0] + elXY[0] - 20), (xy[1] + elXY[1] + 10)], newXY = [(xy[0] + elXY[0]), (xy[1] + elXY[1])], wWidth = (parseInt(win.attrs.width, 10) / 2), align = 'center', orgXY = panel.cfg.getProperty('xy') || [0,0], _knob = panel.editor_knob, xDiff = 0, yDiff = 0, anim = false; newXY[0] = ((newXY[0] - wWidth) + 20); //Account for the Scroll bars in a scrolled editor window. newXY[0] = newXY[0] - Dom.getDocumentScrollLeft(this._getDoc()); newXY[1] = newXY[1] - Dom.getDocumentScrollTop(this._getDoc()); if (this._isElement(this.currentElement[0], 'img')) { if (this.currentElement[0].src.indexOf(this.get('blankimage')) != -1) { newXY[0] = (newXY[0] + (75 / 2)); //Placeholder size newXY[1] = (newXY[1] + 75); //Placeholder sizea } else { var w = parseInt(this.currentElement[0].width, 10); var h = parseInt(this.currentElement[0].height, 10); newXY[0] = (newXY[0] + (w / 2)); newXY[1] = (newXY[1] + h); } newXY[1] = newXY[1] + 15; } else { var fs = Dom.getStyle(this.currentElement[0], 'fontSize'); if (fs && fs.indexOf && fs.indexOf('px') != -1) { newXY[1] = newXY[1] + parseInt(Dom.getStyle(this.currentElement[0], 'fontSize'), 10) + 5; } else { newXY[1] = newXY[1] + 20; } } if (newXY[0] < elXY[0]) { newXY[0] = elXY[0] + 5; align = 'left'; } if ((newXY[0] + (wWidth * 2)) > (elXY[0] + parseInt(this.get('iframe').get('element').clientWidth, 10))) { newXY[0] = ((elXY[0] + parseInt(this.get('iframe').get('element').clientWidth, 10)) - (wWidth * 2) - 5); align = 'right'; } try { xDiff = (newXY[0] - orgXY[0]); yDiff = (newXY[1] - orgXY[1]); } catch (e) {} var iTop = elXY[1] + parseInt(this.get('height'), 10); var iLeft = elXY[0] + parseInt(this.get('width'), 10); if (newXY[1] > iTop) { newXY[1] = iTop; } if (newXY[0] > iLeft) { newXY[0] = (iLeft / 2); } //Convert negative numbers to positive so we can get the difference in distance xDiff = ((xDiff < 0) ? (xDiff * -1) : xDiff); yDiff = ((yDiff < 0) ? (yDiff * -1) : yDiff); if (((xDiff > 10) || (yDiff > 10)) || force) { //Only move the window if it's supposed to move more than 10px or force was passed (new window) var _knobLeft = 0, elW = 0; if (this.currentElement[0].width) { elW = (parseInt(this.currentElement[0].width, 10) / 2); } var leftOffset = xy[0] + elXY[0] + elW; _knobLeft = leftOffset - newXY[0]; //Check to see if the knob will go off either side & reposition it if (_knobLeft > (parseInt(win.attrs.width, 10) - 1)) { _knobLeft = ((parseInt(win.attrs.width, 10) - 30) - 1); } else if (_knobLeft < 40) { _knobLeft = 1; } if (isNaN(_knobLeft)) { _knobLeft = 1; } if (force) { if (_knob) { _knob.style.left = _knobLeft + 'px'; } //Removed Animation from a forced move.. panel.cfg.setProperty('xy', newXY); } else { if (this.get('animate')) { anim = new YAHOO.util.Anim(panel.element, {}, 0.5, YAHOO.util.Easing.easeOut); anim.attributes = { top: { to: newXY[1] }, left: { to: newXY[0] } }; anim.onComplete.subscribe(function() { panel.cfg.setProperty('xy', newXY); }); //We have to animate the iframe shim at the same time as the panel or we get scrollbar bleed .. var iframeAnim = new YAHOO.util.Anim(panel.iframe, anim.attributes, 0.5, YAHOO.util.Easing.easeOut); var _knobAnim = new YAHOO.util.Anim(_knob, { left: { to: _knobLeft } }, 0.6, YAHOO.util.Easing.easeOut); anim.animate(); iframeAnim.animate(); _knobAnim.animate(); } else { _knob.style.left = _knobLeft + 'px'; panel.cfg.setProperty('xy', newXY); } } } }, /** * @private * @method _closeWindow * @description Close the currently open EditorWindow with the Escape key. * @param {Event} ev The keypress Event that we are trapping */ _closeWindow: function(ev) { //if ((ev.charCode == 87) && ev.shiftKey && ev.ctrlKey) { if (this._checkKey(this._keyMap.CLOSE_WINDOW, ev)) { if (this.currentWindow) { this.closeWindow(); } } }, /** * @method closeWindow * @description Close the currently open EditorWindow. */ closeWindow: function(keepOpen) { YAHOO.log('closeWindow: ' + this.currentWindow.name, 'info', 'Editor'); this.fireEvent('window' + this.currentWindow.name + 'Close', { type: 'window' + this.currentWindow.name + 'Close', win: this.currentWindow, el: this.currentElement[0] }); this.fireEvent('closeWindow', { type: 'closeWindow', win: this.currentWindow }); this.currentWindow = null; this.get('panel').hide(); this.get('panel').cfg.setProperty('xy', [-900,-900]); this.get('panel').syncIframe(); //Needed to move the iframe with the hidden panel this.unsubscribeAll('afterExecCommand'); this.toolbar.set('disabled', false); //enable the toolbar now that the window is closed this.toolbar.resetAllButtons(); this.focus(); Event.removeListener(document, 'keydown', this._closeWindow); }, /* {{{ Command Overrides - These commands are only over written when we are using the advanced version */ /** * @method cmd_undo * @description Pulls an item from the Undo stack and updates the Editor * @param value Value passed from the execCommand method */ cmd_undo: function(value) { if (this._hasUndoLevel()) { if (!this._undoLevel) { this._undoLevel = this._undoCache.length; } this._undoLevel = (this._undoLevel - 1); if (this._undoCache[this._undoLevel]) { var html = this._getUndo(this._undoLevel); this.setEditorHTML(html); } else { this._undoLevel = null; this.toolbar.disableButton('undo'); } } return [false]; }, /** * @method cmd_redo * @description Pulls an item from the Undo stack and updates the Editor * @param value Value passed from the execCommand method */ cmd_redo: function(value) { this._undoLevel = this._undoLevel + 1; if (this._undoLevel >= this._undoCache.length) { this._undoLevel = this._undoCache.length; } YAHOO.log(this._undoLevel + ' :: ' + this._undoCache.length, 'warn', 'SimpleEditor'); if (this._undoCache[this._undoLevel]) { var html = this._getUndo(this._undoLevel); this.setEditorHTML(html); } else { this.toolbar.disableButton('redo'); } return [false]; }, /** * @method cmd_heading * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('heading') is used. */ cmd_heading: function(value) { var exec = true, el = null, action = 'heading', _sel = this._getSelection(), _selEl = this._getSelectedElement(); if (_selEl) { _sel = _selEl; } if (this.browser.ie) { action = 'formatblock'; } if (value == this.STR_NONE) { if ((_sel && _sel.tagName && (_sel.tagName.toLowerCase().substring(0,1) == 'h')) || (_sel && _sel.parentNode && _sel.parentNode.tagName && (_sel.parentNode.tagName.toLowerCase().substring(0,1) == 'h'))) { if (_sel.parentNode.tagName.toLowerCase().substring(0,1) == 'h') { _sel = _sel.parentNode; } if (this._isElement(_sel, 'html')) { return [false]; } el = this._swapEl(_selEl, 'span', function(el) { el.className = 'yui-non'; }); this._selectNode(el); this.currentElement[0] = el; } exec = false; } else { if (this._isElement(_selEl, 'h1') || this._isElement(_selEl, 'h2') || this._isElement(_selEl, 'h3') || this._isElement(_selEl, 'h4') || this._isElement(_selEl, 'h5') || this._isElement(_selEl, 'h6')) { el = this._swapEl(_selEl, value); this._selectNode(el); this.currentElement[0] = el; } else { this._createCurrentElement(value); this._selectNode(this.currentElement[0]); } exec = false; } return [exec, action]; }, /** * @method cmd_hiddenelements * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('hiddenelements') is used. */ cmd_hiddenelements: function(value) { if (this._showingHiddenElements) { //Don't auto highlight the hidden button this._lastButton = null; YAHOO.log('Enabling hidden CSS File', 'info', 'SimpleEditor'); this._showingHiddenElements = false; this.toolbar.deselectButton('hiddenelements'); Dom.removeClass(this._getDoc().body, this.CLASS_HIDDEN); } else { YAHOO.log('Disabling hidden CSS File', 'info', 'SimpleEditor'); this._showingHiddenElements = true; Dom.addClass(this._getDoc().body, this.CLASS_HIDDEN); this.toolbar.selectButton('hiddenelements'); } return [false]; }, /** * @method cmd_removeformat * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('removeformat') is used. */ cmd_removeformat: function(value) { var exec = true; /* * @knownissue Remove Format issue * @browser Safari 2.x * @description There is an issue here with Safari, that it may not always remove the format of the item that is selected. * Due to the way that Safari 2.x handles ranges, it is very difficult to determine what the selection holds. * So here we are making the best possible guess and acting on it. */ if (this.browser.webkit && !this._getDoc().queryCommandEnabled('removeformat')) { var _txt = this._getSelection()+''; this._createCurrentElement('span'); this.currentElement[0].className = 'yui-non'; this.currentElement[0].innerHTML = _txt; for (var i = 1; i < this.currentElement.length; i++) { this.currentElement[i].parentNode.removeChild(this.currentElement[i]); } exec = false; } return [exec]; }, /** * @method cmd_script * @param action action passed from the execCommand method * @param value Value passed from the execCommand method * @description This is a combined execCommand override method. It is called from the cmd_superscript and cmd_subscript methods. */ cmd_script: function(action, value) { var exec = true, tag = action.toLowerCase().substring(0, 3), _span = null, _selEl = this._getSelectedElement(); if (this.browser.webkit) { YAHOO.log('Safari dom fun again (' + action + ')..', 'info', 'EditorSafari'); if (this._isElement(_selEl, tag)) { YAHOO.log('we are a child of tag (' + tag + '), reverse process', 'info', 'EditorSafari'); _span = this._swapEl(this.currentElement[0], 'span', function(el) { el.className = 'yui-non'; }); this._selectNode(_span); } else { this._createCurrentElement(tag); var _sub = this._swapEl(this.currentElement[0], tag); this._selectNode(_sub); this.currentElement[0] = _sub; } exec = false; } return exec; }, /** * @method cmd_superscript * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('superscript') is used. */ cmd_superscript: function(value) { return [this.cmd_script('superscript', value)]; }, /** * @method cmd_subscript * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('subscript') is used. */ cmd_subscript: function(value) { return [this.cmd_script('subscript', value)]; }, /** * @method cmd_indent * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('indent') is used. */ cmd_indent: function(value) { var exec = true, selEl = this._getSelectedElement(), _bq = null; //if (this.browser.webkit || this.browser.ie || this.browser.gecko) { //if (this.browser.webkit || this.browser.ie) { if (this.browser.ie) { if (this._isElement(selEl, 'blockquote')) { _bq = this._getDoc().createElement('blockquote'); _bq.innerHTML = selEl.innerHTML; selEl.innerHTML = ''; selEl.appendChild(_bq); this._selectNode(_bq); } else { _bq = this._getDoc().createElement('blockquote'); var html = this._getRange().htmlText; _bq.innerHTML = html; this._createCurrentElement('blockquote'); /* for (var i = 0; i < this.currentElement.length; i++) { _bq = this._getDoc().createElement('blockquote'); _bq.innerHTML = this.currentElement[i].innerHTML; this.currentElement[i].parentNode.replaceChild(_bq, this.currentElement[i]); this.currentElement[i] = _bq; } */ this.currentElement[0].parentNode.replaceChild(_bq, this.currentElement[0]); this.currentElement[0] = _bq; this._selectNode(this.currentElement[0]); } exec = false; } else { value = 'blockquote'; } return [exec, 'formatblock', value]; }, /** * @method cmd_outdent * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('outdent') is used. */ cmd_outdent: function(value) { var exec = true, selEl = this._getSelectedElement(), _bq = null, _span = null; //if (this.browser.webkit || this.browser.ie || this.browser.gecko) { if (this.browser.webkit || this.browser.ie) { //if (this.browser.ie) { selEl = this._getSelectedElement(); if (this._isElement(selEl, 'blockquote')) { var par = selEl.parentNode; if (this._isElement(selEl.parentNode, 'blockquote')) { par.innerHTML = selEl.innerHTML; this._selectNode(par); } else { _span = this._getDoc().createElement('span'); _span.innerHTML = selEl.innerHTML; YAHOO.util.Dom.addClass(_span, 'yui-non'); par.replaceChild(_span, selEl); this._selectNode(_span); } } else { YAHOO.log('Can not outdent, we are not inside a blockquote', 'warn', 'Editor'); } exec = false; } else { value = false; } return [exec, 'outdent', value]; }, /** * @method cmd_justify * @param dir The direction to justify * @description This is a factory method for the justify family of commands. */ cmd_justify: function(dir) { if (this.browser.ie) { if (this._hasSelection()) { this._createCurrentElement('span'); this._swapEl(this.currentElement[0], 'div', function(el) { el.style.textAlign = dir; }); return [false]; } } return [true, 'justify' + dir, '']; }, /** * @method cmd_justifycenter * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('justifycenter') is used. */ cmd_justifycenter: function() { return [this.cmd_justify('center')]; }, /** * @method cmd_justifyleft * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('justifyleft') is used. */ cmd_justifyleft: function() { return [this.cmd_justify('left')]; }, /** * @method cmd_justifyright * @param value Value passed from the execCommand method * @description This is an execCommand override method. It is called from execCommand when the execCommand('justifyright') is used. */ cmd_justifyright: function() { return [this.cmd_justify('right')]; }, /* }}}*/ /** * @method toString * @description Returns a string representing the editor. * @return {String} */ toString: function() { var str = 'Editor'; if (this.get && this.get('element_cont')) { str = 'Editor (#' + this.get('element_cont').get('id') + ')' + ((this.get('disabled') ? ' Disabled' : '')); } return str; } }); /** * @event beforeOpenWindow * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @param {Overlay} panel The Overlay object that is used to create the window. * @description Event fires before an Editor Window is opened. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event afterOpenWindow * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @param {Overlay} panel The Overlay object that is used to create the window. * @description Event fires after an Editor Window is opened. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event closeWindow * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @description Event fires after an Editor Window is closed. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event windowCMDOpen * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @param {Overlay} panel The Overlay object that is used to create the window. * @description Dynamic event fired when an <a href="YAHOO.widget.EditorWindow.html">EditorWindow</a> is opened.. The dynamic event is based on the name of the window. Example Window: createlink, opening this window would fire the windowcreatelinkOpen event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event windowCMDClose * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @param {Overlay} panel The Overlay object that is used to create the window. * @description Dynamic event fired when an <a href="YAHOO.widget.EditorWindow.html">EditorWindow</a> is closed.. The dynamic event is based on the name of the window. Example Window: createlink, opening this window would fire the windowcreatelinkClose event. See <a href="YAHOO.util.Element.html#addListener">Element.addListener</a> for more information on listening for this event. * @type YAHOO.util.CustomEvent */ /** * @event windowRender * @param {<a href="YAHOO.widget.EditorWindow.html">EditorWindow</a>} win The EditorWindow object * @param {Overlay} panel The Overlay object that is used to create the window. * @description Event fired when the initial Overlay is rendered. Can be used to manipulate the content of the panel. * @type YAHOO.util.CustomEvent */ /** * @event windowInsertImageRender * @param {Overlay} panel The Overlay object that is used to create the window. * @param {HTMLElement} body The HTML element used as the body of the window.. * @param {Toolbar} toolbar A reference to the toolbar object used inside this window. * @description Event fired when the pre render of the Insert Image window has finished. * @type YAHOO.util.CustomEvent */ /** * @event windowCreateLinkRender * @param {Overlay} panel The Overlay object that is used to create the window. * @param {HTMLElement} body The HTML element used as the body of the window.. * @description Event fired when the pre render of the Create Link window has finished. * @type YAHOO.util.CustomEvent */ /** * @description Class to hold Window information between uses. We use the same panel to show the windows, so using this will allow you to configure a window before it is shown. * This is what you pass to Editor.openWindow();. These parameters will not take effect until the openWindow() is called in the editor. * @class EditorWindow * @param {String} name The name of the window. * @param {Object} attrs Attributes for the window. Current attributes used are : height and width */ YAHOO.widget.EditorWindow = function(name, attrs) { /** * @private * @property name * @description A unique name for the window */ this.name = name.replace(' ', '_'); /** * @private * @property attrs * @description The window attributes */ this.attrs = attrs; }; YAHOO.widget.EditorWindow.prototype = { /** * @private * @property header * @description Holder for the header of the window, used in Editor.openWindow */ header: null, /** * @private * @property body * @description Holder for the body of the window, used in Editor.openWindow */ body: null, /** * @private * @property footer * @description Holder for the footer of the window, used in Editor.openWindow */ footer: null, /** * @method setHeader * @description Sets the header for the window. * @param {String/HTMLElement} str The string or DOM reference to be used as the windows header. */ setHeader: function(str) { this.header = str; }, /** * @method setBody * @description Sets the body for the window. * @param {String/HTMLElement} str The string or DOM reference to be used as the windows body. */ setBody: function(str) { this.body = str; }, /** * @method setFooter * @description Sets the footer for the window. * @param {String/HTMLElement} str The string or DOM reference to be used as the windows footer. */ setFooter: function(str) { this.footer = str; }, /** * @method toString * @description Returns a string representing the EditorWindow. * @return {String} */ toString: function() { return 'Editor Window (' + this.name + ')'; } }; })(); YAHOO.register("editor", YAHOO.widget.Editor, {version: "2.7.0", build: "1796"});
/* eslint no-unused-expressions: 0 */ describe('initializers', function() { it('run the initilizer', async function() { expect(global.enabledInitializerVar).to.be.true }) it('don\'t run the initilizer', async function() { expect(global.disabledInitializerVar).to.be.undefined }) })
'use strict'; var fs = require('fs'); var http = require('http'); var https = require('https'); var express = require('express'); var bodyParser = require('body-parser'); var socketio = require('socket.io'); var inherits = require('util').inherits; var BaseService = require('../service'); var bitcore = require('bitcore-lib'); var _ = bitcore.deps._; var index = require('../'); var log = index.log; /** * This service represents a hub for combining several services over a single HTTP port. Services * can extend routes by implementing the methods `getRoutePrefix` and `setupRoutes`. Additionally * events that are exposed via the `getPublishEvents` and API methods exposed via `getAPIMethods` * will be available over a socket.io connection. * * @param {Object} options * @param {Node} options.node - A reference to the node * @param {Boolean} options.https - Enable https, will default to node.https settings. * @param {Object} options.httpsOptions - Options passed into https.createServer, defaults to node settings. * @param {String} options.httpsOptions.key - Path to key file * @param {String} options.httpsOptions.cert - Path to cert file * @param {Boolean} options.enableSocketRPC - Option to enable/disable websocket RPC handling * @param {Number} options.port - The port for the service, defaults to node settings. */ var WebService = function(options) { var self = this; this.node = options.node; this.https = options.https || this.node.https; this.httpsOptions = options.httpsOptions || this.node.httpsOptions; this.port = options.port || this.node.port || 3456; // set the maximum size of json payload, defaults to express default // see: https://github.com/expressjs/body-parser#limit this.jsonRequestLimit = options.jsonRequestLimit || '100kb'; this.enableSocketRPC = _.isUndefined(options.enableSocketRPC) ? WebService.DEFAULT_SOCKET_RPC : options.enableSocketRPC; this.node.on('ready', function() { self.eventNames = self.getEventNames(); self.setupAllRoutes(); self.server.listen(self.port); self.createMethodsMap(); }); }; inherits(WebService, BaseService); WebService.dependencies = []; WebService.DEFAULT_SOCKET_RPC = true; /** * Called by Node to start the service * @param {Function} callback */ WebService.prototype.start = function(callback) { this.app = express(); this.app.use(bodyParser.json({limit: this.jsonRequestLimit})); if(this.https) { this.transformHttpsOptions(); this.server = https.createServer(this.httpsOptions, this.app); } else { this.server = http.createServer(this.app); } this.io = socketio.listen(this.server); this.io.on('connection', this.socketHandler.bind(this)); setImmediate(callback); }; /** * Called by Node. stop the service * @param {Function} callback */ WebService.prototype.stop = function(callback) { var self = this; setImmediate(function() { if(self.server) { self.server.close(); } callback(); }); }; /** * This function will iterate over all of the available services gathering * all of the exposed HTTP routes. */ WebService.prototype.setupAllRoutes = function() { for(var key in this.node.services) { var subApp = new express(); var service = this.node.services[key]; if(service.getRoutePrefix && service.setupRoutes) { this.app.use('/' + this.node.services[key].getRoutePrefix(), subApp); this.node.services[key].setupRoutes(subApp, express); } else { log.debug('No routes defined for: ' + key); } } }; /** * This function will construct an API methods map of all of the * available methods that can be called from enable services. */ WebService.prototype.createMethodsMap = function() { var self = this; var methods = this.node.getAllAPIMethods(); this.methodsMap = {}; methods.forEach(function(data) { var name = data[0]; var instance = data[1]; var method = data[2]; var args = data[3]; self.methodsMap[name] = { fn: function() { return method.apply(instance, arguments); }, args: args }; }); }; /** * This function will gather all of the available events exposed from * the enabled services. */ WebService.prototype.getEventNames = function() { var events = this.node.getAllPublishEvents(); var eventNames = []; function addEventName(name) { if(eventNames.indexOf(name) > -1) { throw new Error('Duplicate event ' + name); } eventNames.push(name); } events.forEach(function(event) { addEventName(event.name); if(event.extraEvents) { event.extraEvents.forEach(function(name) { addEventName(name); }); } }); return eventNames; }; WebService.prototype._getRemoteAddress = function(socket) { return socket.client.request.headers['cf-connecting-ip'] || socket.conn.remoteAddress; }; /** * This function is responsible for managing a socket.io connection, including * instantiating a new Bus, subscribing/unsubscribing and handling RPC commands. * @param {Socket} socket - A socket.io socket instance */ WebService.prototype.socketHandler = function(socket) { var self = this; var remoteAddress = self._getRemoteAddress(socket); var bus = this.node.openBus({remoteAddress: remoteAddress}); if (this.enableSocketRPC) { socket.on('message', this.socketMessageHandler.bind(this)); } socket.on('subscribe', function(name, params) { log.info(remoteAddress, 'web socket subscribe:', name); bus.subscribe(name, params); }); socket.on('unsubscribe', function(name, params) { log.info(remoteAddress, 'web socket unsubscribe:', name); bus.unsubscribe(name, params); }); this.eventNames.forEach(function(eventName) { bus.on(eventName, function() { if(socket.connected) { var results = []; for(var i = 0; i < arguments.length; i++) { results.push(arguments[i]); } var params = [eventName].concat(results); socket.emit.apply(socket, params); } }); }); socket.on('disconnect', function() { log.info(remoteAddress, 'web socket disconnect'); bus.close(); }); }; /** * This method will handle incoming RPC messages to a socket.io connection, * call the appropriate method, and respond with the result. * @param {Object} message - The socket.io "message" object * @param {Function} socketCallback */ WebService.prototype.socketMessageHandler = function(message, socketCallback) { if (this.methodsMap[message.method]) { var params = message.params; if(!params || !params.length) { params = []; } if(params.length !== this.methodsMap[message.method].args) { return socketCallback({ error: { message: 'Expected ' + this.methodsMap[message.method].args + ' parameter(s)' } }); } var callback = function(err, result) { var response = {}; if(err) { response.error = { message: err.toString() }; } if(result) { response.result = result; } socketCallback(response); }; params = params.concat(callback); this.methodsMap[message.method].fn.apply(this, params); } else { socketCallback({ error: { message: 'Method Not Found' } }); } }; /** * This method will read `key` and `cert` from disk based on `httpsOptions` and * replace the options with the files. */ WebService.prototype.transformHttpsOptions = function() { if(!this.httpsOptions || !this.httpsOptions.key || !this.httpsOptions.cert) { throw new Error('Missing https options'); } this.httpsOptions = { key: fs.readFileSync(this.httpsOptions.key), cert: fs.readFileSync(this.httpsOptions.cert) }; }; module.exports = WebService;
const serializer = require('./serializer') module.exports = (data, model, options = {baseUrl: '/'}) => { return serializer(options).serialize(JSON.parse(JSON.stringify(data)), model) }
import React from 'react'; import Post from './Post.js'; import {Decorator as Cerebral} from 'cerebral-react'; @Cerebral({ posts: ['posts'] }) class PostsList extends React.Component { renderPost(post_id, index) { return <Post key={index} index={index} post={this.props.posts[post_id]}/>; } render() { return ( <section id="main"> <ul className="list-group"> {Object.keys(this.props.posts) .map(this.renderPost.bind(this))} </ul> </section> ); } } export default PostsList;
define(function(require) { var Loader = require('../lib/loader'); var Actors = require('../lib/actor'); var Input = require('../lib/input'); var Sheets = require('../lib/sheets'); var Paths = require('../lib/path'); var Audio = require('../lib/audio'); var Effects = require('../lib/effects'); var Particles = require('../lib/particles'); var Enlil = { version: '0.0.3', }; function delay(seconds) { } function onLoaderChange(newState) { console.log(newState); switch (newState) { case 'finished': break; } Enlil.loadingDiv.innerHTML = 'STATUS: ' + newState; } function loadPackage(url, stageDiv, startFunc) { Enlil.stageDiv = document.getElementById(stageDiv); Enlil.loadingDiv = document.createElement('div'); Enlil.loadingDiv.style.position = "absolute"; Enlil.stageDiv.appendChild(Enlil.loadingDiv); Loader.addObserver(onLoaderChange); Loader.requestPackage(url, startFunc); } function loadAudio(url, callback) { var afterloaded = function(buffer) { var typedArray = new Uint8Array(buffer); var index; Audio.init(); if ((index = Audio.decodeMidiAsset(typedArray)) == -1) index = Audio.decodeAudioAsset(buffer); callback(index); }; Loader.requestBinaryData(url, afterloaded); } function playAudio(index, when, loop) { Audio.play(index, when, loop); } function startFPS() { Enlil.fps = 0; Enlil.frameCount = 0; Enlil.animCount = 0; Enlil.lastTimestamp = new Date(); Enlil.currTimestamp = new Date(); Enlil.avgDelay = 0; } function drawFrame() { var i; var locations; var rollover; var actors = Actors.getAll(); /* Calculate location and animation frame. */ locations = Paths.interpolateAll(); /* Draw the stage background first. */ actors[0].draw(0, 0, 0); for (i = 1; i < actors.length; i++) { /* Draw actor with specified group? */ if (locations[i - 1].gid) { var sheet = actors[i].getSheet(); if(!sheet)continue; rollover = sheet.getGroupLength(locations[i - 1].gid); actors[i].drawGroup(locations[i - 1].gid, Enlil.animCount % rollover, locations[i - 1].x, locations[i - 1].y); } else { /* Don't use groups, just raw offset. */ actors[i].draw(Enlil.animCount % 4, locations[i - 1].x, locations[i - 1].y); } } } function tick() { Enlil.frameCount++; Enlil.currTimestamp = new Date(); var delay = Enlil.currTimestamp - Enlil.lastTimestamp; Enlil.avgDelay += (delay - Enlil.avgDelay) / 10; Enlil.lastTimestamp = Enlil.currTimestamp; Enlil.fps = (1000 / Enlil.avgDelay).toFixed(1); if (Enlil.frameCount % 5 === 0) Enlil.animCount++; } function registerRunLoop(func) { Enlil.runLoop = func; } function addEventHandler(node, type, handler, matchFunc) { Input.addHandler(node, type, handler, matchFunc); } var requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback) { window.setTimeout(callback, 1000 / 60); }; })(); function animFrame() { Input.processHandlers(); Effects.processEffects(); if(Enlil.frameCount % 5 === 0) Particles.processParticles(); Enlil.runLoop(); requestAnimFrame(animFrame); } function start() { animFrame(); } Enlil.delay = delay; Enlil.loadPackage = loadPackage; Enlil.loadAudio = loadAudio; Enlil.playAudio = playAudio; Enlil.startFPS = startFPS; Enlil.drawFrame = drawFrame; Enlil.tick = tick; Enlil.registerRunLoop = registerRunLoop; Enlil.addEventHandler = addEventHandler; Enlil.start = start; return Enlil; });
import React from 'react'; import Loadable from 'react-loadable'; import LoadingComponent from '../../components/LoadingComponent/LoadingComponent'; import { RestrictedRoute } from '../../containers/RestrictedRoute'; import { Route, Switch } from 'react-router-dom'; function MyLoadable(opts, preloadComponents) { return Loadable(Object.assign({ loading: LoadingComponent, render(loaded, props) { if(preloadComponents!==undefined && preloadComponents instanceof Array){ preloadComponents.map(component=>component.preload()); } let Component = loaded.default; return <Component {...props}/>; } }, opts)); }; const AsyncDashboard = MyLoadable({loader: () => import('../../containers/Dashboard/Dashboard')}); const AsyncAbout = MyLoadable({loader: () => import('../../containers/About/About')}); const AsyncPublicChats = MyLoadable({loader: () => import('../../containers/PublicChats/PublicChats')}); const AsyncMyAccount = MyLoadable({loader: () => import('../../containers/MyAccount/MyAccount')}); const AsyncPredefinedChatMessages = MyLoadable({loader: () => import('../../containers/PredefinedChatMessages/PredefinedChatMessages')}); const AsyncTask = MyLoadable({loader: () => import('../../containers/Tasks/Task')}); const AsyncTasks = MyLoadable({loader: () => import('../../containers/Tasks/Tasks')}, [AsyncTask]); const AsyncRole = MyLoadable({loader: () => import('../../containers/Roles/Role')}); const AsyncRoles = MyLoadable({loader: () => import('../../containers/Roles/Roles')}, AsyncRole); const AsyncChat = MyLoadable({loader: () => import('../../containers/Chats/Chat')}); const AsyncCreateChat = MyLoadable({loader: () => import('../../containers/Chats/CreateChat')}); const AsyncChats = MyLoadable({loader: () => import('../../containers/Chats/Chats')}, [AsyncChat, AsyncCreateChat]); const AsyncCompany = MyLoadable({loader: () => import('../../containers/Companies/Company')}); const AsyncCompanies = MyLoadable({loader: () => import('../../containers/Companies/Companies')}, [AsyncCompany]); const AsyncCampaign = MyLoadable({loader: () => import('../../containers/Campaigns/Campaign')}); const AsyncCampaigns = MyLoadable({loader: () => import('../../containers/Campaigns/Campaigns')}, [AsyncCampaign]); const AsyncAsset = MyLoadable({loader: () => import('../../containers/Assets/Asset')}); const AsyncAssets = MyLoadable({loader: () => import('../../containers/Assets/Assets')}, [AsyncAsset]); const AsyncCampaignPage= MyLoadable({loader: () => import('../../containers/Campaigns/CampaignPage')},); const AsyncUser = MyLoadable({loader: () => import('../../containers/Users/User')}); const AsyncUsers = MyLoadable({loader: () => import('../../containers/Users/Users')}, [AsyncUser]); const AsyncSignIn = MyLoadable({loader: () => import('../../containers/SignIn/SignIn')}); const AsyncPageNotFound = MyLoadable({loader: () => import('../../components/PageNotFound/PageNotFound')}); const Routes = (props, context) => { return ( <Switch > <RestrictedRoute type='private' path="/" exact component={AsyncDashboard} /> <RestrictedRoute type='private' path="/dashboard" exact component={AsyncDashboard} /> <RestrictedRoute type='private' path="/loading" exact component={LoadingComponent} /> <RestrictedRoute type='private' path="/public_chats" exact component={AsyncPublicChats} /> <RestrictedRoute type='private' path="/tasks" exact component={AsyncTasks} /> <RestrictedRoute type='private' path="/tasks/edit/:uid" exact component={AsyncTask} /> <RestrictedRoute type='private' path="/tasks/create" exact component={AsyncTask} /> <RestrictedRoute type='private' path="/roles" exact component={AsyncRoles} /> <RestrictedRoute type='private' path="/roles/edit/:uid" exact component={AsyncRole} /> <RestrictedRoute type='private' path="/roles/create" exact component={AsyncRole} /> <RestrictedRoute type='private' path="/companies" exact component={AsyncCompanies} /> <RestrictedRoute type='private' path="/companies/edit/:uid" exact component={AsyncCompany} /> <RestrictedRoute type='private' path="/companies/create" exact component={AsyncCompany} /> <RestrictedRoute type='private' path="/campaigns" exact component={AsyncCampaigns} /> <RestrictedRoute type='private' path="/campaigns/edit/:uid" exact component={AsyncCampaign} /> <RestrictedRoute type='private' path="/campaigns/create" exact component={AsyncCampaign} /> <RestrictedRoute type='private' path="/assets" exact component={AsyncAssets} /> <RestrictedRoute type='private' path="/assets/edit/:uid" exact component={AsyncAsset} /> <RestrictedRoute type='private' path="/assets/create" exact component={AsyncAsset} /> <RestrictedRoute type='private' path="/campaigns/:uid" exact component={AsyncCampaignPage} /> <RestrictedRoute type='private' path="/predefined_chat_messages" exact component={AsyncPredefinedChatMessages} /> <RestrictedRoute type='private' path="/chats" exact component={AsyncChats} /> <RestrictedRoute type='private' path="/chats/edit/:uid" exact component={AsyncChat} /> <RestrictedRoute type='private' path="/chats/create" exact component={AsyncCreateChat} /> <RestrictedRoute type='private' path="/users" exact component={AsyncUsers} /> <RestrictedRoute type='private' path="/users/edit/:uid/:editType" exact component={AsyncUser} /> <RestrictedRoute type='private' path="/about" exact component={AsyncAbout} /> <RestrictedRoute type='private' path="/my_account" exact component={AsyncMyAccount} /> <RestrictedRoute type='public' path="/signin" component={AsyncSignIn} /> <Route component={AsyncPageNotFound} /> </Switch> ); } export default Routes;
var path = require('path'); var calypso = require('calypso'); var LevelDriver = require('calypso-level'); var levelup = require('levelup'); var medeadown = require('medeadown'); var Query = calypso.Query; var medea = require('medea'); var async = require('async'); var Registry = module.exports = function(opts){ opts = opts || {}; var self = this; this.collection = opts.collection; if (opts.db) { this.db = opts.db; } else { this.location = path.join(process.cwd(), opts.path); this.compactor = medea(); } this.session = null; }; Registry.prototype._init = function(cb) { var self = this; function buildCalypsoEngine(cb) { var map = {}; map[self.collection] = self.db; var driver = LevelDriver.create({ collectionMap: map }); var engine = calypso.configure({ driver: driver }); engine.build(function(err, connection) { if (err) { cb(err); return; } self.session = connection.createSession(); cb(); }); } if(this.compactor) { async.series([ function(next) { self.compactor.open(self.location, next); }, function(next) { self.compactor.compact(next); }, function(next) { self.compactor.close(next); } ], function(err) { if(err) { cb(err); } else { self.db = levelup(self.location, { db: medeadown, valueEncoding: 'json' }); buildCalypsoEngine(cb); } }); } else { buildCalypsoEngine(cb); } }; Registry.prototype.match = function(query, value, cb) { if (!this.session) { var self = this; this._init(function(err) { if (err) { cb(err); return; } self._match(query, value, cb); }); } else { this._match(query, value, cb); } }; Registry.prototype._match = function(query, value, cb) { var match; try { match = this.session.match(query, value); } catch (err) { cb(err); return; } cb(null, match); }; Registry.prototype.find = function(query, cb) { if (!this.session) { var self = this; this._init(function(err) { if (err) { cb(err); return; } self._find(query, cb); }); } else { this._find(query, cb); } }; Registry.prototype._find = function(q, cb) { var query = Query.of(this.collection); if (q instanceof Query) { query = q; } else if (typeof q === 'object') { Object.keys(q).forEach(function(key) { query = query.where(key, { eq: q[key] }); }); } else { query = query.ql(q); } // run a match to test if the query is valid try { this.session.match(query, {}); } catch(err) { return cb(err); } this.session.find(query, function(err, results) { if(err) { cb(err); } else { var objects = []; results.forEach(function(peer) { if(typeof peer === 'string') { peer = JSON.parse(peer); } objects.push(peer); }); cb(null, objects); } }); }; Registry.prototype.get = function(id, cb) { this.db.get(id, { valueEncoding: 'json' }, function(err, result){ if(err) { cb(err); } else { if(typeof result === 'object') { cb(null, result); } else { cb(null, JSON.parse(result)); } } }); }; Registry.prototype.close = function() { this.db.close.apply(this.db, arguments); };
/** * Styles a row in the invoice table. Moved to a general component so it can consistently style both the header and * body rows (which are in different files). This is a bit klutzy: better to style each individually - but it's * simple & practical for this situation. */ import styled from 'styled-components'; const StyledRow = styled.div` margin: 0; &.header-row { border-bottom: 2px solid #999999; > div { font-weight: bold; } } &>div { padding: 2px 0; } select { margin-left: 4px; height: 26px; } .price-field input { width: 100%; } .total-field span, .delete-item span { display: inline-block; margin: 2px 0 0 4px; } `; export default StyledRow;
var React = require('react'); module.exports = React.createClass({displayName: "exports", getInitialState: function() { return { items: this.props.items, disabled: true } }, componentDidMount: function() { this.setState({ disabled: false }) }, handleClick: function() { this.setState({ items: this.state.items.concat('Item ' + this.state.items.length) }) }, render: function() { return ( React.createElement("div", null, React.createElement("button", {onClick: this.handleClick, disabled: this.state.disabled}, "Add Item"), React.createElement("ul", null, this.state.items.map(function(item) { return React.createElement("li", null, item) }) ) ) ) }, });
function increment() { return { type: 'INCREMENT_COUNTER' }; } function incrementAsync() { return dispatch => { setTimeout(() => { dispatch(increment()); }, 1000); }; } store.dispatch(incrementAsync());
'use strict'; const expect = require('chai').expect; const SilentError = require('silent-error'); const TestServerTask = require('../../../lib/tasks/test-server'); const MockProject = require('../../helpers/mock-project'); const MockUI = require('console-ui/mock'); const MockWatcher = require('../../helpers/mock-watcher'); describe('test server', function() { let subject; it('transforms the options and invokes testem properly', function(done) { let ui = new MockUI(); let watcher = new MockWatcher(); subject = new TestServerTask({ project: new MockProject(), ui, addonMiddlewares() { return ['middleware1', 'middleware2']; }, testem: { startDev(options) { expect(options.host).to.equal('greatwebsite.com'); expect(options.port).to.equal(123324); expect(options.cwd).to.equal('blerpy-derpy'); expect(options.reporter).to.equal('xunit'); expect(options.middleware).to.deep.equal(['middleware1', 'middleware2']); expect(options.test_page).to.equal('http://my/test/page'); expect(options.config_dir).to.be.an('string'); done(); }, }, }); subject.run({ host: 'greatwebsite.com', port: 123324, reporter: 'xunit', outputPath: 'blerpy-derpy', watcher, testPage: 'http://my/test/page', }); watcher.emit('change'); }); describe('completion', function() { let ui, watcher, subject, runOptions; before(function() { ui = new MockUI(); watcher = new MockWatcher(); runOptions = { reporter: 'xunit', outputPath: 'blerpy-derpy', watcher, testPage: 'http://my/test/page', }; subject = new TestServerTask({ project: new MockProject(), ui, addonMiddlewares() { return ['middleware1', 'middleware2']; }, testem: { startDev(options, finalizer) { throw new TypeError('startDev not implemented'); }, }, }); }); describe('firstRun', function() { it('rejects with testem exceptions', function() { let error = new Error('OMG'); subject.testem.startDev = function(options, finalizer) { finalizer(1, error); }; let runResult = subject.run(runOptions).then(function() { expect(true, 'should have rejected, but fulfilled').to.be.false; }, function(reason) { expect(reason).to.eql(error); }); watcher.emit('change'); return runResult; }); it('rejects with exit status (1)', function() { let error = new SilentError('Testem finished with non-zero exit code. Tests failed.'); subject.testem.startDev = function(options, finalizer) { finalizer(1); }; let runResult = subject.run(runOptions).then(function() { expect(true, 'should have rejected, but fulfilled').to.be.false; }, function(reason) { expect(reason).to.eql(error); }); watcher.emit('change'); return runResult; }); it('resolves with exit status (0)', function() { subject.testem.startDev = function(options, finalizer) { finalizer(0); }; let runResult = subject.run(runOptions).then(function(value) { expect(value, 'expected exist status of 0').to.eql(0); }); watcher.emit('change'); return runResult; }); }); describe('restart', function() { it('rejects with testem exceptions', function() { let error = new Error('OMG'); subject.testem.startDev = function(options, finalizer) { finalizer(0); }; let runResult = subject.run(runOptions); watcher.emit('change'); return runResult.then(function() { subject.testem.startDev = function(options, finalizer) { finalizer(0, error); }; runResult = subject.run(runOptions).then(function() { expect(true, 'should have rejected, but fulfilled').to.be.false; }, function(reason) { expect(reason).to.eql(error); }); watcher.emit('change'); return runResult; }); }); }); }); });
/*jshint node:true */ 'use strict'; /** * Returns the package for the given name if found or undefined otherwise * * @param {String} The name of the package to try to load * * @return {*} */ module.exports = function optionale(optionalDependency) { try { return require(optionalDependency); } catch (ignore) { } };
var Man = function(name){ this.name = name; } Man.prototype.showName = function(){ console.log('hello ' + this.name); return 'hello ' + this.name; } module.exports = Man;
'use strict'; /*global m */ // todo modules var app = require('./app'); var model = require('./model'); require('./header'); require('./new-task'); require('./list-of-tasks'); require('./task'); require('./footer'); module.exports = m.element('todos-demo', { controller: function(){ // Todo collection app.todos = new model.Todos(); // Todo list filter app.filter = m.prop(m.route.param('filter') || ''); }, view: function(){ return m('#todoapp',[ m('header',[ m('new-task') ]), m('list-of-tasks', [ m('$task') ]), m('footer') ]); } });
// AMD Wrapper Header define(function(require, exports, module) { // moment.js language configuration // language : danish (da) // author : Ulrik Nielsen : https://github.com/mrbase require('../moment').lang('da', { months : "Januar_Februar_Marts_April_Maj_Juni_Juli_August_September_Oktober_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_Maj_Jun_Jul_Aug_Sep_Okt_Nov_Dec".split("_"), weekdays : "Sรธndag_Mandag_Tirsdag_Onsdag_Torsdag_Fredag_Lรธrdag".split("_"), weekdaysShort : "Sรธn_Man_Tir_Ons_Tor_Fre_Lรธr".split("_"), weekdaysMin : "Sรธ_Ma_Ti_On_To_Fr_Lรธ".split("_"), longDateFormat : { LT : "h:mm A", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY h:mm A", LLLL : "dddd D. MMMM, YYYY h:mm A" }, calendar : { sameDay : '[I dag kl.] LT', nextDay : '[I morgen kl.] LT', nextWeek : 'dddd [kl.] LT', lastDay : '[I gรฅr kl.] LT', lastWeek : '[sidste] dddd [kl] LT', sameElse : 'L' }, relativeTime : { future : "om %s", past : "%s siden", s : "fรฅ sekunder", m : "minut", mm : "%d minutter", h : "time", hh : "%d timer", d : "dag", dd : "%d dage", M : "mรฅnede", MM : "%d mรฅneder", y : "รฅr", yy : "%d รฅr" }, ordinal : '%d.', week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); // AMD Wrapper Footer });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. JavaScript code in this file should be added after the last require_* statement. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require angular //= require turbolinks //= require_tree .
pc.extend(pc, function () { 'use strict'; var EVENT_RESIZE = 'resizecanvas'; // Exceptions function UnsupportedBrowserError(message) { this.name = "UnsupportedBrowserError"; this.message = (message || ""); } UnsupportedBrowserError.prototype = Error.prototype; function ContextCreationError(message) { this.name = "ContextCreationError"; this.message = (message || ""); } ContextCreationError.prototype = Error.prototype; var _contextLostHandler = function () { logWARNING("Context lost."); }; var _contextRestoredHandler = function () { logINFO("Context restored."); }; var _createContext = function (canvas, options) { var names = ["webgl", "experimental-webgl"]; var context = null; for (var i = 0; i < names.length; i++) { try { context = canvas.getContext(names[i], options); } catch(e) {} if (context) { break; } } return context; }; var _downsampleImage = function (image, size) { var srcW = image.width; var srcH = image.height; if ((srcW > size) || (srcH > size)) { var scale = size / Math.max(srcW, srcH); var dstW = Math.floor(srcW * scale); var dstH = Math.floor(srcH * scale); console.warn('Image dimensions larger than max supported texture size of ' + size + '. ' + 'Resizing from ' + srcW + ', ' + srcH + ' to ' + dstW + ', ' + dstH + '.'); var canvas = document.createElement('canvas'); canvas.width = dstW; canvas.height = dstH; var context = canvas.getContext('2d'); context.drawImage(image, 0, 0, srcW, srcH, 0, 0, dstW, dstH); return canvas; } return image; }; function _isIE() { var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); var trident = navigator.userAgent.match(/Trident.*rv\:11\./); return (msie > 0 || !!trident); }; var _pixelFormat2Size = null; function gpuTexSize(gl, tex) { if (!_pixelFormat2Size) { _pixelFormat2Size = {}; _pixelFormat2Size[pc.PIXELFORMAT_A8] = 1; _pixelFormat2Size[pc.PIXELFORMAT_L8] = 1; _pixelFormat2Size[pc.PIXELFORMAT_L8_A8] = 1; _pixelFormat2Size[pc.PIXELFORMAT_R5_G6_B5] = 2; _pixelFormat2Size[pc.PIXELFORMAT_R5_G5_B5_A1] = 2; _pixelFormat2Size[pc.PIXELFORMAT_R4_G4_B4_A4] = 2; _pixelFormat2Size[pc.PIXELFORMAT_R8_G8_B8] = 4; _pixelFormat2Size[pc.PIXELFORMAT_R8_G8_B8_A8] = 4; _pixelFormat2Size[pc.PIXELFORMAT_RGB16F] = 8; _pixelFormat2Size[pc.PIXELFORMAT_RGBA16F] = 8; _pixelFormat2Size[pc.PIXELFORMAT_RGB32F] = 16; _pixelFormat2Size[pc.PIXELFORMAT_RGBA32F] = 16; } var mips = 1; if (tex.autoMipmap || tex._minFilter===gl.NEAREST_MIPMAP_NEAREST || tex._minFilter===gl.NEAREST_MIPMAP_LINEAR || tex._minFilter===gl.LINEAR_MIPMAP_NEAREST || tex._minFilter===gl.LINEAR_MIPMAP_LINEAR) { mips = Math.round(Math.log2(Math.max(tex._width, tex._height)) + 1); } var mipWidth = tex._width; var mipHeight = tex._height; var size = 0; for(var i=0; i<mips; i++) { if (!tex._compressed) { size += mipWidth * mipHeight * _pixelFormat2Size[tex._format]; } else if (tex._format===pc.PIXELFORMAT_ETC1) { size += Math.floor((mipWidth + 3) / 4) * Math.floor((mipHeight + 3) / 4) * 8; } else if (tex._format===pc.PIXELFORMAT_PVRTC_2BPP_RGB_1 || tex._format===pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1) { size += Math.max(mipWidth, 16) * Math.max(mipHeight, 8) / 4; } else if (tex._format===pc.PIXELFORMAT_PVRTC_4BPP_RGB_1 || tex._format===pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1) { size += Math.max(mipWidth, 8) * Math.max(mipHeight, 8) / 2; } else { var DXT_BLOCK_WIDTH = 4; var DXT_BLOCK_HEIGHT = 4; var blockSize = tex._format===pc.PIXELFORMAT_DXT1? 8 : 16; var numBlocksAcross = Math.floor((mipWidth + DXT_BLOCK_WIDTH - 1) / DXT_BLOCK_WIDTH); var numBlocksDown = Math.floor((mipHeight + DXT_BLOCK_HEIGHT - 1) / DXT_BLOCK_HEIGHT); var numBlocks = numBlocksAcross * numBlocksDown; size += numBlocks * blockSize; } mipWidth = Math.max(mipWidth * 0.5, 1); mipHeight = Math.max(mipHeight * 0.5, 1); } if (tex._cubemap) size *= 6; return size; }; /** * @name pc.GraphicsDevice * @class The graphics device manages the underlying graphics context. It is responsible * for submitting render state changes and graphics primitives to the hardware. A graphics * device is tied to a specific canvas HTML element. It is valid to have more than one * canvas element per page and create a new graphics device against each. * @constructor Creates a new graphics device. * @param {Object} canvas The canvas to which the graphics device is tied. * @param {Object} [options] Options passed when creating the WebGL context. More info here https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/getContext * @property {Number} width Width of the back buffer in pixels (read-only). * @property {Number} height Height of the back buffer in pixels (read-only). * @property {Number} maxAnisotropy The maximum supported texture anisotropy setting (read-only). * @property {Number} maxCubeMapSize The maximum supported dimension of a cube map (read-only). * @property {Number} maxTextureSize The maximum supported dimension of a texture (read-only). * is attached is fullscreen or not. */ /** * @event * @name pc.GraphicsDevice#resizecanvas * @description The 'resizecanvas' event is fired when the canvas is resized * @param {Number} width The new width of the canvas in pixels * @param {Number} height The new height of the canvas in pixels */ var GraphicsDevice = function (canvas, options) { this.gl = undefined; this.canvas = canvas; this.shader = null; this.indexBuffer = null; this.vertexBuffers = []; this.precision = "highp"; this.enableAutoInstancing = false; this.autoInstancingMaxObjects = 16384; this.attributesInvalidated = true; this.boundBuffer = null; this.instancedAttribs = {}; this.enabledAttributes = {}; this.textureUnits = []; this.commitFunction = {}; this._maxPixelRatio = 1; // local width/height without pixelRatio applied this._width = 0; this._height = 0; if (!window.WebGLRenderingContext) { throw new pc.UnsupportedBrowserError(); } // Retrieve the WebGL context if (canvas) { this.gl = _createContext(canvas, options); } if (!this.gl) { throw new pc.ContextCreationError(); } var gl = this.gl; // put the rest of the contructor in a function // so that the constructor remains small. Small constructors // are optimized by Firefox due to type inference (function() { var i; canvas.addEventListener("webglcontextlost", _contextLostHandler, false); canvas.addEventListener("webglcontextrestored", _contextRestoredHandler, false); this.canvas = canvas; this.shader = null; this.indexBuffer = null; this.vertexBuffers = []; this.precision = 'highp'; this.maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE); this.maxCubeMapSize = gl.getParameter(gl.MAX_CUBE_MAP_TEXTURE_SIZE); this.maxRenderBufferSize = gl.getParameter(gl.MAX_RENDERBUFFER_SIZE); // Query the precision supported by ints and floats in vertex and fragment shaders var vertexShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_FLOAT); var vertexShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_FLOAT); var vertexShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_FLOAT); var fragmentShaderPrecisionHighpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_FLOAT); var fragmentShaderPrecisionMediumpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_FLOAT ); var fragmentShaderPrecisionLowpFloat = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_FLOAT); var vertexShaderPrecisionHighpInt = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.HIGH_INT); var vertexShaderPrecisionMediumpInt = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.MEDIUM_INT); var vertexShaderPrecisionLowpInt = gl.getShaderPrecisionFormat(gl.VERTEX_SHADER, gl.LOW_INT); var fragmentShaderPrecisionHighpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.HIGH_INT); var fragmentShaderPrecisionMediumpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.MEDIUM_INT); var fragmentShaderPrecisionLowpInt = gl.getShaderPrecisionFormat(gl.FRAGMENT_SHADER, gl.LOW_INT); var highpAvailable = vertexShaderPrecisionHighpFloat.precision > 0 && fragmentShaderPrecisionHighpFloat.precision > 0; var mediumpAvailable = vertexShaderPrecisionMediumpFloat.precision > 0 && fragmentShaderPrecisionMediumpFloat.precision > 0; if (!highpAvailable) { if (mediumpAvailable) { this.precision = "mediump"; console.warn("WARNING: highp not supported, using mediump"); } else { this.precision = "lowp"; console.warn( "WARNING: highp and mediump not supported, using lowp" ); } } this.maxPrecision = this.precision; this.defaultClearOptions = { color: [0, 0, 0, 1], depth: 1, flags: pc.CLEARFLAG_COLOR | pc.CLEARFLAG_DEPTH }; this.glAddress = [ gl.REPEAT, gl.CLAMP_TO_EDGE, gl.MIRRORED_REPEAT ]; this.glBlendEquation = [ gl.FUNC_ADD, gl.FUNC_SUBTRACT, gl.FUNC_REVERSE_SUBTRACT ]; this.glBlendFunction = [ gl.ZERO, gl.ONE, gl.SRC_COLOR, gl.ONE_MINUS_SRC_COLOR, gl.DST_COLOR, gl.ONE_MINUS_DST_COLOR, gl.SRC_ALPHA, gl.SRC_ALPHA_SATURATE, gl.ONE_MINUS_SRC_ALPHA, gl.DST_ALPHA, gl.ONE_MINUS_DST_ALPHA ]; this.glClearFlag = [ 0, gl.COLOR_BUFFER_BIT, gl.DEPTH_BUFFER_BIT, gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, gl.STENCIL_BUFFER_BIT, gl.STENCIL_BUFFER_BIT | gl.COLOR_BUFFER_BIT, gl.STENCIL_BUFFER_BIT | gl.DEPTH_BUFFER_BIT, gl.STENCIL_BUFFER_BIT | gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT ]; this.glFilter = [ gl.NEAREST, gl.LINEAR, gl.NEAREST_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.LINEAR_MIPMAP_LINEAR ]; this.glPrimitive = [ gl.POINTS, gl.LINES, gl.LINE_LOOP, gl.LINE_STRIP, gl.TRIANGLES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN ]; this.glType = [ gl.BYTE, gl.UNSIGNED_BYTE, gl.SHORT, gl.UNSIGNED_SHORT, gl.INT, gl.UNSIGNED_INT, gl.FLOAT ]; // Initialize extensions this.extTextureFloat = gl.getExtension("OES_texture_float"); this.extTextureFloatLinear = gl.getExtension("OES_texture_float_linear"); this.extTextureHalfFloat = gl.getExtension("OES_texture_half_float"); this.extUintElement = gl.getExtension("OES_element_index_uint"); this.maxVertexTextures = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); this.supportsBoneTextures = this.extTextureFloat && this.maxVertexTextures > 0; // Test if we can render to floating-point RGBA texture this.extTextureFloatRenderable = !!this.extTextureFloat; if (this.extTextureFloat) { var __texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, __texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); var __width = 2; var __height = 2; gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, __width, __height, 0, gl.RGBA, gl.FLOAT, null); // Try to use this texture as a render target. var __fbo = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, __fbo); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, __texture, 0); gl.bindTexture(gl.TEXTURE_2D, null); // It is legal for a WebGL implementation exposing the OES_texture_float extension to // support floating-point textures but not as attachments to framebuffer objects. if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) { this.extTextureFloatRenderable = false; } } this.extTextureLod = gl.getExtension('EXT_shader_texture_lod'); this.fragmentUniformsCount = gl.getParameter(gl.MAX_FRAGMENT_UNIFORM_VECTORS); this.samplerCount = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); this.useTexCubeLod = this.extTextureLod && this.samplerCount < 16; this.extDepthTexture = null; //gl.getExtension("WEBKIT_WEBGL_depth_texture"); this.extStandardDerivatives = gl.getExtension("OES_standard_derivatives"); if (this.extStandardDerivatives) { gl.hint(this.extStandardDerivatives.FRAGMENT_SHADER_DERIVATIVE_HINT_OES, gl.NICEST); } this.extTextureFilterAnisotropic = gl.getExtension('EXT_texture_filter_anisotropic'); if (!this.extTextureFilterAnisotropic) { this.extTextureFilterAnisotropic = gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic'); } this.extCompressedTextureS3TC = gl.getExtension('WEBGL_compressed_texture_s3tc'); if (!this.extCompressedTextureS3TC) { this.extCompressedTextureS3TC = gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc'); } if (this.extCompressedTextureS3TC) { if (_isIE()) { // IE 11 can't use mip maps with S3TC this.extCompressedTextureS3TC = false; } } if (this.extCompressedTextureS3TC) { var formats = gl.getParameter(gl.COMPRESSED_TEXTURE_FORMATS); for (i = 0; i < formats.length; i++) { switch (formats[i]) { case this.extCompressedTextureS3TC.COMPRESSED_RGB_S3TC_DXT1_EXT: break; case this.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT1_EXT: break; case this.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT3_EXT: break; case this.extCompressedTextureS3TC.COMPRESSED_RGBA_S3TC_DXT5_EXT: break; default: break; } } } this.extInstancing = gl.getExtension("ANGLE_instanced_arrays"); this.extCompressedTextureETC1 = gl.getExtension('WEBGL_compressed_texture_etc1'); this.extCompressedTexturePVRTC = gl.getExtension('WEBGL_compressed_texture_pvrtc') || gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); this.extDrawBuffers = gl.getExtension('EXT_draw_buffers'); this.maxDrawBuffers = this.extDrawBuffers ? gl.getParameter(this.extDrawBuffers.MAX_DRAW_BUFFERS_EXT) : 1; this.maxColorAttachments = this.extDrawBuffers ? gl.getParameter(this.extDrawBuffers.MAX_COLOR_ATTACHMENTS_EXT) : 1; // Create the default render target this.renderTarget = null; // Create the ScopeNamespace for shader attributes and variables this.scope = new pc.ScopeSpace("Device"); // Define the uniform commit functions this.commitFunction = {}; this.commitFunction[pc.UNIFORMTYPE_BOOL ] = function (locationId, value) { gl.uniform1i(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_INT ] = function (locationId, value) { gl.uniform1i(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_FLOAT] = function (locationId, value) { if (typeof value == "number") gl.uniform1f(locationId, value); else gl.uniform1fv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_VEC2] = function (locationId, value) { gl.uniform2fv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_VEC3] = function (locationId, value) { gl.uniform3fv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_VEC4] = function (locationId, value) { gl.uniform4fv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_IVEC2] = function (locationId, value) { gl.uniform2iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_BVEC2] = function (locationId, value) { gl.uniform2iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_IVEC3] = function (locationId, value) { gl.uniform3iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_BVEC3] = function (locationId, value) { gl.uniform3iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_IVEC4] = function (locationId, value) { gl.uniform4iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_BVEC4] = function (locationId, value) { gl.uniform4iv(locationId, value); }; this.commitFunction[pc.UNIFORMTYPE_MAT2] = function (locationId, value) { gl.uniformMatrix2fv(locationId, false, value); }; this.commitFunction[pc.UNIFORMTYPE_MAT3] = function (locationId, value) { gl.uniformMatrix3fv(locationId, false, value); }; this.commitFunction[pc.UNIFORMTYPE_MAT4] = function (locationId, value) { gl.uniformMatrix4fv(locationId, false, value); }; // Set the initial render state this.setBlending(false); this.setBlendFunction(pc.BLENDMODE_ONE, pc.BLENDMODE_ZERO); this.setBlendEquation(pc.BLENDEQUATION_ADD); this.setColorWrite(true, true, true, true); this.setCullMode(pc.CULLFACE_BACK); this.setDepthTest(true); this.setDepthWrite(true); this.setClearDepth(1); this.setClearColor(0, 0, 0, 0); gl.enable(gl.SCISSOR_TEST); this.programLib = new pc.ProgramLibrary(this); for (var generator in pc.programlib) { this.programLib.register(generator, pc.programlib[generator]); } // Calculate a estimate of the maximum number of bones that can be uploaded to the GPU // based on the number of available uniforms and the number of uniforms required for non- // bone data. This is based off of the Phong shader. A user defined shader may have // even less space available for bones so this calculated value can be overridden via // pc.GraphicsDevice.setBoneLimit. var numUniforms = gl.getParameter(gl.MAX_VERTEX_UNIFORM_VECTORS); numUniforms -= 4 * 4; // Model, view, projection and shadow matrices numUniforms -= 8; // 8 lights max, each specifying a position vector numUniforms -= 1; // Eye position numUniforms -= 4 * 4; // Up to 4 texture transforms this.boneLimit = Math.floor(numUniforms / 4); // HACK: If the number of bones is above ~120-124, performance on the Mac Mini // degrades drastically if (this.boneLimit > 110) { this.boneLimit = 110; } pc.events.attach(this); this.boundBuffer = null; this.instancedAttribs = {}; this.activeTexture = 0; this.textureUnits = []; this.attributesInvalidated = true; this.enabledAttributes = {}; this._drawCallsPerFrame = 0; this._shaderSwitchesPerFrame = 0; this._primsPerFrame = []; for(i=pc.PRIMITIVE_POINTS; i<=pc.PRIMITIVE_TRIFAN; i++) { this._primsPerFrame[i] = 0; } this._vram = { tex: 0, vb: 0, ib: 0 }; // Handle IE11's inability to take UNSIGNED_BYTE as a param for vertexAttribPointer var bufferId = gl.createBuffer(); var storage = new ArrayBuffer(16); gl.bindBuffer(gl.ARRAY_BUFFER, bufferId); gl.bufferData(gl.ARRAY_BUFFER, storage, gl.STATIC_DRAW); gl.getError(); // Clear error flag gl.vertexAttribPointer(0, 4, gl.UNSIGNED_BYTE, false, 4, 0); this.supportsUnsignedByte = (gl.getError() === 0); gl.deleteBuffer(bufferId); }).call(this); }; GraphicsDevice.prototype = { /** * @function * @name pc.GraphicsDevice#setViewport * @description Set the active rectangle for rendering on the specified device. * @param {Number} x The pixel space x-coordinate of the bottom left corner of the viewport. * @param {Number} y The pixel space y-coordinate of the bottom left corner of the viewport. * @param {Number} w The width of the viewport in pixels. * @param {Number} h The height of the viewport in pixels. */ setViewport: function (x, y, width, height) { var gl = this.gl; gl.viewport(x, y, width, height); }, /** * @function * @name pc.GraphicsDevice#setScissor * @description Set the active scissor rectangle on the specified device. * @param {Number} x The pixel space x-coordinate of the bottom left corner of the scissor rectangle. * @param {Number} y The pixel space y-coordinate of the bottom left corner of the scissor rectangle. * @param {Number} w The width of the scissor rectangle in pixels. * @param {Number} h The height of the scissor rectangle in pixels. */ setScissor: function (x, y, width, height) { var gl = this.gl; gl.scissor(x, y, width, height); }, /** * @function * @name pc.GraphicsDevice#getProgramLibrary * @description Retrieves the program library assigned to the specified graphics device. * @returns {pc.ProgramLibrary} The program library assigned to the device. */ getProgramLibrary: function () { return this.programLib; }, /** * @function * @name pc.GraphicsDevice#setProgramLibrary * @description Assigns a program library to the specified device. By default, a graphics * device is created with a program library that manages all of the programs that are * used to render any graphical primitives. However, this function allows the user to * replace the existing program library with a new one. * @param {pc.ProgramLibrary} programLib The program library to assign to the device. */ setProgramLibrary: function (programLib) { this.programLib = programLib; }, /** * @function * @name pc.GraphicsDevice#updateBegin * @description Marks the beginning of a block of rendering. Internally, this function * binds the render target currently set on the device. This function should be matched * with a call to pc.GraphicsDevice#updateEnd. Calls to pc.GraphicsDevice#updateBegin * and pc.GraphicsDevice#updateEnd must not be nested. */ updateBegin: function () { var gl = this.gl; this.boundBuffer = null; this.indexBuffer = null; // Set the render target var target = this.renderTarget; if (target) { // Create a new WebGL frame buffer object if (!target._glFrameBuffer) { target._glFrameBuffer = gl.createFramebuffer(); gl.bindFramebuffer(gl.FRAMEBUFFER, target._glFrameBuffer); var colorBuffer = target._colorBuffer; if (!colorBuffer._glTextureId) { // Clamp the render buffer size to the maximum supported by the device colorBuffer._width = Math.min(colorBuffer.width, this.maxRenderBufferSize); colorBuffer._height = Math.min(colorBuffer.height, this.maxRenderBufferSize); this.setTexture(colorBuffer, 0); } gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, colorBuffer._cubemap ? gl.TEXTURE_CUBE_MAP_POSITIVE_X + target._face : gl.TEXTURE_2D, colorBuffer._glTextureId, 0); if (target._depth) { if (!target._glDepthBuffer) { target._glDepthBuffer = gl.createRenderbuffer(); } gl.bindRenderbuffer(gl.RENDERBUFFER, target._glDepthBuffer); gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, target.width, target.height); gl.bindRenderbuffer(gl.RENDERBUFFER, null); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, target._glDepthBuffer); } // Ensure all is well var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER); switch (status) { case gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT: console.error("ERROR: FRAMEBUFFER_INCOMPLETE_ATTACHMENT"); break; case gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: console.error("ERROR: FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT"); break; case gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS: console.error("ERROR: FRAMEBUFFER_INCOMPLETE_DIMENSIONS"); break; case gl.FRAMEBUFFER_UNSUPPORTED: console.error("ERROR: FRAMEBUFFER_UNSUPPORTED"); break; case gl.FRAMEBUFFER_COMPLETE: break; default: break; } } else { gl.bindFramebuffer(gl.FRAMEBUFFER, target._glFrameBuffer); } } else { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } for (var i = 0; i < 16; i++) { this.textureUnits[i] = null; } }, /** * @function * @name pc.GraphicsDevice#updateEnd * @description Marks the end of a block of rendering. This function should be called * after a matching call to pc.GraphicsDevice#updateBegin. Calls to pc.GraphicsDevice#updateBegin * and pc.GraphicsDevice#updateEnd must not be nested. */ updateEnd: function () { var gl = this.gl; // Unset the render target var target = this.renderTarget; if (target) { gl.bindFramebuffer(gl.FRAMEBUFFER, null); } }, initializeTexture: function (texture) { var gl = this.gl; texture._glTextureId = gl.createTexture(); texture._glTarget = texture._cubemap ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D; switch (texture._format) { case pc.PIXELFORMAT_A8: texture._glFormat = gl.ALPHA; texture._glInternalFormat = gl.ALPHA; texture._glPixelType = gl.UNSIGNED_BYTE; break; case pc.PIXELFORMAT_L8: texture._glFormat = gl.LUMINANCE; texture._glInternalFormat = gl.LUMINANCE; texture._glPixelType = gl.UNSIGNED_BYTE; break; case pc.PIXELFORMAT_L8_A8: texture._glFormat = gl.LUMINANCE_ALPHA; texture._glInternalFormat = gl.LUMINANCE_ALPHA; texture._glPixelType = gl.UNSIGNED_BYTE; break; case pc.PIXELFORMAT_R5_G6_B5: texture._glFormat = gl.RGB; texture._glInternalFormat = gl.RGB; texture._glPixelType = gl.UNSIGNED_SHORT_5_6_5; break; case pc.PIXELFORMAT_R5_G5_B5_A1: texture._glFormat = gl.RGBA; texture._glInternalFormat = gl.RGBA; texture._glPixelType = gl.UNSIGNED_SHORT_5_5_5_1; break; case pc.PIXELFORMAT_R4_G4_B4_A4: texture._glFormat = gl.RGBA; texture._glInternalFormat = gl.RGBA; texture._glPixelType = gl.UNSIGNED_SHORT_4_4_4_4; break; case pc.PIXELFORMAT_R8_G8_B8: texture._glFormat = gl.RGB; texture._glInternalFormat = gl.RGB; texture._glPixelType = gl.UNSIGNED_BYTE; break; case pc.PIXELFORMAT_R8_G8_B8_A8: texture._glFormat = gl.RGBA; texture._glInternalFormat = gl.RGBA; texture._glPixelType = gl.UNSIGNED_BYTE; break; case pc.PIXELFORMAT_DXT1: ext = this.extCompressedTextureS3TC; texture._glFormat = gl.RGB; texture._glInternalFormat = ext.COMPRESSED_RGB_S3TC_DXT1_EXT; break; case pc.PIXELFORMAT_DXT3: ext = this.extCompressedTextureS3TC; texture._glFormat = gl.RGBA; texture._glInternalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT; break; case pc.PIXELFORMAT_DXT5: ext = this.extCompressedTextureS3TC; texture._glFormat = gl.RGBA; texture._glInternalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT; break; case pc.PIXELFORMAT_ETC1: ext = this.extCompressedTextureETC1; texture._glFormat = gl.RGB; texture._glInternalFormat = ext.COMPRESSED_RGB_ETC1_WEBGL; break; case pc.PIXELFORMAT_PVRTC_2BPP_RGB_1: ext = this.extCompressedTexturePVRTC; texture._glFormat = gl.RGB; texture._glInternalFormat = ext.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; break; case pc.PIXELFORMAT_PVRTC_2BPP_RGBA_1: ext = this.extCompressedTexturePVRTC; texture._glFormat = gl.RGBA; texture._glInternalFormat = ext.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; break; case pc.PIXELFORMAT_PVRTC_4BPP_RGB_1: ext = this.extCompressedTexturePVRTC; texture._glFormat = gl.RGB; texture._glInternalFormat = ext.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; break; case pc.PIXELFORMAT_PVRTC_4BPP_RGBA_1: ext = this.extCompressedTexturePVRTC; texture._glFormat = gl.RGBA; texture._glInternalFormat = ext.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; break; case pc.PIXELFORMAT_RGB16F: ext = this.extTextureHalfFloat; texture._glFormat = gl.RGB; texture._glInternalFormat = gl.RGB; texture._glPixelType = ext.HALF_FLOAT_OES; break; case pc.PIXELFORMAT_RGBA16F: ext = this.extTextureHalfFloat; texture._glFormat = gl.RGBA; texture._glInternalFormat = gl.RGBA; texture._glPixelType = ext.HALF_FLOAT_OES; break; case pc.PIXELFORMAT_RGB32F: texture._glFormat = gl.RGB; texture._glInternalFormat = gl.RGB; texture._glPixelType = gl.FLOAT; break; case pc.PIXELFORMAT_RGBA32F: texture._glFormat = gl.RGBA; texture._glInternalFormat = gl.RGBA; texture._glPixelType = gl.FLOAT; break; } }, uploadTexture: function (texture) { var gl = this.gl; var mipLevel = 0; var mipObject; while(texture._levels[mipLevel] || mipLevel==0) { // Upload all existing mip levels. Initialize 0 mip anyway. mipObject = texture._levels[mipLevel]; if (mipLevel == 1 && ! texture._compressed) { // We have more than one mip levels we want to assign, but we need all mips to make // the texture complete. Therefore first generate all mip chain from 0, then assign custom mips. gl.generateMipmap(texture._glTarget); } if (texture._cubemap) { var face; gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); if ((mipObject[0] instanceof HTMLCanvasElement) || (mipObject[0] instanceof HTMLImageElement) || (mipObject[0] instanceof HTMLVideoElement)) { // Upload the image, canvas or video for (face = 0; face < 6; face++) { if (! texture._levelsUpdated[0][face]) continue; var src = mipObject[face]; // Downsize images that are too large to be used as cube maps if (src instanceof HTMLImageElement) { if (src.width > this.maxCubeMapSize || src.height > this.maxCubeMapSize) { src = _downsampleImage(src, this.maxCubeMapSize); if (mipLevel===0) { texture.width = src.width; texture.height = src.height; } } } gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, mipLevel, texture._glInternalFormat, texture._glFormat, texture._glPixelType, src); } } else { // Upload the byte array var resMult = 1 / Math.pow(2, mipLevel); for (face = 0; face < 6; face++) { if (! texture._levelsUpdated[0][face]) continue; var texData = mipObject[face]; if (texture._compressed) { gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, mipLevel, texture._glInternalFormat, Math.max(texture._width * resMult, 1), Math.max(texture._height * resMult, 1), 0, texData); } else { gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, mipLevel, texture._glInternalFormat, Math.max(texture._width * resMult, 1), Math.max(texture._height * resMult, 1), 0, texture._glFormat, texture._glPixelType, texData); } } } } else { if ((mipObject instanceof HTMLCanvasElement) || (mipObject instanceof HTMLImageElement) || (mipObject instanceof HTMLVideoElement)) { // Downsize images that are too large to be used as textures if (mipObject instanceof HTMLImageElement) { if (mipObject.width > this.maxTextureSize || mipObject.height > this.maxTextureSize) { mipObject = _downsampleImage(mipObject, this.maxTextureSize); if (mipLevel===0) { texture.width = mipObject.width; texture.height = mipObject.height; } } } // Upload the image, canvas or video gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, mipLevel, texture._glInternalFormat, texture._glFormat, texture._glPixelType, mipObject); } else { // Upload the byte array gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); var resMult = 1 / Math.pow(2, mipLevel); if (texture._compressed) { gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, texture._glInternalFormat, Math.max(texture._width * resMult, 1), Math.max(texture._height * resMult, 1), 0, mipObject); } else { gl.texImage2D(gl.TEXTURE_2D, mipLevel, texture._glInternalFormat, Math.max(texture._width * resMult, 1), Math.max(texture._height * resMult, 1), 0, texture._glFormat, texture._glPixelType, mipObject); } } } mipLevel++; } if (texture._cubemap) { for(var i = 0; i < 6; i++) texture._levelsUpdated[0][i] = false; } else { texture._levelsUpdated[0] = false; } if (texture.autoMipmap && pc.math.powerOfTwo(texture._width) && pc.math.powerOfTwo(texture._height) && texture._levels.length === 1 && !texture._compressed) { gl.generateMipmap(texture._glTarget); } this._vram.tex += gpuTexSize(gl, texture); }, setTexture: function (texture, textureUnit) { var gl = this.gl; if (!texture._glTextureId) { this.initializeTexture(texture); } if (this.activeTexture !== textureUnit) { gl.activeTexture(gl.TEXTURE0 + textureUnit); this.activeTexture = textureUnit; } var target = texture._glTarget; if (this.textureUnits[textureUnit] !== texture) { gl.bindTexture(target, texture._glTextureId); this.textureUnits[textureUnit] = texture; } if (texture._minFilterDirty) { gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, this.glFilter[texture._minFilter]); texture._minFilterDirty = false; } if (texture._magFilterDirty) { gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, this.glFilter[texture._magFilter]); texture._magFilterDirty = false; } if (texture._addressUDirty) { gl.texParameteri(target, gl.TEXTURE_WRAP_S, this.glAddress[texture._addressU]); texture._addressUDirty = false; } if (texture._addressVDirty) { gl.texParameteri(target, gl.TEXTURE_WRAP_T, this.glAddress[texture._addressV]); texture._addressVDirty = false; } if (texture._anisotropyDirty) { var ext = this.extTextureFilterAnisotropic; if (ext) { var maxAnisotropy = this.maxAnisotropy; var anisotropy = texture.anisotropy; anisotropy = Math.min(anisotropy, maxAnisotropy); gl.texParameterf(target, ext.TEXTURE_MAX_ANISOTROPY_EXT, anisotropy); } texture._anisotropyDirty = false; } if (texture._needsUpload) { this.uploadTexture(texture); texture._needsUpload = false; } }, /** * @function * @name pc.GraphicsDevice#draw * @description Submits a graphical primitive to the hardware for immediate rendering. * @param {Object} primitive Primitive object describing how to submit current vertex/index buffers defined as follows: * @param {pc.PRIMITIVE} primitive.type The type of primitive to render. * @param {Number} primitive.base The offset of the first index or vertex to dispatch in the draw call. * @param {Number} primitive.count The number of indices or vertices to dispatch in the draw call. * @param {Boolean} primitive.indexed True to interpret the primitive as indexed, thereby using the currently set index buffer and false otherwise. * @example * // Render a single, unindexed triangle * device.draw({ * type: pc.PRIMITIVE_TRIANGLES, * base: 0, * count: 3, * indexed: false * )}; */ draw: function (primitive, numInstances) { var gl = this.gl; var i, j, len, sampler, samplerValue, texture, numTextures, uniform, scopeId, uniformVersion, programVersion; var shader = this.shader; var samplers = shader.samplers; var uniforms = shader.uniforms; if (numInstances > 1) { this.boundBuffer = null; this.attributesInvalidated = true; } // Commit the vertex buffer inputs if (this.attributesInvalidated) { var attribute, element, vertexBuffer; var attributes = shader.attributes; for (i = 0, len = attributes.length; i < len; i++) { attribute = attributes[i]; // Retrieve vertex element for this shader attribute element = attribute.scopeId.value; // Check the vertex element is valid if (element !== null) { // Retrieve the vertex buffer that contains this element vertexBuffer = this.vertexBuffers[element.stream]; // Set the active vertex buffer object if (this.boundBuffer !== vertexBuffer.bufferId) { gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.bufferId); this.boundBuffer = vertexBuffer.bufferId; } // Hook the vertex buffer to the shader program if (!this.enabledAttributes[attribute.locationId]) { gl.enableVertexAttribArray(attribute.locationId); this.enabledAttributes[attribute.locationId] = true; } gl.vertexAttribPointer(attribute.locationId, element.numComponents, this.glType[element.dataType], element.normalize, element.stride, element.offset); if (element.stream===1 && numInstances>1) { if (!this.instancedAttribs[attribute.locationId]) { this.extInstancing.vertexAttribDivisorANGLE(attribute.locationId, 1); this.instancedAttribs[attribute.locationId] = true; } } else if (this.instancedAttribs[attribute.locationId]) { this.extInstancing.vertexAttribDivisorANGLE(attribute.locationId, 0); this.instancedAttribs[attribute.locationId] = false; } } } this.attributesInvalidated = false; } // Commit the shader program variables textureUnit = 0; for (i = 0, len = samplers.length; i < len; i++) { sampler = samplers[i]; samplerValue = sampler.scopeId.value; if (samplerValue instanceof pc.Texture) { texture = samplerValue; this.setTexture(texture, textureUnit); if (sampler.slot !== textureUnit) { gl.uniform1i(sampler.locationId, textureUnit); sampler.slot = textureUnit; } textureUnit++; } else { // Array sampler.array.length = 0; numTexures = samplerValue.length; for (j = 0; j < numTexures; j++) { texture = samplerValue[j]; this.setTexture(texture, textureUnit); sampler.array[j] = textureUnit; textureUnit++; } gl.uniform1iv(sampler.locationId, sampler.array); } } // Commit any updated uniforms for (i = 0, len = uniforms.length; i < len; i++) { uniform = uniforms[i]; scopeId = uniform.scopeId; uniformVersion = uniform.version; programVersion = scopeId.versionObject.version; // Check the value is valid if (uniformVersion.globalId !== programVersion.globalId || uniformVersion.revision !== programVersion.revision) { uniformVersion.globalId = programVersion.globalId; uniformVersion.revision = programVersion.revision; // Call the function to commit the uniform value if (scopeId.value!==null) { this.commitFunction[uniform.dataType](uniform.locationId, scopeId.value); } } } this._drawCallsPerFrame++; this._primsPerFrame[primitive.type] += primitive.count * (numInstances > 1? numInstances : 1); if (primitive.indexed) { if (numInstances > 1) { this.extInstancing.drawElementsInstancedANGLE(this.glPrimitive[primitive.type], primitive.count, this.indexBuffer.glFormat, primitive.base * 2, numInstances); this.boundBuffer = null; this.attributesInvalidated = true; } else { gl.drawElements(this.glPrimitive[primitive.type], primitive.count, this.indexBuffer.glFormat, primitive.base * this.indexBuffer.bytesPerIndex); } } else { if (numInstances > 1) { this.extInstancing.drawArraysInstancedANGLE(this.glPrimitive[primitive.type], primitive.base, primitive.count, numInstances); this.boundBuffer = null; this.attributesInvalidated = true; } else { gl.drawArrays(this.glPrimitive[primitive.type], primitive.base, primitive.count); } } }, /** * @function * @name pc.GraphicsDevice#clear * @description Clears the frame buffer of the currently set render target. * @param {Object} options Optional options object that controls the behavior of the clear operation defined as follows: * @param {Array} options.color The color to clear the color buffer to in the range 0.0 to 1.0 for each component. * @param {Number} options.depth The depth value to clear the depth buffer to in the range 0.0 to 1.0. * @param {pc.CLEARFLAG} options.flags The buffers to clear (the types being color, depth and stencil). * @example * // Clear color buffer to black and depth buffer to 1.0 * device.clear(); * * // Clear just the color buffer to red * device.clear({ * color: [1, 0, 0, 1], * flags: pc.CLEARFLAG_COLOR * }); * * // Clear color buffer to yellow and depth to 1.0 * device.clear({ * color: [1, 1, 0, 1], * depth: 1.0, * flags: pc.CLEARFLAG_COLOR | pc.CLEARFLAG_DEPTH * }); */ clear: function (options) { var defaultOptions = this.defaultClearOptions; options = options || defaultOptions; var flags = (options.flags === undefined) ? defaultOptions.flags : options.flags; if (flags !== 0) { var gl = this.gl; // Set the clear color if (flags & pc.CLEARFLAG_COLOR) { var color = (options.color === undefined) ? defaultOptions.color : options.color; this.setClearColor(color[0], color[1], color[2], color[3]); } if (flags & pc.CLEARFLAG_DEPTH) { // Set the clear depth var depth = (options.depth === undefined) ? defaultOptions.depth : options.depth; this.setClearDepth(depth); if (!this.depthWrite) { gl.depthMask(true); } } // Clear the frame buffer gl.clear(this.glClearFlag[flags]); if (flags & pc.CLEARFLAG_DEPTH) { if (!this.depthWrite) { gl.depthMask(false); } } } }, readPixels: function (x, y, w, h, pixels) { var gl = this.gl; gl.readPixels(x, y, w, h, gl.RGBA, gl.UNSIGNED_BYTE, pixels); }, setClearDepth: function (depth) { if (depth !== this.clearDepth) { this.gl.clearDepth(depth); this.clearDepth = depth; } }, setClearColor: function (r, g, b, a) { if ((r !== this.clearRed) || (g !== this.clearGreen) || (b !== this.clearBlue) || (a !== this.clearAlpha)) { this.gl.clearColor(r, g, b, a); this.clearRed = r; this.clearGreen = g; this.clearBlue = b; this.clearAlpha = a; } }, /** * @function * @name pc.GraphicsDevice#setRenderTarget * @description Sets the specified render target on the device. If null * is passed as a parameter, the back buffer becomes the current target * for all rendering operations. * @param {pc.RenderTarget} The render target to activate. * @example * // Set a render target to receive all rendering output * device.setRenderTarget(renderTarget); * * // Set the back buffer to receive all rendering output * device.setRenderTarget(null); */ setRenderTarget: function (renderTarget) { this.renderTarget = renderTarget; }, /** * @function * @name pc.GraphicsDevice#getRenderTarget * @description Queries the currently set render target on the device. * @returns {pc.RenderTarget} The current render target. * @example * // Get the current render target * var renderTarget = device.getRenderTarget(); */ getRenderTarget: function () { return this.renderTarget; }, /** * @function * @name pc.GraphicsDevice#getDepthTest * @description Queries whether depth testing is enabled. * @returns {Boolean} true if depth testing is enabled and false otherwise. * @example * var depthTest = device.getDepthTest(); * console.log('Depth testing is ' + depthTest ? 'enabled' : 'disabled'); */ getDepthTest: function () { return this.depthTest; }, /** * @function * @name pc.GraphicsDevice#setDepthTest * @description Enables or disables depth testing of fragments. Once this state * is set, it persists until it is changed. By default, depth testing is enabled. * @param {Boolean} depthTest true to enable depth testing and false otherwise. * @example * device.setDepthTest(true); */ setDepthTest: function (depthTest) { if (this.depthTest !== depthTest) { var gl = this.gl; if (depthTest) { gl.enable(gl.DEPTH_TEST); } else { gl.disable(gl.DEPTH_TEST); } this.depthTest = depthTest; } }, /** * @function * @name pc.GraphicsDevice#getDepthWrite * @description Queries whether writes to the depth buffer are enabled. * @returns {Boolean} true if depth writing is enabled and false otherwise. * @example * var depthWrite = device.getDepthWrite(); * console.log('Depth writing is ' + depthWrite ? 'enabled' : 'disabled'); */ getDepthWrite: function () { return this.depthWrite; }, /** * @function * @name pc.GraphicsDevice#setDepthWrite * @description Enables or disables writes to the depth buffer. Once this state * is set, it persists until it is changed. By default, depth writes are enabled. * @param {Boolean} writeDepth true to enable depth writing and false otherwise. * @example * device.setDepthWrite(true); */ setDepthWrite: function (writeDepth) { if (this.depthWrite !== writeDepth) { this.gl.depthMask(writeDepth); this.depthWrite = writeDepth; } }, /** * @function * @name pc.GraphicsDevice#setColorWrite * @description Enables or disables writes to the color buffer. Once this state * is set, it persists until it is changed. By default, color writes are enabled * for all color channels. * @param {Boolean} writeRed true to enable writing of the red channel and false otherwise. * @param {Boolean} writeGreen true to enable writing of the green channel and false otherwise. * @param {Boolean} writeBlue true to enable writing of the blue channel and false otherwise. * @param {Boolean} writeAlpha true to enable writing of the alpha channel and false otherwise. * @example * // Just write alpha into the frame buffer * device.setColorWrite(false, false, false, true); */ setColorWrite: function (writeRed, writeGreen, writeBlue, writeAlpha) { if ((this.writeRed !== writeRed) || (this.writeGreen !== writeGreen) || (this.writeBlue !== writeBlue) || (this.writeAlpha !== writeAlpha)) { this.gl.colorMask(writeRed, writeGreen, writeBlue, writeAlpha); this.writeRed = writeRed; this.writeGreen = writeGreen; this.writeBlue = writeBlue; this.writeAlpha = writeAlpha; } }, /** * @function * @name pc.GraphicsDevice#getBlending * @description Queries whether blending is enabled. * @returns {Boolean} True if blending is enabled and false otherwise. */ getBlending: function () { return this.blending; }, /** * @function * @name pc.GraphicsDevice#setBlending * @description Enables or disables blending. * @param {Boolean} blending True to enable blending and false to disable it. */ setBlending: function (blending) { if (this.blending !== blending) { var gl = this.gl; if (blending) { gl.enable(gl.BLEND); } else { gl.disable(gl.BLEND); } this.blending = blending; } }, /** * @function * @name pc.GraphicsDevice#setBlendFunction * @description Configures blending operations. * @param {pc.BLENDMODE} blendSrc The source blend function. * @param {pc.BLENDMODE} blendDst The destination blend function. */ setBlendFunction: function (blendSrc, blendDst) { if ((this.blendSrc !== blendSrc) || (this.blendDst !== blendDst)) { this.gl.blendFunc(this.glBlendFunction[blendSrc], this.glBlendFunction[blendDst]); this.blendSrc = blendSrc; this.blendDst = blendDst; } }, /** * @function * @name pc.GraphicsDevice#setBlendEquation * @description Configures the blending equation. The default blend equation is * pc.BLENDEQUATION_ADD. * @param {pc.BLENDEQUATION} blendEquation The blend equation. */ setBlendEquation: function (blendEquation) { if (this.blendEquation !== blendEquation) { var gl = this.gl; gl.blendEquation(this.glBlendEquation[blendEquation]); this.blendEquation = blendEquation; } }, /** * @function * @name pc.GraphicsDevice#setCullMode * @description Configures the cull mode. The default cull mode is * pc.CULLFACE_BACK. * @param {pc.CULLFACE} cullMode The cull mode. */ setCullMode: function (cullMode) { if (this.cullMode !== cullMode) { var gl = this.gl; switch (cullMode) { case pc.CULLFACE_NONE: gl.disable(gl.CULL_FACE); break; case pc.CULLFACE_FRONT: gl.enable(gl.CULL_FACE); gl.cullFace(gl.FRONT); break; case pc.CULLFACE_BACK: gl.enable(gl.CULL_FACE); gl.cullFace(gl.BACK); break; case pc.CULLFACE_FRONTANDBACK: gl.enable(gl.CULL_FACE); gl.cullFace(gl.FRONT_AND_BACK); break; } this.cullMode = cullMode; } }, getCullMode: function () { return this.cullMode; }, /** * @function * @name pc.GraphicsDevice#setIndexBuffer * @description Sets the current index buffer on the graphics device. On subsequent * calls to pc.GraphicsDevice#draw, the specified index buffer will be used to provide * index data for any indexed primitives. * @param {pc.IndexBuffer} indexBuffer The index buffer to assign to the device. */ setIndexBuffer: function (indexBuffer) { // Store the index buffer if (this.indexBuffer !== indexBuffer) { this.indexBuffer = indexBuffer; // Set the active index buffer object var gl = this.gl; gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer ? indexBuffer.bufferId : null); } }, /** * @function * @name pc.GraphicsDevice#setVertexBuffer * @description Sets the current vertex buffer for a specific stream index on the graphics * device. On subsequent calls to pc.GraphicsDevice#draw, the specified vertex buffer will be * used to provide vertex data for any primitives. * @param {pc.VertexBuffer} vertexBuffer The vertex buffer to assign to the device. * @param {Number} stream The stream index for the vertex buffer, indexed from 0 upwards. */ setVertexBuffer: function (vertexBuffer, stream) { if (this.vertexBuffers[stream] !== vertexBuffer) { // Store the vertex buffer for this stream index this.vertexBuffers[stream] = vertexBuffer; // Push each vertex element in scope var vertexFormat = vertexBuffer.getFormat(); var i = 0; var elements = vertexFormat.elements; var numElements = elements.length; while (i < numElements) { var vertexElement = elements[i++]; vertexElement.stream = stream; vertexElement.scopeId.setValue(vertexElement); } this.attributesInvalidated = true; } }, /** * @function * @name pc.GraphicsDevice#setShader * @description Sets the active shader to be used during subsequent draw calls. * @param {pc.Shader} shader The shader to set to assign to the device. */ setShader: function(shader) { if (shader !== this.shader) { this.shader = shader; if (! shader.ready) shader.link(); // Set the active shader this._shaderSwitchesPerFrame++; this.gl.useProgram(shader.program); this.attributesInvalidated = true; } }, /** * @private * @function * @name pc.GraphicsDevice#getBoneLimit * @description Queries the maximum number of bones that can be referenced by a shader. * The shader generators (pc.programlib) use this number to specify the matrix array * size of the uniform 'matrix_pose[0]'. The value is calculated based on the number of * available uniform vectors available after subtracting the number taken by a typical * heavyweight shader. If a different number is required, it can be tuned via * pc.GraphicsDevice#setBoneLimit. * @returns {Number} The maximum number of bones that can be supported by the host hardware. */ getBoneLimit: function () { return this.boneLimit; }, /** * @private * @function * @name pc.GraphicsDevice#setBoneLimit * @description Specifies the maximum number of bones that the device can support on * the current hardware. This function allows the default calculated value based on * available vector uniforms to be overridden. * @param {Number} maxBones The maximum number of bones supported by the host hardware. */ setBoneLimit: function (maxBones) { this.boneLimit = maxBones; }, /* DEPRECATED */ enableValidation: function (enable) { console.warn('enableValidation: This function is deprecated and will be removed shortly.'); }, validate: function () { console.warn('validate: This function is deprecated and will be removed shortly.'); }, /** * @function * @name pc.GraphicsDevice#resizeCanvas * @description Sets the width and height of the canvas, then fires the 'resizecanvas' event. */ resizeCanvas: function (width, height) { this._width = width; this._height = height; var ratio = Math.min(this._maxPixelRatio, window.devicePixelRatio); width *= ratio; height *= ratio; this.canvas.width = width; this.canvas.height = height; this.fire(EVENT_RESIZE, width, height); } }; Object.defineProperty(GraphicsDevice.prototype, 'width', { get: function () { return this.gl.drawingBufferWidth || this.canvas.width; } }); Object.defineProperty(GraphicsDevice.prototype, 'height', { get: function () { return this.gl.drawingBufferHeight || this.canvas.height; } }); Object.defineProperty(GraphicsDevice.prototype, 'fullscreen', { get: function () { return !!document.fullscreenElement; }, set: function (fullscreen) { if (fullscreen) { var canvas = this.gl.canvas; canvas.requestFullscreen(); } else { document.exitFullscreen(); } } }); Object.defineProperty(GraphicsDevice.prototype, 'maxAnisotropy', { get: ( function () { var maxAniso; return function () { if (maxAniso === undefined) { maxAniso = 1; var gl = this.gl; var glExt = this.extTextureFilterAnisotropic; if (glExt) { maxAniso = gl.getParameter(glExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT); } } return maxAniso; } } )() }); Object.defineProperty(GraphicsDevice.prototype, 'maxPixelRatio', { get: function () { return this._maxPixelRatio; }, set: function (ratio) { this._maxPixelRatio = ratio; this.resizeCanvas(this._width, this._height); } }); return { UnsupportedBrowserError: UnsupportedBrowserError, ContextCreationError: ContextCreationError, GraphicsDevice: GraphicsDevice, precalculatedTangents: true }; }());
(function (root, factory) { if (typeof exports === 'object') { var jquery = require('jquery'); module.exports = factory(jquery); } else if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } }(this, function ($) { // @include mtchart.core.js return MT.ChartAPI; }));
define([ 'jquery', 'utils', 'semantic-ui' ], function( $, Utils ) { var module = {}; module.container = $("#feng-theme-container"); module.init = function() { module.container.on("click", ".feng-theme-add", function() { $("#feng-theme-modal .header").text("Add new theme"); $("#feng-theme-modal .header").attr("theme-id", ""); $("#feng-theme-modal .theme-name").val(""); $("#feng-theme-modal .theme-description").val(""); $("#feng-theme-modal").modal("show"); }).on("click", ".feng-theme-edit", function() { var theme_id = $(this).attr("theme-id"); var theme_name = $(this).closest("tr").find(".theme-name").text().trim(); var theme_description = $(this).closest("tr").find(".theme-description").text().trim(); $("#feng-theme-modal .header").text("Edit theme"); $("#feng-theme-modal .header").attr("theme-id", theme_id); $("#feng-theme-modal .theme-name").val(theme_name); $("#feng-theme-modal .theme-description").val(theme_description); $("#feng-theme-modal").modal("show"); }).on("click", ".feng-theme-remove", function() { $.ajax({ url: '/api_dashboard/theme/', type: 'post', data: { action: "remove-theme", theme_id: $(this).attr("theme-id"), }, success: function(xhr) { module.container.html(xhr.html); } }) }); $("body").on("click", ".feng-theme-save", function() { $.ajax({ url: '/api_dashboard/theme/', type: 'post', data: { action: "save-theme", theme_id: $("#feng-theme-modal .header").attr("theme-id"), theme_name: $("#feng-theme-modal .theme-name").val(), theme_description: $("#feng-theme-modal .theme-description").val() }, success: function(xhr) { $("#feng-theme-modal").modal("hide"); module.container.html(xhr.html); } }) }); } module.init(); $.ajax({ url: '/api_dashboard/theme/', type: 'post', data: { 'action': 'get-theme', }, success: function(xhr) { $("#feng-theme-container").html(xhr.html); } }); return module; });
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './DockerOriginal.svg' /** DockerOriginal */ function DockerOriginal({ width, height, className }) { return ( <SVGDeviconInline className={'DockerOriginal' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } DockerOriginal.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default DockerOriginal
define([ "Praxigento_Core/js/grid/column/link" ], function (Column) { "use strict"; return Column.extend({ defaults: { idAttrName: "fromMlmId", route: "/customer/downline/index/mlmId/" } }); });
/** * Some setup to help test locally via node. See line 11 for HackerRank functionality. */ var bot; var fs = require('fs'); // Node's file system lib. (function() { 'use strict'; /** * HackerRank bot code starts here..., remove comments on lines: * 15, 16 & 241 - comment out line 240. */ // process.stdin.resume(); // process.stdin.setEncoding('ascii'); // Our models... var cityObj = function() { this.isSafe = true; }; var roadObj = function() { this.city1: null, this.city2: null, this.effort: null, this.canSkip: false }; // Our bot... /** * Our Bot's constructor, intialize's our params and sets * up our event handlers for reading input. * * @param {Object} input */ var Bot = function(input) { this.input = input; this.init() .bindings(); }; /** * Initialize the configuration and settings for our bot. * * @return {Bot} */ Bot.prototype.init = function() { // System vars... this.debug = true; this.commands = ''; // Data being read into our bot. this.data = []; // Array of our commands, itemized by line. // Unit counts... this.cityCount = 0; // N this.roadCount = 0; // N-1 this.machineCount = 0; // K // Collections... this.cities = []; this.roads = []; this.machines = []; return this; }; /** * Set bindings up for our bot. * * @return {Bot} */ Bot.prototype.bindings = function() { this.input.on('data', this.store.bind(this) ); this.input.on('end', this.run.bind(this) ); return this; }; /** * Stores the commands sent to us via std input. * * @param {Buffer} data */ Bot.prototype.store = function(data) { this.commands += data; }; /** * Formats our data input/commands for analysis * and triggers our bot. */ Bot.prototype.run = function() { this.data = this.commands.split('\n'); this.process(); }; /** * Analyze our commands and form our solution. */ Bot.prototype.process = function() { // Snag counts, build city and road lists. var counts = this.data.shift(); this.cityCount = counts[0]; // N this.roadCount = this.cityCount - 1; // N-1 this.machineCount = counts[2]; // K // Segment types of data. var roadData = this.data.splice(0, this.roadCount); var machineData = this.data; // Build our objects. // (Order is important here so that we can map // machines to cities and cities to roads.) this.formatMachines(machineData); this.buildCities(); this.buildRoads(roadData); var res = this.determineEffort(); process.stdout.write(res + '\n'); }; /** * Grabs the first item of each of our arrays (first char of each line) * since all machine input is a single integer on each line. * * @param {Array} machines */ Bot.prototype.formatMachines = function(machines) { machines.forEach(function(machine) { this.push( parseInt(machine[0], 10) // Typecast to keep our int values for index searching. ); }, this.machines); }; /** * Builds our list of city objects. */ Bot.prototype.buildCities = function() { for (var i = 0; i < this.cityCount; i++) { var city = new cityObj(); city.isSafe = this.machines.indexOf(i) === -1 ? 1 : 0; this.cities.push(city); } }, /** * Builds our list of road objects. * * @param {Array} roads */ Bot.prototype.buildRoads = function(roads) { roads.forEach(function(roadConfig) { var road = new roadObj(); road.city1 = parseInt(roadConfig[0], 10); road.city2 = parseInt(roadConfig[2], 10); road.effort = parseInt(roadConfig[4], 10); road.canSkip = this.canWeSkip(roadConfig[0], roadConfig[2]); this.roads.push(road); }, this); }; /** * Determines if the cities connected by a single road are both infected with machines OR * are both free of machines. If they are, then it would seem like a waste of time * destroying this particular bridge. Let's skip it. * * @param {Integer} city1 * @param {Integer} city2 * @return {Boolean} */ Bot.prototype.canWeSkip = function(city1, city2) { return ( (!this.cities[city1].isSafe && !this.cities[city2].isSafe) || (this.cities[city1].isSafe && this.cities[city2].isSafe) ); }; /** * Determines the level of effort it would take destroying all bridges * that connect an infected city to a machine free zone. * * @return {Integer} */ Bot.prototype.determineEffort = function() { var effort = 0; (this.roads).forEach(function(road) { if (!road.canSkip) { effort += road.effort; } }); return effort; }; /** * Helper function for debugging. * * @param {String} string */ Bot.prototype.log = function(string) { if (!this.debug) { return false; } process.stderr.write(string + '\n'); }; var input = fs.createReadStream('input.txt'); // var input = process.stdin; var bot = new Bot(input); })();
define(['mout/function/makeIterator_'], function(makeIterator_){ describe('function/makeIterator_', function(){ it('should return source argument if it is already a function', function(){ var fn = function(){}; expect( makeIterator_(fn) ).toBe(fn); }); it('should return a function that calls object/matches if argument is an object', function(){ var fn = makeIterator_({a:1,b:2}); expect( fn({a:1,b:2}) ).toBe( true ); expect( fn({a:2,b:2}) ).toBe( false ); }); it('should return a function that returns the property value if argument is a string', function(){ var fn = makeIterator_('a'); expect( fn({a:1,b:2}) ).toBe( 1 ); expect( fn({a:2,b:2}) ).toBe( 2 ); }); it('should return a function that returns the property value if argument is a number', function(){ var fn = makeIterator_(1); expect( fn([0,4,5]) ).toBe( 4 ); expect( fn([6,7,8]) ).toBe( 7 ); }); it('should return return source argument if it is from an unsupported type', function(){ expect( makeIterator_(null) ).toBe( null ); expect( makeIterator_(void(0)) ).toBe( void(0) ); }); }); });
/** * Parse string expressions like "L x[L y[x(y)]]" into a UserExpression. * * This isn't used in the app itself, but is useful for testing and development * purposes. * * @flow */ import { UserFuncCall, UserLambda, UserReference, UserVariable, } from './types' import type {UserExpression} from './types'; export const parseExpr = (str: string): UserExpression => { // Allow redundant whitespace. str = str.trim(); if (str.endsWith(']')) { // Expression like "L x[x(x)]" assertSame('L ', str.substring(0, 2)); const openBracketIndex = str.indexOf('['); const varName = str.substring(2, openBracketIndex).trim(); const bodyStr = str.substring(openBracketIndex + 1, str.length - 1).trim(); let body; if (bodyStr == '_') { body = null; } else { body = parseExpr(bodyStr); } return UserLambda.make(varName, body); } else if (str.endsWith(")")) { let level = 1; let index = str.length - 1; while (level > 0) { index--; if (str.charAt(index) == ')') { level++; } else if (str.charAt(index) == '(') { level--; } } // Now index is the index of the open-paren character. const funcStr = str.substring(0, index); const argStr = str.substring(index + 1, str.length - 1); return UserFuncCall.make( parseExpr(funcStr), parseExpr(argStr)); } else if (str === str.toUpperCase()) { assertNoBrackets(str); return UserReference.make(str); } else { assertNoBrackets(str); return UserVariable.make(str); } }; const assertNoBrackets = (str: string) => { const message = "Unexpected string " + str; assert(str.indexOf("(") === -1, message); assert(str.indexOf(")") === -1, message); assert(str.indexOf("[") === -1, message); assert(str.indexOf("]") === -1, message); }; const assertSame = (val1: any, val2: any) => { assert(val1 === val2, `Expected ${val1} got ${val2}.`); }; const assert = (condition: bool, message: string) => { if (!condition) { throw new Error(message || 'Assertion failed.'); } }; export const formatExpr = (expr: UserExpression): string => { return expr.match({ userLambda: ({body, varName}) => `L ${varName}[${body ? formatExpr(body) : '_'}]`, userFuncCall: ({func, arg}) => `${formatExpr(func)}(${formatExpr(arg)})`, userVariable: ({varName}) => varName, userReference: ({defName}) => defName, }); };
var util = require('util'); var debuglog = util.debuglog('nodemilter'); var async = require('async'); var constants = require('./constants'); var SMFIS = constants.SMFIS; var SMFI_VERSION = constants.SMFI_VERSION; var SMFI_VERSION_MDS = 0x01000002; var MI_CONTINUE = 1; var MI_SUCCESS = constants.MI_SUCCESS; var MI_FAILURE = constants.MI_FAILURE; var MILTER_LEN_BYTES = constants.MILTER_LEN_BYTES; var MILTER_OPTLEN = (MILTER_LEN_BYTES * 3); var MILTER_MDS_64K = ((64 * 1024) - 1); var MILTER_MDS_256K = ((256 * 1024) - 1); var MILTER_MDS_1M = ((1024 * 1024) - 1); var SMFI_V1_ACTS = 0x0000000F; // The actions of V1 filter var SMFI_V2_ACTS = 0x0000003F; // The actions of V2 filter var SMFI_CURR_ACTS = 0x000001FF;// actions of current version var SMFI_V1_PROT = 0x0000003F; // The protocol of V1 filter var SMFI_V2_PROT = 0x0000007F; // The protocol of V2 filter // all defined protocol bits var SMFI_CURR_PROT = 0x001FFFFF; // internal flags: only used between MTA and libmilter var SMFI_INTERNAL = 0x70000000; /* address families */ var SMFIA_UNKNOWN = 'U'; // unknown var SMFIA_UNIX = 'L'; // unix/local var SMFIA_INET = '4'; // inet var SMFIA_INET6 = '6'; // inet6 var SMFIC = constants.SMFIC; var SMFIR = constants.SMFIR; var SMFIP = constants.SMFIP; /* possible values for cm_todo */ var CT_CONT = 0x0000; /* continue reading commands */ var CT_IGNO = 0x0001; /* continue even when error */ /* not needed right now, done via return code instead */ var CT_KEEP = 0x0004; /* keep buffer (contains symbols) */ var CT_END = 0x0008; /* last command of session, stop replying */ var CI_NONE = -1; var CI_CONN = 0; var CI_HELO = 1; var CI_MAIL = 2; var CI_RCPT = 3; var CI_DATA = 4; var CI_EOM = 5; var CI_EOH = 6; var ST = constants.ST; function ST_IN_MAIL(st) { return (st >= ST.MAIL && st < ST.ENDM); } var bitset = constants.bitset; /* ** set of next states ** each state (ST_*) corresponds to bit in an int value (1 << state) ** each state has a set of allowed transitions ('or' of bits of states) ** so a state transition is valid if the mask of the next state ** is set in the NX_* value ** this function is coded in trans_ok(), see below. */ var MI_MASK = function(x) { return (0x0001 << (x)); }; var NX_INIT = (MI_MASK(ST.OPTS)); var NX_OPTS = (MI_MASK(ST.CONN) | MI_MASK(ST.UNKN)); var NX_CONN = (MI_MASK(ST.HELO) | MI_MASK(ST.MAIL) | MI_MASK(ST.UNKN)); var NX_HELO = (MI_MASK(ST.HELO) | MI_MASK(ST.MAIL) | MI_MASK(ST.UNKN)); var NX_MAIL = (MI_MASK(ST.RCPT) | MI_MASK(ST.ABRT) | MI_MASK(ST.UNKN)); var NX_RCPT = (MI_MASK(ST.HDRS) | MI_MASK(ST.EOHS) | MI_MASK(ST.DATA) | MI_MASK(ST.BODY) | MI_MASK(ST.ENDM) | MI_MASK(ST.RCPT) | MI_MASK(ST.ABRT) | MI_MASK(ST.UNKN)); var NX_DATA = (MI_MASK(ST.EOHS) | MI_MASK(ST.HDRS) | MI_MASK(ST.ABRT)); var NX_HDRS = (MI_MASK(ST.EOHS) | MI_MASK(ST.HDRS) | MI_MASK(ST.ABRT)); var NX_EOHS = (MI_MASK(ST.BODY) | MI_MASK(ST.ENDM) | MI_MASK(ST.ABRT)); var NX_BODY = (MI_MASK(ST.BODY) | MI_MASK(ST.ENDM) | MI_MASK(ST.ABRT)); var NX_ENDM = (MI_MASK(ST.QUIT) | MI_MASK(ST.MAIL) | MI_MASK(ST.UNKN) | MI_MASK(ST.Q_NC)); var NX_QUIT = 0; var NX_ABRT = 0; var NX_UNKN = (MI_MASK(ST.HELO) | MI_MASK(ST.MAIL) | MI_MASK(ST.RCPT) | MI_MASK(ST.DATA) | MI_MASK(ST.BODY) | MI_MASK(ST.UNKN) | MI_MASK(ST.ABRT) | MI_MASK(ST.QUIT) | MI_MASK(ST.Q_NC)); var NX_Q_NC = (MI_MASK(ST.CONN) | MI_MASK(ST.UNKN)); var NX_SKIP = MI_MASK(ST.SKIP); var next_states = [ NX_INIT, NX_OPTS, NX_CONN, NX_HELO, NX_MAIL, NX_RCPT, NX_DATA, NX_HDRS, NX_EOHS, NX_BODY, NX_ENDM, NX_QUIT, NX_ABRT, NX_UNKN, NX_Q_NC ]; var SIZE_NEXT_STATES = next_states.length; module.exports.getNextStates = function() { return util._extend({}, next_states); }; module.exports.setNextStates = function(states) { next_states = util._extend({}, states); }; var cmds = [ { cmd: SMFIC.ABORT, next: ST.ABRT, todo: CT_CONT, macro: CI_NONE, func: '_abort' }, { cmd: SMFIC.MACRO, next: ST.NONE, todo: CT_KEEP, macro: CI_NONE, func: '_macros' }, { cmd: SMFIC.BODY, next: ST.BODY, todo: CT_CONT, macro: CI_NONE, func: '_bodychunk' }, { cmd: SMFIC.CONNECT, next: ST.CONN, todo: CT_CONT, macro: CI_CONN, func: '_connectinfo' }, { cmd: SMFIC.BODYEOB, next: ST.ENDM, todo: CT_CONT, macro: CI_EOM, func: '_bodyend' }, { cmd: SMFIC.HELO, next: ST.HELO, todo: CT_CONT, macro: CI_HELO, func: '_helo' }, { cmd: SMFIC.HEADER, next: ST.HDRS, todo: CT_CONT, macro: CI_NONE, func: '_header' }, { cmd: SMFIC.MAIL, next: ST.MAIL, todo: CT_CONT, macro: CI_MAIL, func: '_sender' }, { cmd: SMFIC.OPTNEG, next: ST.OPTS, todo: CT_CONT, macro: CI_NONE, func: '_optionneg' }, { cmd: SMFIC.EOH, next: ST.EOHS, todo: CT_CONT, macro: CI_EOH, func: '_eoh' }, { cmd: SMFIC.QUIT, next: ST.QUIT, todo: CT_END, macro: CI_NONE, func: '_quit' }, { cmd: SMFIC.DATA, next: ST.DATA, todo: CT_CONT, macro: CI_DATA, func: '_data' }, { cmd: SMFIC.RCPT, next: ST.RCPT, todo: CT_IGNO, macro: CI_RCPT, func: '_rcpt' }, { cmd: SMFIC.UNKNOWN, next: ST.UNKN, todo: CT_IGNO, macro: CI_NONE, func: '_unknown' }, { cmd: SMFIC.QUIT_NC, next: ST.Q_NC, todo: CT_CONT, macro: CI_NONE, func: '_quit' }, ]; var MILTER_MAX_DATA_SIZE = 65535; // default milter command data limit var Maxdatasize = MILTER_MAX_DATA_SIZE; function setmaxdatasize(sz) { var old = Maxdatasize; Maxdatasize = sz; return old; } module.exports.getmaxdatasize = function() { return Maxdatasize; }; var MAX_MACROS_ENTRIES = constants.MAX_MACROS_ENTRIES; function Dispatcher(ctx) { if (!(this instanceof Dispatcher)) { return new Dispatcher(ctx); } this._ctx = ctx; this._curstate = ctx._state; this._buffer = null; ctx._clear_macros(0); fix_stm(ctx); } module.exports.Dispatcher = Dispatcher; Dispatcher.prototype._execute = function(data, callback) { var self = this; var ctx = this._ctx; callback = callback || function() {}; if (self._buffer) { data = Buffer.concat([self._buffer, data]); self._buffer = null; } if (data.length > MILTER_LEN_BYTES) { var len = data.readUInt32BE(); if ((len - 1) > Maxdatasize) { debuglog('[%s] too big data size (len = %d, max = %d)', ctx._id, (len - 1), Maxdatasize); ctx._socketend(); callback(); } else if (data.length >= (MILTER_LEN_BYTES + len)) { var cmd = String.fromCharCode(data[MILTER_LEN_BYTES]); var buf = data.slice(MILTER_LEN_BYTES + 1, MILTER_LEN_BYTES + len); self._buffer = data.slice(MILTER_LEN_BYTES + len); data = new Buffer(0); self._dispatch(cmd, buf, function(err) { self._execute(data, callback); }); } else { self._buffer = data; callback(); } } else { self._buffer = data; callback(); } }; Dispatcher.prototype._dispatch = function(cmd, data, callback) { var self = this; var ctx = this._ctx; var fi_abort = ctx._milter._abort; var call_abort = ST_IN_MAIL(self._curstate); callback = callback || function() {}; debuglog('[%s] got cmd \'%s\' len %d', ctx._id, cmd, data.length); var index = -1; async.waterfall([ function(callback) { for (var i = 0; i < cmds.length; i++) { if (cmds[i].cmd === cmd) { index = i; break; } } if (index < 0) { debuglog('[%s] cmd \'%s\' unknown', ctx._id, cmd); callback(MI_FAILURE); return; } callback(); }, function(callback) { var newstate = cmds[index].next; debuglog('[%s] cur %d new %d nextmask 0x%s', ctx._id, self._curstate, newstate, next_states[self._curstate].toString(16)); if (newstate !== ST.NONE && !trans_ok(self._curstate, newstate)) { debuglog('[%s] abort: cur %d (0x%s) new %d (0x%s) next 0x%s', ctx._id, self._curstate, MI_MASK(self._curstate).toString(16), newstate, MI_MASK(newstate).toString(16), next_states[self._curstate].toString(16)); if (fi_abort && call_abort) { fi_abort(ctx, function() {}); } self._curstate = ST.HELO; if (!trans_ok(self._curstate, newstate)) { callback(MI_CONTINUE); return; } } callback(null, newstate); }, function(newstate, callback) { if (newstate !== ST.NONE) { self._curstate = newstate; ctx._state = self._curstate; } call_abort = ST_IN_MAIL(self._curstate); var macro = cmds[index].macro; self[cmds[index].func](data, macro, function(status) { debuglog('[%s] status = %d', ctx._id, status); callback(null, status); }); }, function(status, callback) { self._sendreply(status, function(result) { if (result !== MI_SUCCESS) { callback(MI_FAILURE); return; } if (status === SMFIS.ACCEPT) { self._curstate = ST.HELO; } else if (status === SMFIS.REJECT || status === SMFIS.DISCARD || status === SMFIS.TEMPFAIL) { if (!bitset(CT_IGNO, cmds[index].todo)) { this._curstate = ST.HELO; } } else if (status === SMFIS._ABORT) { callback(MI_FAILURE); return; } callback(MI_SUCCESS); }); } ], function(err) { if (err && (err === MI_FAILURE || err === MI_SUCCESS)) { ctx._state = self._curstate; if (err === MI_FAILURE) { if (fi_abort && call_abort) { fi_abort(ctx, function() {}); } } if (ctx._state !== ST.QUIT) { var fi_close = ctx._milter._close; if (fi_close) { fi_close(ctx, function() {}); } } if (err === MI_FAILURE || ctx._state === ST.QUIT) { ctx._socketend(); } ctx._clear_macros(0); } callback(err); }); }; Dispatcher.prototype._abort = function(data, macro, callback) { debuglog('[%s] abort called', this._ctx._id); var ctx = this._ctx; var fi_abort = ctx._milter._abort; if (fi_abort) { fi_abort(ctx, callback); return; } callback(SMFIS._NOREPLY); }; Dispatcher.prototype._macros = function(data, macro, callback) { debuglog('[%s] macros called', this._ctx._id); var ctx = this._ctx; if (data.length < 1) { callback(SMFIS._FAIL); return; } var argv = dec_argv(data, 1); if (argv.length === 0) { callback(SMFIS._FAIL); return; } var index; switch (String.fromCharCode(data[0])) { case SMFIC.CONNECT: index = CI_CONN; break; case SMFIC.HELO: index = CI_HELO; break; case SMFIC.MAIL: index = CI_MAIL; break; case SMFIC.RCPT: index = CI_RCPT; break; case SMFIC.DATA: index = CI_DATA; break; case SMFIC.BODYEOB: index = CI_EOM; break; case SMFIC.EOH: index = CI_EOH; break; default: callback(SMFIS._FAIL); return; } ctx._mac_buf[index] = argv; callback(SMFIS._KEEP); }; Dispatcher.prototype._bodychunk = function(data, macro, callback) { debuglog('[%s] bodychunk called', this._ctx._id); var ctx = this._ctx; var fi_body = ctx._milter._body; if (fi_body) { fi_body(ctx, data, callback); return; } callback(SMFIS.CONTINUE); }; Dispatcher.prototype._connectinfo = function(data, macro, callback) { debuglog('[%s] connectinfo called', this._ctx._id); var ctx = this._ctx; var fi_connect = ctx._milter._connect; ctx._clear_macros(macro + 1); if (!fi_connect) { callback(SMFIS.CONTINUE); return; } var i = 0; while (data[i] !== 0 && i < data.length) { i++; } if ((i + 1) >= data.length) { callback(SMFIS._ABORT); return; } var hostname = data.toString('ascii', 0, i); var port, address; i++; var family = data[i++]; if (family !== SMFIA_UNKNOWN) { if (i + 2 >= data.length) { debuglog('[%s] connect: wrong len %d >= %d', ctx._id, i, data.length); callback(SMFIS._ABORT); return; } port = data.readUInt16BE(i); i += 2; if (data[data.length - 1] !== 0) { callback(SMFIS._ABORT); return; } address = data.toString('ascii', i, (data.length - 1)); } fi_connect(ctx, hostname, address, port, callback); }; Dispatcher.prototype._bodyend = function(data, macro, callback) { debuglog('[%s] bodyend called', this._ctx._id); var self = this; var ctx = this._ctx; var fi_body = ctx._milter._body; var fi_eom = ctx._milter._eom; function bodyend(callback) { if (fi_eom) { fi_eom(ctx, callback); return; } callback(SMFIS.CONTINUE); } if (fi_body && data.length > 0) { fi_body(ctx, data, function(status) { if (status !== SMFIS.CONTINUE) { self._sendreply(status, function(result) { if (result !== MI_SUCCESS) { callback(SMFIS._ABORT); } else { bodyend(callback); } }); } else { bodyend(callback); } }); } else { bodyend(callback); } }; Dispatcher.prototype._helo = function(data, macro, callback) { debuglog('[%s] helo called', this._ctx._id); var ctx = this._ctx; var fi_helo = ctx._milter._helo; ctx._clear_macros(macro + 1); if (fi_helo) { if (data.length === 0 || data[data.length - 1] !== 0) { callback(SMFIS._FAIL); return; } data = dec_argv(data)[0]; fi_helo(ctx, data, callback); return; } callback(SMFIS.CONTINUE); }; Dispatcher.prototype._header = function(data, macro, callback) { debuglog('[%s] header called', this._ctx._id); var ctx = this._ctx; var fi_header = ctx._milter._header; if (!fi_header) { callback(SMFIS.CONTINUE); return; } var elem = dec_argv(data); if (elem.length !== 2) { callback(SMFIS._ABORT); return; } fi_header(ctx, elem[0], elem[1], callback); }; Dispatcher.prototype._sender = function(data, macro, callback) { debuglog('[%s] sender called', this._ctx._id); var ctx = this._ctx; var fi_envfrom = ctx._milter._envfrom; ctx._clear_macros(macro + 1); if (!fi_envfrom) { callback(SMFIS.CONTINUE); return; } var argv = dec_argv(data); if (argv.length === 0) { callback(SMFIS._ABORT); return; } fi_envfrom(ctx, argv, callback); }; Dispatcher.prototype._optionneg = function(data, macro, callback) { debuglog('[%s] optionneg called', this._ctx._id); var self = this; var ctx = this._ctx; var fi_negotiate = ctx._milter._negotiate; ctx._clear_macros(macro + 1); var SMFI_PROT_VERSION = 6; ctx._prot_vers = SMFI_PROT_VERSION; if (data.length < MILTER_OPTLEN) { debuglog('[%s] %s: optionneg: len too short %d < %d', ctx._id, ctx._milter._name, data.length, MILTER_OPTLEN); callback(SMFIS._ABORT); return; } var v; var SMFI_PROT_VERSION_MIN = 2; v = data.readUInt32BE(0); if (v < SMFI_PROT_VERSION_MIN) { debuglog('[%s] %s: optionneg: protocol version too old %d < %d', ctx._id, ctx._milter._name, v, SMFI_PROT_VERSION_MIN); callback(SMFIS._ABORT); return; } ctx._mta_prot_vers = v; if (ctx._prot_vers < ctx._mta_prot_vers) { ctx._prot_vers2mta = ctx._prot_vers; } else { ctx._prot_vers2mta = ctx._mta_prot_vers; } v = data.readUInt32BE(4); if (v === 0) { v = SMFI_V1_ACTS; } ctx._mta_aflags = v; var internal_pflags = 0; v = data.readUInt32BE(8); if (v === 0) { v = SMFI_V1_PROT; } else if (ctx._milter._version >= SMFI_VERSION_MDS) { if (bitset(SMFIP.MDS_1M, v)) { internal_pflags |= SMFIP.MDS_1M; setmaxdatasize(MILTER_MDS_1M); } else if (bitset(SMFIP.MDS_256K, v)) { internal_pflags |= SMFIP.MDS_256K; setmaxdatasize(MILTER_MDS_256K); } } ctx._mta_pflags = (v & ~SMFI_INTERNAL) | internal_pflags; ctx._aflags = ctx._milter._flags; var fake_pflags = SMFIP.NR_CONN | SMFIP.NR_HELO | SMFIP.NR_MAIL | SMFIP.NR_RCPT | SMFIP.NR_DATA | SMFIP.NR_UNKN | SMFIP.NR_HDR | SMFIP.NR_EOH | SMFIP.NR_BODY; if (ctx._milter._version > 4 && fi_negotiate) { var aflags, pflags, f2, f3; f2 = f3 = 0; aflags = ctx._mta_aflags; pflags = ctx._pflags; if ((SMFIP.SKIP & ctx._mta_pflags) !== 0) { pflags |= SMFIP.SKIP; } fi_negotiate(ctx, ctx._mta_aflags, ctx._mta_pflags | fake_pflags, 0, 0, function(status, aflags, pflags, f2, f3) { if (status === SMFIS.ALL_OPTS) { ctx._aflags = ctx._mta_aflags; ctx._pflags2mta = ctx._pflags; if ((SMFIP.SKIP & ctx._mta_pflags) !== 0) { ctx._pflags2mta |= SMFIP.SKIP; } } else if (status !== SMFIS.CONTINUE) { debuglog('[%s] %s: negotiate returned %d (protocol options=0x%s, SMFIR=0x%s)', ctx._id, ctx._milter._name, status, ctx._mta_pflags.toString(16), ctx._mta_aflags.toString(16)); callback(SMFIS._ABORT); return; } else { ctx._aflags = aflags; ctx._pflags = pflags; ctx._pflags2mta = pflags; } var i = ctx._pflags2mta; var idx, b; if ((ctx._mta_pflags & i) !== i) { for (idx = 0; idx < 32; idx++) { b = 1 << idx; if ((ctx._mta_pflags & b) !== b && (fake_pflags & b) === b) { ctx._pflags2mta &= ~b; } } } optionneg(callback); } ); } else { ctx._pflags2mta = ctx._pflags; optionneg(callback); } function optionneg(callback) { var i; i = ctx._aflags; if ((i & ctx._mta_aflags) !== i) { callback(SMFIS._ABORT); return; } i = ctx._pflags2mta; if ((i & ctx._mta_pflags) !== i) { if (bitset(SMFIP.NODATA, ctx._pflags2mta) && !bitset(SMFIP.NODATA, ctx._mta_pflags)) { ctx._pflags2mta &= ~SMFIP.NODATA; } if (bitset(SMFIP.NOUNKNOWN, ctx._pflags2mta) && !bitset(SMFIP.NOUNKNOWN, ctx._mta_pflags)) { ctx._pflags2mta &= ~SMFIP.NOUNKNOWN; } i = ctx._pflags2mta; } if ((ctx._mta_pflags & i) != i) { callback(SMFIS._ABORT); return; } fix_stm(ctx); debuglog('[%s] milter_negotiate: mta_actions=0x%s, mta_flags=0x%s actions=0x%s, flags=0x%s', ctx._id, ctx._mta_aflags.toString(16), ctx._mta_pflags.toString(16), ctx._aflags.toString(16), ctx._pflags.toString(16)); ctx._pflags2mta = (ctx._pflags2mta & ~SMFI_INTERNAL) | internal_pflags; callback(SMFIS._OPTIONS); } }; Dispatcher.prototype._eoh = function(data, macro, callback) { debuglog('[%s] eoh called', this._ctx._id); var ctx = this._ctx; var fi_eoh = ctx._milter._eoh; if (fi_eoh) { fi_eoh(ctx, callback); return; } callback(SMFIS.CONTINUE); }; Dispatcher.prototype._quit = function(data, macro, callback) { debuglog('[%s] quit called', this._ctx._id); var ctx = this._ctx; var fi_close = ctx._milter._close; function close(callback) { ctx._clear_macros(0); callback(SMFIS._NOREPLY); } if (fi_close) { fi_close(ctx, function() { close(callback); }); } else { close(callback); } }; Dispatcher.prototype._data = function(data, macro, callback) { debuglog('[%s] data called', this._ctx._id); var ctx = this._ctx; var fi_data = ctx._milter._data; if (fi_data) { fi_data(ctx, callback); return; } callback(SMFIS.CONTINUE); }; Dispatcher.prototype._rcpt = function(data, macro, callback) { debuglog('[%s] rcpt called', this._ctx._id); var ctx = this._ctx; var fi_envrcpt = ctx._milter._envrcpt; ctx._clear_macros(macro + 1); if (!fi_envrcpt) { callback(SMFIS.CONTINUE); return; } var argv = dec_argv(data); if (argv.length === 0) { callback(SMFIS._ABORT); return; } fi_envrcpt(ctx, argv, callback); }; Dispatcher.prototype._unknown = function(data, macro, callback) { debuglog('[%s] unknown called', this._ctx._id); var ctx = this._ctx; var fi_unknown = ctx._milter._unknown; if (ctx._milter._version > 2 && fi_unknown) { fi_unknown(ctx, data, callback); return; } callback(SMFIS.CONTINUE); }; var trans_ok = module.exports._trans_ok = function(oldstate, newstate) { var s, n; s = oldstate; if (s >= SIZE_NEXT_STATES) { return false; } do { if ((MI_MASK(newstate) & next_states[s]) !== 0) { return true; } n = s + 1; if (n >= SIZE_NEXT_STATES) { return false; } if (bitset(NX_SKIP, next_states[n])) { s = n; } else { return false; } } while (s < SIZE_NEXT_STATES); return false; }; var dec_argv = module.exports._dec_argv = function(data, offset) { offset = offset || 0; var start, end; var elem = []; for (start = offset, end = 0; end < data.length; end++) { if (data[end] === 0) { elem.push(data.slice(start, end).toString()); start = end + 1; } } return elem; }; var fix_stm = module.exports._fix_stm = function(ctx) { var fl = ctx._pflags; if (bitset(SMFIP.NOCONNECT, fl)) { next_states[ST.CONN] |= NX_SKIP; } if (bitset(SMFIP.NOHELO, fl)) { next_states[ST.HELO] |= NX_SKIP; } if (bitset(SMFIP.NOMAIL, fl)) { next_states[ST.MAIL] |= NX_SKIP; } if (bitset(SMFIP.NORCPT, fl)) { next_states[ST.RCPT] |= NX_SKIP; } if (bitset(SMFIP.NOHDRS, fl)) { next_states[ST.HDRS] |= NX_SKIP; } if (bitset(SMFIP.NOEOH, fl)) { next_states[ST.EOHS] |= NX_SKIP; } if (bitset(SMFIP.NOBODY, fl)) { next_states[ST.BODY] |= NX_SKIP; } if (bitset(SMFIP.NODATA, fl)) { next_states[ST.DATA] |= NX_SKIP; } if (bitset(SMFIP.NOUNKNOWN, fl)) { next_states[ST.UNKN] |= NX_SKIP; } }; Dispatcher.prototype._sendreply = function(status, callback) { debuglog('[%s] sendreply called', this._ctx._id); var ctx = this._ctx; var bit = get_nr_bit(ctx._state); if (bit !== 0 && (ctx._pflags & bit) !== 0 && status !== SMFIS.NOREPLY) { if (status >= SMFIS.CONTINUE && status < SMFIS._KEEP) { debuglog('[%s] %s: milter claimed not to reply in state %d but did anyway %d', ctx._id, ctx._milter._name, ctx._state, status); } switch (status) { case SMFIS.CONTINUE: case SMFIS.TEMPFAIL: case SMFIS.REJECT: case SMFIS.DISCARD: case SMFIS.ACCEPT: case SMFIS.SKIP: case SMFIS._OPTIONS: status = SMFIS.NOREPLY; break; } } switch (status) { case SMFIS.CONTINUE: ctx._write_command(SMFIR.CONTINUE, callback); return; case SMFIS.TEMPFAIL: case SMFIS.REJECT: if (ctx._reply && ((status === SMFIS.TEMPFAIL && ctx._reply[0] === 0x34) || (status === SMFIS.REJECT && ctx._reply[0] === 0x35))) { ctx._write_command(SMFIR.REPLYCODE, ctx._reply, function(result) { ctx._replay = null; callback(result); }); } else { ctx._write_command( status === SMFIS.REJECT ? SMFIR.REJECT : SMFIR.TEMPFAIL, callback ); } return; case SMFIS.DISCARD: ctx._write_command(SMFIR.DISCARD, callback); return; case SMFIS.ACCEPT: ctx._write_command(SMFIR.ACCEPT, callback); return; case SMFIS.SKIP: ctx._write_command(SMFIR.SKIP, callback); return; case SMFIS._OPTIONS: var data = new Buffer(MILTER_OPTLEN); data.writeUInt32BE(ctx._prot_vers2mta, 0); data.writeUInt32BE(ctx._pflags2mta, MILTER_LEN_BYTES * 2); data.writeUInt32BE(ctx._aflags, MILTER_LEN_BYTES); for (var i = 0; i < MAX_MACROS_ENTRIES; i++) { if (!ctx._mac_list[i]) { continue; } var buf = new Buffer(MILTER_LEN_BYTES); buf.writeUInt32BE(i); data = Buffer.concat([data, buf, new Buffer(ctx._mac_list[i])]); } ctx._write_command(SMFIC.OPTNEG, data, callback); return; case SMFIS.NOREPLY: if (bit !== 0 && (ctx._pflags & bit) !== 0 && (ctx._mta_pflags & bit) === 0) { ctx._write_command(SMFIR.CONTINUE, callback); return; } break; } callback(MI_SUCCESS); }; function get_nr_bit(state) { var bit; switch (state) { case ST.CONN: bit = SMFIP.NR_CONN; break; case ST.HELO: bit = SMFIP.NR_HELO; break; case ST.MAIL: bit = SMFIP.NR_MAIL; break; case ST.RCPT: bit = SMFIP.NR_RCPT; break; case ST.DATA: bit = SMFIP.NR_DATA; break; case ST.UNKN: bit = SMFIP.NR_UNKN; break; case ST.HDRS: bit = SMFIP.NR_HDR; break; case ST.EOHS: bit = SMFIP.NR_EOH; break; case ST.BODY: bit = SMFIP.NR_BODY; break; default: bit = 0; break; } return bit; }
//= link_tree ../images //= link_directory ../stylesheets .css //= link letter_opener_web_manifest.js
module.exports = function(grunt) { var path = require('path'), connect = require('connect'), tmp = require('tmp'), fs = require('fs'); function linkInDir(srcpath, dirpath) { var destpath = path.join(dirpath, path.basename(srcpath)); fs.symlinkSync(path.resolve(srcpath), destpath); } function staticPaths(filepaths) { return grunt.file .expand(filepaths) .map(function(p) { return path.join('/', path.basename(process.env.PWD), p); }); } function buildRunner(dirpath, data) { var jst = fs.readFileSync( path.join(__dirname, 'runner.jst'), {encoding: 'utf8'}); fs.writeFileSync( path.join(dirpath, 'index.html'), grunt.template.process(jst, {data: data})); } grunt.registerMultiTask( 'mochaRunner', 'Serve a mocha browser test runner with the configured source and spec scripts.', function() { var options = this.options({ title: 'Mocha Spec Runner', ui: 'bdd', port: 8000, hostname: 'localhost' }); if (options.hostname === '*') { options.hostname = null; } var data = this.data; var done = this.async(); tmp.dir(function(err, dirpath) { var modulesDir = path.resolve(__dirname, '..', 'node_modules'); linkInDir(path.join(modulesDir, 'chai', 'chai.js'), dirpath); linkInDir(path.join(modulesDir, 'mocha', 'mocha.js'), dirpath); linkInDir(path.join(modulesDir, 'mocha', 'mocha.css'), dirpath); linkInDir(process.env.PWD, dirpath); // NOTE: 'src' and 'spec' are deprecated and will be removed in v1.0.0 data.scripts = (data.scripts || []).concat(data.src || [], data.spec || []); buildRunner(dirpath, { options: options, paths: { styles: staticPaths(data.styles || []), scripts: staticPaths(data.scripts) } }); connect() .use(connect.static(dirpath)) .listen(options.port, options.hostname) .on('listening', function() { done(); }); }); }); };
// moment.js // version : 2.0.0 // author : Tim Wood // license : MIT // momentjs.com (function (undefined) { /************************************ Constants ************************************/ var moment, VERSION = "2.0.0", round = Math.round, i, // internal storage for language config files languages = {}, // check for nodeJS hasModule = (typeof module !== 'undefined' && module.exports), // ASP.NET json date format regex aspNetJsonRegex = /^\/?Date\((\-?\d+)/i, // format tokens formattingTokens = /(\[[^\[]*\])|(\\)?(Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|YYYYY|YYYY|YY|a|A|hh?|HH?|mm?|ss?|SS?S?|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LT|LL?L?L?|l{1,4})/g, // parsing tokens parseMultipleFormatChunker = /([0-9a-zA-Z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)/gi, // parsing token regexes parseTokenOneOrTwoDigits = /\d\d?/, // 0 - 99 parseTokenOneToThreeDigits = /\d{1,3}/, // 0 - 999 parseTokenThreeDigits = /\d{3}/, // 000 - 999 parseTokenFourDigits = /\d{1,4}/, // 0 - 9999 parseTokenSixDigits = /[+\-]?\d{1,6}/, // -999,999 - 999,999 parseTokenWord = /[0-9]*[a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF]+\s*?[\u0600-\u06FF]+/i, // any word (or two) characters or numbers including two word month in arabic. parseTokenTimezone = /Z|[\+\-]\d\d:?\d\d/i, // +00:00 -00:00 +0000 -0000 or Z parseTokenT = /T/i, // T (ISO seperator) parseTokenTimestampMs = /[\+\-]?\d+(\.\d{1,3})?/, // 123456789 123456789.123 // preliminary iso regex // 0000-00-00 + T + 00 or 00:00 or 00:00:00 or 00:00:00.000 + +00:00 or +0000 isoRegex = /^\s*\d{4}-\d\d-\d\d((T| )(\d\d(:\d\d(:\d\d(\.\d\d?\d?)?)?)?)?([\+\-]\d\d:?\d\d)?)?/, isoFormat = 'YYYY-MM-DDTHH:mm:ssZ', // iso time formats and regexes isoTimes = [ ['HH:mm:ss.S', /(T| )\d\d:\d\d:\d\d\.\d{1,3}/], ['HH:mm:ss', /(T| )\d\d:\d\d:\d\d/], ['HH:mm', /(T| )\d\d:\d\d/], ['HH', /(T| )\d\d/] ], // timezone chunker "+10:00" > ["10", "00"] or "-1530" > ["-15", "30"] parseTimezoneChunker = /([\+\-]|\d\d)/gi, // getter and setter names proxyGettersAndSetters = 'Month|Date|Hours|Minutes|Seconds|Milliseconds'.split('|'), unitMillisecondFactors = { 'Milliseconds' : 1, 'Seconds' : 1e3, 'Minutes' : 6e4, 'Hours' : 36e5, 'Days' : 864e5, 'Months' : 2592e6, 'Years' : 31536e6 }, // format function strings formatFunctions = {}, // tokens to ordinalize and pad ordinalizeTokens = 'DDD w W M D d'.split(' '), paddedTokens = 'M D H h m s w W'.split(' '), formatTokenFunctions = { M : function () { return this.month() + 1; }, MMM : function (format) { return this.lang().monthsShort(this, format); }, MMMM : function (format) { return this.lang().months(this, format); }, D : function () { return this.date(); }, DDD : function () { return this.dayOfYear(); }, d : function () { return this.day(); }, dd : function (format) { return this.lang().weekdaysMin(this, format); }, ddd : function (format) { return this.lang().weekdaysShort(this, format); }, dddd : function (format) { return this.lang().weekdays(this, format); }, w : function () { return this.week(); }, W : function () { return this.isoWeek(); }, YY : function () { return leftZeroFill(this.year() % 100, 2); }, YYYY : function () { return leftZeroFill(this.year(), 4); }, YYYYY : function () { return leftZeroFill(this.year(), 5); }, a : function () { return this.lang().meridiem(this.hours(), this.minutes(), true); }, A : function () { return this.lang().meridiem(this.hours(), this.minutes(), false); }, H : function () { return this.hours(); }, h : function () { return this.hours() % 12 || 12; }, m : function () { return this.minutes(); }, s : function () { return this.seconds(); }, S : function () { return ~~(this.milliseconds() / 100); }, SS : function () { return leftZeroFill(~~(this.milliseconds() / 10), 2); }, SSS : function () { return leftZeroFill(this.milliseconds(), 3); }, Z : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(a / 60), 2) + ":" + leftZeroFill(~~a % 60, 2); }, ZZ : function () { var a = -this.zone(), b = "+"; if (a < 0) { a = -a; b = "-"; } return b + leftZeroFill(~~(10 * a / 6), 4); }, X : function () { return this.unix(); } }; function padToken(func, count) { return function (a) { return leftZeroFill(func.call(this, a), count); }; } function ordinalizeToken(func) { return function (a) { return this.lang().ordinal(func.call(this, a)); }; } while (ordinalizeTokens.length) { i = ordinalizeTokens.pop(); formatTokenFunctions[i + 'o'] = ordinalizeToken(formatTokenFunctions[i]); } while (paddedTokens.length) { i = paddedTokens.pop(); formatTokenFunctions[i + i] = padToken(formatTokenFunctions[i], 2); } formatTokenFunctions.DDDD = padToken(formatTokenFunctions.DDD, 3); /************************************ Constructors ************************************/ function Language() { } // Moment prototype object function Moment(config) { extend(this, config); } // Duration Constructor function Duration(duration) { var data = this._data = {}, years = duration.years || duration.year || duration.y || 0, months = duration.months || duration.month || duration.M || 0, weeks = duration.weeks || duration.week || duration.w || 0, days = duration.days || duration.day || duration.d || 0, hours = duration.hours || duration.hour || duration.h || 0, minutes = duration.minutes || duration.minute || duration.m || 0, seconds = duration.seconds || duration.second || duration.s || 0, milliseconds = duration.milliseconds || duration.millisecond || duration.ms || 0; // representation for dateAddRemove this._milliseconds = milliseconds + seconds * 1e3 + // 1000 minutes * 6e4 + // 1000 * 60 hours * 36e5; // 1000 * 60 * 60 // Because of dateAddRemove treats 24 hours as different from a // day when working around DST, we need to store them separately this._days = days + weeks * 7; // It is impossible translate months into days without knowing // which months you are are talking about, so we have to store // it separately. this._months = months + years * 12; // The following code bubbles up values, see the tests for // examples of what that means. data.milliseconds = milliseconds % 1000; seconds += absRound(milliseconds / 1000); data.seconds = seconds % 60; minutes += absRound(seconds / 60); data.minutes = minutes % 60; hours += absRound(minutes / 60); data.hours = hours % 24; days += absRound(hours / 24); days += weeks * 7; data.days = days % 30; months += absRound(days / 30); data.months = months % 12; years += absRound(months / 12); data.years = years; } /************************************ Helpers ************************************/ function extend(a, b) { for (var i in b) { if (b.hasOwnProperty(i)) { a[i] = b[i]; } } return a; } function absRound(number) { if (number < 0) { return Math.ceil(number); } else { return Math.floor(number); } } // left zero fill a number // see http://jsperf.com/left-zero-filling for performance comparison function leftZeroFill(number, targetLength) { var output = number + ''; while (output.length < targetLength) { output = '0' + output; } return output; } // helper function for _.addTime and _.subtractTime function addOrSubtractDurationFromMoment(mom, duration, isAdding) { var ms = duration._milliseconds, d = duration._days, M = duration._months, currentDate; if (ms) { mom._d.setTime(+mom + ms * isAdding); } if (d) { mom.date(mom.date() + d * isAdding); } if (M) { currentDate = mom.date(); mom.date(1) .month(mom.month() + M * isAdding) .date(Math.min(currentDate, mom.daysInMonth())); } } // check if is an array function isArray(input) { return Object.prototype.toString.call(input) === '[object Array]'; } // compare two arrays, return the number of differences function compareArrays(array1, array2) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if (~~array1[i] !== ~~array2[i]) { diffs++; } } return diffs + lengthDiff; } /************************************ Languages ************************************/ Language.prototype = { set : function (config) { var prop, i; for (i in config) { prop = config[i]; if (typeof prop === 'function') { this[i] = prop; } else { this['_' + i] = prop; } } }, _months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), months : function (m) { return this._months[m.month()]; }, _monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), monthsShort : function (m) { return this._monthsShort[m.month()]; }, monthsParse : function (monthName) { var i, mom, regex, output; if (!this._monthsParse) { this._monthsParse = []; } for (i = 0; i < 12; i++) { // make the regex if we don't have it already if (!this._monthsParse[i]) { mom = moment([2000, i]); regex = '^' + this.months(mom, '') + '|^' + this.monthsShort(mom, ''); this._monthsParse[i] = new RegExp(regex.replace('.', ''), 'i'); } // test the regex if (this._monthsParse[i].test(monthName)) { return i; } } }, _weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdays : function (m) { return this._weekdays[m.day()]; }, _weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysShort : function (m) { return this._weekdaysShort[m.day()]; }, _weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), weekdaysMin : function (m) { return this._weekdaysMin[m.day()]; }, _longDateFormat : { LT : "h:mm A", L : "MM/DD/YYYY", LL : "MMMM D YYYY", LLL : "MMMM D YYYY LT", LLLL : "dddd, MMMM D YYYY LT" }, longDateFormat : function (key) { var output = this._longDateFormat[key]; if (!output && this._longDateFormat[key.toUpperCase()]) { output = this._longDateFormat[key.toUpperCase()].replace(/MMMM|MM|DD|dddd/g, function (val) { return val.slice(1); }); this._longDateFormat[key] = output; } return output; }, meridiem : function (hours, minutes, isLower) { if (hours > 11) { return isLower ? 'pm' : 'PM'; } else { return isLower ? 'am' : 'AM'; } }, _calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[last] dddd [at] LT', sameElse : 'L' }, calendar : function (key, mom) { var output = this._calendar[key]; return typeof output === 'function' ? output.apply(mom) : output; }, _relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, relativeTime : function (number, withoutSuffix, string, isFuture) { var output = this._relativeTime[string]; return (typeof output === 'function') ? output(number, withoutSuffix, string, isFuture) : output.replace(/%d/i, number); }, pastFuture : function (diff, output) { var format = this._relativeTime[diff > 0 ? 'future' : 'past']; return typeof format === 'function' ? format(output) : format.replace(/%s/i, output); }, ordinal : function (number) { return this._ordinal.replace("%d", number); }, _ordinal : "%d", preparse : function (string) { return string; }, postformat : function (string) { return string; }, week : function (mom) { return weekOfYear(mom, this._week.dow, this._week.doy); }, _week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }; // Loads a language definition into the `languages` cache. The function // takes a key and optionally values. If not in the browser and no values // are provided, it will load the language file module. As a convenience, // this function also returns the language values. function loadLang(key, values) { values.abbr = key; if (!languages[key]) { languages[key] = new Language(); } languages[key].set(values); return languages[key]; } // Determines which language definition to use and returns it. // // With no parameters, it will return the global language. If you // pass in a language key, such as 'en', it will return the // definition for 'en', so long as 'en' has already been loaded using // moment.lang. function getLangDefinition(key) { if (!key) { return moment.fn._lang; } if (!languages[key] && hasModule) { require('./lang/' + key); } return languages[key]; } /************************************ Formatting ************************************/ function removeFormattingTokens(input) { if (input.match(/\[.*\]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format) { var array = format.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function (mom) { var output = ""; for (i = 0; i < length; i++) { output += typeof array[i].call === 'function' ? array[i].call(mom, format) : array[i]; } return output; }; } // format date using native date object function formatMoment(m, format) { var i = 5; function replaceLongDateFormatTokens(input) { return m.lang().longDateFormat(input) || input; } while (i-- && localFormattingTokens.test(format)) { format = format.replace(localFormattingTokens, replaceLongDateFormatTokens); } if (!formatFunctions[format]) { formatFunctions[format] = makeFormatFunction(format); } return formatFunctions[format](m); } /************************************ Parsing ************************************/ // get the regex to find the next token function getParseRegexForToken(token) { switch (token) { case 'DDDD': return parseTokenThreeDigits; case 'YYYY': return parseTokenFourDigits; case 'YYYYY': return parseTokenSixDigits; case 'S': case 'SS': case 'SSS': case 'DDD': return parseTokenOneToThreeDigits; case 'MMM': case 'MMMM': case 'dd': case 'ddd': case 'dddd': case 'a': case 'A': return parseTokenWord; case 'X': return parseTokenTimestampMs; case 'Z': case 'ZZ': return parseTokenTimezone; case 'T': return parseTokenT; case 'MM': case 'DD': case 'YY': case 'HH': case 'hh': case 'mm': case 'ss': case 'M': case 'D': case 'd': case 'H': case 'h': case 'm': case 's': return parseTokenOneOrTwoDigits; default : return new RegExp(token.replace('\\', '')); } } // function to convert string input to date function addTimeToArrayFromToken(token, input, config) { var a, b, datePartArray = config._a; switch (token) { // MONTH case 'M' : // fall through to MM case 'MM' : datePartArray[1] = (input == null) ? 0 : ~~input - 1; break; case 'MMM' : // fall through to MMMM case 'MMMM' : a = getLangDefinition(config._l).monthsParse(input); // if we didn't find a month name, mark the date as invalid. if (a != null) { datePartArray[1] = a; } else { config._isValid = false; } break; // DAY OF MONTH case 'D' : // fall through to DDDD case 'DD' : // fall through to DDDD case 'DDD' : // fall through to DDDD case 'DDDD' : if (input != null) { datePartArray[2] = ~~input; } break; // YEAR case 'YY' : datePartArray[0] = ~~input + (~~input > 68 ? 1900 : 2000); break; case 'YYYY' : case 'YYYYY' : datePartArray[0] = ~~input; break; // AM / PM case 'a' : // fall through to A case 'A' : config._isPm = ((input + '').toLowerCase() === 'pm'); break; // 24 HOUR case 'H' : // fall through to hh case 'HH' : // fall through to hh case 'h' : // fall through to hh case 'hh' : datePartArray[3] = ~~input; break; // MINUTE case 'm' : // fall through to mm case 'mm' : datePartArray[4] = ~~input; break; // SECOND case 's' : // fall through to ss case 'ss' : datePartArray[5] = ~~input; break; // MILLISECOND case 'S' : case 'SS' : case 'SSS' : datePartArray[6] = ~~ (('0.' + input) * 1000); break; // UNIX TIMESTAMP WITH MS case 'X': config._d = new Date(parseFloat(input) * 1000); break; // TIMEZONE case 'Z' : // fall through to ZZ case 'ZZ' : config._useUTC = true; a = (input + '').match(parseTimezoneChunker); if (a && a[1]) { config._tzh = ~~a[1]; } if (a && a[2]) { config._tzm = ~~a[2]; } // reverse offsets if (a && a[0] === '+') { config._tzh = -config._tzh; config._tzm = -config._tzm; } break; } // if the input is null, the date is not valid if (input == null) { config._isValid = false; } } // convert an array to a date. // the array should mirror the parameters below // note: all values past the year are optional and will default to the lowest possible value. // [year, month, day , hour, minute, second, millisecond] function dateFromArray(config) { var i, date, input = []; if (config._d) { return; } for (i = 0; i < 7; i++) { config._a[i] = input[i] = (config._a[i] == null) ? (i === 2 ? 1 : 0) : config._a[i]; } // add the offsets to the time to be parsed so that we can have a clean array for checking isValid input[3] += config._tzh || 0; input[4] += config._tzm || 0; date = new Date(0); if (config._useUTC) { date.setUTCFullYear(input[0], input[1], input[2]); date.setUTCHours(input[3], input[4], input[5], input[6]); } else { date.setFullYear(input[0], input[1], input[2]); date.setHours(input[3], input[4], input[5], input[6]); } config._d = date; } // date from string and format string function makeDateFromStringAndFormat(config) { // This array is used to make a Date, either with `new Date` or `Date.UTC` var tokens = config._f.match(formattingTokens), string = config._i, i, parsedInput; config._a = []; for (i = 0; i < tokens.length; i++) { parsedInput = (getParseRegexForToken(tokens[i]).exec(string) || [])[0]; if (parsedInput) { string = string.slice(string.indexOf(parsedInput) + parsedInput.length); } // don't parse if its not a known token if (formatTokenFunctions[tokens[i]]) { addTimeToArrayFromToken(tokens[i], parsedInput, config); } } // handle am pm if (config._isPm && config._a[3] < 12) { config._a[3] += 12; } // if is 12 am, change hours to 0 if (config._isPm === false && config._a[3] === 12) { config._a[3] = 0; } // return dateFromArray(config); } // date from string and array of format strings function makeDateFromStringAndArray(config) { var tempConfig, tempMoment, bestMoment, scoreToBeat = 99, i, currentDate, currentScore; while (config._f.length) { tempConfig = extend({}, config); tempConfig._f = config._f.pop(); makeDateFromStringAndFormat(tempConfig); tempMoment = new Moment(tempConfig); if (tempMoment.isValid()) { bestMoment = tempMoment; break; } currentScore = compareArrays(tempConfig._a, tempMoment.toArray()); if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempMoment; } } extend(config, bestMoment); } // date from iso format function makeDateFromString(config) { var i, string = config._i; if (isoRegex.exec(string)) { config._f = 'YYYY-MM-DDT'; for (i = 0; i < 4; i++) { if (isoTimes[i][1].exec(string)) { config._f += isoTimes[i][0]; break; } } if (parseTokenTimezone.exec(string)) { config._f += " Z"; } makeDateFromStringAndFormat(config); } else { config._d = new Date(string); } } function makeDateFromInput(config) { var input = config._i, matched = aspNetJsonRegex.exec(input); if (input === undefined) { config._d = new Date(); } else if (matched) { config._d = new Date(+matched[1]); } else if (typeof input === 'string') { makeDateFromString(config); } else if (isArray(input)) { config._a = input.slice(0); dateFromArray(config); } else { config._d = input instanceof Date ? new Date(+input) : new Date(input); } } /************************************ Relative Time ************************************/ // helper function for moment.fn.from, moment.fn.fromNow, and moment.duration.fn.humanize function substituteTimeAgo(string, number, withoutSuffix, isFuture, lang) { return lang.relativeTime(number || 1, !!withoutSuffix, string, isFuture); } function relativeTime(milliseconds, withoutSuffix, lang) { var seconds = round(Math.abs(milliseconds) / 1000), minutes = round(seconds / 60), hours = round(minutes / 60), days = round(hours / 24), years = round(days / 365), args = seconds < 45 && ['s', seconds] || minutes === 1 && ['m'] || minutes < 45 && ['mm', minutes] || hours === 1 && ['h'] || hours < 22 && ['hh', hours] || days === 1 && ['d'] || days <= 25 && ['dd', days] || days <= 45 && ['M'] || days < 345 && ['MM', round(days / 30)] || years === 1 && ['y'] || ['yy', years]; args[2] = withoutSuffix; args[3] = milliseconds > 0; args[4] = lang; return substituteTimeAgo.apply({}, args); } /************************************ Week of Year ************************************/ // firstDayOfWeek 0 = sun, 6 = sat // the day of the week that starts the week // (usually sunday or monday) // firstDayOfWeekOfYear 0 = sun, 6 = sat // the first week is the week that contains the first // of this day of the week // (eg. ISO weeks use thursday (4)) function weekOfYear(mom, firstDayOfWeek, firstDayOfWeekOfYear) { var end = firstDayOfWeekOfYear - firstDayOfWeek, daysToDayOfWeek = firstDayOfWeekOfYear - mom.day(); if (daysToDayOfWeek > end) { daysToDayOfWeek -= 7; } if (daysToDayOfWeek < end - 7) { daysToDayOfWeek += 7; } return Math.ceil(moment(mom).add('d', daysToDayOfWeek).dayOfYear() / 7); } /************************************ Top Level Functions ************************************/ function makeMoment(config) { var input = config._i, format = config._f; if (input === null || input === '') { return null; } if (typeof input === 'string') { config._i = input = getLangDefinition().preparse(input); } if (moment.isMoment(input)) { config = extend({}, input); config._d = new Date(+input._d); } else if (format) { if (isArray(format)) { makeDateFromStringAndArray(config); } else { makeDateFromStringAndFormat(config); } } else { makeDateFromInput(config); } return new Moment(config); } moment = function (input, format, lang) { return makeMoment({ _i : input, _f : format, _l : lang, _isUTC : false }); }; // creating with utc moment.utc = function (input, format, lang) { return makeMoment({ _useUTC : true, _isUTC : true, _l : lang, _i : input, _f : format }); }; // creating with unix timestamp (in seconds) moment.unix = function (input) { return moment(input * 1000); }; // duration moment.duration = function (input, key) { var isDuration = moment.isDuration(input), isNumber = (typeof input === 'number'), duration = (isDuration ? input._data : (isNumber ? {} : input)), ret; if (isNumber) { if (key) { duration[key] = input; } else { duration.milliseconds = input; } } ret = new Duration(duration); if (isDuration && input.hasOwnProperty('_lang')) { ret._lang = input._lang; } return ret; }; // version number moment.version = VERSION; // default format moment.defaultFormat = isoFormat; // This function will load languages and then set the global language. If // no arguments are passed in, it will simply return the current global // language key. moment.lang = function (key, values) { var i; if (!key) { return moment.fn._lang._abbr; } if (values) { loadLang(key, values); } else if (!languages[key]) { getLangDefinition(key); } moment.duration.fn._lang = moment.fn._lang = getLangDefinition(key); }; // returns language data moment.langData = function (key) { if (key && key._lang && key._lang._abbr) { key = key._lang._abbr; } return getLangDefinition(key); }; // compare moment object moment.isMoment = function (obj) { return obj instanceof Moment; }; // for typechecking Duration objects moment.isDuration = function (obj) { return obj instanceof Duration; }; /************************************ Moment Prototype ************************************/ moment.fn = Moment.prototype = { clone : function () { return moment(this); }, valueOf : function () { return +this._d; }, unix : function () { return Math.floor(+this._d / 1000); }, toString : function () { return this.format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); }, toDate : function () { return this._d; }, toJSON : function () { return moment.utc(this).format('YYYY-MM-DD[T]HH:mm:ss.SSS[Z]'); }, toArray : function () { var m = this; return [ m.year(), m.month(), m.date(), m.hours(), m.minutes(), m.seconds(), m.milliseconds() ]; }, isValid : function () { if (this._isValid == null) { if (this._a) { this._isValid = !compareArrays(this._a, (this._isUTC ? moment.utc(this._a) : moment(this._a)).toArray()); } else { this._isValid = !isNaN(this._d.getTime()); } } return !!this._isValid; }, utc : function () { this._isUTC = true; return this; }, local : function () { this._isUTC = false; return this; }, format : function (inputString) { var output = formatMoment(this, inputString || moment.defaultFormat); return this.lang().postformat(output); }, add : function (input, val) { var dur; // switch args to support add('s', 1) and add(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, 1); return this; }, subtract : function (input, val) { var dur; // switch args to support subtract('s', 1) and subtract(1, 's') if (typeof input === 'string') { dur = moment.duration(+val, input); } else { dur = moment.duration(input, val); } addOrSubtractDurationFromMoment(this, dur, -1); return this; }, diff : function (input, units, asFloat) { var that = this._isUTC ? moment(input).utc() : moment(input).local(), zoneDiff = (this.zone() - that.zone()) * 6e4, diff, output; if (units) { // standardize on singular form units = units.replace(/s$/, ''); } if (units === 'year' || units === 'month') { diff = (this.daysInMonth() + that.daysInMonth()) * 432e5; // 24 * 60 * 60 * 1000 / 2 output = ((this.year() - that.year()) * 12) + (this.month() - that.month()); output += ((this - moment(this).startOf('month')) - (that - moment(that).startOf('month'))) / diff; if (units === 'year') { output = output / 12; } } else { diff = (this - that) - zoneDiff; output = units === 'second' ? diff / 1e3 : // 1000 units === 'minute' ? diff / 6e4 : // 1000 * 60 units === 'hour' ? diff / 36e5 : // 1000 * 60 * 60 units === 'day' ? diff / 864e5 : // 1000 * 60 * 60 * 24 units === 'week' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7 diff; } return asFloat ? output : absRound(output); }, from : function (time, withoutSuffix) { return moment.duration(this.diff(time)).lang(this.lang()._abbr).humanize(!withoutSuffix); }, fromNow : function (withoutSuffix) { return this.from(moment(), withoutSuffix); }, calendar : function () { var diff = this.diff(moment().startOf('day'), 'days', true), format = diff < -6 ? 'sameElse' : diff < -1 ? 'lastWeek' : diff < 0 ? 'lastDay' : diff < 1 ? 'sameDay' : diff < 2 ? 'nextDay' : diff < 7 ? 'nextWeek' : 'sameElse'; return this.format(this.lang().calendar(format, this)); }, isLeapYear : function () { var year = this.year(); return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; }, isDST : function () { return (this.zone() < moment([this.year()]).zone() || this.zone() < moment([this.year(), 5]).zone()); }, day : function (input) { var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); return input == null ? day : this.add({ d : input - day }); }, startOf: function (units) { units = units.replace(/s$/, ''); // the following switch intentionally omits break keywords // to utilize falling through the cases. switch (units) { case 'year': this.month(0); /* falls through */ case 'month': this.date(1); /* falls through */ case 'week': case 'day': this.hours(0); /* falls through */ case 'hour': this.minutes(0); /* falls through */ case 'minute': this.seconds(0); /* falls through */ case 'second': this.milliseconds(0); /* falls through */ } // weeks are a special case if (units === 'week') { this.day(0); } return this; }, endOf: function (units) { return this.startOf(units).add(units.replace(/s?$/, 's'), 1).subtract('ms', 1); }, isAfter: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) > +moment(input).startOf(units); }, isBefore: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) < +moment(input).startOf(units); }, isSame: function (input, units) { units = typeof units !== 'undefined' ? units : 'millisecond'; return +this.clone().startOf(units) === +moment(input).startOf(units); }, zone : function () { return this._isUTC ? 0 : this._d.getTimezoneOffset(); }, daysInMonth : function () { return moment.utc([this.year(), this.month() + 1, 0]).date(); }, dayOfYear : function (input) { var dayOfYear = round((moment(this).startOf('day') - moment(this).startOf('year')) / 864e5) + 1; return input == null ? dayOfYear : this.add("d", (input - dayOfYear)); }, isoWeek : function (input) { var week = weekOfYear(this, 1, 4); return input == null ? week : this.add("d", (input - week) * 7); }, week : function (input) { var week = this.lang().week(this); return input == null ? week : this.add("d", (input - week) * 7); }, // If passed a language key, it will set the language for this // instance. Otherwise, it will return the language configuration // variables for this instance. lang : function (key) { if (key === undefined) { return this._lang; } else { this._lang = getLangDefinition(key); return this; } } }; // helper for adding shortcuts function makeGetterAndSetter(name, key) { moment.fn[name] = moment.fn[name + 's'] = function (input) { var utc = this._isUTC ? 'UTC' : ''; if (input != null) { this._d['set' + utc + key](input); return this; } else { return this._d['get' + utc + key](); } }; } // loop through and add shortcuts (Month, Date, Hours, Minutes, Seconds, Milliseconds) for (i = 0; i < proxyGettersAndSetters.length; i ++) { makeGetterAndSetter(proxyGettersAndSetters[i].toLowerCase().replace(/s$/, ''), proxyGettersAndSetters[i]); } // add shortcut for year (uses different syntax than the getter/setter 'year' == 'FullYear') makeGetterAndSetter('year', 'FullYear'); // add plural methods moment.fn.days = moment.fn.day; moment.fn.weeks = moment.fn.week; moment.fn.isoWeeks = moment.fn.isoWeek; /************************************ Duration Prototype ************************************/ moment.duration.fn = Duration.prototype = { weeks : function () { return absRound(this.days() / 7); }, valueOf : function () { return this._milliseconds + this._days * 864e5 + this._months * 2592e6; }, humanize : function (withSuffix) { var difference = +this, output = relativeTime(difference, !withSuffix, this.lang()); if (withSuffix) { output = this.lang().pastFuture(difference, output); } return this.lang().postformat(output); }, lang : moment.fn.lang }; function makeDurationGetter(name) { moment.duration.fn[name] = function () { return this._data[name]; }; } function makeDurationAsGetter(name, factor) { moment.duration.fn['as' + name] = function () { return +this / factor; }; } for (i in unitMillisecondFactors) { if (unitMillisecondFactors.hasOwnProperty(i)) { makeDurationAsGetter(i, unitMillisecondFactors[i]); makeDurationGetter(i.toLowerCase()); } } makeDurationAsGetter('Weeks', 6048e5); /************************************ Default Lang ************************************/ // Set default language, other languages will inherit from English. moment.lang('en', { ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); /************************************ Exposing Moment ************************************/ // CommonJS module is defined if (hasModule) { module.exports = moment; } /*global ender:false */ if (typeof ender === 'undefined') { // here, `this` means `window` in the browser, or `global` on the server // add `moment` as a global object via a string identifier, // for Closure Compiler "advanced" mode this['moment'] = moment; } /*global define:false */ if (typeof define === "function" && define.amd) { define("moment", [], function () { return moment; }); } }).call(this);
/** * @license AngularJS v1.2.14 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngRoute * @description * * # ngRoute * * The `ngRoute` module provides routing and deeplinking services and directives for angular apps. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * * <div doc-module-components="ngRoute"></div> */ /* global -ngRouteModule */ var ngRouteModule = angular.module('ngRoute', ['ng']). provider('$route', $RouteProvider); /** * @ngdoc provider * @name $routeProvider * @function * * @description * * Used for configuring routes. * * ## Example * See {@link ngRoute.$route#example $route} for an example of configuring and using `ngRoute`. * * ## Dependencies * Requires the {@link ngRoute `ngRoute`} module to be installed. */ function $RouteProvider(){ function inherit(parent, extra) { return angular.extend(new (angular.extend(function() {}, {prototype:parent}))(), extra); } var routes = {}; /** * @ngdoc method * @name $routeProvider#when * * @param {string} path Route path (matched against `$location.path`). If `$location.path` * contains redundant trailing slash or is missing one, the route will still match and the * `$location.path` will be updated to add or drop the trailing slash to exactly match the * route definition. * * * `path` can contain named groups starting with a colon: e.g. `:name`. All characters up * to the next slash are matched and stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain named groups starting with a colon and ending with a star: * e.g.`:name*`. All characters are eagerly stored in `$routeParams` under the given `name` * when the route matches. * * `path` can contain optional named groups with a question mark: e.g.`:name?`. * * For example, routes like `/color/:color/largecode/:largecode*\/edit` will match * `/color/brown/largecode/code/with/slashes/edit` and extract: * * * `color: brown` * * `largecode: code/with/slashes`. * * * @param {Object} route Mapping information to be assigned to `$route.current` on route * match. * * Object properties: * * - `controller` รขโ‚ฌโ€œ `{(string|function()=}` รขโ‚ฌโ€œ Controller fn that should be associated with * newly created scope or the name of a {@link angular.Module#controller registered * controller} if passed as a string. * - `controllerAs` รขโ‚ฌโ€œ `{string=}` รขโ‚ฌโ€œ A controller alias name. If present the controller will be * published to scope under the `controllerAs` name. * - `template` รขโ‚ฌโ€œ `{string=|function()=}` รขโ‚ฌโ€œ html template as a string or a function that * returns an html template as a string which should be used by {@link * ngRoute.directive:ngView ngView} or {@link ng.directive:ngInclude ngInclude} directives. * This property takes precedence over `templateUrl`. * * If `template` is a function, it will be called with the following parameters: * * - `{Array.&lt;Object&gt;}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `templateUrl` รขโ‚ฌโ€œ `{string=|function()=}` รขโ‚ฌโ€œ path or function that returns a path to an html * template that should be used by {@link ngRoute.directive:ngView ngView}. * * If `templateUrl` is a function, it will be called with the following parameters: * * - `{Array.&lt;Object&gt;}` - route parameters extracted from the current * `$location.path()` by applying the current route * * - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should * be injected into the controller. If any of these dependencies are promises, the router * will wait for them all to be resolved or one to be rejected before the controller is * instantiated. * If all the promises are resolved successfully, the values of the resolved promises are * injected and {@link ngRoute.$route#$routeChangeSuccess $routeChangeSuccess} event is * fired. If any of the promises are rejected the * {@link ngRoute.$route#$routeChangeError $routeChangeError} event is fired. The map object * is: * * - `key` รขโ‚ฌโ€œ `{string}`: a name of a dependency to be injected into the controller. * - `factory` - `{string|function}`: If `string` then it is an alias for a service. * Otherwise if function, then it is {@link auto.$injector#invoke injected} * and the return value is treated as the dependency. If the result is a promise, it is * resolved before its value is injected into the controller. Be aware that * `ngRoute.$routeParams` will still refer to the previous route within these resolve * functions. Use `$route.current.params` to access the new route parameters, instead. * * - `redirectTo` รขโ‚ฌโ€œ {(string|function())=} รขโ‚ฌโ€œ value to update * {@link ng.$location $location} path with and trigger route redirection. * * If `redirectTo` is a function, it will be called with the following parameters: * * - `{Object.<string>}` - route parameters extracted from the current * `$location.path()` by applying the current route templateUrl. * - `{string}` - current `$location.path()` * - `{Object}` - current `$location.search()` * * The custom `redirectTo` function is expected to return a string which will be used * to update `$location.path()` and `$location.search()`. * * - `[reloadOnSearch=true]` - {boolean=} - reload route when only `$location.search()` * or `$location.hash()` changes. * * If the option is set to `false` and url in the browser changes, then * `$routeUpdate` event is broadcasted on the root scope. * * - `[caseInsensitiveMatch=false]` - {boolean=} - match routes without being case sensitive * * If the option is set to `true`, then the particular route can be matched without being * case sensitive * * @returns {Object} self * * @description * Adds a new route definition to the `$route` service. */ this.when = function(path, route) { routes[path] = angular.extend( {reloadOnSearch: true}, route, path && pathRegExp(path, route) ); // create redirection for trailing slashes if (path) { var redirectPath = (path[path.length-1] == '/') ? path.substr(0, path.length-1) : path +'/'; routes[redirectPath] = angular.extend( {redirectTo: path}, pathRegExp(redirectPath, route) ); } return this; }; /** * @param path {string} path * @param opts {Object} options * @return {?Object} * * @description * Normalizes the given path, returning a regular expression * and the original path. * * Inspired by pathRexp in visionmedia/express/lib/utils.js. */ function pathRegExp(path, opts) { var insensitive = opts.caseInsensitiveMatch, ret = { originalPath: path, regexp: path }, keys = ret.keys = []; path = path .replace(/([().])/g, '\\$1') .replace(/(\/)?:(\w+)([\?\*])?/g, function(_, slash, key, option){ var optional = option === '?' ? option : null; var star = option === '*' ? option : null; keys.push({ name: key, optional: !!optional }); slash = slash || ''; return '' + (optional ? '' : slash) + '(?:' + (optional ? slash : '') + (star && '(.+?)' || '([^/]+)') + (optional || '') + ')' + (optional || ''); }) .replace(/([\/$\*])/g, '\\$1'); ret.regexp = new RegExp('^' + path + '$', insensitive ? 'i' : ''); return ret; } /** * @ngdoc method * @name $routeProvider#otherwise * * @description * Sets route definition that will be used on route change when no other route definition * is matched. * * @param {Object} params Mapping information to be assigned to `$route.current`. * @returns {Object} self */ this.otherwise = function(params) { this.when(null, params); return this; }; this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache', '$sce', function($rootScope, $location, $routeParams, $q, $injector, $http, $templateCache, $sce) { /** * @ngdoc service * @name $route * @requires $location * @requires $routeParams * * @property {Object} current Reference to the current route definition. * The route definition contains: * * - `controller`: The controller constructor as define in route definition. * - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for * controller instantiation. The `locals` contain * the resolved values of the `resolve` map. Additionally the `locals` also contain: * * - `$scope` - The current route scope. * - `$template` - The current route template HTML. * * @property {Array.&lt;Object&gt;} routes Array of all configured routes. * * @description * `$route` is used for deep-linking URLs to controllers and views (HTML partials). * It watches `$location.url()` and tries to map the path to an existing route definition. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * You can define routes through {@link ngRoute.$routeProvider $routeProvider}'s API. * * The `$route` service is typically used in conjunction with the * {@link ngRoute.directive:ngView `ngView`} directive and the * {@link ngRoute.$routeParams `$routeParams`} service. * * @example This example shows how changing the URL hash causes the `$route` to match a route against the URL, and the `ngView` pulls in the partial. Note that this example is using {@link ng.directive:script inlined templates} to get it working on jsfiddle as well. <example name="$route-service" module="ngRouteExample" deps="angular-route.js" fixBase="true"> <file name="index.html"> <div ng-controller="MainCntl"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div ng-view></div> <hr /> <pre>$location.path() = {{$location.path()}}</pre> <pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre> <pre>$route.current.params = {{$route.current.params}}</pre> <pre>$route.current.scope.name = {{$route.current.scope.name}}</pre> <pre>$routeParams = {{$routeParams}}</pre> </div> </file> <file name="book.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> </file> <file name="chapter.html"> controller: {{name}}<br /> Book Id: {{params.bookId}}<br /> Chapter Id: {{params.chapterId}} </file> <file name="script.js"> angular.module('ngRouteExample', ['ngRoute']) .config(function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, resolve: { // I will cause a 1 second delay delay: function($q, $timeout) { var delay = $q.defer(); $timeout(delay.resolve, 1000); return delay.promise; } } }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($scope, $route, $routeParams, $location) { $scope.$route = $route; $scope.$location = $location; $scope.$routeParams = $routeParams; } function BookCntl($scope, $routeParams) { $scope.name = "BookCntl"; $scope.params = $routeParams; } function ChapterCntl($scope, $routeParams) { $scope.name = "ChapterCntl"; $scope.params = $routeParams; } </file> <file name="protractor.js" type="protractor"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name $route#$routeChangeStart * @eventType broadcast on root scope * @description * Broadcasted before a route change. At this point the route services starts * resolving all of the dependencies needed for the route change to occur. * Typically this involves fetching the view template as well as any dependencies * defined in `resolve` route property. Once all of the dependencies are resolved * `$routeChangeSuccess` is fired. * * @param {Object} angularEvent Synthetic event object. * @param {Route} next Future route information. * @param {Route} current Current route information. */ /** * @ngdoc event * @name $route#$routeChangeSuccess * @eventType broadcast on root scope * @description * Broadcasted after a route dependencies are resolved. * {@link ngRoute.directive:ngView ngView} listens for the directive * to instantiate the controller and render the view. * * @param {Object} angularEvent Synthetic event object. * @param {Route} current Current route information. * @param {Route|Undefined} previous Previous route information, or undefined if current is * first route entered. */ /** * @ngdoc event * @name $route#$routeChangeError * @eventType broadcast on root scope * @description * Broadcasted if any of the resolve promises are rejected. * * @param {Object} angularEvent Synthetic event object * @param {Route} current Current route information. * @param {Route} previous Previous route information. * @param {Route} rejection Rejection of the promise. Usually the error of the failed promise. */ /** * @ngdoc event * @name $route#$routeUpdate * @eventType broadcast on root scope * @description * * The `reloadOnSearch` property has been set to false, and we are reusing the same * instance of the Controller. */ var forceReload = false, $route = { routes: routes, /** * @ngdoc method * @name $route#reload * * @description * Causes `$route` service to reload the current route even if * {@link ng.$location $location} hasn't changed. * * As a result of that, {@link ngRoute.directive:ngView ngView} * creates new scope, reinstantiates the controller. */ reload: function() { forceReload = true; $rootScope.$evalAsync(updateRoute); } }; $rootScope.$on('$locationChangeSuccess', updateRoute); return $route; ///////////////////////////////////////////////////// /** * @param on {string} current url * @param route {Object} route regexp to match the url against * @return {?Object} * * @description * Check if the route matches the current url. * * Inspired by match in * visionmedia/express/lib/router/router.js. */ function switchRouteMatcher(on, route) { var keys = route.keys, params = {}; if (!route.regexp) return null; var m = route.regexp.exec(on); if (!m) return null; for (var i = 1, len = m.length; i < len; ++i) { var key = keys[i - 1]; var val = 'string' == typeof m[i] ? decodeURIComponent(m[i]) : m[i]; if (key && val) { params[key.name] = val; } } return params; } function updateRoute() { var next = parseRoute(), last = $route.current; if (next && last && next.$$route === last.$$route && angular.equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) { last.params = next.params; angular.copy(last.params, $routeParams); $rootScope.$broadcast('$routeUpdate', last); } else if (next || last) { forceReload = false; $rootScope.$broadcast('$routeChangeStart', next, last); $route.current = next; if (next) { if (next.redirectTo) { if (angular.isString(next.redirectTo)) { $location.path(interpolate(next.redirectTo, next.params)).search(next.params) .replace(); } else { $location.url(next.redirectTo(next.pathParams, $location.path(), $location.search())) .replace(); } } } $q.when(next). then(function() { if (next) { var locals = angular.extend({}, next.resolve), template, templateUrl; angular.forEach(locals, function(value, key) { locals[key] = angular.isString(value) ? $injector.get(value) : $injector.invoke(value); }); if (angular.isDefined(template = next.template)) { if (angular.isFunction(template)) { template = template(next.params); } } else if (angular.isDefined(templateUrl = next.templateUrl)) { if (angular.isFunction(templateUrl)) { templateUrl = templateUrl(next.params); } templateUrl = $sce.getTrustedResourceUrl(templateUrl); if (angular.isDefined(templateUrl)) { next.loadedTemplateUrl = templateUrl; template = $http.get(templateUrl, {cache: $templateCache}). then(function(response) { return response.data; }); } } if (angular.isDefined(template)) { locals['$template'] = template; } return $q.all(locals); } }). // after route change then(function(locals) { if (next == $route.current) { if (next) { next.locals = locals; angular.copy(next.params, $routeParams); } $rootScope.$broadcast('$routeChangeSuccess', next, last); } }, function(error) { if (next == $route.current) { $rootScope.$broadcast('$routeChangeError', next, last, error); } }); } } /** * @returns {Object} the current active route, by matching it against the URL */ function parseRoute() { // Match a route var params, match; angular.forEach(routes, function(route, path) { if (!match && (params = switchRouteMatcher($location.path(), route))) { match = inherit(route, { params: angular.extend({}, $location.search(), params), pathParams: params}); match.$$route = route; } }); // No route matched; fallback to "otherwise" route return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}}); } /** * @returns {string} interpolation of the redirect path with the parameters */ function interpolate(string, params) { var result = []; angular.forEach((string||'').split(':'), function(segment, i) { if (i === 0) { result.push(segment); } else { var segmentMatch = segment.match(/(\w+)(.*)/); var key = segmentMatch[1]; result.push(params[key]); result.push(segmentMatch[2] || ''); delete params[key]; } }); return result.join(''); } }]; } ngRouteModule.provider('$routeParams', $RouteParamsProvider); /** * @ngdoc service * @name $routeParams * @requires $route * * @description * The `$routeParams` service allows you to retrieve the current set of route parameters. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * The route parameters are a combination of {@link ng.$location `$location`}'s * {@link ng.$location#search `search()`} and {@link ng.$location#path `path()`}. * The `path` parameters are extracted when the {@link ngRoute.$route `$route`} path is matched. * * In case of parameter name collision, `path` params take precedence over `search` params. * * The service guarantees that the identity of the `$routeParams` object will remain unchanged * (but its properties will likely change) even when a route change occurs. * * Note that the `$routeParams` are only updated *after* a route change completes successfully. * This means that you cannot rely on `$routeParams` being correct in route resolve functions. * Instead you can use `$route.current.params` to access the new route's parameters. * * @example * ```js * // Given: * // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby * // Route: /Chapter/:chapterId/Section/:sectionId * // * // Then * $routeParams ==> {chapterId:1, sectionId:2, search:'moby'} * ``` */ function $RouteParamsProvider() { this.$get = function() { return {}; }; } ngRouteModule.directive('ngView', ngViewFactory); ngRouteModule.directive('ngView', ngViewFillContentFactory); /** * @ngdoc directive * @name ngView * @restrict ECA * * @description * # Overview * `ngView` is a directive that complements the {@link ngRoute.$route $route} service by * including the rendered template of the current route into the main layout (`index.html`) file. * Every time the current route changes, the included view changes with it according to the * configuration of the `$route` service. * * Requires the {@link ngRoute `ngRoute`} module to be installed. * * @animations * enter - animation is used to bring new content into the browser. * leave - animation is used to animate existing content away. * * The enter and leave animation occur concurrently. * * @scope * @priority 400 * @param {string=} onload Expression to evaluate whenever the view updates. * * @param {string=} autoscroll Whether `ngView` should call {@link ng.$anchorScroll * $anchorScroll} to scroll the viewport after the view is updated. * * - If the attribute is not set, disable scrolling. * - If the attribute is set without value, enable scrolling. * - Otherwise enable scrolling only if the `autoscroll` attribute value evaluated * as an expression yields a truthy value. * @example <example name="ngView-directive" module="ngViewExample" deps="angular-route.js;angular-animate.js" animations="true" fixBase="true"> <file name="index.html"> <div ng-controller="MainCntl as main"> Choose: <a href="Book/Moby">Moby</a> | <a href="Book/Moby/ch/1">Moby: Ch1</a> | <a href="Book/Gatsby">Gatsby</a> | <a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> | <a href="Book/Scarlet">Scarlet Letter</a><br/> <div class="view-animate-container"> <div ng-view class="view-animate"></div> </div> <hr /> <pre>$location.path() = {{main.$location.path()}}</pre> <pre>$route.current.templateUrl = {{main.$route.current.templateUrl}}</pre> <pre>$route.current.params = {{main.$route.current.params}}</pre> <pre>$route.current.scope.name = {{main.$route.current.scope.name}}</pre> <pre>$routeParams = {{main.$routeParams}}</pre> </div> </file> <file name="book.html"> <div> controller: {{book.name}}<br /> Book Id: {{book.params.bookId}}<br /> </div> </file> <file name="chapter.html"> <div> controller: {{chapter.name}}<br /> Book Id: {{chapter.params.bookId}}<br /> Chapter Id: {{chapter.params.chapterId}} </div> </file> <file name="animations.css"> .view-animate-container { position:relative; height:100px!important; position:relative; background:white; border:1px solid black; height:40px; overflow:hidden; } .view-animate { padding:10px; } .view-animate.ng-enter, .view-animate.ng-leave { -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 1.5s; display:block; width:100%; border-left:1px solid black; position:absolute; top:0; left:0; right:0; bottom:0; padding:10px; } .view-animate.ng-enter { left:100%; } .view-animate.ng-enter.ng-enter-active { left:0; } .view-animate.ng-leave.ng-leave-active { left:-100%; } </file> <file name="script.js"> angular.module('ngViewExample', ['ngRoute', 'ngAnimate'], function($routeProvider, $locationProvider) { $routeProvider.when('/Book/:bookId', { templateUrl: 'book.html', controller: BookCntl, controllerAs: 'book' }); $routeProvider.when('/Book/:bookId/ch/:chapterId', { templateUrl: 'chapter.html', controller: ChapterCntl, controllerAs: 'chapter' }); // configure html5 to get links working on jsfiddle $locationProvider.html5Mode(true); }); function MainCntl($route, $routeParams, $location) { this.$route = $route; this.$location = $location; this.$routeParams = $routeParams; } function BookCntl($routeParams) { this.name = "BookCntl"; this.params = $routeParams; } function ChapterCntl($routeParams) { this.name = "ChapterCntl"; this.params = $routeParams; } </file> <file name="protractor.js" type="protractor"> it('should load and compile correct template', function() { element(by.linkText('Moby: Ch1')).click(); var content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: ChapterCntl/); expect(content).toMatch(/Book Id\: Moby/); expect(content).toMatch(/Chapter Id\: 1/); element(by.partialLinkText('Scarlet')).click(); content = element(by.css('[ng-view]')).getText(); expect(content).toMatch(/controller\: BookCntl/); expect(content).toMatch(/Book Id\: Scarlet/); }); </file> </example> */ /** * @ngdoc event * @name ngView#$viewContentLoaded * @eventType emit on the current ngView scope * @description * Emitted every time the ngView content is reloaded. */ ngViewFactory.$inject = ['$route', '$anchorScroll', '$animate']; function ngViewFactory( $route, $anchorScroll, $animate) { return { restrict: 'ECA', terminal: true, priority: 400, transclude: 'element', link: function(scope, $element, attr, ctrl, $transclude) { var currentScope, currentElement, previousElement, autoScrollExp = attr.autoscroll, onloadExp = attr.onload || ''; scope.$on('$routeChangeSuccess', update); update(); function cleanupLastView() { if(previousElement) { previousElement.remove(); previousElement = null; } if(currentScope) { currentScope.$destroy(); currentScope = null; } if(currentElement) { $animate.leave(currentElement, function() { previousElement = null; }); previousElement = currentElement; currentElement = null; } } function update() { var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (angular.isDefined(template)) { var newScope = scope.$new(); var current = $route.current; // Note: This will also link all children of ng-view that were contained in the original // html. If that content contains controllers, ... they could pollute/change the scope. // However, using ng-view on an element with additional content does not make sense... // Note: We can't remove them in the cloneAttchFn of $transclude as that // function is called before linking the content, which would apply child // directives to non existing elements. var clone = $transclude(newScope, function(clone) { $animate.enter(clone, null, currentElement || $element, function onNgViewEnter () { if (angular.isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) { $anchorScroll(); } }); cleanupLastView(); }); currentElement = clone; currentScope = current.scope = newScope; currentScope.$emit('$viewContentLoaded'); currentScope.$eval(onloadExp); } else { cleanupLastView(); } } } }; } // This directive is called during the $transclude call of the first `ngView` directive. // It will replace and compile the content of the element with the loaded template. // We need this directive so that the element content is already filled when // the link function of another directive on the same element as ngView // is called. ngViewFillContentFactory.$inject = ['$compile', '$controller', '$route']; function ngViewFillContentFactory($compile, $controller, $route) { return { restrict: 'ECA', priority: -400, link: function(scope, $element) { var current = $route.current, locals = current.locals; $element.html(locals.$template); var link = $compile($element.contents()); if (current.controller) { locals.$scope = scope; var controller = $controller(current.controller, locals); if (current.controllerAs) { scope[current.controllerAs] = controller; } $element.data('$ngControllerController', controller); $element.children().data('$ngControllerController', controller); } link(scope); } }; } })(window, window.angular);
var os = require('os') var path = require('path') var fs = require('fs') var builder = require('xmlbuilder') var pathIsAbsolute = require('path-is-absolute') // concatenate test suite(s) and test description by default function defaultNameFormatter (browser, result) { return result.suite.join(' ') + ' ' + result.description } var JUnitReporter = function (baseReporterDecorator, config, logger, helper, formatError) { var log = logger.create('reporter.junit') var reporterConfig = config.junitReporter || {} var pkgName = reporterConfig.suite || '' var outputDir = reporterConfig.outputDir var outputFile = reporterConfig.outputFile var useBrowserName = reporterConfig.useBrowserName var nameFormatter = reporterConfig.nameFormatter || defaultNameFormatter var classNameFormatter = reporterConfig.classNameFormatter var suites var pendingFileWritings = 0 var fileWritingFinished = function () {} var allMessages = [] if (outputDir == null) { outputDir = '.' } outputDir = helper.normalizeWinPath(path.resolve(config.basePath, outputDir)) + path.sep if (typeof useBrowserName === 'undefined') { useBrowserName = true } baseReporterDecorator(this) this.adapters = [ function (msg) { allMessages.push(msg) } ] var initializeXmlForBrowser = function (browser) { var timestamp = (new Date()).toISOString().substr(0, 19) var suite = suites[browser.id] = builder.create('testsuite') suite.att('name', browser.name) .att('package', pkgName) .att('timestamp', timestamp) .att('id', 0) .att('hostname', os.hostname()) suite.ele('properties') .ele('property', {name: 'browser.fullName', value: browser.fullName}) } var writeXmlForBrowser = function (browser) { var safeBrowserName = browser.name.replace(/ /g, '_') var newOutputFile if (outputFile && pathIsAbsolute(outputFile)) { newOutputFile = outputFile } else if (outputFile != null) { var dir = useBrowserName ? path.join(outputDir, safeBrowserName) : outputDir newOutputFile = path.join(dir, outputFile) } else if (useBrowserName) { newOutputFile = path.join(outputDir, 'TESTS-' + safeBrowserName + '.xml') } else { newOutputFile = path.join(outputDir, 'TESTS.xml') } var xmlToOutput = suites[browser.id] if (!xmlToOutput) { return // don't die if browser didn't start } pendingFileWritings++ helper.mkdirIfNotExists(path.dirname(newOutputFile), function () { fs.writeFile(newOutputFile, xmlToOutput.end({pretty: true}), function (err) { if (err) { log.warn('Cannot write JUnit xml\n\t' + err.message) } else { log.debug('JUnit results written to "%s".', newOutputFile) } if (!--pendingFileWritings) { fileWritingFinished() } }) }) } var getClassName = function (browser, result) { var browserName = browser.name.replace(/ /g, '_').replace(/\./g, '_') + '.' return (useBrowserName ? browserName : '') + (pkgName ? pkgName + '.' : '') + result.suite[0] } this.onRunStart = function (browsers) { suites = Object.create(null) // TODO(vojta): remove once we don't care about Karma 0.10 browsers.forEach(initializeXmlForBrowser) } this.onBrowserStart = function (browser) { initializeXmlForBrowser(browser) } this.onBrowserComplete = function (browser) { var suite = suites[browser.id] var result = browser.lastResult if (!suite || !result) { return // don't die if browser didn't start } suite.att('tests', result.total) suite.att('errors', result.disconnected || result.error ? 1 : 0) suite.att('failures', result.failed) suite.att('time', (result.netTime || 0) / 1000) suite.ele('system-out').dat(allMessages.join() + '\n') suite.ele('system-err') writeXmlForBrowser(browser) } this.onRunComplete = function () { suites = null allMessages.length = 0 } this.specSuccess = this.specSkipped = this.specFailure = function (browser, result) { var spec = suites[browser.id].ele('testcase', { name: nameFormatter(browser, result), time: ((result.time || 0) / 1000), classname: (typeof classNameFormatter === 'function' ? classNameFormatter : getClassName)(browser, result) }) if (result.skipped) { spec.ele('skipped') } if (!result.success) { result.log.forEach(function (err) { spec.ele('failure', {type: ''}, formatError(err)) }) } } // wait for writing all the xml files, before exiting this.onExit = function (done) { if (pendingFileWritings) { fileWritingFinished = done } else { done() } } } JUnitReporter.$inject = ['baseReporterDecorator', 'config', 'logger', 'helper', 'formatError'] // PUBLISH DI MODULE module.exports = { 'reporter:junit': ['type', JUnitReporter] }
'use strict'; /* globals require, module, console, process */ var superagent = require('superagent'); var config = require('./config'); var refreshIntervaldId; var specifiedInterval; var buildUpdateUrl = function(host) { return 'https://' + host.username + ':' + host.password + '@dyndns.strato.com/nic/update?hostname=' + host.hostname; }; var updateDyanmicDnsIP = function(host) { var updateUrl = buildUpdateUrl(host); superagent .get(updateUrl) .end(function(err, res) { if(err) { return console.log(err); } if(res.text.indexOf('badauth') > -1) console.log('Wrong login informations: ', res.text); if(res.text.indexOf('abuse') > -1) console.log('Too much update requests or it\'s still the same IP: ', res.text); if(res.text.indexOf('good') > -1) console.log('IP is successfully updated: ', res.text); }); }; var goThrowAllHosts = function(config) { var hosts = config.hosts; if(hosts.length === 0) { console.log('Host configuration is empty, first add an host to update'); process.exit(); } for(var host in hosts) { updateDyanmicDnsIP(hosts[host]); } }; var setUpdateIntervalAndStartUpdating = function(config, minutes) { goThrowAllHosts(config); refreshIntervaldId = setInterval(function() { goThrowAllHosts(config); }, minutes); }; var renewConfigurationWatcher = function() { config.renewConfigurationWatcher(function() { restartUpdating(); }); } var startUpdating = function(interval) { renewConfigurationWatcher(); config.getConfiguration(function(data) { var configurationFile = JSON.parse(data); specifiedInterval = interval || 5; var minutes = 1000 * 60 * specifiedInterval; setUpdateIntervalAndStartUpdating(configurationFile, minutes); }); }; var restartUpdating = function() { clearInterval(refreshIntervaldId); startUpdating(specifiedInterval); }; module.exports.start = startUpdating;
/** * combo loader for KISSY. using combo to load module files. * @ignore * @author yiminghe@gmail.com */ (function (S, undefined) { // ie11 is a new one! var oldIE = S.UA.ieMode < 10; function loadScripts(runtime, rss, callback, charset, timeout) { var count = rss && rss.length, errorList = [], successList = []; function complete() { if (!(--count)) { callback(successList, errorList); } } S.each(rss, function (rs) { var mod; var config = { timeout: timeout, success: function () { successList.push(rs); if (mod && currentMod) { // standard browser(except ie9) fire load after KISSY.add immediately logger.debug('standard browser get mod name after load : ' + mod.name); Utils.registerModule(runtime, mod.name, currentMod.factory, currentMod.config); currentMod = undefined; } complete(); }, error: function () { errorList.push(rs); complete(); }, charset: charset }; if (!rs.combine) { mod = rs.mods[0]; if (mod.getType() === 'css') { mod = undefined; } else if (oldIE) { startLoadModName = mod.name; startLoadModTime = S.now(); config.attrs = { 'data-mod-name': mod.name }; } } S.Config.loadModsFn(rs, config); }); } var logger = S.getLogger('s/loader'); var Loader = S.Loader, Status = Loader.Status, Utils = Loader.Utils, getHash = Utils.getHash, LOADING = Status.LOADING, LOADED = Status.LOADED, READY_TO_ATTACH = Status.READY_TO_ATTACH, ERROR = Status.ERROR, groupTag = S.now(); ComboLoader.groupTag = groupTag; /** * @class KISSY.Loader.ComboLoader * using combo to load module files * @param runtime KISSY * @param waitingModules * @private */ function ComboLoader(runtime, waitingModules) { S.mix(this, { runtime: runtime, waitingModules: waitingModules }); } var currentMod; var startLoadModName; var startLoadModTime; function checkKISSYRequire(config, factory) { // use require primitive statement // function(S,require){require('node')} if (!config && typeof factory === 'function' && factory.length > 1) { var requires = Utils.getRequiresFromFn(factory); if (requires.length) { config = config || {}; config.requires = requires; } } else { // KISSY.add(function(){},{requires:[]}) if (config && config.requires && !config.cjs) { config.cjs = 0; } } return config; } ComboLoader.add = function (name, factory, config, runtime, argsLen) { // KISSY.add('xx',[],function(){}); if (argsLen === 3 && S.isArray(factory)) { var tmp = factory; factory = config; config = { requires: tmp, cjs: 1 }; } // KISSY.add(function(){}), KISSY.add('a'), KISSY.add(function(){},{requires:[]}) if (typeof name === 'function' || argsLen === 1) { config = factory; factory = name; config = checkKISSYRequire(config, factory); if (oldIE) { // http://groups.google.com/group/commonjs/browse_thread/thread/5a3358ece35e688e/43145ceccfb1dc02#43145ceccfb1dc02 name = findModuleNameByInteractive(); // S.log('oldIE get modName by interactive: ' + name); Utils.registerModule(runtime, name, factory, config); startLoadModName = null; startLoadModTime = 0; } else { // ๅ…ถไป–ๆต่งˆๅ™จ onload ๆ—ถ๏ผŒๅ…ณ่”ๆจกๅ—ๅไธŽๆจกๅ—ๅฎšไน‰ currentMod = { factory: factory, config: config }; } } else { // KISSY.add('x',function(){},{requires:[]}) if (oldIE) { startLoadModName = null; startLoadModTime = 0; } else { currentMod = undefined; } config = checkKISSYRequire(config, factory); Utils.registerModule(runtime, name, factory, config); } }; // oldIE ็‰นๆœ‰๏ผŒๆ‰พๅˆฐๅฝ“ๅ‰ๆญฃๅœจไบคไบ’็š„่„šๆœฌ๏ผŒๆ นๆฎ่„šๆœฌๅ็กฎๅฎšๆจกๅ—ๅ // ๅฆ‚ๆžœๆ‰พไธๅˆฐ๏ผŒ่ฟ”ๅ›žๅ‘้€ๅ‰้‚ฃไธช่„šๆœฌ function findModuleNameByInteractive() { var scripts = S.Env.host.document.getElementsByTagName('script'), re, i, name, script; for (i = scripts.length - 1; i >= 0; i--) { script = scripts[i]; if (script.readyState === 'interactive') { re = script; break; } } if (re) { name = re.getAttribute('data-mod-name'); } else { // sometimes when read module file from cache, // interactive status is not triggered // module code is executed right after inserting into dom // i has to preserve module name before insert module script into dom, // then get it back here logger.debug('can not find interactive script,time diff : ' + (S.now() - startLoadModTime)); logger.debug('old_ie get mod name from cache : ' + startLoadModName); name = startLoadModName; } return name; } function debugRemoteModules(rss) { S.each(rss, function (rs) { var ms = []; S.each(rs.mods, function (m) { if (m.status === LOADED) { ms.push(m.name); } }); if (ms.length) { logger.info('load remote modules: "' + ms.join(', ') + '" from: "' + rs.fullpath + '"'); } }); } function getCommonPrefix(str1, str2) { str1 = str1.split(/\//); str2 = str2.split(/\//); var l = Math.min(str1.length, str2.length); for (var i = 0; i < l; i++) { if (str1[i] !== str2[i]) { break; } } return str1.slice(0, i).join('/') + '/'; } S.augment(ComboLoader, { /** * load modules asynchronously */ use: function (normalizedModNames) { var self = this, allModNames, comboUrls, timeout = S.Config.timeout, runtime = self.runtime; allModNames = S.keys(self.calculate(normalizedModNames)); Utils.createModulesInfo(runtime, allModNames); comboUrls = self.getComboUrls(allModNames); // load css first to avoid page blink S.each(comboUrls.css, function (cssOne) { loadScripts(runtime, cssOne, function (success, error) { if ('@DEBUG@') { debugRemoteModules(success); } S.each(success, function (one) { S.each(one.mods, function (mod) { Utils.registerModule(runtime, mod.name, S.noop); // notify all loader instance mod.notifyAll(); }); }); S.each(error, function (one) { S.each(one.mods, function (mod) { var msg = mod.name + ' is not loaded! can not find module in path : ' + one.fullpath; S.log(msg, 'error'); mod.status = ERROR; // notify all loader instance mod.notifyAll(); }); }); }, cssOne.charset, timeout); }); // jss css download in parallel S.each(comboUrls.js, function (jsOne) { loadScripts(runtime, jsOne, function (success) { if ('@DEBUG@') { debugRemoteModules(success); } S.each(jsOne, function (one) { S.each(one.mods, function (mod) { // fix #111 // https://github.com/kissyteam/kissy/issues/111 if (!mod.factory) { var msg = mod.name + ' is not loaded! can not find module in path : ' + one.fullpath; S.log(msg, 'error'); mod.status = ERROR; } // notify all loader instance mod.notifyAll(); }); }); }, jsOne.charset, timeout); }); }, /** * calculate dependency */ calculate: function (modNames, cache, ret) { var i, m, mod, modStatus, self = this, waitingModules = self.waitingModules, runtime = self.runtime; ret = ret || {}; // ๆ้ซ˜ๆ€ง่ƒฝ๏ผŒไธ็”จๆฏไธชๆจกๅ—้ƒฝๅ†ๆฌกๅ…จ้ƒจไพ่ต–่ฎก็ฎ— // ๅšไธช็ผ“ๅญ˜๏ผŒๆฏไธชๆจกๅ—ๅฏนๅบ”็š„ๅพ…ๅŠจๆ€ๅŠ ่ฝฝๆจกๅ— cache = cache || {}; for (i = 0; i < modNames.length; i++) { m = modNames[i]; if (cache[m]) { continue; } cache[m] = 1; mod = Utils.createModuleInfo(runtime, m); modStatus = mod.status; if (modStatus >= READY_TO_ATTACH) { continue; } if (modStatus !== LOADED) { if (!waitingModules.contains(m)) { if (modStatus !== LOADING) { mod.status = LOADING; ret[m] = 1; } /*jshint loopfunc:true*/ mod.wait(function (mod) { waitingModules.remove(mod.name); // notify current loader instance waitingModules.notifyAll(); }); waitingModules.add(m); } } self.calculate(mod.getNormalizedRequires(), cache, ret); } return ret; }, /** * get combo mods for modNames */ getComboMods: function (modNames, comboPrefixes) { var comboMods = {}, packageUri, runtime = this.runtime, i = 0, l = modNames.length, modName, mod, packageInfo, type, typedCombos, mods, tag, charset, packagePath, packageName, group, fullpath; for (; i < l; ++i) { modName = modNames[i]; mod = Utils.createModuleInfo(runtime, modName); type = mod.getType(); fullpath = mod.getFullPath(); packageInfo = mod.getPackage(); packageName = packageInfo.name; charset = packageInfo.getCharset(); tag = packageInfo.getTag(); group = packageInfo.getGroup(); packagePath = packageInfo.getPrefixUriForCombo(); packageUri = packageInfo.getPackageUri(); var comboName = packageName; // whether group packages can be combined (except default package and non-combo modules) if ((mod.canBeCombined = packageInfo.isCombine() && S.startsWith(fullpath, packagePath)) && group) { // combined package name comboName = group + '_' + charset + '_' + groupTag; var groupPrefixUri; if ((groupPrefixUri = comboPrefixes[comboName])) { if (groupPrefixUri.isSameOriginAs(packageUri)) { groupPrefixUri.setPath(getCommonPrefix(groupPrefixUri.getPath(), packageUri.getPath())); } else { comboName = packageName; comboPrefixes[packageName] = packageUri; } } else { comboPrefixes[comboName] = packageUri.clone(); } } else { comboPrefixes[packageName] = packageUri; } typedCombos = comboMods[type] = comboMods[type] || {}; if (!(mods = typedCombos[comboName])) { mods = typedCombos[comboName] = []; mods.charset = charset; mods.tags = [tag]; // [package tag] } else { if (!(mods.tags.length === 1 && mods.tags[0] === tag)) { mods.tags.push(tag); } } mods.push(mod); } return comboMods; }, /** * Get combo urls */ getComboUrls: function (modNames) { var runtime = this.runtime, Config = runtime.Config, comboPrefix = Config.comboPrefix, comboSep = Config.comboSep, maxFileNum = Config.comboMaxFileNum, maxUrlLength = Config.comboMaxUrlLength; var comboPrefixes = {}; // {type, {comboName, [modInfo]}}} var comboMods = this.getComboMods(modNames, comboPrefixes); // {type, {comboName, [url]}}} var comboRes = {}; // generate combo urls for (var type in comboMods) { comboRes[type] = {}; for (var comboName in comboMods[type]) { var currentComboUrls = []; var currentComboMods = []; var mods = comboMods[type][comboName]; var tags = mods.tags; var tag = tags.length > 1 ? getHash(tags.join('')) : tags[0]; var suffix = (tag ? '?t=' + encodeURIComponent(tag) + '.' + type : ''), suffixLength = suffix.length, basePrefix = comboPrefixes[comboName].toString(), baseLen = basePrefix.length, prefix = basePrefix + comboPrefix, res = comboRes[type][comboName] = []; var l = prefix.length; res.charset = mods.charset; res.mods = []; /*jshint loopfunc:true*/ var pushComboUrl = function () { //noinspection JSReferencingMutableVariableFromClosure res.push({ combine: 1, fullpath: prefix + currentComboUrls.join(comboSep) + suffix, mods: currentComboMods }); }; for (var i = 0; i < mods.length; i++) { var currentMod = mods[i]; res.mods.push(currentMod); var fullpath = currentMod.getFullPath(); if (!currentMod.canBeCombined) { res.push({ combine: 0, fullpath: fullpath, mods: [currentMod] }); continue; } // ignore query parameter var path = fullpath.slice(baseLen).replace(/\?.*$/, ''); currentComboUrls.push(path); currentComboMods.push(currentMod); if (currentComboUrls.length > maxFileNum || (l + currentComboUrls.join(comboSep).length + suffixLength > maxUrlLength)) { currentComboUrls.pop(); currentComboMods.pop(); pushComboUrl(); currentComboUrls = []; currentComboMods = []; i--; } } if (currentComboUrls.length) { pushComboUrl(); } } } return comboRes; } }); Loader.ComboLoader = ComboLoader; })(KISSY); /* 2013-09-11 - union simple loader and combo loader 2013-07-25 ้˜ฟๅค, yiminghe - support group combo for packages 2013-06-04 yiminghe@gmail.com - refactor merge combo loader and simple loader - support error callback 2012-02-20 yiminghe note: - three status 0: initialized LOADED: load into page ATTACHED: factory executed */
// This is the base controller. Used for base routes, such as the default index/root path, 404 error pages, and others. module.exports = { index: { handler: function(request, reply){ // Render the view with the custom greeting reply.view('index', { title: 'Awesome Boiler Plate Homepage' }); }, app: { name: 'index' } }, about: { handler: function(request, reply){ reply.view('about', { title: 'This is the example about page' }); }, app: { name: 'about' } }, missing: { handler: function(request, reply){ reply.view('404', { title: 'You found a missing page, but won the 404 error!' }).code(404); }, app: { name: '404' } } }
"use strict"; var core_1 = require('@angular/core'); var CardsComponent = (function () { function CardsComponent() { } CardsComponent = __decorate([ core_1.Component({ templateUrl: 'app/components/cards/cards.component.html' }), __metadata('design:paramtypes', []) ], CardsComponent); return CardsComponent; }()); exports.CardsComponent = CardsComponent; //# sourceMappingURL=cards.component.js.map
/*! * Author: Abdullah A Almsaeed * Date: 4 Jan 2014 * Description: * This file should be included in all pages !**/ /* * Global variables. If you change any of these vars, don't forget * to change the values in the less files! */ var left_side_width = 220; //Sidebar width in pixels $(function() { "use strict"; //Enable sidebar toggle $("[data-toggle='offcanvas']").click(function(e) { e.preventDefault(); //If window is small enough, enable sidebar push menu if ($(window).width() <= 992) { $('.row-offcanvas').toggleClass('active'); $('.left-side').removeClass("collapse-left"); $(".right-side").removeClass("strech"); $('.row-offcanvas').toggleClass("relative"); } else { //Else, enable content streching $('.left-side').toggleClass("collapse-left"); $(".right-side").toggleClass("strech"); } }); //Add hover support for touch devices $('.btn').bind('touchstart', function() { $(this).addClass('hover'); }).bind('touchend', function() { $(this).removeClass('hover'); }); //Activate tooltips $("[data-toggle='tooltip']").tooltip(); /* * Add collapse and remove events to boxes */ $("[data-widget='collapse']").click(function() { //Find the box parent var box = $(this).parents(".box").first(); //Find the body and the footer var bf = box.find(".box-body, .box-footer"); if (!box.hasClass("collapsed-box")) { box.addClass("collapsed-box"); bf.slideUp(); } else { box.removeClass("collapsed-box"); bf.slideDown(); } }); /* * ADD SLIMSCROLL TO THE TOP NAV DROPDOWNS * --------------------------------------- */ $(".navbar .menu").slimscroll({ height: "200px", alwaysVisible: false, size: "3px" }).css("width", "100%"); /* * INITIALIZE BUTTON TOGGLE * ------------------------ */ $('.btn-group[data-toggle="btn-toggle"]').each(function() { var group = $(this); $(this).find(".btn").click(function(e) { group.find(".btn.active").removeClass("active"); $(this).addClass("active"); e.preventDefault(); }); }); $("[data-widget='remove']").click(function() { //Find the box parent var box = $(this).parents(".box").first(); box.slideUp(); }); /* Sidebar tree view */ $(".sidebar .treeview").tree(); /* * Make sure that the sidebar is streched full height * --------------------------------------------- * We are gonna assign a min-height value every time the * wrapper gets resized and upon page load. We will use * Ben Alman's method for detecting the resize event. * **/ function _fix() { //Get window height and the wrapper height var height = $(window).height() - $("body > .header").height(); $(".wrapper").css("min-height", height + "px"); var content = $(".wrapper").height(); //If the wrapper height is greater than the window if (content > height) //then set sidebar height to the wrapper $(".left-side, html, body").css("min-height", content + "px"); else { //Otherwise, set the sidebar to the height of the window $(".left-side, html, body").css("min-height", height + "px"); } } //Fire upon load _fix(); //Fire when wrapper is resized $(".wrapper").resize(function() { _fix(); fix_sidebar(); }); //Fix the fixed layout sidebar scroll bug fix_sidebar(); /* * We are gonna initialize all checkbox and radio inputs to * iCheck plugin in. * You can find the documentation at http://fronteed.com/iCheck/ */ }); function fix_sidebar() { //Make sure the body tag has the .fixed class if (!$("body").hasClass("fixed")) { return; } //Add slimscroll $(".sidebar").slimscroll({ height: ($(window).height() - $(".header").height()) + "px", color: "rgba(0,0,0,0.2)" }); } function change_layout() { $("body").toggleClass("fixed"); fix_sidebar(); } function change_skin(cls) { $("body").removeClass("skin-blue skin-black"); $("body").addClass(cls); } /*END DEMO*/ $(window).load(function() { /*! pace 0.4.17 */ (function() { var a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V = [].slice, W = {}.hasOwnProperty, X = function(a, b) { function c() { this.constructor = a } for (var d in b) W.call(b, d) && (a[d] = b[d]); return c.prototype = b.prototype, a.prototype = new c, a.__super__ = b.prototype, a }, Y = [].indexOf || function(a) { for (var b = 0, c = this.length; c > b; b++) if (b in this && this[b] === a) return b; return-1 }; for (t = {catchupTime:500, initialRate:.03, minTime:500, ghostTime:500, maxProgressPerFrame:10, easeFactor:1.25, startOnPageLoad:!0, restartOnPushState:!0, restartOnRequestAfter:500, target:"body", elements:{checkInterval:100, selectors:["body"]}, eventLag:{minSamples:10, sampleCount:3, lagThreshold:3}, ajax:{trackMethods:["GET"], trackWebSockets:!1}}, B = function() { var a; return null != (a = "undefined" != typeof performance && null !== performance ? "function" == typeof performance.now ? performance.now() : void 0 : void 0) ? a : +new Date }, D = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame, s = window.cancelAnimationFrame || window.mozCancelAnimationFrame, null == D && (D = function(a) { return setTimeout(a, 50) }, s = function(a) { return clearTimeout(a) }), F = function(a) { var b, c; return b = B(), (c = function() { var d; return d = B() - b, d >= 33 ? (b = B(), a(d, function() { return D(c) })) : setTimeout(c, 33 - d) })() }, E = function() { var a, b, c; return c = arguments[0], b = arguments[1], a = 3 <= arguments.length ? V.call(arguments, 2) : [], "function" == typeof c[b] ? c[b].apply(c, a) : c[b] }, u = function() { var a, b, c, d, e, f, g; for (b = arguments[0], d = 2 <= arguments.length?V.call(arguments, 1):[], f = 0, g = d.length; g > f; f++) if (c = d[f]) for (a in c) W.call(c, a) && (e = c[a], null != b[a] && "object" == typeof b[a] && null != e && "object" == typeof e ? u(b[a], e) : b[a] = e); return b }, p = function(a) { var b, c, d, e, f; for (c = b = 0, e = 0, f = a.length; f > e; e++) d = a[e], c += Math.abs(d), b++; return c / b }, w = function(a, b) { var c, d, e; if (null == a && (a = "options"), null == b && (b = !0), e = document.querySelector("[data-pace-" + a + "]")) { if (c = e.getAttribute("data-pace-" + a), !b) return c; try { return JSON.parse(c) } catch (f) { return d = f, "undefined" != typeof console && null !== console ? console.error("Error parsing inline pace options", d) : void 0 } } }, g = function() { function a() { } return a.prototype.on = function(a, b, c, d) { var e; return null == d && (d = !1), null == this.bindings && (this.bindings = {}), null == (e = this.bindings)[a] && (e[a] = []), this.bindings[a].push({handler: b, ctx: c, once: d}) }, a.prototype.once = function(a, b, c) { return this.on(a, b, c, !0) }, a.prototype.off = function(a, b) { var c, d, e; if (null != (null != (d = this.bindings) ? d[a] : void 0)) { if (null == b) return delete this.bindings[a]; for (c = 0, e = []; c < this.bindings[a].length; ) this.bindings[a][c].handler === b ? e.push(this.bindings[a].splice(c, 1)) : e.push(c++); return e } }, a.prototype.trigger = function() { var a, b, c, d, e, f, g, h, i; if (c = arguments[0], a = 2 <= arguments.length ? V.call(arguments, 1) : [], null != (g = this.bindings) ? g[c] : void 0) { for (e = 0, i = []; e < this.bindings[c].length; ) h = this.bindings[c][e], d = h.handler, b = h.ctx, f = h.once, d.apply(null != b ? b : this, a), f ? i.push(this.bindings[c].splice(e, 1)) : i.push(e++); return i } }, a }(), null == window.Pace && (window.Pace = {}), u(Pace, g.prototype), C = Pace.options = u({}, t, window.paceOptions, w()), S = ["ajax", "document", "eventLag", "elements"], O = 0, Q = S.length; Q > O; O++) I = S[O], C[I] === !0 && (C[I] = t[I]); i = function(a) { function b() { return T = b.__super__.constructor.apply(this, arguments) } return X(b, a), b }(Error), b = function() { function a() { this.progress = 0 } return a.prototype.getElement = function() { var a; if (null == this.el) { if (a = document.querySelector(C.target), !a) throw new i; this.el = document.createElement("div"), this.el.className = "pace pace-active", document.body.className = document.body.className.replace("pace-done", ""), document.body.className += " pace-running", this.el.innerHTML = '<div class="pace-progress">\n <div class="pace-progress-inner"></div>\n</div>\n<div class="pace-activity"></div>', null != a.firstChild ? a.insertBefore(this.el, a.firstChild) : a.appendChild(this.el) } return this.el }, a.prototype.finish = function() { var a; return a = this.getElement(), a.className = a.className.replace("pace-active", ""), a.className += " pace-inactive", document.body.className = document.body.className.replace("pace-running", ""), document.body.className += " pace-done" }, a.prototype.update = function(a) { return this.progress = a, this.render() }, a.prototype.destroy = function() { try { this.getElement().parentNode.removeChild(this.getElement()) } catch (a) { i = a } return this.el = void 0 }, a.prototype.render = function() { var a, b; return null == document.querySelector(C.target) ? !1 : (a = this.getElement(), a.children[0].style.width = "" + this.progress + "%", (!this.lastRenderedProgress || this.lastRenderedProgress | 0 !== this.progress | 0) && (a.children[0].setAttribute("data-progress-text", "" + (0 | this.progress) + "%"), this.progress >= 100 ? b = "99" : (b = this.progress < 10 ? "0" : "", b += 0 | this.progress), a.children[0].setAttribute("data-progress", "" + b)), this.lastRenderedProgress = this.progress) }, a.prototype.done = function() { return this.progress >= 100 }, a }(), h = function() { function a() { this.bindings = {} } return a.prototype.trigger = function(a, b) { var c, d, e, f, g; if (null != this.bindings[a]) { for (f = this.bindings[a], g = [], d = 0, e = f.length; e > d; d++) c = f[d], g.push(c.call(this, b)); return g } }, a.prototype.on = function(a, b) { var c; return null == (c = this.bindings)[a] && (c[a] = []), this.bindings[a].push(b) }, a }(), N = window.XMLHttpRequest, M = window.XDomainRequest, L = window.WebSocket, v = function(a, b) { var c, d, e, f; f = []; for (d in b.prototype) try { e = b.prototype[d], null == a[d] && "function" != typeof e ? f.push(a[d] = e) : f.push(void 0) } catch (g) { c = g } return f }, z = [], Pace.ignore = function() { var a, b, c; return b = arguments[0], a = 2 <= arguments.length ? V.call(arguments, 1) : [], z.unshift("ignore"), c = b.apply(null, a), z.shift(), c }, Pace.track = function() { var a, b, c; return b = arguments[0], a = 2 <= arguments.length ? V.call(arguments, 1) : [], z.unshift("track"), c = b.apply(null, a), z.shift(), c }, H = function(a) { var b; if (null == a && (a = "GET"), "track" === z[0]) return"force"; if (!z.length && C.ajax) { if ("socket" === a && C.ajax.trackWebSockets) return!0; if (b = a.toUpperCase(), Y.call(C.ajax.trackMethods, b) >= 0) return!0 } return!1 }, j = function(a) { function b() { var a, c = this; b.__super__.constructor.apply(this, arguments), a = function(a) { var b; return b = a.open, a.open = function(d, e) { return H(d) && c.trigger("request", {type: d, url: e, request: a}), b.apply(a, arguments) } }, window.XMLHttpRequest = function(b) { var c; return c = new N(b), a(c), c }, v(window.XMLHttpRequest, N), null != M && (window.XDomainRequest = function() { var b; return b = new M, a(b), b }, v(window.XDomainRequest, M)), null != L && C.ajax.trackWebSockets && (window.WebSocket = function(a, b) { var d; return d = new L(a, b), H("socket") && c.trigger("request", {type: "socket", url: a, protocols: b, request: d}), d }, v(window.WebSocket, L)) } return X(b, a), b }(h), P = null, x = function() { return null == P && (P = new j), P }, x().on("request", function(b) { var c, d, e, f; return f = b.type, e = b.request, Pace.running || C.restartOnRequestAfter === !1 && "force" !== H(f) ? void 0 : (d = arguments, c = C.restartOnRequestAfter || 0, "boolean" == typeof c && (c = 0), setTimeout(function() { var b, c, g, h, i, j; if (b = "socket" === f ? e.readyState < 2 : 0 < (h = e.readyState) && 4 > h) { for (Pace.restart(), i = Pace.sources, j = [], c = 0, g = i.length; g > c; c++) { if (I = i[c], I instanceof a) { I.watch.apply(I, d); break } j.push(void 0) } return j } }, c)) }), a = function() { function a() { var a = this; this.elements = [], x().on("request", function() { return a.watch.apply(a, arguments) }) } return a.prototype.watch = function(a) { var b, c, d; return d = a.type, b = a.request, c = "socket" === d ? new m(b) : new n(b), this.elements.push(c) }, a }(), n = function() { function a(a) { var b, c, d, e, f, g, h = this; if (this.progress = 0, null != window.ProgressEvent) for (c = null, a.addEventListener("progress", function(a) { return h.progress = a.lengthComputable ? 100 * a.loaded / a.total : h.progress + (100 - h.progress) / 2 }), g = ["load", "abort", "timeout", "error"], d = 0, e = g.length; e > d; d++) b = g[d], a.addEventListener(b, function() { return h.progress = 100 }); else f = a.onreadystatechange, a.onreadystatechange = function() { var b; return 0 === (b = a.readyState) || 4 === b ? h.progress = 100 : 3 === a.readyState && (h.progress = 50), "function" == typeof f ? f.apply(null, arguments) : void 0 } } return a }(), m = function() { function a(a) { var b, c, d, e, f = this; for (this.progress = 0, e = ["error", "open"], c = 0, d = e.length; d > c; c++) b = e[c], a.addEventListener(b, function() { return f.progress = 100 }) } return a }(), d = function() { function a(a) { var b, c, d, f; for (null == a && (a = {}), this.elements = [], null == a.selectors && (a.selectors = []), f = a.selectors, c = 0, d = f.length; d > c; c++) b = f[c], this.elements.push(new e(b)) } return a }(), e = function() { function a(a) { this.selector = a, this.progress = 0, this.check() } return a.prototype.check = function() { var a = this; return document.querySelector(this.selector) ? this.done() : setTimeout(function() { return a.check() }, C.elements.checkInterval) }, a.prototype.done = function() { return this.progress = 100 }, a }(), c = function() { function a() { var a, b, c = this; this.progress = null != (b = this.states[document.readyState]) ? b : 100, a = document.onreadystatechange, document.onreadystatechange = function() { return null != c.states[document.readyState] && (c.progress = c.states[document.readyState]), "function" == typeof a ? a.apply(null, arguments) : void 0 } } return a.prototype.states = {loading: 0, interactive: 50, complete: 100}, a }(), f = function() { function a() { var a, b, c, d, e, f = this; this.progress = 0, a = 0, e = [], d = 0, c = B(), b = setInterval(function() { var g; return g = B() - c - 50, c = B(), e.push(g), e.length > C.eventLag.sampleCount && e.shift(), a = p(e), ++d >= C.eventLag.minSamples && a < C.eventLag.lagThreshold ? (f.progress = 100, clearInterval(b)) : f.progress = 100 * (3 / (a + 3)) }, 50) } return a }(), l = function() { function a(a) { this.source = a, this.last = this.sinceLastUpdate = 0, this.rate = C.initialRate, this.catchup = 0, this.progress = this.lastProgress = 0, null != this.source && (this.progress = E(this.source, "progress")) } return a.prototype.tick = function(a, b) { var c; return null == b && (b = E(this.source, "progress")), b >= 100 && (this.done = !0), b === this.last ? this.sinceLastUpdate += a : (this.sinceLastUpdate && (this.rate = (b - this.last) / this.sinceLastUpdate), this.catchup = (b - this.progress) / C.catchupTime, this.sinceLastUpdate = 0, this.last = b), b > this.progress && (this.progress += this.catchup * a), c = 1 - Math.pow(this.progress / 100, C.easeFactor), this.progress += c * this.rate * a, this.progress = Math.min(this.lastProgress + C.maxProgressPerFrame, this.progress), this.progress = Math.max(0, this.progress), this.progress = Math.min(100, this.progress), this.lastProgress = this.progress, this.progress }, a }(), J = null, G = null, q = null, K = null, o = null, r = null, Pace.running = !1, y = function() { return C.restartOnPushState ? Pace.restart() : void 0 }, null != window.history.pushState && (R = window.history.pushState, window.history.pushState = function() { return y(), R.apply(window.history, arguments) }), null != window.history.replaceState && (U = window.history.replaceState, window.history.replaceState = function() { return y(), U.apply(window.history, arguments) }), k = {ajax: a, elements: d, document: c, eventLag: f}, (A = function() { var a, c, d, e, f, g, h, i; for (Pace.sources = J = [], g = ["ajax", "elements", "document", "eventLag"], c = 0, e = g.length; e > c; c++) a = g[c], C[a] !== !1 && J.push(new k[a](C[a])); for (i = null != (h = C.extraSources)?h:[], d = 0, f = i.length; f > d; d++) I = i[d], J.push(new I(C)); return Pace.bar = q = new b, G = [], K = new l })(), Pace.stop = function() { return Pace.trigger("stop"), Pace.running = !1, q.destroy(), r = !0, null != o && ("function" == typeof s && s(o), o = null), A() }, Pace.restart = function() { return Pace.trigger("restart"), Pace.stop(), Pace.start() }, Pace.go = function() { return Pace.running = !0, q.render(), r = !1, o = F(function(a, b) { var c, d, e, f, g, h, i, j, k, m, n, o, p, s, t, u, v; for (j = 100 - q.progress, d = o = 0, e = !0, h = p = 0, t = J.length; t > p; h = ++p) for (I = J[h], m = null != G[h]?G[h]:G[h] = [], g = null != (v = I.elements)?v:[I], i = s = 0, u = g.length; u > s; i = ++s) f = g[i], k = null != m[i] ? m[i] : m[i] = new l(f), e &= k.done, k.done || (d++, o += k.tick(a)); return c = o / d, q.update(K.tick(a, c)), n = B(), q.done() || e || r ? (q.update(100), Pace.trigger("done"), setTimeout(function() { return q.finish(), Pace.running = !1, Pace.trigger("hide") }, Math.max(C.ghostTime, Math.min(C.minTime, B() - n)))) : b() }) }, Pace.start = function(a) { u(C, a), Pace.running = !0; try { q.render() } catch (b) { i = b } return document.querySelector(".pace") ? (Pace.trigger("start"), Pace.go()) : setTimeout(Pace.start, 50) }, "function" == typeof define && define.amd ? define('theme-app', [], function() { return Pace }) : "object" == typeof exports ? module.exports = Pace : C.startOnPageLoad && Pace.start() }).call(this); }); /* * BOX REFRESH BUTTON * ------------------ * This is a custom plugin to use with the compenet BOX. It allows you to add * a refresh button to the box. It converts the box's state to a loading state. * * USAGE: * $("#box-widget").boxRefresh( options ); * */ (function($) { "use strict"; $.fn.boxRefresh = function(options) { // Render options var settings = $.extend({ //Refressh button selector trigger: ".refresh-btn", //File source to be loaded (e.g: ajax/src.php) source: "", //Callbacks onLoadStart: function(box) { }, //Right after the button has been clicked onLoadDone: function(box) { } //When the source has been loaded }, options); //The overlay var overlay = $('<div class="overlay"></div><div class="loading-img"></div>'); return this.each(function() { //if a source is specified if (settings.source === "") { if (console) { console.log("Please specify a source first - boxRefresh()"); } return; } //the box var box = $(this); //the button var rBtn = box.find(settings.trigger).first(); //On trigger click rBtn.click(function(e) { e.preventDefault(); //Add loading overlay start(box); //Perform ajax call box.find(".box-body").load(settings.source, function() { done(box); }); }); }); function start(box) { //Add overlay and loading img box.append(overlay); settings.onLoadStart.call(box); } function done(box) { //Remove overlay and loading img box.find(overlay).remove(); settings.onLoadDone.call(box); } }; })(jQuery); /* * SIDEBAR MENU * ------------ * This is a custom plugin for the sidebar menu. It provides a tree view. * * Usage: * $(".sidebar).tree(); * * Note: This plugin does not accept any options. Instead, it only requires a class * added to the element that contains a sub-menu. * * When used with the sidebar, for example, it would look something like this: * <ul class='sidebar-menu'> * <li class="treeview active"> * <a href="#>Menu</a> * <ul class='treeview-menu'> * <li class='active'><a href=#>Level 1</a></li> * </ul> * </li> * </ul> * * Add .active class to <li> elements if you want the menu to be open automatically * on page load. See above for an example. */ (function($) { "use strict"; $.fn.tree = function() { return this.each(function() { var btn = $(this).children("a").first(); var menu = $(this).children(".treeview-menu").first(); var isActive = $(this).hasClass('active'); //initialize already active menus if (isActive) { menu.show(); btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down"); } //Slide open or close the menu on link click btn.click(function(e) { e.preventDefault(); if (isActive) { //Slide up to close menu menu.slideUp(); isActive = false; btn.children(".fa-angle-down").first().removeClass("fa-angle-down").addClass("fa-angle-left"); btn.parent("li").removeClass("active"); } else { //Slide down to open menu menu.slideDown(); isActive = true; btn.children(".fa-angle-left").first().removeClass("fa-angle-left").addClass("fa-angle-down"); btn.parent("li").addClass("active"); } }); /* Add margins to submenu elements to give it a tree look */ menu.find("li > a").each(function() { var pad = parseInt($(this).css("margin-left")) + 10; $(this).css({"margin-left": pad + "px"}); }); }); }; }(jQuery)); /* * TODO LIST CUSTOM PLUGIN * ----------------------- * This plugin depends on iCheck plugin for checkbox and radio inputs */ (function($) { "use strict"; $.fn.todolist = function(options) { // Render options var settings = $.extend({ //When the user checks the input onCheck: function(ele) { }, //When the user unchecks the input onUncheck: function(ele) { } }, options); return this.each(function() { $('input', this).on('ifChecked', function(event) { var ele = $(this).parents("li").first(); ele.toggleClass("done"); settings.onCheck.call(ele); }); $('input', this).on('ifUnchecked', function(event) { var ele = $(this).parents("li").first(); ele.toggleClass("done"); settings.onUncheck.call(ele); }); }); }; }(jQuery)); /* CENTER ELEMENTS */ (function($) { "use strict"; jQuery.fn.center = function(parent) { if (parent) { parent = this.parent(); } else { parent = window; } this.css({ "position": "absolute", "top": ((($(parent).height() - this.outerHeight()) / 2) + $(parent).scrollTop() + "px"), "left": ((($(parent).width() - this.outerWidth()) / 2) + $(parent).scrollLeft() + "px") }); return this; } }(jQuery)); /* * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */ (function($, h, c) { var a = $([]), e = $.resize = $.extend($.resize, {}), i, k = "setTimeout", j = "resize", d = j + "-special-event", b = "delay", f = "throttleWindow"; e[b] = 250; e[f] = true; $.event.special[j] = {setup: function() { if (!e[f] && this[k]) { return false; } var l = $(this); a = a.add(l); $.data(this, d, {w: l.width(), h: l.height()}); if (a.length === 1) { g(); } }, teardown: function() { if (!e[f] && this[k]) { return false } var l = $(this); a = a.not(l); l.removeData(d); if (!a.length) { clearTimeout(i); } }, add: function(l) { if (!e[f] && this[k]) { return false } var n; function m(s, o, p) { var q = $(this), r = $.data(this, d); r.w = o !== c ? o : q.width(); r.h = p !== c ? p : q.height(); n.apply(this, arguments) } if ($.isFunction(l)) { n = l; return m } else { n = l.handler; l.handler = m } }}; function g() { i = h[k](function() { a.each(function() { var n = $(this), m = n.width(), l = n.height(), o = $.data(this, d); if (m !== o.w || l !== o.h) { n.trigger(j, [o.w = m, o.h = l]) } }); g() }, e[b]) }} )(jQuery, this); /*! * SlimScroll https://github.com/rochal/jQuery-slimScroll * ======================================================= * * Copyright (c) 2011 Piotr Rochala (http://rocha.la) Dual licensed under the MIT */ (function(f) { jQuery.fn.extend({slimScroll: function(h) { var a = f.extend({width: "auto", height: "250px", size: "7px", color: "#000", position: "right", distance: "1px", start: "top", opacity: 0.4, alwaysVisible: !1, disableFadeOut: !1, railVisible: !1, railColor: "#333", railOpacity: 0.2, railDraggable: !0, railClass: "slimScrollRail", barClass: "slimScrollBar", wrapperClass: "slimScrollDiv", allowPageScroll: !1, wheelStep: 20, touchScrollStep: 200, borderRadius: "0px", railBorderRadius: "0px"}, h); this.each(function() { function r(d) { if (s) { d = d || window.event; var c = 0; d.wheelDelta && (c = -d.wheelDelta / 120); d.detail && (c = d.detail / 3); f(d.target || d.srcTarget || d.srcElement).closest("." + a.wrapperClass).is(b.parent()) && m(c, !0); d.preventDefault && !k && d.preventDefault(); k || (d.returnValue = !1) } } function m(d, f, h) { k = !1; var e = d, g = b.outerHeight() - c.outerHeight(); f && (e = parseInt(c.css("top")) + d * parseInt(a.wheelStep) / 100 * c.outerHeight(), e = Math.min(Math.max(e, 0), g), e = 0 < d ? Math.ceil(e) : Math.floor(e), c.css({top: e + "px"})); l = parseInt(c.css("top")) / (b.outerHeight() - c.outerHeight()); e = l * (b[0].scrollHeight - b.outerHeight()); h && (e = d, d = e / b[0].scrollHeight * b.outerHeight(), d = Math.min(Math.max(d, 0), g), c.css({top: d + "px"})); b.scrollTop(e); b.trigger("slimscrolling", ~~e); v(); p() } function C() { window.addEventListener ? (this.addEventListener("DOMMouseScroll", r, !1), this.addEventListener("mousewheel", r, !1), this.addEventListener("MozMousePixelScroll", r, !1)) : document.attachEvent("onmousewheel", r) } function w() { u = Math.max(b.outerHeight() / b[0].scrollHeight * b.outerHeight(), D); c.css({height: u + "px"}); var a = u == b.outerHeight() ? "none" : "block"; c.css({display: a}) } function v() { w(); clearTimeout(A); l == ~~l ? (k = a.allowPageScroll, B != l && b.trigger("slimscroll", 0 == ~~l ? "top" : "bottom")) : k = !1; B = l; u >= b.outerHeight() ? k = !0 : (c.stop(!0, !0).fadeIn("fast"), a.railVisible && g.stop(!0, !0).fadeIn("fast")) } function p() { a.alwaysVisible || (A = setTimeout(function() { a.disableFadeOut && s || (x || y) || (c.fadeOut("slow"), g.fadeOut("slow")) }, 1E3)) } var s, x, y, A, z, u, l, B, D = 30, k = !1, b = f(this); if (b.parent().hasClass(a.wrapperClass)) { var n = b.scrollTop(), c = b.parent().find("." + a.barClass), g = b.parent().find("." + a.railClass); w(); if (f.isPlainObject(h)) { if ("height"in h && "auto" == h.height) { b.parent().css("height", "auto"); b.css("height", "auto"); var q = b.parent().parent().height(); b.parent().css("height", q); b.css("height", q) } if ("scrollTo"in h) n = parseInt(a.scrollTo); else if ("scrollBy"in h) n += parseInt(a.scrollBy); else if ("destroy"in h) { c.remove(); g.remove(); b.unwrap(); return } m(n, !1, !0) } } else { a.height = "auto" == a.height ? b.parent().height() : a.height; n = f("<div></div>").addClass(a.wrapperClass).css({position: "relative", overflow: "hidden", width: a.width, height: a.height}); b.css({overflow: "hidden", width: a.width, height: a.height}); var g = f("<div></div>").addClass(a.railClass).css({width: a.size, height: "100%", position: "absolute", top: 0, display: a.alwaysVisible && a.railVisible ? "block" : "none", "border-radius": a.railBorderRadius, background: a.railColor, opacity: a.railOpacity, zIndex: 90}), c = f("<div></div>").addClass(a.barClass).css({background: a.color, width: a.size, position: "absolute", top: 0, opacity: a.opacity, display: a.alwaysVisible ? "block" : "none", "border-radius": a.borderRadius, BorderRadius: a.borderRadius, MozBorderRadius: a.borderRadius, WebkitBorderRadius: a.borderRadius, zIndex: 99}), q = "right" == a.position ? {right: a.distance} : {left: a.distance}; g.css(q); c.css(q); b.wrap(n); b.parent().append(c); b.parent().append(g); a.railDraggable && c.bind("mousedown", function(a) { var b = f(document); y = !0; t = parseFloat(c.css("top")); pageY = a.pageY; b.bind("mousemove.slimscroll", function(a) { currTop = t + a.pageY - pageY; c.css("top", currTop); m(0, c.position().top, !1) }); b.bind("mouseup.slimscroll", function(a) { y = !1; p(); b.unbind(".slimscroll") }); return!1 }).bind("selectstart.slimscroll", function(a) { a.stopPropagation(); a.preventDefault(); return!1 }); g.hover(function() { v() }, function() { p() }); c.hover(function() { x = !0 }, function() { x = !1 }); b.hover(function() { s = !0; v(); p() }, function() { s = !1; p() }); b.bind("touchstart", function(a, b) { a.originalEvent.touches.length && (z = a.originalEvent.touches[0].pageY) }); b.bind("touchmove", function(b) { k || b.originalEvent.preventDefault(); b.originalEvent.touches.length && (m((z - b.originalEvent.touches[0].pageY) / a.touchScrollStep, !0), z = b.originalEvent.touches[0].pageY) }); w(); "bottom" === a.start ? (c.css({top: b.outerHeight() - c.outerHeight()}), m(0, !0)) : "top" !== a.start && (m(f(a.start).position().top, null, !0), a.alwaysVisible || c.hide()); C() } }); return this }}); jQuery.fn.extend({slimscroll: jQuery.fn.slimScroll}) })(jQuery); /*! iCheck v1.0.1 by Damir Sultanov, http://git.io/arlzeA, MIT Licensed */ (function(h) { function F(a, b, d) { var c = a[0], e = /er/.test(d) ? m : /bl/.test(d) ? s : l, f = d == H ? {checked: c[l], disabled: c[s], indeterminate: "true" == a.attr(m) || "false" == a.attr(w)} : c[e]; if (/^(ch|di|in)/.test(d) && !f) D(a, e); else if (/^(un|en|de)/.test(d) && f) t(a, e); else if (d == H) for (e in f) f[e] ? D(a, e, !0) : t(a, e, !0); else if (!b || "toggle" == d) { if (!b) a[p]("ifClicked"); f ? c[n] !== u && t(a, e) : D(a, e) } } function D(a, b, d) { var c = a[0], e = a.parent(), f = b == l, A = b == m, B = b == s, K = A ? w : f ? E : "enabled", p = k(a, K + x(c[n])), N = k(a, b + x(c[n])); if (!0 !== c[b]) { if (!d && b == l && c[n] == u && c.name) { var C = a.closest("form"), r = 'input[name="' + c.name + '"]', r = C.length ? C.find(r) : h(r); r.each(function() { this !== c && h(this).data(q) && t(h(this), b) }) } A ? (c[b] = !0, c[l] && t(a, l, "force")) : (d || (c[b] = !0), f && c[m] && t(a, m, !1)); L(a, f, b, d) } c[s] && k(a, y, !0) && e.find("." + I).css(y, "default"); e[v](N || k(a, b) || ""); B ? e.attr("aria-disabled", "true") : e.attr("aria-checked", A ? "mixed" : "true"); e[z](p || k(a, K) || "") } function t(a, b, d) { var c = a[0], e = a.parent(), f = b == l, h = b == m, q = b == s, p = h ? w : f ? E : "enabled", t = k(a, p + x(c[n])), u = k(a, b + x(c[n])); if (!1 !== c[b]) { if (h || !d || "force" == d) c[b] = !1; L(a, f, p, d) } !c[s] && k(a, y, !0) && e.find("." + I).css(y, "pointer"); e[z](u || k(a, b) || ""); q ? e.attr("aria-disabled", "false") : e.attr("aria-checked", "false"); e[v](t || k(a, p) || "") } function M(a, b) { if (a.data(q)) { a.parent().html(a.attr("style", a.data(q).s || "")); if (b) a[p](b); a.off(".i").unwrap(); h(G + '[for="' + a[0].id + '"]').add(a.closest(G)).off(".i") } } function k(a, b, d) { if (a.data(q)) return a.data(q).o[b + (d ? "" : "Class")] } function x(a) { return a.charAt(0).toUpperCase() + a.slice(1) } function L(a, b, d, c) { if (!c) { if (b) a[p]("ifToggled"); a[p]("ifChanged")[p]("if" + x(d)) } } var q = "iCheck", I = q + "-helper", u = "radio", l = "checked", E = "un" + l, s = "disabled", w = "determinate", m = "in" + w, H = "update", n = "type", v = "addClass", z = "removeClass", p = "trigger", G = "label", y = "cursor", J = /ipad|iphone|ipod|android|blackberry|windows phone|opera mini|silk/i.test(navigator.userAgent); h.fn[q] = function(a, b) { var d = 'input[type="checkbox"], input[type="' + u + '"]', c = h(), e = function(a) { a.each(function() { var a = h(this); c = a.is(d) ? c.add(a) : c.add(a.find(d)) }) }; if (/^(check|uncheck|toggle|indeterminate|determinate|disable|enable|update|destroy)$/i.test(a)) return a = a.toLowerCase(), e(this), c.each(function() { var c = h(this); "destroy" == a ? M(c, "ifDestroyed") : F(c, !0, a); h.isFunction(b) && b() }); if ("object" != typeof a && a) return this; var f = h.extend({checkedClass: l, disabledClass: s, indeterminateClass: m, labelHover: !0, aria: !1}, a), k = f.handle, B = f.hoverClass || "hover", x = f.focusClass || "focus", w = f.activeClass || "active", y = !!f.labelHover, C = f.labelHoverClass || "hover", r = ("" + f.increaseArea).replace("%", "") | 0; if ("checkbox" == k || k == u) d = 'input[type="' + k + '"]'; -50 > r && (r = -50); e(this); return c.each(function() { var a = h(this); M(a); var c = this, b = c.id, e = -r + "%", d = 100 + 2 * r + "%", d = {position: "absolute", top: e, left: e, display: "block", width: d, height: d, margin: 0, padding: 0, background: "#fff", border: 0, opacity: 0}, e = J ? {position: "absolute", visibility: "hidden"} : r ? d : {position: "absolute", opacity: 0}, k = "checkbox" == c[n] ? f.checkboxClass || "icheckbox" : f.radioClass || "i" + u, m = h(G + '[for="' + b + '"]').add(a.closest(G)), A = !!f.aria, E = q + "-" + Math.random().toString(36).replace("0.", ""), g = '<div class="' + k + '" ' + (A ? 'role="' + c[n] + '" ' : ""); m.length && A && m.each(function() { g += 'aria-labelledby="'; this.id ? g += this.id : (this.id = E, g += E); g += '"' }); g = a.wrap(g + "/>")[p]("ifCreated").parent().append(f.insert); d = h('<ins class="' + I + '"/>').css(d).appendTo(g); a.data(q, {o: f, s: a.attr("style")}).css(e); f.inheritClass && g[v](c.className || ""); f.inheritID && b && g.attr("id", q + "-" + b); "static" == g.css("position") && g.css("position", "relative"); F(a, !0, H); if (m.length) m.on("click.i mouseover.i mouseout.i touchbegin.i touchend.i", function(b) { var d = b[n], e = h(this); if (!c[s]) { if ("click" == d) { if (h(b.target).is("a")) return; F(a, !1, !0) } else y && (/ut|nd/.test(d) ? (g[z](B), e[z](C)) : (g[v](B), e[v](C))); if (J) b.stopPropagation(); else return!1 } }); a.on("click.i focus.i blur.i keyup.i keydown.i keypress.i", function(b) { var d = b[n]; b = b.keyCode; if ("click" == d) return!1; if ("keydown" == d && 32 == b) return c[n] == u && c[l] || (c[l] ? t(a, l) : D(a, l)), !1; if ("keyup" == d && c[n] == u) !c[l] && D(a, l); else if (/us|ur/.test(d)) g["blur" == d ? z : v](x) }); d.on("click mousedown mouseup mouseover mouseout touchbegin.i touchend.i", function(b) { var d = b[n], e = /wn|up/.test(d) ? w : B; if (!c[s]) { if ("click" == d) F(a, !1, !0); else { if (/wn|er|in/.test(d)) g[v](e); else g[z](e + " " + w); if (m.length && y && e == B) m[/ut|nd/.test(d) ? z : v](C) } if (J) b.stopPropagation(); else return!1 } }) }) } })(window.jQuery || window.Zepto);
"use strict"; module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Define the configuration for all the tasks grunt.initConfig({ // Project settings paths: { src: 'src', dist: '.', vendor: 'bower_components', test: 'test' }, pkg: grunt.file.readJSON('package.json'), banner: '/**\n' + ' * <%= pkg.name %> v<%= pkg.version %>\n' + ' * Copyright <%= grunt.template.today("yyyy") %> <%= pkg.author %>\n' + ' */\n', // Watches files for changes and runs tasks based on the changed files watch: { options: { interrupt: false, livereload: true }, src: { files: [ 'Gruntfile.js', '<%= paths.src %>', '<%= paths.test %>/unit/*.js' ], tasks: ['default'] } }, 'strip_code': { options: { 'start_comment': 'start-test-block', 'end_comment': 'end-test-block' }, stripTestCode: { src: '<%= paths.src %>/<%= pkg.name %>.js', dest: '<%= paths.dist %>/<%= pkg.name %>.js' } }, // Minify JavaScript uglify: { dist: { src: '<%= paths.dist %>/<%= pkg.name %>.js', dest: '<%= paths.dist %>/<%= pkg.name %>.min.js' } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= paths.src %>/*.js' ] }, // JavaScript unit tests karma: { options: { configFile: '<%= paths.test %>/unit/karma.conf.js', singleRun: true }, unit: {}, travis: { browsers: ['PhantomJS'] } }, coveralls: { options: { 'coverage_dir': './coverage' } }, // Create OS notifications alerting progress notify: { default: { options: { title: '<%= pkg.title %>', message: 'SUCCESS: Grunt Complete' } } } }); grunt.registerTask('default', [ 'jshint', 'karma:unit', 'strip_code', 'uglify', 'notify:default' ]); grunt.registerTask('test', [ 'jshint', 'karma:travis', 'coveralls' ]); };
const request = require('supertest'); const app = require('../'); describe('dot', () => { it('200', (done) => { request(app.listen()) .get('/dot') .expect(200) .end(() => { done(); }); }); });
var koa = require('koa'); var json = require('koa-json'); var app = koa(); app.use(json()); app.use(function *(next){ this.body = { randomNumber : '' + getRandomNumber(), lowerBound : "1" , upperBound : "10"}; }); console.log("listen by port 3000"); app.listen(3000); function getRandomNumber() { return Math.floor(Math.random()*10) + 1; };
/** * Created by long on 15-8-14. */ var flax = flax || {}; /** * System variables * @namespace * @name flax.sys */ flax.sys = {}; var sys = flax.sys; /** * English language code * @memberof flax.sys * @name LANGUAGE_ENGLISH * @constant * @type {Number} */ sys.LANGUAGE_ENGLISH = "en"; /** * Chinese language code * @memberof flax.sys * @name LANGUAGE_CHINESE * @constant * @type {Number} */ sys.LANGUAGE_CHINESE = "zh"; /** * French language code * @memberof flax.sys * @name LANGUAGE_FRENCH * @constant * @type {Number} */ sys.LANGUAGE_FRENCH = "fr"; /** * Italian language code * @memberof flax.sys * @name LANGUAGE_ITALIAN * @constant * @type {Number} */ sys.LANGUAGE_ITALIAN = "it"; /** * German language code * @memberof flax.sys * @name LANGUAGE_GERMAN * @constant * @type {Number} */ sys.LANGUAGE_GERMAN = "de"; /** * Spanish language code * @memberof flax.sys * @name LANGUAGE_SPANISH * @constant * @type {Number} */ sys.LANGUAGE_SPANISH = "es"; /** * Spanish language code * @memberof flax.sys * @name LANGUAGE_DUTCH * @constant * @type {Number} */ sys.LANGUAGE_DUTCH = "du"; /** * Russian language code * @memberof flax.sys * @name LANGUAGE_RUSSIAN * @constant * @type {Number} */ sys.LANGUAGE_RUSSIAN = "ru"; /** * Korean language code * @memberof flax.sys * @name LANGUAGE_KOREAN * @constant * @type {Number} */ sys.LANGUAGE_KOREAN = "ko"; /** * Japanese language code * @memberof flax.sys * @name LANGUAGE_JAPANESE * @constant * @type {Number} */ sys.LANGUAGE_JAPANESE = "ja"; /** * Hungarian language code * @memberof flax.sys * @name LANGUAGE_HUNGARIAN * @constant * @type {Number} */ sys.LANGUAGE_HUNGARIAN = "hu"; /** * Portuguese language code * @memberof flax.sys * @name LANGUAGE_PORTUGUESE * @constant * @type {Number} */ sys.LANGUAGE_PORTUGUESE = "pt"; /** * Arabic language code * @memberof flax.sys * @name LANGUAGE_ARABIC * @constant * @type {Number} */ sys.LANGUAGE_ARABIC = "ar"; /** * Norwegian language code * @memberof flax.sys * @name LANGUAGE_NORWEGIAN * @constant * @type {Number} */ sys.LANGUAGE_NORWEGIAN = "no"; /** * Polish language code * @memberof flax.sys * @name LANGUAGE_POLISH * @constant * @type {Number} */ sys.LANGUAGE_POLISH = "pl"; /** * @memberof flax.sys * @name OS_IOS * @constant * @type {string} */ sys.OS_IOS = "iOS"; /** * @memberof flax.sys * @name OS_ANDROID * @constant * @type {string} */ sys.OS_ANDROID = "Android"; /** * @memberof flax.sys * @name OS_WINDOWS * @constant * @type {string} */ sys.OS_WINDOWS = "Windows"; /** * @memberof flax.sys * @name OS_MARMALADE * @constant * @type {string} */ sys.OS_MARMALADE = "Marmalade"; /** * @memberof flax.sys * @name OS_LINUX * @constant * @type {string} */ sys.OS_LINUX = "Linux"; /** * @memberof flax.sys * @name OS_BADA * @constant * @type {string} */ sys.OS_BADA = "Bada"; /** * @memberof flax.sys * @name OS_BLACKBERRY * @constant * @type {string} */ sys.OS_BLACKBERRY = "Blackberry"; /** * @memberof flax.sys * @name OS_OSX * @constant * @type {string} */ sys.OS_OSX = "OS X"; /** * @memberof flax.sys * @name OS_WP8 * @constant * @type {string} */ sys.OS_WP8 = "WP8"; /** * @memberof flax.sys * @name OS_WINRT * @constant * @type {string} */ sys.OS_WINRT = "WINRT"; /** * @memberof flax.sys * @name OS_UNKNOWN * @constant * @type {string} */ sys.OS_UNKNOWN = "Unknown"; /** * @memberof flax.sys * @name UNKNOWN * @constant * @default * @type {Number} */ sys.UNKNOWN = -1; /** * @memberof flax.sys * @name WIN32 * @constant * @default * @type {Number} */ sys.WIN32 = 0; /** * @memberof flax.sys * @name LINUX * @constant * @default * @type {Number} */ sys.LINUX = 1; /** * @memberof flax.sys * @name MACOS * @constant * @default * @type {Number} */ sys.MACOS = 2; /** * @memberof flax.sys * @name ANDROID * @constant * @default * @type {Number} */ sys.ANDROID = 3; /** * @memberof flax.sys * @name IOS * @constant * @default * @type {Number} */ sys.IPHONE = 4; /** * @memberof flax.sys * @name IOS * @constant * @default * @type {Number} */ sys.IPAD = 5; /** * @memberof flax.sys * @name BLACKBERRY * @constant * @default * @type {Number} */ sys.BLACKBERRY = 6; /** * @memberof flax.sys * @name NACL * @constant * @default * @type {Number} */ sys.NACL = 7; /** * @memberof flax.sys * @name EMSCRIPTEN * @constant * @default * @type {Number} */ sys.EMSCRIPTEN = 8; /** * @memberof flax.sys * @name TIZEN * @constant * @default * @type {Number} */ sys.TIZEN = 9; /** * @memberof flax.sys * @name WINRT * @constant * @default * @type {Number} */ sys.WINRT = 10; /** * @memberof flax.sys * @name WP8 * @constant * @default * @type {Number} */ sys.WP8 = 11; /** * @memberof flax.sys * @name MOBILE_BROWSER * @constant * @default * @type {Number} */ sys.MOBILE_BROWSER = 100; /** * @memberof flax.sys * @name DESKTOP_BROWSER * @constant * @default * @type {Number} */ sys.DESKTOP_BROWSER = 101; sys.BROWSER_TYPE_WECHAT = "wechat"; sys.BROWSER_TYPE_ANDROID = "androidbrowser"; sys.BROWSER_TYPE_IE = "ie"; sys.BROWSER_TYPE_QQ = "qqbrowser"; sys.BROWSER_TYPE_MOBILE_QQ = "mqqbrowser"; sys.BROWSER_TYPE_UC = "ucbrowser"; sys.BROWSER_TYPE_360 = "360browser"; sys.BROWSER_TYPE_BAIDU_APP = "baiduboxapp"; sys.BROWSER_TYPE_BAIDU = "baidubrowser"; sys.BROWSER_TYPE_MAXTHON = "maxthon"; sys.BROWSER_TYPE_OPERA = "opera"; sys.BROWSER_TYPE_OUPENG = "oupeng"; sys.BROWSER_TYPE_MIUI = "miuibrowser"; sys.BROWSER_TYPE_FIREFOX = "firefox"; sys.BROWSER_TYPE_SAFARI = "safari"; sys.BROWSER_TYPE_CHROME = "chrome"; sys.BROWSER_TYPE_LIEBAO = "liebao"; sys.BROWSER_TYPE_QZONE = "qzone"; sys.BROWSER_TYPE_SOUGOU = "sogou"; sys.BROWSER_TYPE_UNKNOWN = "unknown"; /** * Is native ? * @memberof flax.sys * @name isNative * @type {Boolean} */ sys.isNative = false; var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; var ua = nav.userAgent.toLowerCase(); /** * Indicate whether system is mobile system * @memberof flax.sys * @name isMobile * @type {Boolean} */ sys.isMobile = ua.indexOf('mobile') !== -1 || ua.indexOf('android') !== -1; /** * Indicate the running platform * @memberof flax.sys * @name platform * @type {Number} */ sys.platform = sys.isMobile ? sys.MOBILE_BROWSER : sys.DESKTOP_BROWSER; var currLanguage = nav.language; currLanguage = currLanguage ? currLanguage : nav.browserLanguage; currLanguage = currLanguage ? currLanguage.split("-")[0] : sys.LANGUAGE_ENGLISH; /** * Indicate the current language of the running system * @memberof flax.sys * @name language * @type {String} */ sys.language = currLanguage; var browserType = sys.BROWSER_TYPE_UNKNOWN; var browserTypes = ua.match(/sogou|qzone|liebao|micromessenger|qqbrowser|ucbrowser|360 aphone|360browser|baiduboxapp|baidubrowser|maxthon|trident|oupeng|opera|miuibrowser|firefox/i) || ua.match(/chrome|safari/i); if (browserTypes && browserTypes.length > 0) { browserType = browserTypes[0]; if (browserType === 'micromessenger') { browserType = sys.BROWSER_TYPE_WECHAT; } else if (browserType === "safari" && (ua.match(/android.*applewebkit/))) browserType = sys.BROWSER_TYPE_ANDROID; else if (browserType === "trident") browserType = sys.BROWSER_TYPE_IE; else if (browserType === "360 aphone") browserType = sys.BROWSER_TYPE_360; }else if(ua.indexOf("iphone") && ua.indexOf("mobile")){ browserType = "safari"; } /** * Indicate the running browser type * @memberof flax.sys * @name browserType * @type {String} */ sys.browserType = browserType; // Get the os of system var iOS = ( ua.match(/(iPad|iPhone|iPod)/i) ? true : false ); var isAndroid = ua.match(/android/i) || nav.platform.match(/android/i) ? true : false; var osName = sys.OS_UNKNOWN; if (nav.appVersion.indexOf("Win") !== -1) osName = sys.OS_WINDOWS; else if (iOS) osName = sys.OS_IOS; else if (nav.appVersion.indexOf("Mac") !== -1) osName = sys.OS_OSX; else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX; else if (isAndroid) osName = sys.OS_ANDROID; else if (nav.appVersion.indexOf("Linux") !== -1) osName = sys.OS_LINUX; /** * Indicate the running os name * @memberof flax.sys * @name os * @type {String} */ sys.os = osName; var multipleAudioWhiteList = [ sys.BROWSER_TYPE_BAIDU, sys.BROWSER_TYPE_OPERA, sys.BROWSER_TYPE_FIREFOX, sys.BROWSER_TYPE_CHROME, sys.BROWSER_TYPE_BAIDU_APP, sys.BROWSER_TYPE_SAFARI, sys.BROWSER_TYPE_UC, sys.BROWSER_TYPE_QQ, sys.BROWSER_TYPE_MOBILE_QQ, sys.BROWSER_TYPE_IE ]; sys._supportMultipleAudio = multipleAudioWhiteList.indexOf(sys.browserType) > -1; // check if browser supports Web Audio // check Web Audio's context try { sys._supportWebAudio = !!(win.AudioContext || win.webkitAudioContext || win.mozAudioContext); } catch (e) { sys._supportWebAudio = false; } /** * flax.sys.localStorage is a local storage component. * @memberof flax.sys * @name localStorage * @type {Object} */ try { var localStorage = sys.localStorage = win.localStorage; localStorage.setItem("storage", ""); localStorage.removeItem("storage"); localStorage = null; } catch (e) { var warn = function () { flax.warn("Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option"); } sys.localStorage = { getItem : warn, setItem : warn, removeItem : warn, clear : warn }; } /** * Dump system informations * @memberof flax.sys * @name dump * @function */ sys.dump = function () { var self = this; var str = ""; str += "isMobile : " + self.isMobile + "\r\n"; str += "language : " + self.language + "\r\n"; str += "browserType : " + self.browserType + "\r\n"; str += "os : " + self.os + "\r\n"; str += "platform : " + self.platform + "\r\n"; console.log(str); } /** * Open a url in browser * @memberof flax.sys * @name openURL * @param {String} url */ sys.openURL = function(url){ if(typeof window.open == "function") window.open(url); }
var fieldTests = require('./commonFieldTestUtils.js'); var HtmlModelTestConfig = require('../../../modelTestConfig/HtmlModelTestConfig'); module.exports = { before: fieldTests.before, after: fieldTests.after, 'Html field should show correctly in the initial modal': function (browser) { browser.adminUIApp.openFieldList('Html'); browser.listScreen.createFirstItem(); browser.adminUIApp.waitForInitialFormScreen(); browser.initialFormScreen.assertFieldUIVisible({ modelTestConfig: HtmlModelTestConfig, fields: [{name: 'name'}, {name: 'fieldA'}] }); }, 'restoring test state': function(browser) { browser.initialFormScreen.cancel(); browser.adminUIApp.waitForListScreen(); }, 'Html field can be filled via the initial modal': function(browser) { browser.adminUIApp.openFieldList('Html'); browser.listScreen.createFirstItem(); browser.adminUIApp.waitForInitialFormScreen(); browser.initialFormScreen.fillFieldInputs({ modelTestConfig: HtmlModelTestConfig, fields: { 'name': {value: 'Html Field Test 1'}, 'fieldA': {value: 'Some test html code for field A'}, } }); browser.initialFormScreen.assertFieldInputs({ modelTestConfig: HtmlModelTestConfig, fields: { 'name': {value: 'Html Field Test 1'}, 'fieldA': {value: 'Some test html code for field A'}, } }); browser.initialFormScreen.save(); browser.adminUIApp.waitForItemScreen(); browser.itemScreen.assertFieldInputs({ modelTestConfig: HtmlModelTestConfig, fields: { 'name': {value: 'Html Field Test 1'}, 'fieldA': {value: 'Some test html code for field A'}, } }) }, 'Html field should show correctly in the edit form': function(browser) { browser.itemScreen.assertFieldUIVisible({ modelTestConfig: HtmlModelTestConfig, fields: [{name: 'fieldA'}, {name: 'fieldB'}] }); }, 'Html field can be filled via the edit form': function(browser) { browser.itemScreen.fillFieldInputs({ modelTestConfig: HtmlModelTestConfig, fields: { 'fieldB': {value: 'Some test html code for field B'} } }); browser.itemScreen.save(); browser.adminUIApp.waitForItemScreen(); browser.itemScreen.assertFlashMessage('Your changes have been saved successfully'); browser.itemScreen.assertFieldInputs({ modelTestConfig: HtmlModelTestConfig, fields: { 'name': {value: 'Html Field Test 1'}, 'fieldA': {value: 'Some test html code for field A'}, 'fieldB': {value: 'Some test html code for field B'} } }) }, };
'use strict'; const UUID = require('uuid/v4'); const Event = require('../../db/models/Event'); const formatDate = require('../utilities'); // Perform Mongoose query to find all records that are instances of the Event // Model, sort them in reverse chronological order (i.e., newest first), // limit the sort to the 20 most recent records and pass the callback handler: const listEvents = (req, res, next) => { Event .find({}) .sort({ date: 'desc'}) .limit(20) .then(evts => res.send(evts)) .catch(err => { res.status(400).send('Failed to fetch requested events!'); next(); }); }; // Queries the DB for a single document (record) whose UUID corresponds // to the routing param: const getSingleEvent = (req, res, next) => { const sendResponse = (err, docs) => { res.send(docs); } Event .find({}) .limit(+req.params.eventId) .sort({ date: 'desc' }) .then(evt => res.send(evt)) .catch(err => { res.status(400).send('Failed to fetch requested event!'); next(); }); }; // Perform const addSingleEvent = (req, res, next) => { const { name, date, location, description } = req.body; const dd = { name, date, location, description, uuid: UUID(), dateModified: Date.now() }; new Event(dd) .save() .then(() => Event.findOne({ name })) .then(evt => res.json(evt)) .catch(() => { res.status(400).send('Failed to create new event!'); next(); }); }; /** * Edits a single instance of the Event model * @param {string} uuid - The UUID of the event record being edited * @param {object} evtProps - An object of property names and the corresponding edits * @return {promise} A Promise that resolves when the record has been edited */ const updateSingleEvent = (req, res, next) => { const { params: { uuid }, body: evtProps } = req; Event .findOneAndUpdate({ uuid }, Object.assign({}, evtProps, { dateModified: Date.now() })) .then(() => Event.findOne({ uuid })) .then(evt => res.send(evt)) .catch(() => { res.status(400).send('Failed to update specified event!'); next(); }); }; // Perform const deleteSingleEvent = (req, res, next) => { const uuid = req.body.uuid; Event .findOneAndRemove({ uuid }) .then(() => res.json(uuid)) .catch(() => { res.status(400).send('Failed to delete specified event!'); next(); }); }; // const deleteBatchEvents = (req, res, next) => { const uuids = req.body; Event .remove({ uuid: { $in: uuids }}) .then(() => res.json(uuids)) .catch(() => { res.status(400).send('Failed to delete selected events!'); next(); }); }; module.exports = { getSingleEvent, addSingleEvent, listEvents, updateSingleEvent, deleteSingleEvent, deleteBatchEvents };
const { src, dest, watch, series, parallel } = require('gulp'); const sass = require('gulp-sass')(require('sass')); const autoprefixer = require('gulp-autoprefixer'); const concat = require('gulp-concat'); const uglify = require('gulp-uglify'); const rename = require('gulp-rename'); const files = { scssPath: 'src/sass/**/*.scss', jsPath: 'src/**/*.js', jsModulesPath: 'src/modules/**/*.js', demoCSS: 'demo/css', demoJS: 'demo/js', dist: 'dist', }; function scssTask() { return src(files.scssPath, { sourcemaps: true }) // set source and turn on sourcemaps .pipe(sass().on('error', sass.logError)) .pipe(autoprefixer()) .pipe(dest(files.demoCSS, { sourcemaps: '.' })) .pipe(dest(files.dist, { sourcemaps: '.' })); // put final CSS in dist folder with sourcemap } function uglifyTask() { return src([files.jsPath, files.jsModulesPath]) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(dest(files.dist)) .pipe(dest(files.demoJS)) .pipe(concat('flypanels.all.js')) .pipe(uglify()) .pipe(rename({ extname: '.min.js' })) .pipe(dest(files.dist)) .pipe(dest(files.demoJS)); } function copyJS() { return src([files.jsPath, files.jsModulesPath]).pipe(dest(files.dist)).pipe(dest(files.demoJS)); } // Watch task: watch SCSS and JS files for changes // If any change, run scss and js tasks simultaneously function watchTask() { watch( [files.scssPath, files.jsPath], { interval: 1000, usePolling: true }, //Makes docker work series(parallel(scssTask, uglifyTask, copyJS)) ); } exports.default = parallel(scssTask, uglifyTask, copyJS, watchTask); exports.build = parallel(scssTask, uglifyTask, copyJS);
var Command = require('streamhub-sdk/ui/command'); var GalleryAttachmentListView = require('streamhub-sdk/content/views/gallery-attachment-list-view'); var HubButton = require('streamhub-sdk/ui/hub-button'); var inherits = require('inherits'); var ModalView = require('streamhub-sdk/modal'); 'use strict'; function ExpandButton(fnOrCommand, opts) { opts = opts || {}; opts.className = opts.className || 'content-action content-action-expand'; fnOrCommand = fnOrCommand || new Command(this._showExpandModal.bind(this), opts); HubButton.call(this, fnOrCommand, opts); } inherits(ExpandButton, HubButton); ExpandButton.prototype.elClassPrefix = 'hub'; ExpandButton.prototype._showExpandModal = function () { var modal = new ModalView(); modal.show(new GalleryAttachmentListView(this.opts.contentView)); }; module.exports = ExpandButton;
/** * Generic boilerplate used for building SASS and compiling sprites. Feel free to change this to suit your needs! * * For usage, please see README.md. * * @site YOUR_SITE_NAME * @author Patrick Nelson, pat@catchyour.com * @link https://github.com/patricknelson/sassified-sprites * @since 2015-08-10 */ module.exports = function(grunt) { require('load-grunt-tasks')(grunt); grunt.initConfig({ // Configure file paths here. config: { path: { css: 'css', scss: 'scss', imagesrc: 'images/sprites/src', imagebuild: 'images/sprites/build' } }, // Compiles CSS sass: { options: { sourcemap: 'auto', style: 'compressed', bundleExec: true }, dist: { files: [{ expand: true, cwd: '<%= config.path.scss %>', src: '**/*.{scss,sass}', dest: '<%= config.path.css %>', ext: '.css' }] } }, // Adds vendor prefixes to compiled CSS for better backward compatibility. postcss: { options: { map: true, processors: [ require('autoprefixer-core')({ browsers: ['last 2 versions', 'ie 8', 'ie 9'] }) ] }, // Auto-prefix ALL CSS files. dist: { files: [{ expand: true, cwd: '<%= config.path.css %>', src: '**/*.css', dest: '<%= config.path.css %>' }] } }, // Sprite compilation configuration. sprites: { main: { src: ['<%= config.path.imagesrc %>/*.png'], css: '<%= config.path.scss %>/build/_sprites.scss', map: '<%= config.path.imagebuild %>/sprites.png', output: 'scss', dimensions: true, classPrefix: "sprite", staticImagePath: '/<%= config.path.imagebuild %>' } }, // Minify generated sprite PNG files. pngmin: { options: { ext: '.png', force: true }, sprites: { files: [{ expand: true, cwd: '<%= config.path.imagebuild %>', src: '**/*.png', dest: '<%= config.path.imagebuild %>' }] } }, // Watches for file changes, runs tasks, and triggers livereload. watch: { options: { livereload: true }, sass: { files: ['<%= config.path.scss %>/**/*.scss'], tasks: ['sass'] }, sprites: { files: [ '<%= config.path.image %>/sprites/*.png', '<%= config.path.image %>/investors-sprite/*.png' ], tasks: ['build-sprites'] } } }); // Alias for generating all sprites from source sprite files. grunt.registerTask('build-sprites', [ 'sprites', 'pngmin' ]); // Build everything. grunt.registerTask('build', [ 'build-sprites', 'sass', 'postcss' ]); // Build everything, but wait for changes and re-build. grunt.registerTask('dev', [ 'build', 'watch' ]); };
๏ปฟ// Test setup /////////////////////////////////////// var specs = require("../../SpecHelpers"); //specs.debug(); specs.ensureWindow(); // Imports /////////////////////////////////////// specs.requireMsAjax(); specs.requireJQueryExtend(); specs.ensureNamespace("ExoWeb"); specs.require("model.PropertyChain"); specs.require("msajax.ObserverProvider"); // Test Suites /////////////////////////////////////// describe("PropertyChain", function() { beforeEach(function() { var model = new Model(); this.model = model; var fooType = new Type(model, "Foo"); var barType = new Type(model, "Bar"); var barTypeType = new Type(model, "BarType"); barType.addProperty({ name: "Type", type: BarType }); barTypeType.addProperty({ name: "Name", type: String }); fooType.addProperty({ name: "Bars", type: Bar, isList: true }); var foo = new Foo(); this.foo = foo; var aType = new BarType({ Name: "A" }); this.aType = aType; var bar1 = new Bar({ Type: aType }); foo.get_Bars().add(bar1); this.bar1 = bar1; var bType = new BarType({ Name: "B" }); this.bType = bType; var bar2 = new Bar({ Type: bType }); foo.get_Bars().add(bar2); this.bar2 = bar2; var barsProp = PropertyChain.create(fooType, new PathTokens("Bars")); this.barsProp = barsProp; var barsTypeProp = Model.property("Bars.Type", fooType); this.barsTypeProp = barsTypeProp; var nameProp = PropertyChain.create(barTypeType, new PathTokens("Name")); this.nameProp = nameProp; var typeNameProp = Model.property("Type.Name", barType); this.typeNameProp = typeNameProp; var barsTypeNameProp = Model.property("Bars.Type.Name", fooType); this.barsTypeNameProp = barsTypeNameProp; }); afterEach(function() { delete global.Foo; delete global.Bar; delete global.BarType; }); describe("each", function() { it("callback is given the target, target index, target array, property, property index, and property array", function() { var nameSpy = jasmine.jasmine.createSpy(); this.nameProp.each(this.aType, nameSpy); expect(nameSpy).toHaveBeenCalledWith(this.aType, -1, null, BarType.$Name, 0, [BarType.$Name]); var barsSpy = jasmine.jasmine.createSpy(); this.barsProp.each(this.foo, barsSpy); expect(barsSpy).toHaveBeenCalledWith(this.foo, -1, null, Foo.$Bars, 0, [Foo.$Bars]); var barsTypeSpy = jasmine.jasmine.createSpy(); this.barsTypeProp.each(this.foo, barsTypeSpy); expect(barsTypeSpy).toHaveBeenCalledWith(this.foo, -1, null, Foo.$Bars, 0, [Foo.$Bars, Bar.$Type]); }); it("iterates over each property in the chain", function() { var spy = jasmine.jasmine.createSpy(); this.typeNameProp.each(this.bar1, spy); expect(spy).toHaveBeenCalled(); expect(spy.callCount).toBe(2); }); it("also iterates over each target in the chain when one or more properties are an array", function() { var spy = jasmine.jasmine.createSpy(); this.barsTypeNameProp.each(this.foo, spy); expect(spy).toHaveBeenCalled(); expect(spy.callCount).toBe(5); }); }); describe("isInited", function() { it("returns true if all property values are initialized", function() { expect(this.barsTypeNameProp.isInited(this.foo, true)).toBe(true); }); it("returns false if the path is not complete", function() { this.bar2.set_Type(null); expect(this.barsTypeNameProp.isInited(this.foo, true)).toBe(false); }); it("returns true if the path is not complete but enforceCompleteness is not specified", function() { this.bar2.set_Type(null); expect(this.barsTypeNameProp.isInited(this.foo)).toBe(true); }); }); describe("addChanged", function() { it("executes if all property values are initialized", function() { var handler = jasmine.jasmine.createSpy(); this.barsTypeNameProp.addChanged(handler); this.bar2.get_Type().set_Name("b"); expect(handler).toHaveBeenCalledWith(this.foo, { originalSender: this.bType, property: this.barsTypeNameProp, triggeredBy: BarType.$Name, oldValue: "B", newValue: "b" }); }); it("does not execute if one of the paths is not complete", function() { var handler = jasmine.jasmine.createSpy(); this.barsTypeNameProp.addChanged(handler); this.bar2.set_Type(null); expect(handler).not.toHaveBeenCalled(); }); it("executes if one of the paths is not complete and tolerate partials is set to true", function() { var handler = jasmine.jasmine.createSpy(); this.barsTypeNameProp.addChanged(handler, null, false, true); this.bar2.set_Type(null); expect(handler).toHaveBeenCalledWith(this.foo, { originalSender: this.bar2, property: this.barsTypeNameProp, triggeredBy: Bar.$Type, oldValue: this.bType, newValue: null }); }); }); }); // Run Tests /////////////////////////////////////// jasmine.jasmine.getEnv().addReporter(new jasmineConsole.Reporter()); jasmine.jasmine.getEnv().execute();
import NavTop from './navTop'; import Container from './container' export {NavTop, Container};
const monk = require('monk'); const config = require('../config.json'); const db = monk(config.mongodb); const usersCollection = db.get('users'); const main = async () => { const $group = { $group: { _id: '$username', dups: { $sum: 1 } } }; const $match = { $match: { dups: { $gt: 1 } } }; const pipeline = [$group, $match]; const response = await usersCollection.aggregate(pipeline); const bulkOperations = []; response.forEach(duplicate => { const deleteOne = { /* eslint-disable no-underscore-dangle */ filter: { username: duplicate._id }, }; bulkOperations.push({ deleteOne }); }); await usersCollection.bulkWrite(bulkOperations); db.close(); console.log('All done!'); }; main();
#!/usr/bin/env node 'use strict'; require('babel-register'); console.log('Hello Calendar'); require('./lib/cal');
"use strict"; // Swaggy assumes the current working directory is the project root. // By default it will look for ./rest-api/ directory to scan .js files for endpoints. if (process.cwd() !== __dirname) { process.chdir(__dirname); } var express = require("express"), bodyParser = require("body-parser"), swaggy = require("../../lib/swaggy"), app = express(); // We need body-parser for convenience. app.use(bodyParser.json()); app.get("/", function(req, res){ res.send("Hello World"); }); swaggy(app, function (err) { if (err) { return console.log(err); } app.listen(3001, function() { console.log("Listening on port 3001 ..."); console.log("Go to http://localhost:3001/api/docs"); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:c50522d29416e3f1b343379f39c03ddf9851dc0c77305de2a93b3072db48a4c8 size 70387
/* eslint-env node */ "use strict"; module.exports = function (grunt) { /* * Initialize configurations */ grunt.initConfig({ requirejs: { options: { optimize: "uglify2", uglify2: { output: { beautify: false }, compress: { sequences: false, "global_defs": { DEBUG: false } }, warnings: true, mangle: false } }, bootstrap: { options: { baseUrl: "./assets/js/", name: "bootstrap", out: "./public/js/bootstrap.min.js", paths: { angular: "empty:" } } }, main: { options: { baseUrl: "./generated/js/", name: "main", out: "./public/js/main.min.js", include: ["plugbot/app"], paths: { plugbot: "./", angular: "empty:", domReady: "empty:" }, generateSourceMaps: false, preserveLicenseComments: true } } }, compass: { options: { config: "./config.rb", force: true }, debug: { options: { environment: "development", trace: true, debugInfo: true } }, release: { options: { environment: "production", outputStyle: "expanded" } } }, cssmin: { release: { expand: true, cwd: "./assets/css/", src: "**/*.css", dest: "./public/css/", ext: ".css" } }, html2js: { options: { module: "app.views", base: "./assets/html/" }, htmlTemplates: { src: ["./assets/html/**/*.tpl.html"], dest: "./assets/js/views/index.js" } }, ngAnnotate: { options: {}, main: { files: [{ expand: true, cwd: "./assets/js/", src: [ "./controllers/**/*.js", "./directives/**/*.js", "./services/**/*.js", "./views/**/*.js", "./app.js", "./main.js" ], dest: "./generated/js/", ext: ".js" }] } }, clean: { debug: [ "./assets/css/" ], release: [ "./public/js/", "./public/css/" ], generated: [ "./generated/js/" ] }, watch: { htmlTemplates: { files: ["./assets/html/**/*.tpl.html"], tasks: ["Convert HTML Templates"], options: { spawn: false } } }, shell: { runLocalHttpsServer: { command: "http-server ../" + " -p 443 -a localhost" + " --ssl" + " --cert ./preferences/certificates/ryans-cert.pem" + " --key ./preferences/certificates/ryans-key.pem" } } }); /* * Load tasks */ grunt.loadNpmTasks("grunt-contrib-clean"); grunt.loadNpmTasks("grunt-contrib-compass"); grunt.loadNpmTasks("grunt-contrib-cssmin"); grunt.loadNpmTasks("grunt-contrib-requirejs"); grunt.loadNpmTasks("grunt-contrib-watch"); grunt.loadNpmTasks("grunt-html2js"); grunt.loadNpmTasks("grunt-ng-annotate"); grunt.loadNpmTasks("grunt-shell"); /* * Register tasks */ grunt.registerTask("Build Debug", [ "compass:debug" ]); grunt.registerTask("Build Release", [ "clean:generated", "clean:release", "html2js:htmlTemplates", "ngAnnotate:main", "requirejs:bootstrap", "requirejs:main", "compass:release", "cssmin:release" ]); grunt.registerTask("Convert HTML Templates", [ "html2js:htmlTemplates" ]); grunt.registerTask("Clean Debug", [ "clean:debug" ]); grunt.registerTask("Clean Release", [ "clean:generated", "clean:release" ]); grunt.registerTask("Watch HTML Templates", [ "watch:htmlTemplates" ]); grunt.registerTask("Run Local HTTPS Server", [ "shell:runLocalHttpsServer" ]); };
var localStorageFeature = true; describe('Local storage', function () { 'use strict'; beforeEach(module('ccdb.utils.localStorage.factory')); var localStorage, nativeLocalStorage, patientRule; beforeEach(inject(function (LocalStorage, $localStorage, PatientRule) { localStorage = LocalStorage; nativeLocalStorage = $localStorage; nativeLocalStorage.$reset(); patientRule = PatientRule; })); describe('refresh', function () { it('should save patient into hash with _id as key', function () { localStorage.refresh('/api/patient/something', 'GET', {}, { data: { _id: 'this is id', value: 'some values' } }); expect(nativeLocalStorage.patient).toEqual({ 'this is id': { _id: 'this is id', value: 'some values' } }); }); it('should replace exist patient with the save _id', function () { nativeLocalStorage.patient = { 'this is id': {'some': 'thing'}, 'this is another id': {'some': 'thing else'} }; localStorage.refresh('/api/patient/something', 'GET', {}, { data: { _id: 'this is id', value: 'some values' } }); expect(nativeLocalStorage.patient).toEqual({ 'this is id': {_id: 'this is id', value: 'some values'}, 'this is another id': {'some': 'thing else'} }); }); it('should save patient list into hash one by one with _id as key', function () { localStorage.refresh('/api/patient/something', 'GET', {}, { data: [ { _id: 'this is id', value: 'some values' }, { _id: 'this is another id', value: 'some values' }, { _id: 'this is the third id', value: 'some values' } ] }); expect(nativeLocalStorage.patient).toEqual({ 'this is id': { _id: 'this is id', value: 'some values' }, 'this is another id': { _id: 'this is another id', value: 'some values' }, 'this is the third id': { _id: 'this is the third id', value: 'some values' } }); }); }); describe('read', function () { beforeEach(function () { nativeLocalStorage.patient = { 'some id': 'some value', 'mislead': 'invalid one' }; }); it('should read single patient when query with id', function () { var patient = localStorage.read('/api/patient/patient/', {patientId: "some id"}); expect(patient).toEqual('some value'); }); it('should list patients when search for all', function () { var list = localStorage.read('/api/patient/search/', {}); expect(list).toEqual(['some value', 'invalid one']); }); it('should return null when nothing was found', function () { var nothing = localStorage.read('/api/patient/nothing/', {}); expect(nothing).toBeNull(); }); it('should list patients has matched reference, first/last name when search with query', function () { nativeLocalStorage.patient = { 'some id': {'firstName': 'first fff name'}, 'second id': {'lastName': 'last fff'}, 'third id': {'reference': 'fffreference'}, 'fourth id': {'reference': 'nothing'} }; var list = localStorage.read('/api/patient/search/', {query: 'fff'}); expect(list).toEqual([{firstName: 'first fff name'}, {lastName: 'last fff'}, {reference: 'fffreference'}]); }); }); describe('write', function () { beforeEach(function () { nativeLocalStorage.patient = { 'oneId': 'some value', 'anotherId': 'some thing else' }; }); it('should update exist patient', function () { localStorage.write('/api/patient/patient/', {_id: 'oneId', firstName: 'fff', lastName: 'feng'}); var list = localStorage.read('/api/patient/search/', {query: 'fff'}); expect(list.length).toBe(1); expect(list[0].lastName).toBe('feng'); expect(list[0]._dirty).toBeTruthy(); }); it('should create new patient with id start with "NEW_"', function () { localStorage.write('/api/patient/patient/', {firstName: 'fff', lastName: 'feng'}); localStorage.write('/api/patient/patient/', {firstName: 'fff', lastName: 'feng2'}); var list = localStorage.read('/api/patient/search/', {query: 'fff'}); expect(list.length).toBe(2); expect(list[0]._id).toMatch(/NEW_\w+/); expect(list[0]._dirty).toBeTruthy(); expect(list[1]._id).toMatch(/NEW_\w+/); expect(list[1]._dirty).toBeTruthy(); }); }); describe('drop', function () { beforeEach(function () { nativeLocalStorage.patient = { 'NEW_something': 'some value', 'anotherId': 'some thing else' }; }); it('should return true if drop a local object', function () { var result = localStorage.drop('/api/patient/patient/', 'NEW_something'); expect(result).toBeTruthy(); expect(_.size(nativeLocalStorage.patient)).toBe(1); expect(nativeLocalStorage.patient.NEW_something).toBeUndefined(); }); it('should return false if drop a remote object', function () { var result = localStorage.drop('/api/patient/patient/', 'anotherId'); expect(result).toBeFalsy(); expect(_.size(nativeLocalStorage.patient)).toBe(1); expect(nativeLocalStorage.patient.anotherId).toBeUndefined(); }); it('should throw exception if drop something not exist', function () { var dropNone = function () { localStorage.drop('/api/patient/patient/', 'not_exist'); }; expect(dropNone).toThrowError('Unable to drop something is gone'); }); }); describe('list dirty patient', function () { it('should list dirty patients only', function () { nativeLocalStorage.patient = { 'this is id': {'some': 'thing'}, 'this id': {'some': 'thing', _dirty: false}, 'this is another id': {'some': 'thing else', _dirty: true}, 'this is id': {'some': 'thing else', _dirty: true} }; var dirty = patientRule.listDirty(); expect(dirty.length).toBe(2); }); }); });
/* * Game JS */ Vue.component('goal-select', { template: ` <div> <form class="form-horizontal" v-on:submit.prevent="" v-if="seen"> <div class="form-group"> <label for="topicSearch" class="col-sm-2 control-label">Choose a goal topic</label> <div class="col-sm-10"> <input id="topicSearch" type="text" placeholder="Start typing to search for a topic..." autofocus="autofocus" autocomplete="off" class="form-control" v-model="topic"> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Topics</label> <div class="col-sm-10"> <span v-if="topic == '' ">Start searching or select an example topic</span> <ul> <li v-for="item in topics" v-on:click.prevent.stop="goalPick(item)"> <a href="#">{{ item }}</a> </li> </ul> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Examples</label> <div class="col-sm-10"> <ul> <li v-for="item in examples" v-on:click.prevent.stop="goalPick(item.title)"> <a href="#">{{ item.title }}</a> </li> </ul> </div> </div> </form> <div class="" v-if="chosenGoal != '' "> <div class="col-sm-10"> Chosen Goal: <span id="chosenGoal"><b>{{ chosenGoal }}</b></span> </div> <div class="col-sm-2"><img :src="goalImg" class="sideImage" v-if="goalImg != '' " /></div> </div> </div> `, data: function () { return { seen: true, topic: "", topics: [], examples: [], chosenGoal: "", goalImg: "", } }, created: function () { var self = this; self.loadExamples(); }, watch: { // whenever the topic changes, this function will run topic: function (newTopic) { console.log("Waiting for typing to complete ... " + newTopic); //Execute delayed function this.findTopic(); } }, methods: { findTopic: _.debounce(function () { self = this; console.log("Searching for topic: " + self.topic); $.get("/api/query/" + self.topic) .done(function(data) { self.topics = data[1]; }) .fail(function() { console.log("Error fetching topics"); }); }, 500), goalPick: function(goal) { console.log("Choosing goal: " + goal); this.chosenGoal = goal; this.loadImage(goal); bus.$emit('randomStart:selectGoal'); bus.$emit('gameRound:setGoal', goal); this.seen = false; }, loadExamples: function() { var self = this; $.get("/api/random") .done(function(data) { self.examples = data.query.random; }) .fail(function() { console.log("Error fetching examples"); }); }, loadImage: function(topic) { var self = this; self.goalImg = "/img/undefined.png"; $.get("/api/image/" + topic) .done(function(data) { if(data.original !== undefined) { self.goalImg = data.original; } }) .fail(function() { console.log("Error fetching image"); }); }, }, }); Vue.component('random-start', { template: ` <div v-if="seen"> <div class="col-sm-12" > <span>Starting Topic: <i v-if="!topic">A random topic will be chosen when you start</i> <b v-if="topic">{{ topic }}</b> </span> </div> <div class="col-sm-12" > <button class="btn btn-danger" v-on:click="startOver">Start Over</button> <button class="btn btn-primary" v-on:click="findTopic" v-if="!topic">Let&rsquo;s Play</button> </div> </div> `, data: function () { return { seen: false, topic: "", topics: [], }; }, created: function () { var self = this; //Bind Event Listener bus.$on('randomStart:selectGoal', function () { self.seen = true; }); }, methods: { findTopic: function () { var self = this; console.log("Fetching random topic "); $.get("/api/random") .done(function(data) { self.topics = data.query.random; //Pick a random topic self.topic = self.topics[Math.floor(Math.random()*self.topics.length)].title; bus.$emit('gameRound:selectTopic', self.topic); self.seen = true; }) .fail(function() { console.log("Error fetching topics"); }); }, startOver: function () { location.reload(); }, }, }); Vue.component('game-round', { template: ` <div v-if="seen"> <div class="col-sm-10">Current Topic: <b>{{ topic }}</b></div> <div class="col-sm-2"><img :src="topicImg" class="sideImage" v-if="topicImg != '' " /></div> <div class="col-sm-12">Score: <b>{{ score }}</b></div> <div class="col-sm-12"> <ul> <li v-for="item in outgoingLinks" > <a href="#" v-on:click.prevent.stop="choose(item.title)">{{ item.title }}</a> </li> </ul> </div> </div> `, data: function () { return { seen: false, score: 0, topic: "", topicImg: "", outgoingLinks: [], goal: "", }; }, created: function () { var self = this; //Bind Event Listener bus.$on('gameRound:selectTopic', function (topic) { self.choose(topic); }); bus.$on('gameRound:setGoal', function (goal) { self.goal = goal; }); }, methods: { choose: function (topic) { var self = this; self.seen = true; console.log("Selecting topic: " + topic); self.topic = topic; var normalised = Utils.normalise(topic); //Check if this is a winning move if(self.contains(normalised, self.goal)) { bus.$emit('gameOver:win'); console.log("Yay! You win."); } //Get outgoing links and display them self.getOutgoingLinks(normalised); self.loadImage(normalised); self.score++; }, getOutgoingLinks: function (topic) { var self = this; $.get("/api/outgoing/" + topic) .done(function(data) { if (data.length === 0) { bus.$emit('gameOver:noLinks'); console.log("Uh oh, page has no links!"); } else { self.outgoingLinks = data; } }) .fail(function() { console.log("Error fetching topics"); }); }, contains: function(needle, haystack) { $.get("/api/contains/" + haystack + "/" + needle) .done(function(data) { return data.result; }) .fail(function() { console.log("Error fetching topics"); return false; }); }, loadImage: function(topic) { var self = this; self.topicImg = "/img/undefined.png"; $.get("/api/image/" + topic) .done(function(data) { if(data.original !== undefined) { self.topicImg = data.original; } }) .fail(function() { console.log("Error fetching image"); }); }, }, }); Vue.component('game-over', { template: ` <div v-if="seen"> <h1>Game Over</h1> <div class="col-sm-12"><b>{{ message }}</div> <div> <button class="btn btn-danger" v-on:click="startOver">Start Again</button> </div> </div> `, data: function () { return { seen: false, message: "", }; }, created: function () { var self = this; //Bind Event Listener bus.$on('gameOver:noLinks', function () { self.seen = true; message = "There were no links left!"; }); bus.$on('gameOver:win', function () { self.seen = true; message = "Congratulations! You won."; }); }, methods: { startOver: function () { location.reload(); }, }, }); //Global Event Bus var bus = new Vue(); var game = new Vue({ el: '#game', });
var mongoose = require("mongoose"), Schema = mongoose.Schema; var Message = new Schema({ chat_content: { type: Array, default: [] } }); //Export modules. module.exports = mongoose.model("message", Message);
/* * Copyright (c) Andrรฉ Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ export default () => "standard"; export let foo = () => "standard";
"use strict"; // Here I can modify configuration... const config = require("./config.js"); config.web.port = 8282; // Or execute other custom code! // then run real index.js require("./index.js");
'use strict'; import React from 'react/addons'; import SuitCssify from '../index'; import classNames from 'classnames'; let Button = React.createClass({ mixins: [SuitCssify.mixin], propTypes: { children: React.PropTypes.node, disabled: React.PropTypes.bool, kind: React.PropTypes.oneOf(['primary', 'secondary']), onClick: React.PropTypes.func, size: React.PropTypes.oneOf(['small', 'medium', 'large']) }, render() { const buttonProps = { className: this.getClassName({ modifiers: classNames(this.props.kind, this.props.size), states: classNames({ disabled: this.props.disabled }) }), onClick: this.props.onClick && this.props.onClick() }; const textProps = { className: this.getClassName({ descendantName: 'text' }) }; return ( <button { ...buttonProps }> <span { ...textProps }>{ this.props.children }</span> </button> ); } }); export default Button;
/* * grunt-cache-buster * https://github.com/jparsons/cache-buster * * Copyright (c) 2013 Jon Parsons * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>', ], options: { jshintrc: '.jshintrc', }, }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'], }, // Configuration to be run (and then tested). cache_buster: { default_options: { options: { }, files: { 'tmp/default_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, custom_options: { options: { separator: ': ', punctuation: ' !!!', }, files: { 'tmp/custom_options': ['test/fixtures/testing', 'test/fixtures/123'], }, }, }, // Unit tests. nodeunit: { tests: ['test/*_test.js'], }, }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', 'cache_buster', 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
/** * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import bar from 'data:application/json,{"obj": 456}'; import {foo} from 'data:text/javascript,export const foo = "123"'; export function value() { return {bar, foo}; }
'use strict'; /* eslint-env phantomjs */ /* globals document: true */ var path = require('path'), phridge = require('phridge'), promise = require('bluebird'), utility = require('./utility'), _ = require('lodash'); var phantom; /** * Create the PhantomJS instances, or use the given one. * @param {Object} instance The instance to use, if there is one * @return {promise} */ function init(instance) { if (instance) { phantom = instance; return null; } // Convert to bluebird promise return new promise(function (resolve) { resolve(phridge.spawn({ ignoreSslErrors: 'yes', sslProtocol: 'any' })); }).then(function (ph) { /* Phridge outputs everything to stdout by default */ ph.childProcess.cleanStdout.unpipe(); ph.childProcess.cleanStdout.pipe(process.stderr); phantom = ph; }).disposer(phridge.disposeAll); } /** * This function is called whenever a resource is requested by PhantomJS. * If we are loading either raw HTML or a local page, PhantomJS needs to be able to find the * resource with an absolute path. * There are two possible cases: * - 'file://': This might be either a protocol-less URL or a relative path. Since we * can't handle both, we choose to handle the former. * - 'file:///': This is an absolute path. If options.htmlroot is specified, we have a chance to * redirect the request to the correct location. */ function ResourceHandler(htmlroot, isWindows, resolve) { var ignoredExtensions = ['\\.css', '\\.png', '\\.gif', '\\.jpg', '\\.jpeg', ''], ignoredEndpoints = ['fonts\\.googleapis']; var ignoreRequests = new RegExp(ignoredExtensions.join('$|') + ignoredEndpoints.join('|')); this.onResourceRequested = function (requestData, networkRequest) { var originalUrl = requestData.url, url = originalUrl.split('?')[0].split('#')[0]; if (url.substr(-3) === '.js' && url.substr(0, 7) === 'file://') { /* Try and match protocol-less URLs and absolute ones. * Relative URLs will still not load. */ if (url.substr(5, 3) === '///') { /* Absolute URL * Retry loading the resource appending the htmlroot option */ if (isWindows) { /* Do not strip leading '/' */ url = originalUrl.substr(0, 8) + htmlroot + originalUrl.substr(7); } else { url = originalUrl.substr(0, 7) + htmlroot + originalUrl.substr(7); } } else { /* Protocol-less URL */ url = 'http://' + originalUrl.substr(7); } networkRequest.changeUrl(url); } else if (ignoreRequests.test(url)) { networkRequest.abort(); } }; resolve(); } /** * Helper for fromRaw, fromLocal, fromRemote; * return the phantom page after the timeout * has elapsed * @param {phantom} page Page created by phantom * @param {Object} options * @return {promise} */ function resolveWithPage(page, options) { return function () { return new promise(function (resolve) { setTimeout(function () { return resolve(page); }, options.timeout); }); }; } /** * Load a page given an HTML string. * @param {String} html * @param {Object} options * @return {promise} */ function fromRaw(html, options) { var page = phantom.createPage(), htmlroot = path.join(process.cwd(), options.htmlroot || ''); return page.run(htmlroot, utility.isWindows(), ResourceHandler).then(function () { return page.run(html, function (raw) { this.setContent(raw, 'local'); }); }).then(resolveWithPage(page, options)); } /** * Open a page given a filename. * @param {String} filename * @param {Object} options * @return {promise} */ function fromLocal(filename, options) { var page = phantom.createPage(), htmlroot = path.join(process.cwd(), options.htmlroot || ''); return page.run(htmlroot, utility.isWindows(), ResourceHandler).then(function (data) { return page.run(htmlroot+"\\"+filename, function (source, resolve, reject) { this.open(source, function (status) { if (status !== 'success') { return reject(new Error('PhantomJS: Cannot open ' + this.url)); } resolve(); }); }); }).then(resolveWithPage(page, options)); } /** * Open a page given a URL. * @param {String} url * @param {Object} options * @return {promise} */ function fromRemote(url, options) { /* If the protocol is unspecified, default to HTTP */ if (!/^http/.test(url)) { url = 'http:' + url; } return phantom.openPage(url).then(function (page) { return resolveWithPage(page, options)(); }); } /** * Extract stylesheets' hrefs from dom * @param {Object} page A PhantomJS page * @param {Object} options Options, as passed to UnCSS * @return {promise} */ function getStylesheets(page, options) { if (_.isArray(options.media) === false) { options.media = [options.media]; } var media = _.union(['', 'all', 'screen'], options.media); return page.run(function () { return this.evaluate(function () { return Array.prototype.map.call(document.querySelectorAll('link[rel="stylesheet"]'), function (link) { return { href: link.href, media: link.media }; }); }); }).then(function (stylesheets) { stylesheets = _ .toArray(stylesheets) /* Match only specified media attributes, plus defaults */ .filter(function (sheet) { return media.indexOf(sheet.media) !== -1; }) .map(function (sheet) { return sheet.href; }); return stylesheets; }); } /** * Filter unused selectors. * @param {Object} page A PhantomJS page * @param {Array} sels List of selectors to be filtered * @return {promise} */ function findAll(page, sels) { return page.run(sels, function (args) { return this.evaluate(function (selectors) { // Unwrap noscript elements Array.prototype.forEach.call(document.getElementsByTagName('noscript'), function (ns) { var wrapper = document.createElement('div'); wrapper.innerHTML = ns.innerText; // Insert each child of the <noscript> as its sibling Array.prototype.forEach.call(wrapper.children, function (child) { ns.parentNode.insertBefore(child, ns); }); }); // Do the filtering selectors = selectors.filter(function (selector) { try { if (document.querySelector(selector)) { return true; } } catch (e) { return true; } }); return { selectors: selectors }; }, args); }).then(function (res) { if (res === null) { return []; } return res.selectors; }); } module.exports = { init: init, fromLocal: fromLocal, fromRaw: fromRaw, fromRemote: fromRemote, findAll: findAll, getStylesheets: getStylesheets };
import { expect } from 'chai'; import React from 'react'; import {shallow} from 'enzyme'; import PxAlertLabel from './'; describe('px-alert-label', () => { test('should...', () =>{ const wrapper = shallow( <PxAlertLabel/> ); console.log(wrapper.debug()); expect(true).to.equal(true); }); test('should render correctly', () =>{ const wrapper = shallow( <PxAlertLabel label='Test'/> ); console.log(wrapper.debug()); expect(wrapper.find('.label')).to.have.length(1); expect(wrapper.contains(<span className='label__text'>Test</span>)).to.equal(true); }); });
CollectionHelpers = {}; CollectionHelpers.addCreatedValues = function (doc){ doc.createdAt = moment().utc().format(); doc.createdById = Meteor.userId(); doc.createdByUsername = Meteor.user().username; } CollectionHelpers.addUpdatedValues = function (doc){ doc.updatedAt = moment().utc().format(); doc.updatedById = Meteor.userId(); doc.updatedByUsername = Meteor.user().username; }
import React from 'react'; import jQuery from 'jquery'; import {getTopicDetail,updateTopic} from '../lib/client'; import {redirectUrl} from '../lib/utils'; import TopicEditor from './TopicEditor'; export default class NewTopic extends React.Component{ constructor(props){ super(props); this.state={}; } componentDidMount(){ getTopicDetail(this.props.params.id) .then(topic=> { this.setState({topic}); }) .catch(err => console.log(err)); } render(){ if (!this.state.topic){ return ( <div>ๆญฃๅœจๅŠ ่ฝฝไธญ...</div> ); } return ( <TopicEditor title='็ผ–่พ‘ไธป้ข˜' topic={this.state.topic} onSave={(topic, done)=>{ updateTopic(this.props.params.id,topic.title,topic.tags,topic.content) .then(ret=>{ done(); redirectUrl(`/topic/${ret._id}`); }) .catch(err => { done(); alert(err); }); } } /> ); } }
(function() { 'use strict'; const Class = require('ee-class'); const type = require('ee-types'); const log = require('ee-log'); const EventEmitter = require('ee-event-emitter'); /** * The Permissions Class exposes an interface to query the permissions for one * AccessToken. The class is exposed to the the user via the PermissionSet * class which proxies almost all methods so the user is able to get the permissions * of multiple Permission Class instances. This class cannot be instantiated by the * user! * * @module ee-soa-permission * @class Permission */ module.exports = new Class({ inherits: EventEmitter // the token for this permission , token: null /** * Permission constructor. Instantiatedd by the factory! * * @param {String} token Accesstoken for this permission instance * @param {Array} roles Roles belonging to the token */ , init: function(token, roles) { // tokens may token.once('delete', function() { this.token = null; this.roles = {}; // tell the permissions set that this permission has expired this.emit('delete'); }.bind(this)); // set up the role storage this.roles = {}; // the token for this permission this.token = token; // store roles this.setRoles(roles); } /** * returns the token itself * * @param {sting} the hex encoded token */ , getToken: function() { return this.token ? this.token.getToken() : null; } /** * checks wheter an action on a specific object is allowed * * @param {string} objectName The name of the object to check the permission for * @param {string} actionName The name of the action to check the permission for * * @param {bool} True if the token is allowed to execute the given action * for the given object */ , isActionAllowed: function(objectName, actionName) { return Object.keys(this.roles).some(function(roleName) { return this.roles[roleName].isActionAllowed(objectName, actionName); }.bind(this)); } /** * Checks if the token has a user attached to it * * @returns {bool} True if the token and thus the permission * has an user */ , hasUser: function() { return this.token ? this.token.isUserToken() : false; } /** * Checks if the token has an app attached to it * * @returns {bool} True if the token and thus the permission * has an app */ , hasApp: function() { return this.token ? this.token.isAppToken() : false; } /** * Checks if the token has a user attached to it * * @returns {bool} True if the token and thus the permission * has an user */ , hasTenant: function() { return this.token ? this.token.hasTenant() : false; } /** * Checks if the token has a service attached to it * * @returns {bool} True if the token and thus the permission * has a service */ , hasService: function() { return this.token ? this.token.isServiceToken() : false; } /** * returns the tenant for the permisson if exists * * @returns {object|null} the tenant or null */ , getTenant: function() { return this.token ? this.token.getTenant() : null; } /** * returns the user for the permisson if exists * * @returns {object|null} the user or null */ , getUser: function() { return this.token ? this.token.getUser() : null; } /** * returns the app for the permisson if exists * * @returns {object|null} the app or null */ , getApp: function() { return this.token ? this.token.getApp() : null; } /** * returns the service for the permisson if it exists * * @returns {object|null} the service or null */ , getService: function() { return this.token ? this.token.getService() : null; } /** * collects all permissions for a given object * * @param {string} objectName the name of the object to get the permissions for * @param {object} permissions object to store the permissions on */ , collectObjectPermissions: function(objectName, permissions) { // check all roles Object.keys(this.roles).some(function(roleName) { this.roles[roleName].collectObjectPermissions(objectName, permissions); }.bind(this)); } /** * collects all permissions * * @param {object} permissions object to store the permissions on */ , collectPermissionInfo: function(permissions) { // check all roles Object.keys(this.roles).some(function(roleName) { this.roles[roleName].collectPermissionInfo(permissions); }.bind(this)); } /** * collects all capabilities * * @param {object} capabilities object to store the capabilities on */ , collectCapabilities: function(capabilities) { // check all roles Object.keys(this.roles).some(function(roleName) { this.roles[roleName].collectCapabilities(capabilities); }.bind(this)); } /** * returns the row restrictions for a specific entity. All restrictions * of all roles are merged and returned. * * @param {string} entityName the name of the entity to get the * restrictions for * @param {object} restrictions object to save the restrictions in */ , getRowRestrictions: function(entityName, restrictions) { // collect the restrictions from all roles Object.keys(this.roles).some(function(roleName) { this.roles[roleName].getRowRestrictions(entityName, restrictions); }.bind(this)); } /** * Checks if the token has a specific role attached to it * * @param {string} roleName The name of the role * * @returns {bool} True if the token and thus the permission * has a specific role */ , hasRole: function(roleName) { return !!this.roles[roleName]; } /** * Checks if the token has a specific capability attached to it * * @param {string} capcabilityName The name of the capability * * @returns {bool} True if the token and thus the permission * has a specific capability */ , hasCapability: function(capcabilityName) { return Object.keys(this.roles).some(function(roleName) { return this.roles[roleName].hasCapability(capcabilityName); }.bind(this)); } /** * Returns all the roles attached to the token and thus this permission * * @returns {array} roles Roles */ , getRoles: function() { return this.roles; } /** * Set roles on the permission, should not be used by the user * because it can have severe side effects. Is used only for * caching mechanisms * * @private * * @param {array} roles Array containing roles * * @listens Role:delete * @throws {TypeError} the roles parameter has the wring type */ , setRoles: function(roles) { if (!type.array(roles)) throw new Error('Expected an array of roles, got ยซ'+type(roles)+'ยป!'); // listen for the delete event, // remove the role if it was fired roles.forEach(function(role) { this.roles[role.name] = role; // listen only once role.once('delete', function(role) { delete this.roles[role.name]; }.bind(this)); }.bind(this)); } }); }) ();
a = 1, b = a, c = 1, d = b, e = d, longname = 2; if (longname + 1) { x = 3; if (x)var z = 7 } z = 1, y = 1, x = 1, g += 1, h = g, ++i, j = i, i++, j = i + 17
//= require ./model.js (function () { 'use strict'; var node = typeof window === 'undefined'; var app = node ? {} : window.app; var _ = node ? require('underscore') : window._; var Model = node ? require('./model') : app.Model; var soundManager = node ? null : window.soundManager; var Sound = Model.extend({ tracks: 10, gfxPath: function () { return '/gfx/sounds/' + this.id + '.png'; }, audioPath: function () { return '/audio/sounds/' + this.id + '.mp3'; }, load: function () { if (this.loaded) return; this.loaded = true; this.track = -1; _.times(this.tracks, function () { soundManager.createSound(this.nextTrack(), this.audioPath()).load(); }, this); }, nextTrack: function () { return this.id + '-' + (++this.track % this.tracks); }, emit: function () { this.play(); app.socket.emit('play', {id: this.id, t: +new Date()}); }, play: function () { if (this.loaded) { this.trigger('play'); soundManager.play(this.nextTrack()); } }, key: function () { return String.fromCharCode(this.get('charCode')); } }); Sound.Collection = Model.Collection.extend({ model: Sound, url: '/sounds' }); Sound.all = new Sound.Collection([{ id: 'e-chord', charCode: 81, name: 'E' }, { id: 'f-chord', charCode: 87, name: 'F' }, { id: 'fs-chord', charCode: 69, name: 'Fโ™ฏ' }, { id: 'g-chord', charCode: 82, name: 'G' }, { id: 'gs-chord', charCode: 65, name: 'Gโ™ฏ' }, { id: 'a-chord', charCode: 83, name: 'A' }, { id: 'bb-chord', charCode: 68, name: 'Bโ™ญ' }, { id: 'b-chord', charCode: 70, name: 'B' }, { id: 'c-chord', charCode: 90, name: 'C' }, { id: 'cs-chord', charCode: 88, name: 'Cโ™ฏ' }, { id: 'd-chord', charCode: 67, name: 'D' }, { id: 'eb-chord', charCode: 86, name: 'Eโ™ญ' }, { id: 'hh-closed', charCode: 73, name: 'High-hat (Closed)' }, { id: 'hh-open', charCode: 79, name: 'High-hat (Open)' }, { id: 'crash', charCode: 80, name: 'Crash' }, { id: 'snare', charCode: 85, name: 'Snare' }, { id: 'kick', charCode: 89, name: 'Kick' }, { id: 'clap', charCode: 84, name: 'Clap' }, { id: 'tom', charCode: 75, name: 'Tom' }, { id: 'snap', charCode: 74, name: 'Snap' } ]); node ? module.exports = Sound : app.Sound = Sound; })();
'use strict'; // Declare app level module which depends on views, and components angular.module('NHCApp', [ 'ngRoute', 'NHCApp.aboutus', 'NHCApp.home', 'NHCApp.products', 'NHCApp.contact' ]) .config(['$locationProvider', '$routeProvider', function($locationProvider, $routeProvider) { $locationProvider.hashPrefix('!'); $routeProvider. otherwise({redirectTo: '/'}); }]) .directive('scrollNav',['$window','$timeout', function($window,$timeout){ }]) .controller('MainCtrl',['$scope', function($scope){ $scope.gotToTeam = function(id) { $location.path("/aboutus"); $timeout(function(){ $location.hash(id); $anchorScroll(); }, delay); }; }]);
var movingShapes = (function() { "use strict"; var BROWSER_SAFE_FONTS = [ /*Serif Fonts*/ "Georgia, serif", "\"Palatino Linotype\", \"Book Antiqua\", Palatino, serif", "\"Times New Roman\", Times, serif", /*Sans-Serif Fonts*/ "Arial, Helvetica, sans-serif", "\"Arial Black\", Gadget, sans-serif", "\"Comic Sans MS\", cursive, sans-serif", "Impact, Charcoal, sans-serif", "\"Lucida Sans Unicode\", \"Lucida Grande\", sans-serif", "Tahoma, Geneva, sans-serif", "\"Trebuchet MS\", Helvetica, sans-serif", "Verdana, Geneva, sans-serif", /*Monospace Fonts*/ "\"Courier New\", Courier, monospace", "\"Lucida Console\", Monaco, monospace" ]; var SHAPE_WIDTH = 80; var SHAPE_HEIGHT = 80; var RADIUS_OF_CIRCLE_TRAJECTORY = 100; var WIDTH_OF_RECTANGULAR_TRAJECTORY = 200; var HEIGHT_OF_RECTANGULAR_TRAJECTORY = 100; var movingShapesToRender = {}; function InvalidArumentException(message) { this.message = message; this.name = "InvalidArumentException"; } function add(shapeMovementType) { switch (shapeMovementType) { case "rect": intializeDivMovingInRectangle(); break; case "ellipse": intializeDivMovingInCircle(); break; default: throw new InvalidArumentException("Error! The argument must be either 'rect' or 'ellipse'."); } } function intializeDivMovingInRectangle() { var div = document.createElement("div"); generateRandomStylesForDiv(div); div.className = "moving-in-rect"; div.innerHTML = "rect"; var trajectoryX = getRandomArbitary(0, window.innerWidth - WIDTH_OF_RECTANGULAR_TRAJECTORY - SHAPE_WIDTH); var trajectoryY = getRandomArbitary(0, window.innerHeight - HEIGHT_OF_RECTANGULAR_TRAJECTORY - SHAPE_HEIGHT); div.style.left = trajectoryX + "px"; div.style.top = trajectoryY + "px"; div.setAttribute("data-trajectory-coordinates", trajectoryX + ' ' + trajectoryY); div.setAttribute("data-moving-shape-coordintes", trajectoryX + ' ' + trajectoryY); div.setAttribute("data-clockwise", getRandomArbitary(0, 2) | 0); document.body.appendChild(div); } function intializeDivMovingInCircle() { var div = document.createElement("div"); generateRandomStylesForDiv(div); div.className = "moving-in-ellipse"; div.innerHTML = "ellipse"; var trajectoryX = getRandomArbitary(RADIUS_OF_CIRCLE_TRAJECTORY, window.innerWidth - 2 * RADIUS_OF_CIRCLE_TRAJECTORY); var trajectoryY = getRandomArbitary(RADIUS_OF_CIRCLE_TRAJECTORY, window.innerHeight - 2 * RADIUS_OF_CIRCLE_TRAJECTORY); div.setAttribute("data-trajectory-coordinates", trajectoryX + ' ' + trajectoryY); div.setAttribute("data-degrees", 0); div.setAttribute("data-clockwise", getRandomArbitary(0, 2) | 0); document.body.appendChild(div); } function generateRandomStylesForDiv(div) { div.style.position = "absolute"; div.style.backgroundColor = getRandomColor(); div.style.border = "1px solid " + getRandomColor(); div.style.fontSize = (SHAPE_HEIGHT / 4.5) + "px"; div.style.fontFamily = getRandomFontFamily(); /** * To be sure that font color an background color don"t match. */ do { div.style.color = getRandomColor(); } while (div.style.color == div.style.backgroundColor); div.style.textAlign = "center"; div.style.lineHeight = SHAPE_HEIGHT + "px"; div.style.width = SHAPE_WIDTH + "px"; div.style.height = SHAPE_HEIGHT + "px"; } function moveInRectangularTrajectory() { var divs = document.getElementsByClassName("moving-in-rect"); for (var i = 0, len = divs.length; i < len; i++) { drawDivAtCordinates(divs[i]); } function drawDivAtCordinates(div) { var minX = div.getAttribute("data-trajectory-coordinates").split(" ")[0]; var minY = div.getAttribute("data-trajectory-coordinates").split(" ")[1]; var maxX = parseFloat(minX) + WIDTH_OF_RECTANGULAR_TRAJECTORY; var maxY = parseFloat(minY) + HEIGHT_OF_RECTANGULAR_TRAJECTORY; var divX = parseFloat(div.getAttribute("data-moving-shape-coordintes").split(" ")[0]); var divY = parseFloat(div.getAttribute("data-moving-shape-coordintes").split(" ")[1]); goAntiClockWise(div, divX, divY, minX, maxX, minY, maxY); if (div.getAttribute("data-clockwise") == 1) { goClockWise(div, divX, divY, minX, maxX, minY, maxY); } else { goAntiClockWise(div, divX, divY, minX, maxX, minY, maxY); } } function goClockWise(div, divX, divY, minX, maxX, minY, maxY) { //right if (divX <= maxX && divY == minY) { divX++; } //down if (divX == maxX && divY <= maxY) { divY++; } //left if (divX >= minX && divY == maxY) { divX--; } //up if (divX == minX && divY >= minY) { divY--; } div.style.left = divX + "px"; div.style.top = divY + "px"; div.setAttribute("data-moving-shape-coordintes", divX + " " + divY); } function goAntiClockWise(div, divX, divY, minX, maxX, minY, maxY) { //down if (divX == minX && divY <= maxY) { divY++; } //right if (divX <= maxX && divY == maxY) { divX++; } //up if (divX == maxX && divY >= minY) { divY--; } //left if (divX >= minX && divY == minY) { divX--; } div.style.left = divX + "px"; div.style.top = divY + "px"; div.setAttribute("data-moving-shape-coordintes", divX + " " + divY); } } function moveInCircularTrajectory() { var divs = document.getElementsByClassName("moving-in-ellipse"); for (var i = 0, len = divs.length; i < len; i++) { drawDivAtDegrees(divs[i]); } function drawDivAtDegrees(div) { var trajectory = div.getAttribute("data-trajectory-coordinates").split(" "); var degrees = div.getAttribute("data-degrees"); div.style.left = parseFloat(trajectory[0]) + Math.cos(degrees * Math.PI / 180) * RADIUS_OF_CIRCLE_TRAJECTORY + "px"; div.style.top = parseFloat(trajectory[1]) + Math.sin(degrees * Math.PI / 180) * RADIUS_OF_CIRCLE_TRAJECTORY + "px"; if (div.getAttribute("data-clockwise") == 1) { degrees++; } else { degrees--; } div.setAttribute("data-degrees", degrees); } } // Returns a hex value with starting with "#" function getRandomColor() { var hex = ((1 << 24) * Math.random() | 0).toString(16); var color = "#" + hex; return color; } function getRandomFontFamily() { var fontIndexInList = getRandomArbitary(0, BROWSER_SAFE_FONTS.length) | 0; var randomFont = BROWSER_SAFE_FONTS[fontIndexInList]; return randomFont; } function getRandomArbitary(min, max) { return Math.random() * (max - min) + min; } window.requestAnimFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame; (function renderMovingShapes() { window.requestAnimFrame(renderMovingShapes); moveInRectangularTrajectory(); moveInCircularTrajectory(); })(); return { add: add, }; })();
var gulp = require('gulp'), connect = require('gulp-connect'), less = require('gulp-less'), uglify = require('gulp-uglify'), clean = require('gulp-clean'), minifyCss = require('gulp-minify-css'), concat = require('gulp-concat'), concatVendor = require('gulp-concat-vendor'), htmlify = require('gulp-angular-htmlify'), angularTemplates = require('gulp-angular-templates'), processHtml = require('gulp-processhtml'), minifyHtml = require('gulp-minify-html'), rename = require('gulp-rename'), karma = require('gulp-karma'), insert = require('gulp-insert'), packageConfig = require('./package.json'), open = require('gulp-open'), libGlob = [ 'bower_components/jquery/dist/jquery.js', 'bower_components/angular/angular.js', 'bower_components/angular-*/angular-*.js', '!bower_components/angular-mocks/angular-mocks.js' ], unitTestGlob = [ 'bower_components/jquery/dist/jquery.min.js', 'bower_components/angular/angular.min.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-*/angular-*.min.js', 'app/app.js', 'app/**/*.js', 'app/directives/*.html', 'tests/mockData/*.js', 'tests/unit/**/*.js', '!app/bower/**/*' ]; // server setup ------------------------------- gulp.task('dev-server', function(){ 'use strict'; connect.server({ port: 9000, host: 'localhost', root: 'app', fallback: 'app/index.html', livereload: true }); console.log(connect); }); gulp.task('prod-server', function(){ 'use strict'; connect.server({ port:9009, host: 'localhost', root: 'dist', fallback: 'dist/index.html', livereload: true }); }); gulp.task('refresh', function(){ 'use strict'; return gulp.src('app/index.html') .pipe(connect.reload()); }); // end server setup -------------------- // file processing --------------------- gulp.task('less', function(){ 'use strict'; return gulp.src('app/style/style.less') .pipe(less({ paths: [ 'app/style' ] })) .pipe(gulp.dest('app/style/')); }); gulp.task('css-build', ['less'], function(){ 'use strict'; return gulp.src('app/style/style.css') .pipe(minifyCss()) .pipe(gulp.dest('dist')); }); gulp.task('angular-templates', function(){ 'use strict'; gulp.src('app/components/*.html') .pipe(htmlify()) .pipe(angularTemplates({module: 'vmMusic', basePath: '/components/'})) .pipe(gulp.dest('app/angular-js-templates')); gulp.src('app/directives/*.html') .pipe(htmlify()) .pipe(angularTemplates({module: 'vmMusic', basePath: '/directives/'})) .pipe(gulp.dest('app/angular-js-templates')); }); gulp.task('js-app-build', function(){ 'use strict'; return gulp.src([ 'app/*.js', 'app/services/*.js', 'app/components/*.js', 'app/directives/*.js', 'app/filters/*.js', 'app/angular-js-templates/*.js' ]) .pipe(concat('app.js')) .pipe(gulp.dest('dist/')); }); gulp.task('js-lib-build', function(){ 'use strict'; return gulp.src(libGlob) .pipe(concatVendor('lib.js')) .pipe(gulp.dest('dist/')); }); gulp.task('js-build', ['js-lib-build', 'js-app-build'], function(){ 'use strict'; return gulp.src([ 'dist/lib.js', 'dist/app.js' ]) .pipe(concat('script.js')) .pipe(uglify()) .pipe(insert.prepend('/*\n name: ' + packageConfig.name + '\n description: ' + packageConfig.description + '\n version: ' + packageConfig.version + '\n copyright: ' + packageConfig.author + '\n*/\n') ) .pipe(gulp.dest('dist/')); }); gulp.task('js-deploy', ['js-build'], function(){ 'use strict'; return gulp.src([ 'dist/lib.js', 'dist/app.js' ], {read:false}) .pipe(clean()); }); gulp.task('process-html', function(){ 'use strict'; return gulp.src('app/*.html') .pipe(htmlify()) .pipe(processHtml()) .pipe(minifyHtml()) .pipe(gulp.dest('dist/')); }); gulp.task('process-config', function(){ 'use strict'; return gulp.src('app/config/htaccess.txt') .pipe(rename('.htaccess')) .pipe(gulp.dest('dist/')); }); // end file processing ---------------- //running tests gulp.task('unit-tests-watch', function(){ 'use strict'; return gulp.src(unitTestGlob).pipe(karma({ configFile: 'karma.config.js', action: 'watch' })); }); gulp.task('run-unit-tests', function(){ 'use strict'; return gulp.src(unitTestGlob).pipe(karma({ configFile: 'karma.config.js' })); }); //end running tests gulp.task('open-browser-dev', function () { 'use strict'; return gulp.src('app/index.html') .pipe(open({uri: 'http://localhost:9000'})); }); gulp.task('build',[ 'run-unit-tests', 'css-build', 'angular-templates', 'js-deploy', 'process-html', 'process-config' ]); gulp.task('watch', function(){ 'use strict'; gulp.watch([ 'app/*.js', 'app/*/*.js', 'app/*.html', 'app/*/*.html', 'app/*.css', 'app/*/*.css' ], ['refresh']); gulp.watch('app/style/*.less', ['less']); }); gulp.task('default', ['dev-server', 'unit-tests-watch', 'watch', 'open-browser-dev']);
import React, {PropTypes} from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import Search from '../components/search' import * as searchActions from '../actions/search-actions' const SearchContainer = (props) => ( <div> <Search {...props}></Search> </div> ) const mapStateToProps = state => ({ tracksList: state.search }) const mapDispatchToProps = (dispatch) => ({ actions: bindActionCreators(searchActions, dispatch) }) SearchContainer.propTypes = { actions: PropTypes.object, tracksList: PropTypes.array } export default connect(mapStateToProps, mapDispatchToProps)(SearchContainer)
'use strict'; module.exports = function(grunt) { // load all grunt tasks matching the `grunt-*` pattern require('load-grunt-tasks')(grunt); grunt.initConfig({ // watch for changes and trigger less, jshint and livereload watch: { recess: { files: ['assets/less/*.less'], tasks: ['recess'] }, livereload: { options: { livereload: true }, files: ['*.css', 'assets/js/*.js', '*.html', '*.less', 'assets/img/**/*.{png,jpg,jpeg,gif,webp,svg}'] } }, // less recess: { development: { options: { compile: true }, files: { "assets/css/style.css": "assets/less/main.less" } } }, // javascript linting with jshint jshint: { options: { jshintrc: '.jshintrc', "force": true }, all: [ 'Gruntfile.js', 'assets/js/source/**/*.js' ] }, // image optimization imagemin: { dist: { options: { optimizationLevel: 7, progressive: true }, files: [{ expand: true, cwd: 'assets/img/', src: '**/*', dest: 'assets/img/' }] } }, compress: { main: { options: { archive: 'archive.zip' }, files: [ {src: ['assets/**', 'partials/**', '*.hbs', '*.js', '*.json', '*.md'], dest: 'BiosVision/'} // includes files in path and its subdirs ] } }, }); // register task grunt.registerTask('default', ['watch']); };
var game = require('./sheep/game'); game.init(document.getElementById('stageContainer'));
var sel_number = undefined; var $collapse = $('.collapse'); var $modal_title_lib = $(".modal-title-lib"); var $loading = $(".loading-icon"); $collapse.collapse('hide'); $(document).ready(function() { var IEVersionCheck = function() { var word; var version = "N/A"; var agent = navigator.userAgent.toLowerCase(); var name = navigator.appName; // IE old version ( IE 10 or Lower ) if ( name == "Microsoft Internet Explorer" ) word = "msie "; else { // IE 11 if ( agent.search("trident") > -1 ) word = "trident/.*rv:"; // IE 12 ( Microsoft Edge ) else if ( agent.search("edge/") > -1 ) word = "edge/"; } var reg = new RegExp( word + "([0-9]{1,})(\\.{0,}[0-9]{0,1})" ); if ( reg.exec( agent ) != null ) version = RegExp.$1 + RegExp.$2; return version; }; $('a').click(function(event) { $('#loader').fadeIn("slow", function(){}); $('.need-reveal').addClass("hidden"); $('.need-hide').removeClass('hidden'); $('#information-reveal').removeClass("hidden"); sel_number = $(this).attr('id'); event.preventDefault(); $collapse.collapse('hide'); var xmlhttp = new XMLHttpRequest(); var url = "http://rainclab.net:4567/getLibraryData/" + sel_number + ".json"; xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var data = JSON.parse(this.responseText); $('#collapse-name').html(data.library); $('#manager-name').html(data.assigned_person['name']); $('#manager-phone').html(data.assigned_person['telephone']); ['14', '15'].forEach(function(val, index, array) { var info = data.information["h" + val]; ['title', 'name', 'email', 'detail'].forEach(function(val2, index, array) { $('#time-' + val + '-' + val2).html(info[val2]); }); }); $collapse.collapse('show'); $("body").stop().animate({scrollTop:0}, 1000, 'swing', function() {}); $("#loader").fadeOut("slow", function(){}); } }; xmlhttp.open("GET", url, true); xmlhttp.send(); }); $('#library-search').bind("keyup", function(event) { var val = $(this).val(); if (!IEVersionCheck() == "N/A") { alert("Internet Explorer ์—์„œ๋Š” ํ•ด๋‹น ๊ธฐ๋Šฅ์„ ์ง€์›ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. Chrome ๋ธŒ๋ผ์šฐ์ €๋ฅผ ์„ค์น˜ํ•ด ์ฃผ์„ธ์š”."); location.href="http://chrome.google.com"; } else { $(".library_link").each(function() { if ($(this).html().indexOf(val) == -1) { $(this).css("display", "none"); } else { $(this).css("display", "block"); } }); } }); $("#manager-email").keydown(function (key) { if (key.keyCode == 13){ checkValid(); } }); }); function checkValid() { var $email = $("#manager-email"); var $not = $(".email-not-available"); if ($email.val() == "" || $email.val() == null) { $not.removeClass("hidden"); $not.html("E-mail์„ ์ž…๋ ฅํ•ด ์ฃผ์„ธ์š”!"); return; } if (sel_number == undefined) { alert("์›น์‚ฌ์ดํŠธ์— ์›์ธ์„ ์•Œ ์ˆ˜ ์—†๋Š” ์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค. ๋‹ค์‹œ ์‹œ๋„ํ•ด์ฃผ์„ธ์š”."); location.reload(true); return; } $loading.removeClass("hidden"); var xmlhttp = new XMLHttpRequest(); var url = "http://rainclab.net:4567/infoValidation/" + sel_number + "?email=" + $email.val(); xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var data = JSON.parse(this.responseText); if (data.email_valid == false) { $not.removeClass("hidden"); $not.html("E-mail์ด ์˜ฌ๋ฐ”๋ฅด์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); } else { var info = data.information; $('#time-14-phone').html(info["h14"]); $('#time-15-phone').html(info["h15"]); ['1', '2'].forEach(function(val, index, array) { var temp = info["mc" + val].split(";"); ['name', 'email', 'phone'].forEach(function(val2, index2, array2) { $("#mc-" + val + "-" + val2).html(temp[index2]); }); }); $('.need-reveal').removeClass("hidden"); $('.need-hide').addClass('hidden'); $('#information-reveal').addClass("hidden"); $(".modal").modal('hide'); } $loading.addClass("hidden"); } } xmlhttp.open("GET", url, true); xmlhttp.send(); }
import contains from 'dom-helpers/query/contains'; import PropTypes from 'prop-types'; import React from 'react'; import ReactDOM from 'react-dom'; import addEventListener from './utils/addEventListener'; import ownerDocument from './utils/ownerDocument'; const escapeKeyCode = 27; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } /** * The `<RootCloseWrapper/>` component registers your callback on the document * when rendered. Powers the `<Overlay/>` component. This is used achieve modal * style behavior where your callback is triggered when the user tries to * interact with the rest of the document or hits the `esc` key. */ class RootCloseWrapper extends React.Component { constructor(props, context) { super(props, context); this.preventMouseRootClose = false; } componentDidMount() { if (!this.props.disabled) { this.addEventListeners(); } } componentDidUpdate(prevProps) { if (!this.props.disabled && prevProps.disabled) { this.addEventListeners(); } else if (this.props.disabled && !prevProps.disabled) { this.removeEventListeners(); } } componentWillUnmount() { if (!this.props.disabled) { this.removeEventListeners(); } } addEventListeners = () => { const { event } = this.props; const doc = ownerDocument(this); // Use capture for this listener so it fires before React's listener, to // avoid false positives in the contains() check below if the target DOM // element is removed in the React mouse callback. this.documentMouseCaptureListener = addEventListener(doc, event, this.handleMouseCapture, true); this.documentMouseListener = addEventListener(doc, event, this.handleMouse); this.documentKeyupListener = addEventListener(doc, 'keyup', this.handleKeyUp); } removeEventListeners = () => { if (this.documentMouseCaptureListener) { this.documentMouseCaptureListener.remove(); } if (this.documentMouseListener) { this.documentMouseListener.remove(); } if (this.documentKeyupListener) { this.documentKeyupListener.remove(); } } handleMouseCapture = (e) => { this.preventMouseRootClose = ( isModifiedEvent(e) || !isLeftClickEvent(e) || contains(ReactDOM.findDOMNode(this), e.target) ); }; handleMouse = (e) => { if (!this.preventMouseRootClose && this.props.onRootClose) { this.props.onRootClose(e); } }; handleKeyUp = (e) => { if (e.keyCode === escapeKeyCode && this.props.onRootClose) { this.props.onRootClose(e); } }; render() { return this.props.children; } } RootCloseWrapper.displayName = 'RootCloseWrapper'; RootCloseWrapper.propTypes = { /** * Callback fired after click or mousedown. Also triggers when user hits `esc`. */ onRootClose: PropTypes.func, /** * Children to render. */ children: PropTypes.element, /** * Disable the the RootCloseWrapper, preventing it from triggering `onRootClose`. */ disabled: PropTypes.bool, /** * Choose which document mouse event to bind to. */ event: PropTypes.oneOf(['click', 'mousedown']) }; RootCloseWrapper.defaultProps = { event: 'click' }; export default RootCloseWrapper;
'use strict'; import * as config from "./config"; import Ground from "./ground"; const SCENE_RANGE = 750; class UI { constructor(){ } init(renderer, scene, app){ var cfg = config, gui = new dat.GUI(), folder, obj; // general addColorCtrls(gui, cfg.background, 'background', 'background', v => { renderer.setClearColor(config.background); }); addColorCtrls(gui, scene.fog.color, 'color', 'Fog color'); gui.add(scene.fog, 'density', 0.0, 0.005).name('Fog density'); // light var lightCfg = config.lights; _.each(lightCfg, (lCfg) => { folder = gui.addFolder(lCfg.name); obj = scene.getObjectByName(lCfg.name); addColorCtrls(folder, obj.color); folder.add(obj, 'intensity', 0.1, 1); folder.add(obj, 'distance', 0.1, SCENE_RANGE * 3); folder.add(obj, 'decay', 0.1, 1); addVectorCtrls(folder, obj.position); }); // tree obj = scene.getObjectByName('tree'); folder = gui.addFolder("Tree"); addSingleValueToVectorCtrls(folder, obj, 'scale', 200, 800); addColorCtrls(folder, obj.material.color); addVectorCtrls(folder, obj.position); // ground obj = scene.getObjectByName('ground'); folder = gui.addFolder("Ground"); groundGeomProperty(folder, obj, 'gridDensity', 3, 100); groundGeomProperty(folder, obj, 'width', 100, 5000); groundGeomProperty(folder, obj, 'height', 100, 5000); groundGeomProperty(folder, obj, 'heightVariance', 0, 80); addColorCtrls(folder, obj.material.color); addVectorCtrls(folder, obj.position); // flowers obj = cfg.flowers; var particleSystem = app.getParticleSystem(); folder = gui.addFolder("Flowers"); folder.add(obj, 'count', 10, 10000).onChange( (value) => { particleSystem.refreshCount(); }); folder.add(obj, 'emitRate', 0, 400); folder.add(obj, 'range', 10, 1000); addRangeCtrl(folder, obj, 'life', 10, 1000); addRangeCtrl(folder, obj, 'scale', 1, 100); folder.add(obj, 'velocity', 0.1, 10); folder.add(obj, 'rotVelocity', 0, 2); addColorCtrls(folder, obj.material.color); addVectorCtrls(folder, obj.position); // folder.open(); obj = cfg.flowers.wind; folder = gui.addFolder("Wind"); folder.add(obj, 'speed' , 0, 10); addVectorCtrls(folder, obj.force, 30); // orbit var ctrl = app.getControls(), orbitSpeed = { Slow: 0.5, Normal: 1, Fast: 5 }; // gui.add(ctrl, 'speed').name('Orbit speed').onChange( v => { // console.log(v); // }); gui.add(ctrl, 'enabled').name('Orbit enabled').onChange( v => { ctrl.enabled = v; }); } } /** * We have to recreate geometry, since change of buffer sizes is forbidden */ function groundGeomProperty(folder, obj, prop, min, max){ var groundGeom = obj.geometry, oldCfg = groundGeom.cfg, a = {}; a[prop] = oldCfg[prop]; folder.add(a, prop, min, max).step(1).onChange((value) => { a[prop] = value; groundGeom.dispose(); var g = new Ground(oldCfg); g.init(a) obj.geometry = g; }); }; function addVectorCtrls(gui, pos, range){ range = range || SCENE_RANGE; gui.add(pos, 'x', -range, range); gui.add(pos, 'y', -range, range); gui.add(pos, 'z', -range, range); } function addRangeCtrl(gui, obj, prop, min, max){ var a = {}; a[prop] = (obj[prop][0] + obj[prop][1]) / 2; gui.add(a, prop, min, max).onChange( v =>{ var variance = Math.sqrt(v); obj[prop][0] = Math.max(0, v - variance); obj[prop][1] = v + variance; }); } /** * dat.gui and three does not interoperate nicely on colors */ function addColorCtrls(gui, colorObj, prop, name, cb){ prop = prop || 'color'; name = name || prop; var a = {}; a[prop] = `#${colorObj.getHexString()}`; gui.addColor(a, prop).name(name).onChange((value) => { colorObj.setStyle(value); if(cb) cb(value); }); } function addSingleValueToVectorCtrls(gui, obj, prop, min, max){ var a = {}; a[prop] = obj[prop].x; gui.add(a, prop, min, max).onChange((value) => { obj[prop].set(value, value, value); }); } export default UI;
import {expect} from 'src/external/chai.js'; import {testWorld, loadComponent} from './templates-fixture.js'; describe("Object Editor Component", function() { var that; before("load", function(done){ this.timeout(35000); var templateName = "lively-object-editor"; loadComponent(templateName).then(c => {that = c; done()}).catch(e => done(e)); }); it("should load", function(done) { done(); }); after("cleanup", function() { testWorld().innerHTML = ""; }); });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M20 6h-8l-1.41-1.41C10.21 4.21 9.7 4 9.17 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z" }), 'FolderSharedRounded');
/*global expect*/ describe('Date type', function() { it('inspects without milliseconds when the milliseconds field is zero', function() { expect( new Date(0), 'to inspect as', "new Date('Thu, 01 Jan 1970 00:00:00 GMT')" ); }); it('inspects with three milliseconds digits when the milliseconds field has one digit', function() { expect( new Date(1), 'to inspect as', "new Date('Thu, 01 Jan 1970 00:00:00.001 GMT')" ); }); it('inspects with three milliseconds digits when the milliseconds field has two digits', function() { expect( new Date(10), 'to inspect as', "new Date('Thu, 01 Jan 1970 00:00:00.010 GMT')" ); }); it('inspects with three milliseconds digits when the milliseconds field has three digits', function() { expect( new Date(100), 'to inspect as', "new Date('Thu, 01 Jan 1970 00:00:00.100 GMT')" ); }); });
'use strict'; /** * Click on 'Delete' tab on delete deployment dialog */ exports.clickConfirm = function() { $$('#deleteDialog .confirmationButtons button').get(1).click(); }; /** * Click on 'Cancel' button on delete deployment dialog */ exports.clickCancel = function() { $$('#deleteDialog .confirmationButtons button').first().click(); browser.sleep(1000); }; exports.clickClose = function() { element.all(by.css('.ngdialog-close')).click(); browser.sleep(1000); };
var Animator = { start: function () { var self = this; var animTriggers = $("[data-animate-trigger]"); $(window).scroll(function () { animTriggers.each(function () { if (self.isInView(this) === true) { var $this = $(this).find("[data-animate]"); $this.addClass("animated " + $this.data("animate")); } }); }); }, isInView: function (elem) { var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var padding = 100; var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemTop + padding <= docViewBottom) && (elemTop >= docViewTop)); } } Animator.start();
/* @flow */ const { createAction } = require('redux-actions') export const PATH_UPDATE = 'PATH_UPDATE' import type { Action, Reducer } from 'redux' const reducer : Reducer<{}, Action> = (state = {}, { type, payload }) => { switch (type) { case PATH_UPDATE: return payload default: return state } } export const pathDidUpdate = createAction(PATH_UPDATE) export default reducer
// Import Vue import Vue from 'vue' // Import F7 import Framework7 from 'framework7' // Import F7 Vue Plugin import Framework7Vue from 'framework7-vue' // Import F7 iOS Theme Styles import Framework7Theme from 'framework7/dist/css/framework7.ios.min.css' import Framework7ThemeColors from 'framework7/dist/css/framework7.ios.colors.min.css' /* OR for Material Theme: import Framework7Theme from 'framework7/dist/css/framework7.material.min.css' import Framework7ThemeColors from 'framework7/dist/css/framework7.material.colors.min.css' */ // Import App Custom Styles import AppStyles from './css/app.css' // Import Routes import Routes from './routes.js' // Import App Component import App from './app' // Init F7 Vue Plugin Vue.use(Framework7Vue) var VueFire = require('vuefire') // explicit installation required in module environments Vue.use(VueFire) // Init App new Vue({ el: '#app', template: '<app/>', // Init Framework7 by passing parameters here framework7: { root: '#app', /* Uncomment to enable Material theme: */ // material: true, routes: Routes, }, // Register App Component components: { app: App } });
var UtmCookie; UtmCookie = class UtmCookie { constructor(options = {}) { this._cookieNamePrefix = '_uc_'; this._domain = options.domain; this._sessionLength = options.sessionLength || 1; this._cookieExpiryDays = options.cookieExpiryDays || 365; this._additionalParams = options.additionalParams || []; this._utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content']; this.writeInitialReferrer(); this.writeLastReferrer(); this.writeInitialLandingPageUrl(); this.setCurrentSession(); if (this.additionalParamsPresentInUrl()) { this.writeAdditionalParams(); } if (this.utmPresentInUrl()) { this.writeUtmCookieFromParams(); } return; } createCookie(name, value, days, path, domain, secure) { var cookieDomain, cookieExpire, cookiePath, cookieSecure, date, expireDate; expireDate = null; if (days) { date = new Date; date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000); expireDate = date; } cookieExpire = expireDate != null ? '; expires=' + expireDate.toGMTString() : ''; cookiePath = path != null ? '; path=' + path : '; path=/'; cookieDomain = domain != null ? '; domain=' + domain : ''; cookieSecure = secure != null ? '; secure' : ''; document.cookie = this._cookieNamePrefix + name + '=' + escape(value) + cookieExpire + cookiePath + cookieDomain + cookieSecure; } readCookie(name) { var c, ca, i, nameEQ; nameEQ = this._cookieNamePrefix + name + '='; ca = document.cookie.split(';'); i = 0; while (i < ca.length) { c = ca[i]; while (c.charAt(0) === ' ') { c = c.substring(1, c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } i++; } return null; } eraseCookie(name) { this.createCookie(name, '', -1, null, this._domain); } getParameterByName(name) { var regex, regexS, results; name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]'); regexS = '[\\?&]' + name + '=([^&#]*)'; regex = new RegExp(regexS); results = regex.exec(window.location.search); if (results) { return decodeURIComponent(results[1].replace(/\+/g, ' ')); } else { return ''; } } additionalParamsPresentInUrl() { var j, len, param, ref; ref = this._additionalParams; for (j = 0, len = ref.length; j < len; j++) { param = ref[j]; if (this.getParameterByName(param)) { return true; } } return false; } utmPresentInUrl() { var j, len, param, ref; ref = this._utmParams; for (j = 0, len = ref.length; j < len; j++) { param = ref[j]; if (this.getParameterByName(param)) { return true; } } return false; } writeCookie(name, value) { this.createCookie(name, value, this._cookieExpiryDays, null, this._domain); } writeAdditionalParams() { var j, len, param, ref, value; ref = this._additionalParams; for (j = 0, len = ref.length; j < len; j++) { param = ref[j]; value = this.getParameterByName(param); this.writeCookie(param, value); } } writeUtmCookieFromParams() { var j, len, param, ref, value; ref = this._utmParams; for (j = 0, len = ref.length; j < len; j++) { param = ref[j]; value = this.getParameterByName(param); this.writeCookie(param, value); } } writeCookieOnce(name, value) { var existingValue; existingValue = this.readCookie(name); if (!existingValue) { this.writeCookie(name, value); } } _sameDomainReferrer(referrer) { var hostname; hostname = document.location.hostname; return referrer.indexOf(this._domain) > -1 || referrer.indexOf(hostname) > -1; } _isInvalidReferrer(referrer) { return referrer === '' || referrer === void 0; } writeInitialReferrer() { var value; value = document.referrer; if (this._isInvalidReferrer(value)) { value = 'direct'; } this.writeCookieOnce('referrer', value); } writeLastReferrer() { var value; value = document.referrer; if (!this._sameDomainReferrer(value)) { if (this._isInvalidReferrer(value)) { value = 'direct'; } this.writeCookie('last_referrer', value); } } writeInitialLandingPageUrl() { var value; value = this.cleanUrl(); if (value) { this.writeCookieOnce('initial_landing_page', value); } } initialReferrer() { return this.readCookie('referrer'); } lastReferrer() { return this.readCookie('last_referrer'); } initialLandingPageUrl() { return this.readCookie('initial_landing_page'); } incrementVisitCount() { var cookieName, existingValue, newValue; cookieName = 'visits'; existingValue = parseInt(this.readCookie(cookieName), 10); newValue = 1; if (isNaN(existingValue)) { newValue = 1; } else { newValue = existingValue + 1; } this.writeCookie(cookieName, newValue); } visits() { return this.readCookie('visits'); } setCurrentSession() { var cookieName, existingValue; cookieName = 'current_session'; existingValue = this.readCookie(cookieName); if (!existingValue) { this.createCookie(cookieName, 'true', this._sessionLength / 24, null, this._domain); this.incrementVisitCount(); } } cleanUrl() { var cleanSearch; cleanSearch = window.location.search.replace(/utm_[^&]+&?/g, '').replace(/&$/, '').replace(/^\?$/, ''); return window.location.origin + window.location.pathname + cleanSearch + window.location.hash; } }; var UtmForm, _uf; UtmForm = class UtmForm { constructor(options = {}) { this._utmParamsMap = {}; this._utmParamsMap.utm_source = options.utm_source_field || 'USOURCE'; this._utmParamsMap.utm_medium = options.utm_medium_field || 'UMEDIUM'; this._utmParamsMap.utm_campaign = options.utm_campaign_field || 'UCAMPAIGN'; this._utmParamsMap.utm_content = options.utm_content_field || 'UCONTENT'; this._utmParamsMap.utm_term = options.utm_term_field || 'UTERM'; this._additionalParamsMap = options.additional_params_map || {}; this._initialReferrerField = options.initial_referrer_field || 'IREFERRER'; this._lastReferrerField = options.last_referrer_field || 'LREFERRER'; this._initialLandingPageField = options.initial_landing_page_field || 'ILANDPAGE'; this._visitsField = options.visits_field || 'VISITS'; // Options: // "none": Don't add any fields to any form // "first": Add UTM and other fields to only first form on the page // "all": (Default) Add UTM and other fields to all forms on the page this._addToForm = options.add_to_form || 'all'; this._formQuerySelector = options.form_query_selector || 'form'; this._decodeURIs = options.decode_uris || false; this.utmCookie = new UtmCookie({ domain: options.domain, sessionLength: options.sessionLength, cookieExpiryDays: options.cookieExpiryDays, additionalParams: Object.getOwnPropertyNames(this._additionalParamsMap) }); this.addAllFields(); } addAllFields() { var allForms, i, len; allForms = document.querySelectorAll(this._formQuerySelector); if (this._addToForm === 'none') { len = 0; } else if (this._addToForm === 'first') { len = Math.min(1, allForms.length); } else { len = allForms.length; } i = 0; while (i < len) { this.addAllFieldsToForm(allForms[i]); i++; } } addAllFieldsToForm(form) { var fieldName, param, ref, ref1; if (form && !form._utm_tagged) { form._utm_tagged = true; ref = this._utmParamsMap; for (param in ref) { fieldName = ref[param]; this.addFormElem(form, fieldName, this.utmCookie.readCookie(param)); } ref1 = this._additionalParamsMap; for (param in ref1) { fieldName = ref1[param]; this.addFormElem(form, fieldName, this.utmCookie.readCookie(param)); } this.addFormElem(form, this._initialReferrerField, this.utmCookie.initialReferrer()); this.addFormElem(form, this._lastReferrerField, this.utmCookie.lastReferrer()); this.addFormElem(form, this._initialLandingPageField, this.utmCookie.initialLandingPageUrl()); this.addFormElem(form, this._visitsField, this.utmCookie.visits()); } } addFormElem(form, fieldName, fieldValue) { this.insertAfter(this.getFieldEl(fieldName, fieldValue), form.lastChild); } // NOTE: This should be called for each form element or since it // attaches itself to the first form getFieldEl(fieldName, fieldValue) { var fieldEl; fieldEl = document.createElement('input'); fieldEl.type = "hidden"; fieldEl.name = fieldName; fieldEl.value = this._decodeURIs ? decodeURIComponent(fieldValue) : fieldValue; return fieldEl; } insertAfter(newNode, referenceNode) { return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } }; _uf = window._uf || {}; window.UtmForm = new UtmForm(_uf);
class UTF8Helper { constructor() { } encode(s) { return unescape( encodeURIComponent(s) ); } decode(s) { return decodeURIComponent( escape(s) ); } } export default UTF8Helper;
'use strict'; angular.module('events').controller('EventController', ['$scope','$http','$stateParams','$state','Authentication','Events', function($scope,$http, $stateParams,$state,Authentication,Events){ //used to create a sponsorship called from the createsponsorship.client.view.html $scope.createEvent = function(isValid) { $scope.error = null; if(!isValid){ console.log('Do I go here?'); $scope.broadcast('show-errors-check-validity','articleForm'); return false; } // var beginDate = new Date();//Switch this to date that you get from form. // $scope.events.datePosted = beginDate;//Adds beginDate as datePosted var id = Authentication.user._id; //post to the sponsorship API $http.post('/api/events', $scope.events) //Announcements.createAnnouncement($scope.announcement)//TODO:Make this line work currently undef .then(function(response) { $state.go('events.list', { successMessage: 'Event successfully created!' }); console.log('STATE GO GO GO!'); }, function(error) { //otherwise display the error $scope.error = 'Unable to POST Event!\n' + error; }); }; //Overload this function to sort $scope.findAllEvents = function(){ console.log('Really really'); //$http.get('/api/announcements', $scope.announcement) Events.getAllEvents($scope.events) .then(function(response) { $scope.events = response.data; //$scope.reverseOrder($scope.announcements); //if the object is successfully saved redirect back to the list page //$state.go('sponsorship.list', { successMessage: 'Sponsorship succesfully created!' }); }, function(error) { //otherwise display the error $scope.error = 'Unable to save findAllEvents!\n' + error; }); }; $scope.reverseOrder = function(rawevents){ var temp = []; var length = rawevents.length; for(var i = 0;i<length;i++){ temp[i] = rawevents[length - i - 1]; } $scope.events=temp; }; $scope.updateEvent = function(isValid){ $scope.error=null; if (!isValid) { $scope.$broadcast('show-errors-check-validity', 'eventForm'); return false; } Events.updateEvent($stateParams.eventID, $scope.events) .then(function(response) { $state.go('events.list', { successMessage: 'Event succesfully updated!' }); }, function(error) { $scope.error = 'Unable to update event!\n' + error; }); }; $scope.findOneEvent = function(){ var id = $stateParams.eventID; console.log(id); Events.getOneEvent(id) .then(function(response) { $scope.events = response.data; console.log('Find one shows'); console.log($scope.events); console.log($stateParams); }, function(error) { $scope.error = 'Unable to get event with id "' + id + '"\n' + error; }); }; $scope.deleteEvent = function() { $scope.error = null; console.log('Do I go here?'); var id = $stateParams.eventID; console.log(id); Events.deleteEvent(id).then(function(response) { $state.go('events.list', { successMessage: 'Event successfully removed!' }); }, function(error) { $scope.error = 'Unable to delete the event!\n' + error; }); }; $scope.isAdmin = function() { $scope.roles=Authentication.user.roles; if(Authentication.user) { var indexOfRole = $scope.roles.indexOf('admin'); if (indexOfRole !== -1) { return true; } else{ return false; } } else{ return false; } }; } ]);
"use strict"; jest.mock("@lerna/child-process"); // mocked modules const childProcess = require("@lerna/child-process"); // file under test const hasTags = require("../lib/has-tags"); describe("hasTags()", () => { childProcess.execSync.mockImplementation(() => "v1.0.0\nv1.0.1"); it("calls `git tag` with options passed in", () => { hasTags({ cwd: "test" }); expect(childProcess.execSync).toHaveBeenLastCalledWith("git", ["tag"], { cwd: "test" }); }); it("returns true when tags exist", () => { expect(hasTags()).toBe(true); }); it("returns false when tags do not exist", () => { childProcess.execSync.mockImplementation(() => ""); expect(hasTags()).toBe(false); }); it("returns false when git command errors", () => { childProcess.execSync.mockImplementation(() => { throw new Error("boom"); }); expect(hasTags()).toBe(false); }); });
// Copyright (c) 2013 David Hayes /* global describe, it */ 'use strict'; var assert = require('assert'); var loki = require('../index'); describe('loki-core', function() { it('should expose an object', function() { assert(typeof loki === 'object'); }); it('should expose Game ctor', function() { assert(typeof loki.Game === 'function'); }); it('should expose Entity ctor', function() { assert(typeof loki.Entity === 'function'); }); });
var playState = { create: function(){ var background = game.add.sprite(0, 0, 'cidade'); background.width = 1300; background.height = 650; graphics = game.add.graphics(0, 0); groupCidade = game.add.group(); groupCidade.inputEnableChildren = true; var x = 100; for (var i = 0; i < 3; i++){ // Gera os retangulos que ficarรฃo atras das imagens graphics.beginFill(0xFFFFFF); graphics.lineStyle(3, 0x05005e, 1); graphics.drawRoundedRect(x, 200, 315, 190, 10); graphics.endFill(); var button = groupCidade.create(x, 200, graphics.generateTexture()); button.tint = 0xff8800; button.name = 'groupCidade-child-' + i; x = x + 400; } graphics.destroy(); var cachorro = game.add.sprite(110, 210, 'cachorro'); cachorro.width = 300; cachorro.height = 170; // Desenha o gato e a borda da box var gato = game.add.sprite(510, 210, 'gato'); gato.width = 300; gato.height = 170; // Desenha o passaro e a borda da box var passaro = game.add.sprite(910, 210, 'passaro'); passaro.width = 300; passaro.height = 170; game.time.events.add(Phaser.Timer.SECOND * 2, start, this); function start(){ ocultarOpcoes(1); groupCidade.children[0].x += 230; cachorro.x += 230; groupCidade.children[0].y -= 70; cachorro.y -= 70; game.add.tween(groupCidade.children[0].scale).to( { x: 2, y: 2 }, 3000, Phaser.Easing.Elastic.Out, true); game.add.tween(cachorro.scale).to( { x: 1, y: 1 }, 3000, Phaser.Easing.Elastic.Out, true); game.time.events.add(Phaser.Timer.SECOND * 5, initial, this); } function initial(){ game.add.tween(groupCidade.children[0].scale).to( { x: 1, y: 1 }, 1000, Phaser.Easing.Linear.In, true); game.add.tween(cachorro.scale).to( { x: 0.5, y: 0.5 }, 1000, Phaser.Easing.Linear.In, true); groupCidade.children[0].x -= 230; cachorro.x -= 230; groupCidade.children[0].y += 70; cachorro.y += 70; background.alpha = 0.5; apresentar activateButtons(); } function ocultarOpcoes(numero){ game.add.tween(background).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); if(numero == 1){ groupCidade.children[1].alpha = 0; groupCidade.children[2].alpha = 0; gato.alpha = 0; passaro.alpha = 0; } } function apresentarOpcoes(){ game.add.tween(background).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); if(numero == 1){ game.add.tween(groupCidade.children[1]).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); game.add.tween(groupCidade.children[2]).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); game.add.tween(gato).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); game.add.tween(passaro).to( { alpha: 1 }, 1000, Phaser.Easing.Linear.In, true); } } function activateButtons(){ groupCidade.onChildInputDown.add(onDown, this); groupCidade.onChildInputOver.add(onOver, this); groupCidade.onChildInputOut.add(onOut, this); } function onDown (sprite) { sprite.tint = 0x00ff00; } function onOver (sprite) { sprite.tint = 0xffff00; } function onOut (sprite) { sprite.tint = 0xff8800; // sprite.tint = Math.random() * 0xffffff; } }, update: function(){ }, Win: function(){ game.state.start('win'); } };
/* * Simple event implementation */ var Class = require('./class'); var Event = Class.extend({ init: function () { this._maxListeners = this._maxListeners || -1; } }); Event.prototype.on = function on(arg0, arg1) { this._listeners = this._listeners || {}; switch(typeof arg0){ case 'string': if(Object.prototype.toString.call(this._listeners[arg0]) !== '[object Array]'){ this._listeners[arg0] = []; }; if(typeof arg1 === 'function'){ this._listeners[arg0].push(arg1); }; break; case 'object': for(var attr in arg0){ var func = arg0[attr]; if(Object.prototype.toString.call(this._listeners[attr]) !== '[object Array]'){ this._listeners[attr] = []; }; if(typeof func === 'function' && (this._maxListeners < 0 || this._listeners[attr].length < this._maxListeners)){ this._listeners[attr].push(func); }; } break; } return this; }; Event.prototype.addListener = Event.prototype.on; Event.prototype.off = function off(evName) { delete this._listeners[evName]; }; Event.prototype.trigger = function trigger(name) { if(this._listeners && Array.isArray(this._listeners[name])){ var _listeners = this._listeners[name]; var params = Array.prototype.slice.call(arguments); params.splice(0,1); for(var i = 0, listener; listener = _listeners[i]; i++){ listener.apply(this, params); }; } }; Event.prototype.emit = Event.prototype.trigger; Event.prototype.setMaxListeners = function(n) { if (typeof n !== 'number' || n < 0) throw TypeError('n must be a positive number'); this._maxListeners = n; }; module.exports = Event;