text
stringlengths 2
1.05M
|
|---|
'use strict';
const core = require('../../core');
exports = module.exports = (req, res, next) => core.pihole.enabled()
.then(enabled => res.json({enabled}))
.catch(next);
|
"use strict";
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([
{
conditions: [
new chrome.declarativeContent.PageStateMatcher({
pageUrl: { urlMatches: "contractbook.com" },
}),
],
actions: [new chrome.declarativeContent.ShowPageAction()],
},
]);
});
});
|
/**
* Windows values emitted by the target signal `t` and emits a new signal
* whenever the control signal `s` emits a value.
*
* @private
*/
export default function window (s, t) {
return emit => {
let windowEmit
let innerSubscription
const closeWindow = () => {
if (innerSubscription) {
windowEmit.complete()
innerSubscription.unsubscribe()
innerSubscription = null
}
}
const newWindow = () => {
closeWindow()
const w = emit => {
windowEmit = emit
innerSubscription = t.subscribe(emit)
}
emit.next(w)
}
const subscriptions = [
s.subscribe(newWindow),
t.subscribe({
complete () {
closeWindow()
emit.complete()
}
})
]
// Start a new window immediately
newWindow()
return () => {
closeWindow()
subscriptions.forEach(s => s.unsubscribe())
}
}
}
|
/* yarn example/ */
import test from '../src'
(async () => {
await test()
})()
|
const _ = require('lodash')
const fs = require('fs')
const path = require('path')
const {ChartJSNodeCanvas} = require('chartjs-node-canvas')
const exec = require('child_process').execFileSync
const LIB_FOLDER = path.join(__dirname, '../lib')
const UPDATES_FOLDER = path.join(LIB_FOLDER, 'markdown/updates')
const PARTIALS_FOLDER = path.join(LIB_FOLDER, 'markdown/')
const MD_TEMPLATE = fs.readFileSync(path.join(LIB_FOLDER, 'markdown/template.md'), 'utf8')
const createMarkdownString = _.template(MD_TEMPLATE)
const ALL_DATA = require('../.tmp/combined-data.json')
const ALL_CATEGORIES = require('../data/categories.json')
const DATA_BY_CATEGORY = _.groupBy(ALL_DATA, entity => entity.categories[0])
_.forEach(ALL_CATEGORIES, (value, id) =>
_.assign(value, {id, totalExecutionTime: _.sumBy(DATA_BY_CATEGORY[id], 'totalExecutionTime')})
)
function createUpdatesContent() {
let updates = []
for (const file of fs.readdirSync(UPDATES_FOLDER)) {
const dateRegex = /^(\d{4}-\d{2}-\d{2})/
if (!dateRegex.test(file)) continue
const datePart = file.match(dateRegex)[1]
updates.push(
`## ${datePart} dataset\n\n` + fs.readFileSync(path.join(UPDATES_FOLDER, file), 'utf8')
)
}
return updates.join('\n\n')
}
function createPartialsContent() {
const partials = {}
for (const file of fs.readdirSync(PARTIALS_FOLDER)) {
const partialsRegex = /^(.*)\.partial\.md$/
if (!file.includes('.partial.')) continue
if (!partialsRegex.test(file)) continue
const partialName = file.match(partialsRegex)[1]
partials[partialName] = fs
.readFileSync(path.join(PARTIALS_FOLDER, file), 'utf8')
.replace(/---(.|\s)*?---/m, '')
}
return partials
}
function createMarkdownTable(headers, rows) {
return [
`| ${headers.join(' | ')} |`,
`| ${headers.map(() => '--').join(' | ')} |`,
...rows.map(cells => `| ${cells.join(' | ')} |`),
].join('\n')
}
async function createChartImages() {
const categories = _(ALL_CATEGORIES)
.values()
.sortBy('totalExecutionTime')
.reverse()
.value()
const chartByCategory = new ChartJSNodeCanvas({width: 600, height: 300})
const buffer = await chartByCategory.renderToBuffer({
options: {
legend: {
position: 'left',
labels: {
fontStyle: 'bold'
}
},
},
type: 'doughnut',
data: {
labels: _.map(categories, 'title'),
datasets: [
{
label: 'Breakdown By Category',
backgroundColor: _.map(categories, 'color'),
borderWidth: 1.5,
data: _.map(categories, 'totalExecutionTime'),
},
],
},
}, 'image/png')
fs.writeFileSync(path.join(__dirname, '../by-category.png'), buffer)
}
function createCategorySection(category) {
const categoryRows = _.sortBy(DATA_BY_CATEGORY[category.id], 'averageExecutionTime')
.filter(entry => entry.totalOccurrences >= 1000)
.map((entry, rank) => [
rank + 1,
entry.homepage ? `[${entry.name}](${entry.homepage})` : entry.name,
entry.totalOccurrences.toLocaleString(),
Math.round(entry.averageExecutionTime) + ' ms',
])
const table = createMarkdownTable(['Rank', 'Name', 'Usage', 'Average Impact'], categoryRows)
return [
`<a name="${category.id}"></a>`,
`#### ${category.title}\n`,
`${category.description}\n`,
table,
].join('\n')
}
async function run() {
const categoryTOC = _.map(
ALL_CATEGORIES,
category => `1. [${category.title}](#${category.id})`
).join('\n ')
const categoryContents = _.map(ALL_CATEGORIES, createCategorySection).join('\n\n')
const topDataRows = _.sortBy(ALL_DATA, 'totalExecutionTime')
.reverse()
.slice(0, 200)
.map(entry => [
entry.homepage ? `[${entry.name}](${entry.homepage})` : entry.name,
entry.totalOccurrences.toLocaleString(),
Math.round(entry.totalExecutionTime / 1000).toLocaleString() + ' s',
Math.round(entry.averageExecutionTime) + ' ms',
])
await createChartImages()
const readmePath = path.join(__dirname, '../README.md')
fs.writeFileSync(
readmePath,
createMarkdownString({
partials: createPartialsContent(),
updates_contents: createUpdatesContent(),
category_table_of_contents: categoryTOC,
category_contents: categoryContents,
all_data: createMarkdownTable(
['Name', 'Popularity', 'Total Impact', 'Average Impact'],
topDataRows
),
})
)
exec(path.join(__dirname, '../node_modules/.bin/prettier'), ['--write', readmePath])
}
run().catch(console.error)
|
import * as api from "../api/index";
export const signin = (formData, history) => async (dispatch) => {
try {
const { data } = await api.signIn(formData);
//login user
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log(error);
}
};
export const signup = (formData, history) => async (dispatch) => {
try {
//signup user
const { data } = await api.signUp(formData);
dispatch({ type: "AUTH", data });
history.push("/");
} catch (error) {
console.log(error);
}
};
|
module.exports = {
singleQuote: true,
printWidth: 360,
bracketSpacing: true,
arrowParens: "always",
useTabs: false,
trailingComma: "none",
tabWidth: 2
};
|
/** 放置配置参数( 新API无需密钥 )
* 0. 注意生成环境切忌不要放置敏感数据
* a) 一般敏感数据直接aysnc请求
*/
// export const cors = 'https://cors-anywhere.herokuapp.com/';
export const cors = '';
export const apiPassword = '01389754454ea41309d99d78e4a448c8';
|
import Joi from 'joi';
import Model from '../model';
/**
* Model for datasource objects.
*/
export default class DatasourceModel extends Model {
constructor(server) {
const schema = Joi.object().keys({
title: Joi.string(),
description: Joi.string(),
datasourceType: Joi.string(),
datasourceParams: Joi.object(),
version: Joi.number().integer(),
kibanaSavedObjectMeta: Joi.object().keys({
searchSourceJSON: Joi.string()
})
});
super(server, 'datasource', schema, 'External datasource');
}
_prepare(body) {
super._prepare(body);
// kibi: if we don't have this plugin let's not throw exception here and silently fail
if (this._server.plugins.query_engine) {
const cryptoHelper = this._server.plugins.query_engine.getCryptoHelper();
cryptoHelper.encryptDatasourceParams(this._config, body);
}
}
}
|
// dev config variables name
const dev = {
hostName: 'https://zhweyzgnzg.execute-api.us-east-2.amazonaws.com/prod',
// hostName: 'http://localhost:5001',
};
// production variables name
const prod = {
hostName: 'https://zhweyzgnzg.execute-api.us-east-2.amazonaws.com/prod',
// hostName: 'http://localhost:5001',
};
const config = process.env.REACT_APP_STAGE === 'production' ? prod : dev;
// export the default configuration
export default {
...config,
};
|
var pmx = require('pmx');
const os = require('os')
const { exec } = require("child_process")
module.exports = function memStat(metrics, conf) {
const cmd = "ps up $(pidof java) | tail -n1 | tr -s ' ' | cut -f4 -d' '";
exec(cmd, (err, res) => {
if (!err) {
metrics.memStat.set(res * 1);
}
})
};
|
import ReactNative from 'react-native';
const viewEvents = [
'accessibilityEscape',
'accessibilityTap',
'layout',
'magicTap',
'moveShouldSetResponder',
'moveShouldSetResponderCapture',
'responderGrant',
'responderMove',
'responderReject',
'responderRelease',
'responderTerminate',
'responderTerminationRequest',
'startShouldSetResponder',
'startShouldSetResponderCapture',
];
const eventMap = {
ActivityIndicator: [...viewEvents],
Button: ['layout', 'press'],
DrawerLayoutAndroid: [
...viewEvents,
'drawerClose',
'drawerOpen',
'drawerSlide',
'drawerStateChanged',
],
Image: ['error', 'layout', 'load', 'loadEnd', 'loadStart', 'partialLoad', 'progress'],
Modal: ['dismiss', 'orientationChange', 'requestClose', 'show'],
Picker: [...viewEvents, 'valueChange'],
RefreshControl: [...viewEvents, 'refresh'],
SafeAreaView: [...viewEvents],
ScrollView: [
...viewEvents,
'contentSizeChange',
'momentumScrollBegin',
'momentumScrollEnd',
'scroll',
'scrollBeginDrag',
'scrollEndDrag',
],
Switch: [...viewEvents, 'valueChange'],
Text: ['layout', 'longPress', 'press'],
TextInput: [
...viewEvents,
'blur',
'change',
'changeText',
'contentSizeChange',
'endEditing',
'focus',
'keyPress',
'scroll',
'selectionChange',
'submitEditing',
],
TouchableHighlight: [
'blur',
'focus',
'hideUnderlay',
'layout',
'longPress',
'press',
'pressIn',
'pressOut',
'showUnderlay',
],
TouchableNativeFeedback: ['blur', 'focus', 'layout', 'longPress', 'press', 'pressIn', 'pressOut'],
TouchableOpacity: ['blur', 'focus', 'layout', 'longPress', 'press', 'pressIn', 'pressOut'],
TouchableWithoutFeedback: [
'blur',
'focus',
'layout',
'longPress',
'press',
'pressIn',
'pressOut',
],
View: viewEvents,
};
class NativeTestEvent {
constructor(typeArg, ...args) {
this.args = args;
this.typeArg = typeArg;
this.validTargets = Object.keys(eventMap)
.filter(c => eventMap[c].includes(typeArg))
.map(ComponentName => ReactNative[ComponentName]);
}
set target(target) {
this._target = target;
}
get target() {
return this._target;
}
}
function getEventHandlerName(key) {
return `on${key.charAt(0).toUpperCase()}${key.slice(1)}`;
}
function validateElementType(list, element) {
return list.includes(element.type) || list.includes(element.type.displayName);
}
function isValidTarget(element, event) {
return event.validTargets.length ? validateElementType(event.validTargets, element) : true;
}
function isDisabled(element) {
const { accessibilityStates = [], disabled } = element.props;
return disabled || accessibilityStates.includes('disabled');
}
function findEventTarget(element, event) {
const { typeArg } = event;
const handlerName = getEventHandlerName(typeArg);
const eventHandler = element.props[handlerName];
if (eventHandler && !isDisabled(element) && isValidTarget(element, event)) {
return eventHandler;
}
return element.parent ? findEventTarget(element.parent, event) : null;
}
function fireEvent(element, event) {
event.target = findEventTarget(element, event);
if (event.target) event.target(...event.args);
return event.target;
}
const eventList = Object.keys(eventMap).reduce((list, name) => {
return [...list, ...eventMap[name].filter(event => !list.includes(event))];
}, []);
eventList.forEach(typeArg => {
fireEvent[typeArg] = (node, ...args) => {
return fireEvent(node, new NativeTestEvent(typeArg, ...args));
};
});
export { eventMap, fireEvent, getEventHandlerName, NativeTestEvent };
|
let socket;
export const ConversationsController = {
init: (soc) => {
socket = soc;
},
getConversations: async (token, updateConversation) => {
// make request for the conversations of user and wait for the json response
const res = await fetch("/api/conversations", {
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
});
const result = await res.json();
socket.on("newConversation", (convoObject) => {
updateConversation([convoObject.conversation]);
// send back the conversation to the server to join client to that socket rooms
socket.emit("joinConversations", [convoObject.conversation.id]);
});
// send back the conversations to the server to join client to the appropriate socket rooms
socket.emit(
"joinConversations",
result.conversationList.map((item) => item.id)
);
return res.status !== 200 ? [] : result && result.conversationList ? result.conversationList : [];
},
evaluateDate: (lastDate) => {
// decide whether to return the date as (d/mm/yy) or as time(\d{2}:\d{2} (A|P)M)
// if lastDate within the last 23 hrs display time else use date format
if (lastDate) {
lastDate = new Date(lastDate);
let diff = Date.now() - lastDate.getTime();
const getDate = () => `${lastDate.getDate()} / ${lastDate.getMonth() + 1}
/ ${lastDate.getFullYear().substring(2)}`;
const getTime = () => {
let hr = lastDate.getHours() % 12 || 12; // convert 24hr to 12hr
// pad minutes with 0 to maintain 2 digits in mins section
let min = (lastDate.getMinutes() < 10 ? "0" : "") + lastDate.getMinutes();
let period = lastDate.getHours() < 11 ? "AM" : "PM"; // convert 24hr to am/pm
return hr + ":" + min + " " + period;
};
return diff > 23 * 60 * 60 * 1000 ? getDate() : getTime();
} else return "";
},
createConversation: async (token, participants, title) => {
// make request to create a conversation with participants and title
const res = await fetch("/api/conversations", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
participants,
title,
}),
});
return res.status !== 201;
},
leaveConversation: async (token, conversationId, successorId) => {
// make request to leave conversation
const res = await fetch("/api/conversations", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify({
conversationId,
successorId,
}),
});
const result = await res.json();
return { // return msg to display to user (whether success or fail)
msg: result.msg,
success: result.status === 200
};
}
};
|
// @flow
import * as React from 'react';
import { Accordion } from '@folio/stripes/components';
import { Localize } from '../../../../shared/utils/Function';
import FixedField from './Tags/FixedField';
import BaseTag00X from './Tags/BaseTag00X';
import Leader from './Leader';
import { SEARCH_SEGMENT } from '../../../../config/constants';
export default ({ ...props }) => {
const { record, leaderData, data: { search: { segment } } } = props;
return (
<React.Fragment>
<Accordion label="Leader" id="Leader">
<Leader
{...props}
leaderData={leaderData}
leaderCode={record.leader.code}
leaderValue={record.leader.value}
/>
</Accordion>
<Accordion
id="control-field-create-static"
label={Localize({ key: 'cataloging.accordion.fixedfield.label' })}
>
<BaseTag00X
{...props}
fixedfields={record.fields.filter(f => f.code < '006')}
/>
</Accordion>
<Accordion
id="control-field-dynamic"
label={segment === SEARCH_SEGMENT.BIBLIOGRAPHIC
? Localize({ key: 'cataloging.accordion.fixedfield.editable.label' })
: Localize({ key: 'cataloging.accordion.fixedfield.editable.label.auth' })}
>
<FixedField
{...props}
record={record}
field={record.fields.filter(f => f.code > '005' && f.code < '010')}
/>
</Accordion>
</React.Fragment>
);
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2014 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* A TileSprite is a Sprite that has a repeating texture. The texture can be scrolled and scaled and will automatically wrap on the edges as it does so.
* Please note that TileSprites, as with normal Sprites, have no input handler or physics bodies by default. Both need enabling.
*
* @class Phaser.TileSprite
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {number} x - The x coordinate (in world space) to position the TileSprite at.
* @param {number} y - The y coordinate (in world space) to position the TileSprite at.
* @param {number} width - The width of the TileSprite.
* @param {number} height - The height of the TileSprite.
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the TileSprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture or PIXI.Texture.
* @param {string|number} frame - If this TileSprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.TileSprite = function (game, x, y, width, height, key, frame) {
x = x || 0;
y = y || 0;
width = width || 256;
height = height || 256;
key = key || null;
frame = frame || null;
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {string} name - The user defined name given to this Sprite.
* @default
*/
this.name = '';
/**
* @property {number} type - The const type of this object.
* @readonly
*/
this.type = Phaser.TILESPRITE;
/**
* @property {number} z - The z-depth value of this object within its Group (remember the World is a Group as well). No two objects in a Group can have the same z value.
*/
this.z = 0;
/**
* @property {Phaser.Events} events - The Events you can subscribe to that are dispatched when certain things happen on this Sprite or its components.
*/
this.events = new Phaser.Events(this);
/**
* @property {Phaser.AnimationManager} animations - This manages animations of the sprite. You can modify animations through it (see Phaser.AnimationManager)
*/
this.animations = new Phaser.AnimationManager(this);
/**
* @property {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
*/
this.key = key;
/**
* @property {number} _frame - Internal cache var.
* @private
*/
this._frame = 0;
/**
* @property {string} _frameName - Internal cache var.
* @private
*/
this._frameName = '';
/**
* @property {Phaser.Point} _scroll - Internal cache var.
* @private
*/
this._scroll = new Phaser.Point();
PIXI.TilingSprite.call(this, PIXI.TextureCache['__default'], width, height);
this.loadTexture(key, frame);
this.position.set(x, y);
/**
* @property {Phaser.InputHandler|null} input - The Input Handler for this object. Needs to be enabled with image.inputEnabled = true before you can use it.
*/
this.input = null;
/**
* @property {Phaser.Point} world - The world coordinates of this Sprite. This differs from the x/y coordinates which are relative to the Sprites container.
*/
this.world = new Phaser.Point(x, y);
/**
* Should this Sprite be automatically culled if out of range of the camera?
* A culled sprite has its renderable property set to 'false'.
* Be advised this is quite an expensive operation, as it has to calculate the bounds of the object every frame, so only enable it if you really need it.
*
* @property {boolean} autoCull - A flag indicating if the Sprite should be automatically camera culled or not.
* @default
*/
this.autoCull = false;
/**
* If true the Sprite checks if it is still within the world each frame, when it leaves the world it dispatches Sprite.events.onOutOfBounds
* and optionally kills the sprite (if Sprite.outOfBoundsKill is true). By default this is disabled because the Sprite has to calculate its
* bounds every frame to support it, and not all games need it. Enable it by setting the value to true.
* @property {boolean} checkWorldBounds
* @default
*/
this.checkWorldBounds = false;
/**
* @property {Phaser.Point} cameraOffset - If this object is fixedToCamera then this stores the x/y offset that its drawn at, from the top-left of the camera view.
*/
this.cameraOffset = new Phaser.Point();
/**
* By default Sprites won't add themselves to any physics system and their physics body will be `null`.
* To enable them for physics you need to call `game.physics.enable(sprite, system)` where `sprite` is this object
* and `system` is the Physics system you want to use to manage this body. Once enabled you can access all physics related properties via `Sprite.body`.
*
* Important: Enabling a Sprite for P2 or Ninja physics will automatically set `Sprite.anchor` to 0.5 so the physics body is centered on the Sprite.
* If you need a different result then adjust or re-create the Body shape offsets manually, and/or reset the anchor after enabling physics.
*
* @property {Phaser.Physics.Arcade.Body|Phaser.Physics.P2.Body|Phaser.Physics.Ninja.Body|null} body
* @default
*/
this.body = null;
/**
* A small internal cache:
* 0 = previous position.x
* 1 = previous position.y
* 2 = previous rotation
* 3 = renderID
* 4 = fresh? (0 = no, 1 = yes)
* 5 = outOfBoundsFired (0 = no, 1 = yes)
* 6 = exists (0 = no, 1 = yes)
* 7 = fixed to camera (0 = no, 1 = yes)
* @property {Array} _cache
* @private
*/
this._cache = [ 0, 0, 0, 0, 1, 0, 1, 0 ];
};
Phaser.TileSprite.prototype = Object.create(PIXI.TilingSprite.prototype);
Phaser.TileSprite.prototype.constructor = Phaser.TileSprite;
/**
* Automatically called by World.preUpdate.
*
* @method Phaser.TileSprite#preUpdate
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.preUpdate = function() {
if (this._cache[4] === 1 && this.exists)
{
this.world.setTo(this.parent.position.x + this.position.x, this.parent.position.y + this.position.y);
this.worldTransform.tx = this.world.x;
this.worldTransform.ty = this.world.y;
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (this.body)
{
this.body.preUpdate();
}
this._cache[4] = 0;
return false;
}
this._cache[0] = this.world.x;
this._cache[1] = this.world.y;
this._cache[2] = this.rotation;
if (!this.exists || !this.parent.exists)
{
// Reset the renderOrderID
this._cache[3] = -1;
return false;
}
// Cache the bounds if we need it
if (this.autoCull || this.checkWorldBounds)
{
this._bounds.copyFrom(this.getBounds());
}
if (this.autoCull)
{
// Won't get rendered but will still get its transform updated
this.renderable = this.game.world.camera.screenView.intersects(this._bounds);
}
if (this.checkWorldBounds)
{
// The Sprite is already out of the world bounds, so let's check to see if it has come back again
if (this._cache[5] === 1 && this.game.world.bounds.intersects(this._bounds))
{
this._cache[5] = 0;
this.events.onEnterBounds.dispatch(this);
}
else if (this._cache[5] === 0 && !this.game.world.bounds.intersects(this._bounds))
{
// The Sprite WAS in the screen, but has now left.
this._cache[5] = 1;
this.events.onOutOfBounds.dispatch(this);
}
}
this.world.setTo(this.game.camera.x + this.worldTransform.tx, this.game.camera.y + this.worldTransform.ty);
if (this.visible)
{
this._cache[3] = this.game.stage.currentRenderOrderID++;
}
this.animations.update();
if (this._scroll.x !== 0)
{
this.tilePosition.x += this._scroll.x * this.game.time.physicsElapsed;
}
if (this._scroll.y !== 0)
{
this.tilePosition.y += this._scroll.y * this.game.time.physicsElapsed;
}
if (this.body)
{
this.body.preUpdate();
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].preUpdate();
}
return true;
}
/**
* Override and use this function in your own custom objects to handle any update requirements you may have.
*
* @method Phaser.TileSprite#update
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.update = function() {
}
/**
* Internal function called by the World postUpdate cycle.
*
* @method Phaser.TileSprite#postUpdate
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.postUpdate = function() {
if (this.exists && this.body)
{
this.body.postUpdate();
}
// Fixed to Camera?
if (this._cache[7] === 1)
{
this.position.x = this.game.camera.view.x + this.cameraOffset.x;
this.position.y = this.game.camera.view.y + this.cameraOffset.y;
}
// Update any Children
for (var i = 0, len = this.children.length; i < len; i++)
{
this.children[i].postUpdate();
}
}
/**
* Sets this TileSprite to automatically scroll in the given direction until stopped via TileSprite.stopScroll().
* The scroll speed is specified in pixels per second.
* A negative x value will scroll to the left. A positive x value will scroll to the right.
* A negative y value will scroll up. A positive y value will scroll down.
*
* @method Phaser.TileSprite#autoScroll
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.autoScroll = function(x, y) {
this._scroll.set(x, y);
}
/**
* Stops an automatically scrolling TileSprite.
*
* @method Phaser.TileSprite#stopScroll
* @memberof Phaser.TileSprite
*/
Phaser.TileSprite.prototype.stopScroll = function() {
this._scroll.set(0, 0);
}
/**
* Changes the Texture the TileSprite is using entirely. The old texture is removed and the new one is referenced or fetched from the Cache.
* This causes a WebGL texture update, so use sparingly or in low-intensity portions of your game.
*
* @method Phaser.TileSprite#loadTexture
* @memberof Phaser.TileSprite
* @param {string|Phaser.RenderTexture|Phaser.BitmapData|PIXI.Texture} key - This is the image or texture used by the Sprite during rendering. It can be a string which is a reference to the Cache entry, or an instance of a RenderTexture, BitmapData or PIXI.Texture.
* @param {string|number} frame - If this Sprite is using part of a sprite sheet or texture atlas you can specify the exact frame to use by giving a string or numeric index.
*/
Phaser.TileSprite.prototype.loadTexture = function (key, frame) {
frame = frame || 0;
if (key instanceof Phaser.RenderTexture)
{
this.key = key.key;
this.setTexture(key);
return;
}
else if (key instanceof Phaser.BitmapData)
{
this.key = key;
this.setTexture(key.texture);
return;
}
else if (key instanceof PIXI.Texture)
{
this.key = key;
this.setTexture(key);
return;
}
else
{
if (key === null || typeof key === 'undefined')
{
this.key = '__default';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
else if (typeof key === 'string' && !this.game.cache.checkImageKey(key))
{
this.key = '__missing';
this.setTexture(PIXI.TextureCache[this.key]);
return;
}
if (this.game.cache.isSpriteSheet(key))
{
this.key = key;
// var frameData = this.game.cache.getFrameData(key);
this.animations.loadFrameData(this.game.cache.getFrameData(key));
if (typeof frame === 'string')
{
this.frameName = frame;
}
else
{
this.frame = frame;
}
}
else
{
this.key = key;
this.setTexture(PIXI.TextureCache[key]);
return;
}
}
}
/**
* Destroys the TileSprite. This removes it from its parent group, destroys the event and animation handlers if present
* and nulls its reference to game, freeing it up for garbage collection.
*
* @method Phaser.TileSprite#destroy
* @memberof Phaser.TileSprite
* @param {boolean} [destroyChildren=true] - Should every child of this object have its destroy method called?
*/
Phaser.TileSprite.prototype.destroy = function(destroyChildren) {
if (this.game === null) { return; }
if (typeof destroyChildren === 'undefined') { destroyChildren = true; }
if (this.filters)
{
this.filters = null;
}
if (this.parent)
{
if (this.parent instanceof Phaser.Group)
{
this.parent.remove(this);
}
else
{
this.parent.removeChild(this);
}
}
this.animations.destroy();
this.events.destroy();
var i = this.children.length;
if (destroyChildren)
{
while (i--)
{
this.children[i].destroy(destroyChildren);
}
}
else
{
while (i--)
{
this.removeChild(this.children[i]);
}
}
this.exists = false;
this.visible = false;
this.filters = null;
this.mask = null;
this.game = null;
}
/**
* Play an animation based on the given key. The animation should previously have been added via sprite.animations.add()
* If the requested animation is already playing this request will be ignored. If you need to reset an already running animation do so directly on the Animation object itself.
*
* @method Phaser.TileSprite#play
* @memberof Phaser.TileSprite
* @param {string} name - The name of the animation to be played, e.g. "fire", "walk", "jump".
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} A reference to playing Animation instance.
*/
Phaser.TileSprite.prototype.play = function (name, frameRate, loop, killOnComplete) {
return this.animations.play(name, frameRate, loop, killOnComplete);
}
/**
* Resets the TileSprite. This places the TileSprite at the given x/y world coordinates, resets the tilePosition and then
* sets alive, exists, visible and renderable all to true. Also resets the outOfBounds state.
* If the TileSprite has a physics body that too is reset.
*
* @method Phaser.TileSprite#reset
* @memberof Phaser.TileSprite
* @param {number} x - The x coordinate (in world space) to position the Sprite at.
* @param {number} y - The y coordinate (in world space) to position the Sprite at.
* @return (Phaser.TileSprite) This instance.
*/
Phaser.TileSprite.prototype.reset = function(x, y) {
this.world.setTo(x, y);
this.position.x = x;
this.position.y = y;
this.alive = true;
this.exists = true;
this.visible = true;
this.renderable = true;
this._outOfBoundsFired = false;
this.tilePosition.x = 0;
this.tilePosition.y = 0;
if (this.body)
{
this.body.reset(x, y, false, false);
}
this._cache[4] = 1;
return this;
};
/**
* Indicates the rotation of the Sprite, in degrees, from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation.
* Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement player.angle = 450 is the same as player.angle = 90.
* If you wish to work in radians instead of degrees use the property Sprite.rotation instead. Working in radians is also a little faster as it doesn't have to convert the angle.
*
* @name Phaser.TileSprite#angle
* @property {number} angle - The angle of this Sprite in degrees.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "angle", {
get: function() {
return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.rotation));
},
set: function(value) {
this.rotation = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value));
}
});
/**
* @name Phaser.TileSprite#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "frame", {
get: function () {
return this.animations.frame;
},
set: function (value) {
if (value !== this.animations.frame)
{
this.animations.frame = value;
}
}
});
/**
* @name Phaser.TileSprite#frameName
* @property {string} frameName - Gets or sets the current frame name and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "frameName", {
get: function () {
return this.animations.frameName;
},
set: function (value) {
if (value !== this.animations.frameName)
{
this.animations.frameName = value;
}
}
});
/**
* An TileSprite that is fixed to the camera uses its x/y coordinates as offsets from the top left of the camera. These are stored in TileSprite.cameraOffset.
* Note that the cameraOffset values are in addition to any parent in the display list.
* So if this TileSprite was in a Group that has x: 200, then this will be added to the cameraOffset.x
*
* @name Phaser.TileSprite#fixedToCamera
* @property {boolean} fixedToCamera - Set to true to fix this TileSprite to the Camera at its current world coordinates.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "fixedToCamera", {
get: function () {
return !!this._cache[7];
},
set: function (value) {
if (value)
{
this._cache[7] = 1;
this.cameraOffset.set(this.x, this.y);
}
else
{
this._cache[7] = 0;
}
}
});
/**
* TileSprite.exists controls if the core game loop and physics update this TileSprite or not.
* When you set TileSprite.exists to false it will remove its Body from the physics world (if it has one) and also set TileSprite.visible to false.
* Setting TileSprite.exists to true will re-add the Body to the physics world (if it has a body) and set TileSprite.visible to true.
*
* @name Phaser.TileSprite#exists
* @property {boolean} exists - If the TileSprite is processed by the core game update and physics.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "exists", {
get: function () {
return !!this._cache[6];
},
set: function (value) {
if (value)
{
// exists = true
this._cache[6] = 1;
if (this.body && this.body.type === Phaser.Physics.P2JS)
{
this.body.addToWorld();
}
this.visible = true;
}
else
{
// exists = false
this._cache[6] = 0;
if (this.body && this.body.type === Phaser.Physics.P2JS)
{
this.body.safeRemove = true;
}
this.visible = false;
}
}
});
/**
* By default a TileSprite won't process any input events at all. By setting inputEnabled to true the Phaser.InputHandler is
* activated for this object and it will then start to process click/touch events and more.
*
* @name Phaser.TileSprite#inputEnabled
* @property {boolean} inputEnabled - Set to true to allow this object to receive input events.
*/
Object.defineProperty(Phaser.TileSprite.prototype, "inputEnabled", {
get: function () {
return (this.input && this.input.enabled);
},
set: function (value) {
if (value)
{
if (this.input === null)
{
this.input = new Phaser.InputHandler(this);
this.input.start();
}
}
else
{
if (this.input && this.input.enabled)
{
this.input.stop();
}
}
}
});
|
// ------------------------------------------------------------------------
// Copyright 2009 Applied Research in Patacriticism and the University of Virginia
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------
/*global serverAction */
/*extern ajax_pagination */
function ajax_pagination(actions, els, page) {
var params = {waitMessage: 'Loading page...' };
serverAction({action: { actions: actions, els: els, params: { page: page }}, progress: { waitMessage: 'Loading page...' }});
}
|
const
ScriptFunction = require('./../../../src/definitions/ScriptFunction')
;
module.exports = ScriptFunction(function () {
this.setRender(undefined);
this.finished();
});
|
const {
favicon196,
favicon160,
favicon152,
favicon144,
favicon120,
favicon114,
favicon96,
favicon76,
favicon72,
favicon60,
favicon57,
favicon32,
favicon16,
} = require('../favicon-adp');
const CONFIG = {
markdownFile: `./Awesome-Design-Plugins.md`,
index: `./docs/index-plugins.html`,
promoFlawlessFeedbackBanner__title: 'Leave feedback on iOS apps',
promoFlawlessFeedbackBanner__description: 'Turn UI issues & Bugs Into Jira tickets or Trello cards',
promoFlawlessFeedbackBanner__link: 'https://flawlessapp.io/feedback',
main: {
title: 'Awesome Design Plugins',
themeColor: '#0054d7',
bodyColorScheme: '-green',
logoClassName: '-logo-adp',
head: {
title: 'Awesome Design Plugins',
meta: {
title: 'Awesome Design Plugins',
themeColor: '#028930',
description: 'Design plugins',
image: 'https://flawlessapp.io/images/designtools/awesome-design-tools-sharable-image-general.png',
siteURL: 'https://flawlessapp.io/designplugins',
},
favicon: {
'196': favicon196,
'160': favicon160,
'152': favicon152,
'144': favicon144,
'120': favicon120,
'114': favicon114,
'96': favicon96,
'76': favicon76,
'72': favicon72,
'60': favicon60,
'57': favicon57,
'32': favicon32,
'16': favicon16,
},
},
nav: {
loop: [
{
title: 'Tools',
href: '/designtools',
isActive: false,
className: '-tool',
},
{
title: 'Plugins',
href: '/designplugins',
isActive: true,
className: '-plugin',
},
],
},
welcomeArticle: {
title: 'Awesome Design Plugins',
logoClassName: '-logo-adp',
description: `All the best design plugins for Sketch, Adobe XD, and Figma, gathered in one place.`,
button: {
href: 'https://github.com/LisaDziuba/Awesome-Design-Tools/blob/master/Awesome-Design-Plugins.md',
},
},
},
};
module.exports = CONFIG;
|
/* -*- Mode: Javascript; indent-tabs-mode:nil; js-indent-level: 2 -*- */
/* vim: set ts=2 et sw=2 tw=80: */
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/autoload/ms.js
*
* Implements the HTML-CSS output for <ms> elements.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2010-2017 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Register.StartupHook("HTML-CSS Jax Ready",function () {
var VERSION = "2.7.2-beta.1";
var MML = MathJax.ElementJax.mml,
HTMLCSS = MathJax.OutputJax["HTML-CSS"];
MML.ms.Augment({
toHTML: function (span) {
span = this.HTMLhandleSize(this.HTMLcreateSpan(span));
var values = this.getValues("lquote","rquote","mathvariant");
if (!this.hasValue("lquote") || values.lquote === '"') values.lquote = "\u201C";
if (!this.hasValue("rquote") || values.rquote === '"') values.rquote = "\u201D";
if (values.lquote === "\u201C" && values.mathvariant === "monospace") values.lquote = '"';
if (values.rquote === "\u201D" && values.mathvariant === "monospace") values.rquote = '"';
var text = values.lquote+this.data.join("")+values.rquote; // FIXME: handle mglyph?
this.HTMLhandleVariant(span,this.HTMLgetVariant(),text);
this.HTMLhandleSpace(span);
this.HTMLhandleColor(span);
this.HTMLhandleDir(span);
return span;
}
});
MathJax.Hub.Startup.signal.Post("HTML-CSS ms Ready");
MathJax.Ajax.loadComplete(HTMLCSS.autoloadDir+"/ms.js");
});
|
const path = require('path')
// Create pages from Contentful API
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators
return new Promise((resolve, reject) => {
const postTemplate = path.resolve(`src/templates/post.js`)
// Query for markdown nodes to use in creating pages
resolve(
graphql(
`
{
allContentfulPost {
edges {
node {
id
title
slug
content {
content
}
}
}
}
}
`
).then(result => {
console.log(result)
if (result.errors) {
reject(result.errors)
} else {
// Create posts
result.data.allContentfulPost.edges.forEach(edge => {
createPage({
path: `${edge.node.slug}`,
component: postTemplate,
context: edge.node,
})
})
}
return
})
)
})
}
|
import React from 'react'
import PropTypes from 'prop-types'
import { Explore, Listing, Section, Landing } from '../../components/shared'
import Layout from '../../components/layout'
import SEO from '../../components/SEO'
const Process = ({
id,
seo,
process_section_0: section0,
process_sections: sections
}) => (
<Layout>
<SEO {...seo} />
<Landing {...section0} {...sections} />
{sections.map((section, key, { length }) => (
<Section key={key} index={key} isLast={length - 1 === key} {...section} />
))}
<Listing excludeId={id} />
<Explore />
</Layout>
)
Process.propTypes = {
id: PropTypes.number.isRequired
}
export default Process
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const utils_debug_1 = require("@hint/utils-debug");
const utils_types_1 = require("@hint/utils-types");
const debug = utils_debug_1.debug(__filename);
const module_esnext_typescript_1 = require("./meta/module-esnext-typescript");
const i18n_import_1 = require("./i18n.import");
class WebpackConfigModuleESNextTypescript {
constructor(context) {
let webpackEvent;
let typescriptEvent;
const webpackConfigReceived = (webpackConfigEvent) => {
debug(`'parse::end::webpack-config' received`);
webpackEvent = webpackConfigEvent;
};
const typescriptConfigReceived = (typescriptConfigEvent) => {
debug(`'parse::end::typescript-config' received`);
typescriptEvent = typescriptConfigEvent;
};
const validate = () => {
if (!webpackEvent) {
debug(`no 'parse::end::webpack-config' received`);
return;
}
if (!typescriptEvent) {
debug(`no 'parse::end::typescript-config' received`);
return;
}
const version = parseInt(webpackEvent.version);
if (version < 2) {
return;
}
if (typescriptEvent.config.compilerOptions && typescriptEvent.config.compilerOptions.module.toLowerCase() !== 'esnext') {
context.report(typescriptEvent.resource, i18n_import_1.getMessage('esnext', context.language), { severity: utils_types_1.Severity.error });
}
};
context.on('parse::end::webpack-config', webpackConfigReceived);
context.on('parse::end::typescript-config', typescriptConfigReceived);
context.on('scan::end', validate);
}
}
exports.default = WebpackConfigModuleESNextTypescript;
WebpackConfigModuleESNextTypescript.meta = module_esnext_typescript_1.default;
|
/*
Be Concise III - Sum Squares
You are given a program sumSquares that takes an array as input and returns the sum of the squares of each item in an array. For example:
sumSquares([1,2,3,4,5]) === 55 // 1 ** 2 + 2 ** 2 + 3 ** 2 + 4 ** 2 + 5 ** 2
sumSquares([7,3,9,6,5]) === 200
sumSquares([11,13,15,18,2]) === 843
Shorten the code such that it meets the requirements.
A few hints:
Try researching about built-in Array methods; they may help shorten your code a lot
Good luck!
*/
function sumSquares(array) {
return array.map((n) => n ** 2).reduce((acc, curr) => acc + curr);
// Another Solution:
// return array.reduce((acc, curr) => acc + curr ** 2, 0);
}
|
import React, { useEffect, useState } from 'react';
import { Route, Switch } from 'react-router-dom';
import { ListHeader, ModalYesNo } from '../components';
import ProductDetail from './ProductDetail';
import ProductList from './ProductList';
import useProducts from './useProducts';
const captains = console;
function Products({ history }) {
const [productToDelete, setProductToDelete] = useState(null);
const [showModal, setShowModal] = useState(false);
const {
addProduct,
deleteProduct,
getProducts,
products,
selectProduct,
selectedProduct,
updateProduct,
} = useProducts();
useEffect(() => {
getProducts();
}, [getProducts]);
function addNewProduct() {
selectProduct({});
history.push('/products/0');
}
function handleCancelProduct() {
history.push('/products');
selectProduct(null);
setProductToDelete(null);
}
function handleDeleteProduct(product) {
selectProduct(null);
setProductToDelete(product);
setShowModal(true);
}
function handleSaveProduct(product) {
if (selectedProduct && selectedProduct.name) {
captains.log(product);
updateProduct(product);
} else {
addProduct(product);
}
handleCancelProduct();
}
function handleCloseModal() {
setShowModal(false);
}
function handleDeleteFromModal() {
setShowModal(false);
deleteProduct(productToDelete);
handleCancelProduct();
}
function handleSelectProduct(selectedProduct) {
selectProduct(selectedProduct);
captains.log(`you selected ${selectedProduct.name}`);
}
function handleRefresh() {
handleCancelProduct();
getProducts();
}
return (
<div className="content-container">
<ListHeader
title="Products"
handleAdd={addNewProduct}
handleRefresh={handleRefresh}
routePath="/products"
/>
<div className="columns is-multiline is-variable">
<div className="column is-8">
<Switch>
<Route
exact
path="/products"
component={() => (
<ProductList
products={products}
selectedProduct={selectedProduct}
handleSelectProduct={handleSelectProduct}
handleDeleteProduct={handleDeleteProduct}
/>
)}
/>
<Route
exact
path="/products/:id"
component={() => {
return (
<ProductDetail
product={selectedProduct}
handleCancelProduct={handleCancelProduct}
handleSaveProduct={handleSaveProduct}
/>
);
}}
/>
</Switch>
</div>
</div>
{showModal && (
<ModalYesNo
message={`Would you like to delete ${productToDelete.name}?`}
onNo={handleCloseModal}
onYes={handleDeleteFromModal}
/>
)}
</div>
);
}
export default Products;
|
'use strict';
module.exports = function(/* environment, appConfig */) {
return {
'ember-websockets': {
'socketIO': false
}
};
};
|
function LNPrefix(d){var f=d.parentElement,c=d.value.split(/\r?\n/).length+10;d.style.cssText="width:90%;resize:none;line-height: normal !important;";f.classList.add("LN_area");f.style.cssText="overflow:hidden;height:250px;";function g(j,h){var i=document.createElement("div");i.innerText=h;i.classList.add("LN_n");i.style.cssText="text-align:right;padding-right:.1rem;";j.appendChild(i)}var b=document.getElementsByClassName("LN_sb")[0];if(b){f.removeChild(b)}var e=document.createElement("div");e.classList.add("LN_sb");e.style.cssText="padding-top:.375rem;display:inline-block;float:left;width:auto;";f.insertBefore(e,d);for(var a=0;a<c;a++){g(document.getElementsByClassName("LN_sb")[0],a+1)}input.addEventListener("scroll",function(i){var h=this.parentElement.children[0].style,j=h.margin-this.scrollTop;h.marginTop=String(j)+"px";this.parentElement.style.overflow="hidden"})};
|
/* Copyright 2012 Mozilla Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define('pdfjs/core/evaluator', ['exports', 'pdfjs/shared/util',
'pdfjs/core/primitives', 'pdfjs/core/stream', 'pdfjs/core/parser',
'pdfjs/core/image', 'pdfjs/core/colorspace', 'pdfjs/core/murmurhash3',
'pdfjs/core/fonts', 'pdfjs/core/function', 'pdfjs/core/pattern',
'pdfjs/core/cmap', 'pdfjs/core/metrics', 'pdfjs/core/bidi',
'pdfjs/core/encodings', 'pdfjs/core/standard_fonts',
'pdfjs/core/unicode', 'pdfjs/core/glyphlist'], factory);
} else if (typeof exports !== 'undefined') {
factory(exports, require('../shared/util.js'), require('./primitives.js'),
require('./stream.js'), require('./parser.js'), require('./image.js'),
require('./colorspace.js'), require('./murmurhash3.js'),
require('./fonts.js'), require('./function.js'), require('./pattern.js'),
require('./cmap.js'), require('./metrics.js'), require('./bidi.js'),
require('./encodings.js'), require('./standard_fonts.js'),
require('./unicode.js'), require('./glyphlist.js'));
} else {
factory((root.pdfjsCoreEvaluator = {}), root.pdfjsSharedUtil,
root.pdfjsCorePrimitives, root.pdfjsCoreStream, root.pdfjsCoreParser,
root.pdfjsCoreImage, root.pdfjsCoreColorSpace, root.pdfjsCoreMurmurHash3,
root.pdfjsCoreFonts, root.pdfjsCoreFunction, root.pdfjsCorePattern,
root.pdfjsCoreCMap, root.pdfjsCoreMetrics, root.pdfjsCoreBidi,
root.pdfjsCoreEncodings, root.pdfjsCoreStandardFonts,
root.pdfjsCoreUnicode, root.pdfjsCoreGlyphList);
}
}(this, function (exports, sharedUtil, corePrimitives, coreStream, coreParser,
coreImage, coreColorSpace, coreMurmurHash3, coreFonts,
coreFunction, corePattern, coreCMap, coreMetrics, coreBidi,
coreEncodings, coreStandardFonts, coreUnicode,
coreGlyphList) {
var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX;
var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX;
var UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES;
var ImageKind = sharedUtil.ImageKind;
var OPS = sharedUtil.OPS;
var TextRenderingMode = sharedUtil.TextRenderingMode;
var CMapCompressionType = sharedUtil.CMapCompressionType;
var Util = sharedUtil.Util;
var assert = sharedUtil.assert;
var createPromiseCapability = sharedUtil.createPromiseCapability;
var error = sharedUtil.error;
var info = sharedUtil.info;
var isArray = sharedUtil.isArray;
var isNum = sharedUtil.isNum;
var isString = sharedUtil.isString;
var getLookupTableFactory = sharedUtil.getLookupTableFactory;
var warn = sharedUtil.warn;
var Dict = corePrimitives.Dict;
var Name = corePrimitives.Name;
var isEOF = corePrimitives.isEOF;
var isCmd = corePrimitives.isCmd;
var isDict = corePrimitives.isDict;
var isName = corePrimitives.isName;
var isRef = corePrimitives.isRef;
var isStream = corePrimitives.isStream;
var DecodeStream = coreStream.DecodeStream;
var JpegStream = coreStream.JpegStream;
var Stream = coreStream.Stream;
var Lexer = coreParser.Lexer;
var Parser = coreParser.Parser;
var PDFImage = coreImage.PDFImage;
var ColorSpace = coreColorSpace.ColorSpace;
var MurmurHash3_64 = coreMurmurHash3.MurmurHash3_64;
var ErrorFont = coreFonts.ErrorFont;
var FontFlags = coreFonts.FontFlags;
var Font = coreFonts.Font;
var IdentityToUnicodeMap = coreFonts.IdentityToUnicodeMap;
var ToUnicodeMap = coreFonts.ToUnicodeMap;
var getFontType = coreFonts.getFontType;
var isPDFFunction = coreFunction.isPDFFunction;
var PDFFunction = coreFunction.PDFFunction;
var Pattern = corePattern.Pattern;
var getTilingPatternIR = corePattern.getTilingPatternIR;
var CMapFactory = coreCMap.CMapFactory;
var IdentityCMap = coreCMap.IdentityCMap;
var getMetrics = coreMetrics.getMetrics;
var bidi = coreBidi.bidi;
var WinAnsiEncoding = coreEncodings.WinAnsiEncoding;
var StandardEncoding = coreEncodings.StandardEncoding;
var MacRomanEncoding = coreEncodings.MacRomanEncoding;
var SymbolSetEncoding = coreEncodings.SymbolSetEncoding;
var ZapfDingbatsEncoding = coreEncodings.ZapfDingbatsEncoding;
var getEncoding = coreEncodings.getEncoding;
var getStdFontMap = coreStandardFonts.getStdFontMap;
var getSerifFonts = coreStandardFonts.getSerifFonts;
var getSymbolsFonts = coreStandardFonts.getSymbolsFonts;
var getNormalizedUnicodes = coreUnicode.getNormalizedUnicodes;
var reverseIfRtl = coreUnicode.reverseIfRtl;
var getUnicodeForGlyph = coreUnicode.getUnicodeForGlyph;
var getGlyphsUnicode = coreGlyphList.getGlyphsUnicode;
var PartialEvaluator = (function PartialEvaluatorClosure() {
const DefaultPartialEvaluatorOptions = {
forceDataSchema: false,
maxImageSize: -1,
disableFontFace: false,
disableNativeImageDecoder: false,
ignoreErrors: false,
};
function NativeImageDecoder(xref, resources, handler, forceDataSchema) {
this.xref = xref;
this.resources = resources;
this.handler = handler;
this.forceDataSchema = forceDataSchema;
}
NativeImageDecoder.prototype = {
canDecode(image) {
return image instanceof JpegStream &&
NativeImageDecoder.isDecodable(image, this.xref, this.resources);
},
decode(image) {
// For natively supported JPEGs send them to the main thread for decoding.
var dict = image.dict;
var colorSpace = dict.get('ColorSpace', 'CS');
colorSpace = ColorSpace.parse(colorSpace, this.xref, this.resources);
var numComps = colorSpace.numComps;
var decodePromise = this.handler.sendWithPromise('JpegDecode',
[image.getIR(this.forceDataSchema), numComps]);
return decodePromise.then(function (message) {
var data = message.data;
return new Stream(data, 0, data.length, image.dict);
});
}
};
/**
* Checks if the image can be decoded and displayed by the browser without any
* further processing such as color space conversions.
*/
NativeImageDecoder.isSupported =
function NativeImageDecoder_isSupported(image, xref, res) {
var dict = image.dict;
if (dict.has('DecodeParms') || dict.has('DP')) {
return false;
}
var cs = ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res);
return (cs.name === 'DeviceGray' || cs.name === 'DeviceRGB') &&
cs.isDefaultDecode(dict.getArray('Decode', 'D'));
};
/**
* Checks if the image can be decoded by the browser.
*/
NativeImageDecoder.isDecodable =
function NativeImageDecoder_isDecodable(image, xref, res) {
var dict = image.dict;
if (dict.has('DecodeParms') || dict.has('DP')) {
return false;
}
var cs = ColorSpace.parse(dict.get('ColorSpace', 'CS'), xref, res);
return (cs.numComps === 1 || cs.numComps === 3) &&
cs.isDefaultDecode(dict.getArray('Decode', 'D'));
};
function PartialEvaluator({ pdfManager, xref, handler, pageIndex, idFactory,
fontCache, builtInCMapCache, options = null, }) {
this.pdfManager = pdfManager;
this.xref = xref;
this.handler = handler;
this.pageIndex = pageIndex;
this.idFactory = idFactory;
this.fontCache = fontCache;
this.builtInCMapCache = builtInCMapCache;
this.options = options || DefaultPartialEvaluatorOptions;
this.fetchBuiltInCMap = (name) => {
var cachedCMap = this.builtInCMapCache[name];
if (cachedCMap) {
return Promise.resolve(cachedCMap);
}
return this.handler.sendWithPromise('FetchBuiltInCMap', {
name,
}).then((data) => {
if (data.compressionType !== CMapCompressionType.NONE) {
// Given the size of uncompressed CMaps, only cache compressed ones.
this.builtInCMapCache[name] = data;
}
return data;
});
};
}
// Trying to minimize Date.now() usage and check every 100 time
var TIME_SLOT_DURATION_MS = 20;
var CHECK_TIME_EVERY = 100;
function TimeSlotManager() {
this.reset();
}
TimeSlotManager.prototype = {
check: function TimeSlotManager_check() {
if (++this.checked < CHECK_TIME_EVERY) {
return false;
}
this.checked = 0;
return this.endTime <= Date.now();
},
reset: function TimeSlotManager_reset() {
this.endTime = Date.now() + TIME_SLOT_DURATION_MS;
this.checked = 0;
}
};
// Convert PDF blend mode names to HTML5 blend mode names.
function normalizeBlendMode(value) {
if (!isName(value)) {
return 'source-over';
}
switch (value.name) {
case 'Normal':
case 'Compatible':
return 'source-over';
case 'Multiply':
return 'multiply';
case 'Screen':
return 'screen';
case 'Overlay':
return 'overlay';
case 'Darken':
return 'darken';
case 'Lighten':
return 'lighten';
case 'ColorDodge':
return 'color-dodge';
case 'ColorBurn':
return 'color-burn';
case 'HardLight':
return 'hard-light';
case 'SoftLight':
return 'soft-light';
case 'Difference':
return 'difference';
case 'Exclusion':
return 'exclusion';
case 'Hue':
return 'hue';
case 'Saturation':
return 'saturation';
case 'Color':
return 'color';
case 'Luminosity':
return 'luminosity';
}
warn('Unsupported blend mode: ' + value.name);
return 'source-over';
}
var deferred = Promise.resolve();
var TILING_PATTERN = 1, SHADING_PATTERN = 2;
PartialEvaluator.prototype = {
clone(newOptions = DefaultPartialEvaluatorOptions) {
var newEvaluator = Object.create(this);
newEvaluator.options = newOptions;
return newEvaluator;
},
hasBlendModes: function PartialEvaluator_hasBlendModes(resources) {
if (!isDict(resources)) {
return false;
}
var processed = Object.create(null);
if (resources.objId) {
processed[resources.objId] = true;
}
var nodes = [resources], xref = this.xref;
while (nodes.length) {
var key, i, ii;
var node = nodes.shift();
// First check the current resources for blend modes.
var graphicStates = node.get('ExtGState');
if (isDict(graphicStates)) {
var graphicStatesKeys = graphicStates.getKeys();
for (i = 0, ii = graphicStatesKeys.length; i < ii; i++) {
key = graphicStatesKeys[i];
var graphicState = graphicStates.get(key);
var bm = graphicState.get('BM');
if (isName(bm) && bm.name !== 'Normal') {
return true;
}
}
}
// Descend into the XObjects to look for more resources and blend modes.
var xObjects = node.get('XObject');
if (!isDict(xObjects)) {
continue;
}
var xObjectsKeys = xObjects.getKeys();
for (i = 0, ii = xObjectsKeys.length; i < ii; i++) {
key = xObjectsKeys[i];
var xObject = xObjects.getRaw(key);
if (isRef(xObject)) {
if (processed[xObject.toString()]) {
// The XObject has already been processed, and by avoiding a
// redundant `xref.fetch` we can *significantly* reduce the load
// time for badly generated PDF files (fixes issue6961.pdf).
continue;
}
xObject = xref.fetch(xObject);
}
if (!isStream(xObject)) {
continue;
}
if (xObject.dict.objId) {
if (processed[xObject.dict.objId]) {
// stream has objId and is processed already
continue;
}
processed[xObject.dict.objId] = true;
}
var xResources = xObject.dict.get('Resources');
// Checking objId to detect an infinite loop.
if (isDict(xResources) &&
(!xResources.objId || !processed[xResources.objId])) {
nodes.push(xResources);
if (xResources.objId) {
processed[xResources.objId] = true;
}
}
}
}
return false;
},
buildFormXObject: function PartialEvaluator_buildFormXObject(resources,
xobj, smask,
operatorList,
task,
initialState) {
var dict = xobj.dict;
var matrix = dict.getArray('Matrix');
var bbox = dict.getArray('BBox');
var group = dict.get('Group');
if (group) {
var groupOptions = {
matrix,
bbox,
smask,
isolated: false,
knockout: false
};
var groupSubtype = group.get('S');
var colorSpace;
if (isName(groupSubtype, 'Transparency')) {
groupOptions.isolated = (group.get('I') || false);
groupOptions.knockout = (group.get('K') || false);
colorSpace = (group.has('CS') ?
ColorSpace.parse(group.get('CS'), this.xref, resources) : null);
}
if (smask && smask.backdrop) {
colorSpace = colorSpace || ColorSpace.singletons.rgb;
smask.backdrop = colorSpace.getRgb(smask.backdrop, 0);
}
operatorList.addOp(OPS.beginGroup, [groupOptions]);
}
operatorList.addOp(OPS.paintFormXObjectBegin, [matrix, bbox]);
return this.getOperatorList({
stream: xobj,
task,
resources: dict.get('Resources') || resources,
operatorList,
initialState,
}).then(function () {
operatorList.addOp(OPS.paintFormXObjectEnd, []);
if (group) {
operatorList.addOp(OPS.endGroup, [groupOptions]);
}
});
},
buildPaintImageXObject:
function PartialEvaluator_buildPaintImageXObject(resources, image,
inline, operatorList,
cacheKey, imageCache) {
var dict = image.dict;
var w = dict.get('Width', 'W');
var h = dict.get('Height', 'H');
if (!(w && isNum(w)) || !(h && isNum(h))) {
warn('Image dimensions are missing, or not numbers.');
return;
}
var maxImageSize = this.options.maxImageSize;
if (maxImageSize !== -1 && w * h > maxImageSize) {
warn('Image exceeded maximum allowed size and was removed.');
return;
}
var imageMask = (dict.get('ImageMask', 'IM') || false);
var imgData, args;
if (imageMask) {
// This depends on a tmpCanvas being filled with the
// current fillStyle, such that processing the pixel
// data can't be done here. Instead of creating a
// complete PDFImage, only read the information needed
// for later.
var width = dict.get('Width', 'W');
var height = dict.get('Height', 'H');
var bitStrideLength = (width + 7) >> 3;
var imgArray = image.getBytes(bitStrideLength * height);
var decode = dict.getArray('Decode', 'D');
var inverseDecode = (!!decode && decode[0] > 0);
imgData = PDFImage.createMask(imgArray, width, height,
image instanceof DecodeStream,
inverseDecode);
imgData.cached = true;
args = [imgData];
operatorList.addOp(OPS.paintImageMaskXObject, args);
if (cacheKey) {
imageCache[cacheKey] = {
fn: OPS.paintImageMaskXObject,
args,
};
}
return;
}
var softMask = (dict.get('SMask', 'SM') || false);
var mask = (dict.get('Mask') || false);
var SMALL_IMAGE_DIMENSIONS = 200;
// Inlining small images into the queue as RGB data
if (inline && !softMask && !mask && !(image instanceof JpegStream) &&
(w + h) < SMALL_IMAGE_DIMENSIONS) {
var imageObj = new PDFImage(this.xref, resources, image,
inline, null, null);
// We force the use of RGBA_32BPP images here, because we can't handle
// any other kind.
imgData = imageObj.createImageData(/* forceRGBA = */ true);
operatorList.addOp(OPS.paintInlineImageXObject, [imgData]);
return;
}
var useNativeImageDecoder = !this.options.disableNativeImageDecoder;
// If there is no imageMask, create the PDFImage and a lot
// of image processing can be done here.
var objId = 'img_' + this.idFactory.createObjId();
operatorList.addDependency(objId);
args = [objId, w, h];
if (useNativeImageDecoder &&
!softMask && !mask && image instanceof JpegStream &&
NativeImageDecoder.isSupported(image, this.xref, resources)) {
// These JPEGs don't need any more processing so we can just send it.
operatorList.addOp(OPS.paintJpegXObject, args);
this.handler.send('obj',
[objId, this.pageIndex, 'JpegStream',
image.getIR(this.options.forceDataSchema)]);
return;
}
// Creates native image decoder only if a JPEG image or mask is present.
var nativeImageDecoder = null;
if (useNativeImageDecoder &&
(image instanceof JpegStream || mask instanceof JpegStream ||
softMask instanceof JpegStream)) {
nativeImageDecoder = new NativeImageDecoder(this.xref, resources,
this.handler, this.options.forceDataSchema);
}
PDFImage.buildImage(this.handler, this.xref, resources, image, inline,
nativeImageDecoder).then((imageObj) => {
var imgData = imageObj.createImageData(/* forceRGBA = */ false);
this.handler.send('obj', [objId, this.pageIndex, 'Image', imgData],
[imgData.data.buffer]);
}).catch((reason) => {
warn('Unable to decode image: ' + reason);
this.handler.send('obj', [objId, this.pageIndex, 'Image', null]);
});
operatorList.addOp(OPS.paintImageXObject, args);
if (cacheKey) {
imageCache[cacheKey] = {
fn: OPS.paintImageXObject,
args,
};
}
},
handleSMask: function PartialEvaluator_handleSmask(smask, resources,
operatorList, task,
stateManager) {
var smaskContent = smask.get('G');
var smaskOptions = {
subtype: smask.get('S').name,
backdrop: smask.get('BC')
};
// The SMask might have a alpha/luminosity value transfer function --
// we will build a map of integer values in range 0..255 to be fast.
var transferObj = smask.get('TR');
if (isPDFFunction(transferObj)) {
var transferFn = PDFFunction.parse(this.xref, transferObj);
var transferMap = new Uint8Array(256);
var tmp = new Float32Array(1);
for (var i = 0; i < 256; i++) {
tmp[0] = i / 255;
transferFn(tmp, 0, tmp, 0);
transferMap[i] = (tmp[0] * 255) | 0;
}
smaskOptions.transferMap = transferMap;
}
return this.buildFormXObject(resources, smaskContent, smaskOptions,
operatorList, task,
stateManager.state.clone());
},
handleTilingType:
function PartialEvaluator_handleTilingType(fn, args, resources,
pattern, patternDict,
operatorList, task) {
// Create an IR of the pattern code.
var tilingOpList = new OperatorList();
// Merge the available resources, to prevent issues when the patternDict
// is missing some /Resources entries (fixes issue6541.pdf).
var resourcesArray = [patternDict.get('Resources'), resources];
var patternResources = Dict.merge(this.xref, resourcesArray);
return this.getOperatorList({
stream: pattern,
task,
resources: patternResources,
operatorList: tilingOpList,
}).then(function () {
// Add the dependencies to the parent operator list so they are
// resolved before sub operator list is executed synchronously.
operatorList.addDependencies(tilingOpList.dependencies);
operatorList.addOp(fn, getTilingPatternIR({
fnArray: tilingOpList.fnArray,
argsArray: tilingOpList.argsArray
}, patternDict, args));
});
},
handleSetFont:
function PartialEvaluator_handleSetFont(resources, fontArgs, fontRef,
operatorList, task, state) {
// TODO(mack): Not needed?
var fontName;
if (fontArgs) {
fontArgs = fontArgs.slice();
fontName = fontArgs[0].name;
}
return this.loadFont(fontName, fontRef, resources).then((translated) => {
if (!translated.font.isType3Font) {
return translated;
}
return translated.loadType3Data(this, resources, operatorList, task).
then(function () {
return translated;
}).catch((reason) => {
// Error in the font data -- sending unsupported feature notification.
this.handler.send('UnsupportedFeature',
{featureId: UNSUPPORTED_FEATURES.font});
return new TranslatedFont('g_font_error',
new ErrorFont('Type3 font load error: ' + reason), translated.font);
});
}).then((translated) => {
state.font = translated.font;
translated.send(this.handler);
return translated.loadedName;
});
},
handleText: function PartialEvaluator_handleText(chars, state) {
var font = state.font;
var glyphs = font.charsToGlyphs(chars);
var isAddToPathSet = !!(state.textRenderingMode &
TextRenderingMode.ADD_TO_PATH_FLAG);
if (font.data && (isAddToPathSet || this.options.disableFontFace)) {
var buildPath = (fontChar) => {
if (!font.renderer.hasBuiltPath(fontChar)) {
var path = font.renderer.getPathJs(fontChar);
this.handler.send('commonobj', [
font.loadedName + '_path_' + fontChar,
'FontPath',
path
]);
}
};
for (var i = 0, ii = glyphs.length; i < ii; i++) {
var glyph = glyphs[i];
buildPath(glyph.fontChar);
// If the glyph has an accent we need to build a path for its
// fontChar too, otherwise CanvasGraphics_paintChar will fail.
var accent = glyph.accent;
if (accent && accent.fontChar) {
buildPath(accent.fontChar);
}
}
}
return glyphs;
},
setGState: function PartialEvaluator_setGState(resources, gState,
operatorList, task,
stateManager) {
// This array holds the converted/processed state data.
var gStateObj = [];
var gStateKeys = gState.getKeys();
var promise = Promise.resolve();
for (var i = 0, ii = gStateKeys.length; i < ii; i++) {
let key = gStateKeys[i];
let value = gState.get(key);
switch (key) {
case 'Type':
break;
case 'LW':
case 'LC':
case 'LJ':
case 'ML':
case 'D':
case 'RI':
case 'FL':
case 'CA':
case 'ca':
gStateObj.push([key, value]);
break;
case 'Font':
promise = promise.then(() => {
return this.handleSetFont(resources, null, value[0], operatorList,
task, stateManager.state).
then(function (loadedName) {
operatorList.addDependency(loadedName);
gStateObj.push([key, [loadedName, value[1]]]);
});
});
break;
case 'BM':
gStateObj.push([key, normalizeBlendMode(value)]);
break;
case 'SMask':
if (isName(value, 'None')) {
gStateObj.push([key, false]);
break;
}
if (isDict(value)) {
promise = promise.then(() => {
return this.handleSMask(value, resources, operatorList,
task, stateManager);
});
gStateObj.push([key, true]);
} else {
warn('Unsupported SMask type');
}
break;
// Only generate info log messages for the following since
// they are unlikely to have a big impact on the rendering.
case 'OP':
case 'op':
case 'OPM':
case 'BG':
case 'BG2':
case 'UCR':
case 'UCR2':
case 'TR':
case 'TR2':
case 'HT':
case 'SM':
case 'SA':
case 'AIS':
case 'TK':
// TODO implement these operators.
info('graphic state operator ' + key);
break;
default:
info('Unknown graphic state operator ' + key);
break;
}
}
return promise.then(function () {
if (gStateObj.length > 0) {
operatorList.addOp(OPS.setGState, [gStateObj]);
}
});
},
loadFont: function PartialEvaluator_loadFont(fontName, font, resources) {
function errorFont() {
return Promise.resolve(new TranslatedFont('g_font_error',
new ErrorFont('Font ' + fontName + ' is not available'), font));
}
var fontRef, xref = this.xref;
if (font) { // Loading by ref.
assert(isRef(font));
fontRef = font;
} else { // Loading by name.
var fontRes = resources.get('Font');
if (fontRes) {
fontRef = fontRes.getRaw(fontName);
} else {
warn('fontRes not available');
return errorFont();
}
}
if (!fontRef) {
warn('fontRef not available');
return errorFont();
}
if (this.fontCache.has(fontRef)) {
return this.fontCache.get(fontRef);
}
font = xref.fetchIfRef(fontRef);
if (!isDict(font)) {
return errorFont();
}
// We are holding `font.translated` references just for `fontRef`s that
// are not actually `Ref`s, but rather `Dict`s. See explanation below.
if (font.translated) {
return font.translated;
}
var fontCapability = createPromiseCapability();
var preEvaluatedFont = this.preEvaluateFont(font);
var descriptor = preEvaluatedFont.descriptor;
var fontRefIsRef = isRef(fontRef), fontID;
if (fontRefIsRef) {
fontID = fontRef.toString();
}
if (isDict(descriptor)) {
if (!descriptor.fontAliases) {
descriptor.fontAliases = Object.create(null);
}
var fontAliases = descriptor.fontAliases;
var hash = preEvaluatedFont.hash;
if (fontAliases[hash]) {
var aliasFontRef = fontAliases[hash].aliasRef;
if (fontRefIsRef && aliasFontRef &&
this.fontCache.has(aliasFontRef)) {
this.fontCache.putAlias(fontRef, aliasFontRef);
return this.fontCache.get(fontRef);
}
} else {
fontAliases[hash] = {
fontID: Font.getFontID()
};
}
if (fontRefIsRef) {
fontAliases[hash].aliasRef = fontRef;
}
fontID = fontAliases[hash].fontID;
}
// Workaround for bad PDF generators that reference fonts incorrectly,
// where `fontRef` is a `Dict` rather than a `Ref` (fixes bug946506.pdf).
// In this case we should not put the font into `this.fontCache` (which is
// a `RefSetCache`), since it's not meaningful to use a `Dict` as a key.
//
// However, if we don't cache the font it's not possible to remove it
// when `cleanup` is triggered from the API, which causes issues on
// subsequent rendering operations (see issue7403.pdf).
// A simple workaround would be to just not hold `font.translated`
// references in this case, but this would force us to unnecessarily load
// the same fonts over and over.
//
// Instead, we cheat a bit by attempting to use a modified `fontID` as a
// key in `this.fontCache`, to allow the font to be cached.
// NOTE: This works because `RefSetCache` calls `toString()` on provided
// keys. Also, since `fontRef` is used when getting cached fonts,
// we'll not accidentally match fonts cached with the `fontID`.
if (fontRefIsRef) {
this.fontCache.put(fontRef, fontCapability.promise);
} else {
if (!fontID) {
fontID = this.idFactory.createObjId();
}
this.fontCache.put('id_' + fontID, fontCapability.promise);
}
assert(fontID, 'The "fontID" must be defined.');
// Keep track of each font we translated so the caller can
// load them asynchronously before calling display on a page.
font.loadedName = 'g_' + this.pdfManager.docId + '_f' + fontID;
font.translated = fontCapability.promise;
// TODO move promises into translate font
var translatedPromise;
try {
translatedPromise = this.translateFont(preEvaluatedFont);
} catch (e) {
translatedPromise = Promise.reject(e);
}
translatedPromise.then(function (translatedFont) {
if (translatedFont.fontType !== undefined) {
var xrefFontStats = xref.stats.fontTypes;
xrefFontStats[translatedFont.fontType] = true;
}
fontCapability.resolve(new TranslatedFont(font.loadedName,
translatedFont, font));
}).catch((reason) => {
// TODO fontCapability.reject?
// Error in the font data -- sending unsupported feature notification.
this.handler.send('UnsupportedFeature',
{featureId: UNSUPPORTED_FEATURES.font});
try {
// error, but it's still nice to have font type reported
var descriptor = preEvaluatedFont.descriptor;
var fontFile3 = descriptor && descriptor.get('FontFile3');
var subtype = fontFile3 && fontFile3.get('Subtype');
var fontType = getFontType(preEvaluatedFont.type,
subtype && subtype.name);
var xrefFontStats = xref.stats.fontTypes;
xrefFontStats[fontType] = true;
} catch (ex) { }
fontCapability.resolve(new TranslatedFont(font.loadedName,
new ErrorFont(reason instanceof Error ? reason.message : reason),
font));
});
return fontCapability.promise;
},
buildPath: function PartialEvaluator_buildPath(operatorList, fn, args) {
var lastIndex = operatorList.length - 1;
if (!args) {
args = [];
}
if (lastIndex < 0 ||
operatorList.fnArray[lastIndex] !== OPS.constructPath) {
operatorList.addOp(OPS.constructPath, [[fn], args]);
} else {
var opArgs = operatorList.argsArray[lastIndex];
opArgs[0].push(fn);
Array.prototype.push.apply(opArgs[1], args);
}
},
handleColorN: function PartialEvaluator_handleColorN(operatorList, fn, args,
cs, patterns,
resources, task) {
// compile tiling patterns
var patternName = args[args.length - 1];
// SCN/scn applies patterns along with normal colors
var pattern;
if (isName(patternName) &&
(pattern = patterns.get(patternName.name))) {
var dict = (isStream(pattern) ? pattern.dict : pattern);
var typeNum = dict.get('PatternType');
if (typeNum === TILING_PATTERN) {
var color = cs.base ? cs.base.getRgb(args, 0) : null;
return this.handleTilingType(fn, color, resources, pattern,
dict, operatorList, task);
} else if (typeNum === SHADING_PATTERN) {
var shading = dict.get('Shading');
var matrix = dict.getArray('Matrix');
pattern = Pattern.parseShading(shading, matrix, this.xref, resources,
this.handler);
operatorList.addOp(fn, pattern.getIR());
return Promise.resolve();
}
return Promise.reject(new Error('Unknown PatternType: ' + typeNum));
}
// TODO shall we fail here?
operatorList.addOp(fn, args);
return Promise.resolve();
},
getOperatorList({ stream, task, resources, operatorList,
initialState = null, }) {
// Ensure that `resources`/`initialState` is correctly initialized,
// even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty;
initialState = initialState || new EvalState();
assert(operatorList, 'getOperatorList: missing "operatorList" parameter');
var self = this;
var xref = this.xref;
var imageCache = Object.create(null);
var xobjs = (resources.get('XObject') || Dict.empty);
var patterns = (resources.get('Pattern') || Dict.empty);
var stateManager = new StateManager(initialState);
var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
var timeSlotManager = new TimeSlotManager();
function closePendingRestoreOPS(argument) {
for (var i = 0, ii = preprocessor.savedStatesDepth; i < ii; i++) {
operatorList.addOp(OPS.restore, []);
}
}
return new Promise(function promiseBody(resolve, reject) {
var next = function (promise) {
promise.then(function () {
try {
promiseBody(resolve, reject);
} catch (ex) {
reject(ex);
}
}, reject);
};
task.ensureNotTerminated();
timeSlotManager.reset();
var stop, operation = {}, i, ii, cs;
while (!(stop = timeSlotManager.check())) {
// The arguments parsed by read() are used beyond this loop, so we
// cannot reuse the same array on each iteration. Therefore we pass
// in |null| as the initial value (see the comment on
// EvaluatorPreprocessor_read() for why).
operation.args = null;
if (!(preprocessor.read(operation))) {
break;
}
var args = operation.args;
var fn = operation.fn;
switch (fn | 0) {
case OPS.paintXObject:
if (args[0].code) {
break;
}
// eagerly compile XForm objects
var name = args[0].name;
if (!name) {
warn('XObject must be referred to by name.');
continue;
}
if (imageCache[name] !== undefined) {
operatorList.addOp(imageCache[name].fn, imageCache[name].args);
args = null;
continue;
}
var xobj = xobjs.get(name);
if (xobj) {
assert(isStream(xobj), 'XObject should be a stream');
var type = xobj.dict.get('Subtype');
assert(isName(type), 'XObject should have a Name subtype');
if (type.name === 'Form') {
stateManager.save();
next(self.buildFormXObject(resources, xobj, null,
operatorList, task,
stateManager.state.clone()).
then(function () {
stateManager.restore();
}));
return;
} else if (type.name === 'Image') {
self.buildPaintImageXObject(resources, xobj, false,
operatorList, name, imageCache);
args = null;
continue;
} else if (type.name === 'PS') {
// PostScript XObjects are unused when viewing documents.
// See section 4.7.1 of Adobe's PDF reference.
info('Ignored XObject subtype PS');
continue;
} else {
error('Unhandled XObject subtype ' + type.name);
}
}
break;
case OPS.setFont:
var fontSize = args[1];
// eagerly collect all fonts
next(self.handleSetFont(resources, args, null, operatorList,
task, stateManager.state).
then(function (loadedName) {
operatorList.addDependency(loadedName);
operatorList.addOp(OPS.setFont, [loadedName, fontSize]);
}));
return;
case OPS.endInlineImage:
var cacheKey = args[0].cacheKey;
if (cacheKey) {
var cacheEntry = imageCache[cacheKey];
if (cacheEntry !== undefined) {
operatorList.addOp(cacheEntry.fn, cacheEntry.args);
args = null;
continue;
}
}
self.buildPaintImageXObject(resources, args[0], true,
operatorList, cacheKey, imageCache);
args = null;
continue;
case OPS.showText:
args[0] = self.handleText(args[0], stateManager.state);
break;
case OPS.showSpacedText:
var arr = args[0];
var combinedGlyphs = [];
var arrLength = arr.length;
var state = stateManager.state;
for (i = 0; i < arrLength; ++i) {
var arrItem = arr[i];
if (isString(arrItem)) {
Array.prototype.push.apply(combinedGlyphs,
self.handleText(arrItem, state));
} else if (isNum(arrItem)) {
combinedGlyphs.push(arrItem);
}
}
args[0] = combinedGlyphs;
fn = OPS.showText;
break;
case OPS.nextLineShowText:
operatorList.addOp(OPS.nextLine);
args[0] = self.handleText(args[0], stateManager.state);
fn = OPS.showText;
break;
case OPS.nextLineSetSpacingShowText:
operatorList.addOp(OPS.nextLine);
operatorList.addOp(OPS.setWordSpacing, [args.shift()]);
operatorList.addOp(OPS.setCharSpacing, [args.shift()]);
args[0] = self.handleText(args[0], stateManager.state);
fn = OPS.showText;
break;
case OPS.setTextRenderingMode:
stateManager.state.textRenderingMode = args[0];
break;
case OPS.setFillColorSpace:
stateManager.state.fillColorSpace =
ColorSpace.parse(args[0], xref, resources);
continue;
case OPS.setStrokeColorSpace:
stateManager.state.strokeColorSpace =
ColorSpace.parse(args[0], xref, resources);
continue;
case OPS.setFillColor:
cs = stateManager.state.fillColorSpace;
args = cs.getRgb(args, 0);
fn = OPS.setFillRGBColor;
break;
case OPS.setStrokeColor:
cs = stateManager.state.strokeColorSpace;
args = cs.getRgb(args, 0);
fn = OPS.setStrokeRGBColor;
break;
case OPS.setFillGray:
stateManager.state.fillColorSpace = ColorSpace.singletons.gray;
args = ColorSpace.singletons.gray.getRgb(args, 0);
fn = OPS.setFillRGBColor;
break;
case OPS.setStrokeGray:
stateManager.state.strokeColorSpace = ColorSpace.singletons.gray;
args = ColorSpace.singletons.gray.getRgb(args, 0);
fn = OPS.setStrokeRGBColor;
break;
case OPS.setFillCMYKColor:
stateManager.state.fillColorSpace = ColorSpace.singletons.cmyk;
args = ColorSpace.singletons.cmyk.getRgb(args, 0);
fn = OPS.setFillRGBColor;
break;
case OPS.setStrokeCMYKColor:
stateManager.state.strokeColorSpace = ColorSpace.singletons.cmyk;
args = ColorSpace.singletons.cmyk.getRgb(args, 0);
fn = OPS.setStrokeRGBColor;
break;
case OPS.setFillRGBColor:
stateManager.state.fillColorSpace = ColorSpace.singletons.rgb;
args = ColorSpace.singletons.rgb.getRgb(args, 0);
break;
case OPS.setStrokeRGBColor:
stateManager.state.strokeColorSpace = ColorSpace.singletons.rgb;
args = ColorSpace.singletons.rgb.getRgb(args, 0);
break;
case OPS.setFillColorN:
cs = stateManager.state.fillColorSpace;
if (cs.name === 'Pattern') {
next(self.handleColorN(operatorList, OPS.setFillColorN, args,
cs, patterns, resources, task));
return;
}
args = cs.getRgb(args, 0);
fn = OPS.setFillRGBColor;
break;
case OPS.setStrokeColorN:
cs = stateManager.state.strokeColorSpace;
if (cs.name === 'Pattern') {
next(self.handleColorN(operatorList, OPS.setStrokeColorN, args,
cs, patterns, resources, task));
return;
}
args = cs.getRgb(args, 0);
fn = OPS.setStrokeRGBColor;
break;
case OPS.shadingFill:
var shadingRes = resources.get('Shading');
assert(shadingRes, 'No shading resource found');
var shading = shadingRes.get(args[0].name);
assert(shading, 'No shading object found');
var shadingFill = Pattern.parseShading(shading, null, xref,
resources, self.handler);
var patternIR = shadingFill.getIR();
args = [patternIR];
fn = OPS.shadingFill;
break;
case OPS.setGState:
var dictName = args[0];
var extGState = resources.get('ExtGState');
if (!isDict(extGState) || !extGState.has(dictName.name)) {
break;
}
var gState = extGState.get(dictName.name);
next(self.setGState(resources, gState, operatorList, task,
stateManager));
return;
case OPS.moveTo:
case OPS.lineTo:
case OPS.curveTo:
case OPS.curveTo2:
case OPS.curveTo3:
case OPS.closePath:
self.buildPath(operatorList, fn, args);
continue;
case OPS.rectangle:
self.buildPath(operatorList, fn, args);
continue;
case OPS.markPoint:
case OPS.markPointProps:
case OPS.beginMarkedContent:
case OPS.beginMarkedContentProps:
case OPS.endMarkedContent:
case OPS.beginCompat:
case OPS.endCompat:
// Ignore operators where the corresponding handlers are known to
// be no-op in CanvasGraphics (display/canvas.js). This prevents
// serialization errors and is also a bit more efficient.
// We could also try to serialize all objects in a general way,
// e.g. as done in https://github.com/mozilla/pdf.js/pull/6266,
// but doing so is meaningless without knowing the semantics.
continue;
default:
// Note: Ignore the operator if it has `Dict` arguments, since
// those are non-serializable, otherwise postMessage will throw
// "An object could not be cloned.".
if (args !== null) {
for (i = 0, ii = args.length; i < ii; i++) {
if (args[i] instanceof Dict) {
break;
}
}
if (i < ii) {
warn('getOperatorList - ignoring operator: ' + fn);
continue;
}
}
}
operatorList.addOp(fn, args);
}
if (stop) {
next(deferred);
return;
}
// Some PDFs don't close all restores inside object/form.
// Closing those for them.
closePendingRestoreOPS();
resolve();
}).catch((reason) => {
if (this.options.ignoreErrors) {
// Error(s) in the OperatorList -- sending unsupported feature
// notification and allow rendering to continue.
this.handler.send('UnsupportedFeature',
{ featureId: UNSUPPORTED_FEATURES.unknown });
warn('getOperatorList - ignoring errors during task: ' + task.name);
closePendingRestoreOPS();
return;
}
throw reason;
});
},
getTextContent({ stream, task, resources, stateManager = null,
normalizeWhitespace = false, combineTextItems = false, }) {
// Ensure that `resources`/`stateManager` is correctly initialized,
// even if the provided parameter is e.g. `null`.
resources = resources || Dict.empty;
stateManager = stateManager || new StateManager(new TextState());
var WhitespaceRegexp = /\s/g;
var textContent = {
items: [],
styles: Object.create(null)
};
var textContentItem = {
initialized: false,
str: [],
width: 0,
height: 0,
vertical: false,
lastAdvanceWidth: 0,
lastAdvanceHeight: 0,
textAdvanceScale: 0,
spaceWidth: 0,
fakeSpaceMin: Infinity,
fakeMultiSpaceMin: Infinity,
fakeMultiSpaceMax: -0,
textRunBreakAllowed: false,
transform: null,
fontName: null
};
var SPACE_FACTOR = 0.3;
var MULTI_SPACE_FACTOR = 1.5;
var MULTI_SPACE_FACTOR_MAX = 4;
var self = this;
var xref = this.xref;
// The xobj is parsed iff it's needed, e.g. if there is a `DO` cmd.
var xobjs = null;
var xobjsCache = Object.create(null);
var preprocessor = new EvaluatorPreprocessor(stream, xref, stateManager);
var textState;
function ensureTextContentItem() {
if (textContentItem.initialized) {
return textContentItem;
}
var font = textState.font;
if (!(font.loadedName in textContent.styles)) {
textContent.styles[font.loadedName] = {
fontFamily: font.fallbackName,
ascent: font.ascent,
descent: font.descent,
vertical: font.vertical
};
}
textContentItem.fontName = font.loadedName;
// 9.4.4 Text Space Details
var tsm = [textState.fontSize * textState.textHScale, 0,
0, textState.fontSize,
0, textState.textRise];
if (font.isType3Font &&
textState.fontMatrix !== FONT_IDENTITY_MATRIX &&
textState.fontSize === 1) {
var glyphHeight = font.bbox[3] - font.bbox[1];
if (glyphHeight > 0) {
glyphHeight = glyphHeight * textState.fontMatrix[3];
tsm[3] *= glyphHeight;
}
}
var trm = Util.transform(textState.ctm,
Util.transform(textState.textMatrix, tsm));
textContentItem.transform = trm;
if (!font.vertical) {
textContentItem.width = 0;
textContentItem.height = Math.sqrt(trm[2] * trm[2] + trm[3] * trm[3]);
textContentItem.vertical = false;
} else {
textContentItem.width = Math.sqrt(trm[0] * trm[0] + trm[1] * trm[1]);
textContentItem.height = 0;
textContentItem.vertical = true;
}
var a = textState.textLineMatrix[0];
var b = textState.textLineMatrix[1];
var scaleLineX = Math.sqrt(a * a + b * b);
a = textState.ctm[0];
b = textState.ctm[1];
var scaleCtmX = Math.sqrt(a * a + b * b);
textContentItem.textAdvanceScale = scaleCtmX * scaleLineX;
textContentItem.lastAdvanceWidth = 0;
textContentItem.lastAdvanceHeight = 0;
var spaceWidth = font.spaceWidth / 1000 * textState.fontSize;
if (spaceWidth) {
textContentItem.spaceWidth = spaceWidth;
textContentItem.fakeSpaceMin = spaceWidth * SPACE_FACTOR;
textContentItem.fakeMultiSpaceMin = spaceWidth * MULTI_SPACE_FACTOR;
textContentItem.fakeMultiSpaceMax =
spaceWidth * MULTI_SPACE_FACTOR_MAX;
// It's okay for monospace fonts to fake as much space as needed.
textContentItem.textRunBreakAllowed = !font.isMonospace;
} else {
textContentItem.spaceWidth = 0;
textContentItem.fakeSpaceMin = Infinity;
textContentItem.fakeMultiSpaceMin = Infinity;
textContentItem.fakeMultiSpaceMax = 0;
textContentItem.textRunBreakAllowed = false;
}
textContentItem.initialized = true;
return textContentItem;
}
function replaceWhitespace(str) {
// Replaces all whitespaces with standard spaces (0x20), to avoid
// alignment issues between the textLayer and the canvas if the text
// contains e.g. tabs (fixes issue6612.pdf).
var i = 0, ii = str.length, code;
while (i < ii && (code = str.charCodeAt(i)) >= 0x20 && code <= 0x7F) {
i++;
}
return (i < ii ? str.replace(WhitespaceRegexp, ' ') : str);
}
function runBidiTransform(textChunk) {
var str = textChunk.str.join('');
var bidiResult = bidi(str, -1, textChunk.vertical);
return {
str: (normalizeWhitespace ? replaceWhitespace(bidiResult.str) :
bidiResult.str),
dir: bidiResult.dir,
width: textChunk.width,
height: textChunk.height,
transform: textChunk.transform,
fontName: textChunk.fontName
};
}
function handleSetFont(fontName, fontRef) {
return self.loadFont(fontName, fontRef, resources).
then(function (translated) {
textState.font = translated.font;
textState.fontMatrix = translated.font.fontMatrix ||
FONT_IDENTITY_MATRIX;
});
}
function buildTextContentItem(chars) {
var font = textState.font;
var textChunk = ensureTextContentItem();
var width = 0;
var height = 0;
var glyphs = font.charsToGlyphs(chars);
for (var i = 0; i < glyphs.length; i++) {
var glyph = glyphs[i];
var glyphWidth = null;
if (font.vertical && glyph.vmetric) {
glyphWidth = glyph.vmetric[0];
} else {
glyphWidth = glyph.width;
}
var glyphUnicode = glyph.unicode;
var NormalizedUnicodes = getNormalizedUnicodes();
if (NormalizedUnicodes[glyphUnicode] !== undefined) {
glyphUnicode = NormalizedUnicodes[glyphUnicode];
}
glyphUnicode = reverseIfRtl(glyphUnicode);
var charSpacing = textState.charSpacing;
if (glyph.isSpace) {
var wordSpacing = textState.wordSpacing;
charSpacing += wordSpacing;
if (wordSpacing > 0) {
addFakeSpaces(wordSpacing, textChunk.str);
}
}
var tx = 0;
var ty = 0;
if (!font.vertical) {
var w0 = glyphWidth * textState.fontMatrix[0];
tx = (w0 * textState.fontSize + charSpacing) *
textState.textHScale;
width += tx;
} else {
var w1 = glyphWidth * textState.fontMatrix[0];
ty = w1 * textState.fontSize + charSpacing;
height += ty;
}
textState.translateTextMatrix(tx, ty);
textChunk.str.push(glyphUnicode);
}
if (!font.vertical) {
textChunk.lastAdvanceWidth = width;
textChunk.width += width;
} else {
textChunk.lastAdvanceHeight = height;
textChunk.height += Math.abs(height);
}
return textChunk;
}
function addFakeSpaces(width, strBuf) {
if (width < textContentItem.fakeSpaceMin) {
return;
}
if (width < textContentItem.fakeMultiSpaceMin) {
strBuf.push(' ');
return;
}
var fakeSpaces = Math.round(width / textContentItem.spaceWidth);
while (fakeSpaces-- > 0) {
strBuf.push(' ');
}
}
function flushTextContentItem() {
if (!textContentItem.initialized) {
return;
}
// Do final text scaling
textContentItem.width *= textContentItem.textAdvanceScale;
textContentItem.height *= textContentItem.textAdvanceScale;
textContent.items.push(runBidiTransform(textContentItem));
textContentItem.initialized = false;
textContentItem.str.length = 0;
}
var timeSlotManager = new TimeSlotManager();
return new Promise(function promiseBody(resolve, reject) {
var next = function (promise) {
promise.then(function () {
try {
promiseBody(resolve, reject);
} catch (ex) {
reject(ex);
}
}, reject);
};
task.ensureNotTerminated();
timeSlotManager.reset();
var stop, operation = {}, args = [];
while (!(stop = timeSlotManager.check())) {
// The arguments parsed by read() are not used beyond this loop, so
// we can reuse the same array on every iteration, thus avoiding
// unnecessary allocations.
args.length = 0;
operation.args = args;
if (!(preprocessor.read(operation))) {
break;
}
textState = stateManager.state;
var fn = operation.fn;
args = operation.args;
var advance, diff;
switch (fn | 0) {
case OPS.setFont:
// Optimization to ignore multiple identical Tf commands.
var fontNameArg = args[0].name, fontSizeArg = args[1];
if (textState.font && fontNameArg === textState.fontName &&
fontSizeArg === textState.fontSize) {
break;
}
flushTextContentItem();
textState.fontName = fontNameArg;
textState.fontSize = fontSizeArg;
next(handleSetFont(fontNameArg, null));
return;
case OPS.setTextRise:
flushTextContentItem();
textState.textRise = args[0];
break;
case OPS.setHScale:
flushTextContentItem();
textState.textHScale = args[0] / 100;
break;
case OPS.setLeading:
flushTextContentItem();
textState.leading = args[0];
break;
case OPS.moveText:
// Optimization to treat same line movement as advance
var isSameTextLine = !textState.font ? false :
((textState.font.vertical ? args[0] : args[1]) === 0);
advance = args[0] - args[1];
if (combineTextItems &&
isSameTextLine && textContentItem.initialized &&
advance > 0 &&
advance <= textContentItem.fakeMultiSpaceMax) {
textState.translateTextLineMatrix(args[0], args[1]);
textContentItem.width +=
(args[0] - textContentItem.lastAdvanceWidth);
textContentItem.height +=
(args[1] - textContentItem.lastAdvanceHeight);
diff = (args[0] - textContentItem.lastAdvanceWidth) -
(args[1] - textContentItem.lastAdvanceHeight);
addFakeSpaces(diff, textContentItem.str);
break;
}
flushTextContentItem();
textState.translateTextLineMatrix(args[0], args[1]);
textState.textMatrix = textState.textLineMatrix.slice();
break;
case OPS.setLeadingMoveText:
flushTextContentItem();
textState.leading = -args[1];
textState.translateTextLineMatrix(args[0], args[1]);
textState.textMatrix = textState.textLineMatrix.slice();
break;
case OPS.nextLine:
flushTextContentItem();
textState.carriageReturn();
break;
case OPS.setTextMatrix:
// Optimization to treat same line movement as advance.
advance = textState.calcTextLineMatrixAdvance(
args[0], args[1], args[2], args[3], args[4], args[5]);
if (combineTextItems &&
advance !== null && textContentItem.initialized &&
advance.value > 0 &&
advance.value <= textContentItem.fakeMultiSpaceMax) {
textState.translateTextLineMatrix(advance.width,
advance.height);
textContentItem.width +=
(advance.width - textContentItem.lastAdvanceWidth);
textContentItem.height +=
(advance.height - textContentItem.lastAdvanceHeight);
diff = (advance.width - textContentItem.lastAdvanceWidth) -
(advance.height - textContentItem.lastAdvanceHeight);
addFakeSpaces(diff, textContentItem.str);
break;
}
flushTextContentItem();
textState.setTextMatrix(args[0], args[1], args[2], args[3],
args[4], args[5]);
textState.setTextLineMatrix(args[0], args[1], args[2], args[3],
args[4], args[5]);
break;
case OPS.setCharSpacing:
textState.charSpacing = args[0];
break;
case OPS.setWordSpacing:
textState.wordSpacing = args[0];
break;
case OPS.beginText:
flushTextContentItem();
textState.textMatrix = IDENTITY_MATRIX.slice();
textState.textLineMatrix = IDENTITY_MATRIX.slice();
break;
case OPS.showSpacedText:
var items = args[0];
var offset;
for (var j = 0, jj = items.length; j < jj; j++) {
if (typeof items[j] === 'string') {
buildTextContentItem(items[j]);
} else if (isNum(items[j])) {
ensureTextContentItem();
// PDF Specification 5.3.2 states:
// The number is expressed in thousandths of a unit of text
// space.
// This amount is subtracted from the current horizontal or
// vertical coordinate, depending on the writing mode.
// In the default coordinate system, a positive adjustment
// has the effect of moving the next glyph painted either to
// the left or down by the given amount.
advance = items[j] * textState.fontSize / 1000;
var breakTextRun = false;
if (textState.font.vertical) {
offset = advance;
textState.translateTextMatrix(0, offset);
breakTextRun = textContentItem.textRunBreakAllowed &&
advance > textContentItem.fakeMultiSpaceMax;
if (!breakTextRun) {
// Value needs to be added to height to paint down.
textContentItem.height += offset;
}
} else {
advance = -advance;
offset = advance * textState.textHScale;
textState.translateTextMatrix(offset, 0);
breakTextRun = textContentItem.textRunBreakAllowed &&
advance > textContentItem.fakeMultiSpaceMax;
if (!breakTextRun) {
// Value needs to be subtracted from width to paint left.
textContentItem.width += offset;
}
}
if (breakTextRun) {
flushTextContentItem();
} else if (advance > 0) {
addFakeSpaces(advance, textContentItem.str);
}
}
}
break;
case OPS.showText:
buildTextContentItem(args[0]);
break;
case OPS.nextLineShowText:
flushTextContentItem();
textState.carriageReturn();
buildTextContentItem(args[0]);
break;
case OPS.nextLineSetSpacingShowText:
flushTextContentItem();
textState.wordSpacing = args[0];
textState.charSpacing = args[1];
textState.carriageReturn();
buildTextContentItem(args[2]);
break;
case OPS.paintXObject:
flushTextContentItem();
if (args[0].code) {
break;
}
if (!xobjs) {
xobjs = (resources.get('XObject') || Dict.empty);
}
var name = args[0].name;
if (xobjsCache.key === name) {
if (xobjsCache.texts) {
Util.appendToArray(textContent.items, xobjsCache.texts.items);
Util.extendObj(textContent.styles, xobjsCache.texts.styles);
}
break;
}
var xobj = xobjs.get(name);
if (!xobj) {
break;
}
assert(isStream(xobj), 'XObject should be a stream');
var type = xobj.dict.get('Subtype');
assert(isName(type), 'XObject should have a Name subtype');
if (type.name !== 'Form') {
xobjsCache.key = name;
xobjsCache.texts = null;
break;
}
// Use a new `StateManager` to prevent incorrect positioning of
// textItems *after* the Form XObject, since errors in the data
// can otherwise prevent `restore` operators from being executed.
// NOTE: This is only an issue when `options.ignoreErrors = true`.
var currentState = stateManager.state.clone();
var xObjStateManager = new StateManager(currentState);
var matrix = xobj.dict.getArray('Matrix');
if (isArray(matrix) && matrix.length === 6) {
xObjStateManager.transform(matrix);
}
next(self.getTextContent({
stream: xobj,
task,
resources: xobj.dict.get('Resources') || resources,
stateManager: xObjStateManager,
normalizeWhitespace,
combineTextItems,
}).then(function (formTextContent) {
Util.appendToArray(textContent.items, formTextContent.items);
Util.extendObj(textContent.styles, formTextContent.styles);
xobjsCache.key = name;
xobjsCache.texts = formTextContent;
}));
return;
case OPS.setGState:
flushTextContentItem();
var dictName = args[0];
var extGState = resources.get('ExtGState');
if (!isDict(extGState) || !isName(dictName)) {
break;
}
var gState = extGState.get(dictName.name);
if (!isDict(gState)) {
break;
}
var gStateFont = gState.get('Font');
if (gStateFont) {
textState.fontName = null;
textState.fontSize = gStateFont[1];
next(handleSetFont(null, gStateFont[0]));
return;
}
break;
} // switch
} // while
if (stop) {
next(deferred);
return;
}
flushTextContentItem();
resolve(textContent);
}).catch((reason) => {
if (this.options.ignoreErrors) {
// Error(s) in the TextContent -- allow text-extraction to continue.
warn('getTextContent - ignoring errors during task: ' + task.name);
flushTextContentItem();
return textContent;
}
throw reason;
});
},
extractDataStructures:
function PartialEvaluator_extractDataStructures(dict, baseDict,
properties) {
var xref = this.xref;
// 9.10.2
var toUnicode = (dict.get('ToUnicode') || baseDict.get('ToUnicode'));
var toUnicodePromise = toUnicode ?
this.readToUnicode(toUnicode) : Promise.resolve(undefined);
if (properties.composite) {
// CIDSystemInfo helps to match CID to glyphs
var cidSystemInfo = dict.get('CIDSystemInfo');
if (isDict(cidSystemInfo)) {
properties.cidSystemInfo = {
registry: cidSystemInfo.get('Registry'),
ordering: cidSystemInfo.get('Ordering'),
supplement: cidSystemInfo.get('Supplement')
};
}
var cidToGidMap = dict.get('CIDToGIDMap');
if (isStream(cidToGidMap)) {
properties.cidToGidMap = this.readCidToGidMap(cidToGidMap);
}
}
// Based on 9.6.6 of the spec the encoding can come from multiple places
// and depends on the font type. The base encoding and differences are
// read here, but the encoding that is actually used is chosen during
// glyph mapping in the font.
// TODO: Loading the built in encoding in the font would allow the
// differences to be merged in here not require us to hold on to it.
var differences = [];
var baseEncodingName = null;
var encoding;
if (dict.has('Encoding')) {
encoding = dict.get('Encoding');
if (isDict(encoding)) {
baseEncodingName = encoding.get('BaseEncoding');
baseEncodingName = (isName(baseEncodingName) ?
baseEncodingName.name : null);
// Load the differences between the base and original
if (encoding.has('Differences')) {
var diffEncoding = encoding.get('Differences');
var index = 0;
for (var j = 0, jj = diffEncoding.length; j < jj; j++) {
var data = xref.fetchIfRef(diffEncoding[j]);
if (isNum(data)) {
index = data;
} else if (isName(data)) {
differences[index++] = data.name;
} else {
error('Invalid entry in \'Differences\' array: ' + data);
}
}
}
} else if (isName(encoding)) {
baseEncodingName = encoding.name;
} else {
error('Encoding is not a Name nor a Dict');
}
// According to table 114 if the encoding is a named encoding it must be
// one of these predefined encodings.
if ((baseEncodingName !== 'MacRomanEncoding' &&
baseEncodingName !== 'MacExpertEncoding' &&
baseEncodingName !== 'WinAnsiEncoding')) {
baseEncodingName = null;
}
}
if (baseEncodingName) {
properties.defaultEncoding = getEncoding(baseEncodingName).slice();
} else {
var isSymbolicFont = !!(properties.flags & FontFlags.Symbolic);
var isNonsymbolicFont = !!(properties.flags & FontFlags.Nonsymbolic);
// According to "Table 114" in section "9.6.6.1 General" (under
// "9.6.6 Character Encoding") of the PDF specification, a Nonsymbolic
// font should use the `StandardEncoding` if no encoding is specified.
encoding = StandardEncoding;
if (properties.type === 'TrueType' && !isNonsymbolicFont) {
encoding = WinAnsiEncoding;
}
// The Symbolic attribute can be misused for regular fonts
// Heuristic: we have to check if the font is a standard one also
if (isSymbolicFont) {
encoding = MacRomanEncoding;
if (!properties.file) {
if (/Symbol/i.test(properties.name)) {
encoding = SymbolSetEncoding;
} else if (/Dingbats/i.test(properties.name)) {
encoding = ZapfDingbatsEncoding;
}
}
}
properties.defaultEncoding = encoding;
}
properties.differences = differences;
properties.baseEncodingName = baseEncodingName;
properties.hasEncoding = !!baseEncodingName || differences.length > 0;
properties.dict = dict;
return toUnicodePromise.then((toUnicode) => {
properties.toUnicode = toUnicode;
return this.buildToUnicode(properties);
}).then(function (toUnicode) {
properties.toUnicode = toUnicode;
return properties;
});
},
/**
* Builds a char code to unicode map based on section 9.10 of the spec.
* @param {Object} properties Font properties object.
* @return {Promise} A Promise that is resolved with a
* {ToUnicodeMap|IdentityToUnicodeMap} object.
*/
buildToUnicode: function PartialEvaluator_buildToUnicode(properties) {
properties.hasIncludedToUnicodeMap =
!!properties.toUnicode && properties.toUnicode.length > 0;
// Section 9.10.2 Mapping Character Codes to Unicode Values
if (properties.hasIncludedToUnicodeMap) {
return Promise.resolve(properties.toUnicode);
}
// According to the spec if the font is a simple font we should only map
// to unicode if the base encoding is MacRoman, MacExpert, or WinAnsi or
// the differences array only contains adobe standard or symbol set names,
// in pratice it seems better to always try to create a toUnicode
// map based of the default encoding.
var toUnicode, charcode, glyphName;
if (!properties.composite /* is simple font */) {
toUnicode = [];
var encoding = properties.defaultEncoding.slice();
var baseEncodingName = properties.baseEncodingName;
// Merge in the differences array.
var differences = properties.differences;
for (charcode in differences) {
glyphName = differences[charcode];
if (glyphName === '.notdef') {
// Skip .notdef to prevent rendering errors, e.g. boxes appearing
// where there should be spaces (fixes issue5256.pdf).
continue;
}
encoding[charcode] = glyphName;
}
var glyphsUnicodeMap = getGlyphsUnicode();
for (charcode in encoding) {
// a) Map the character code to a character name.
glyphName = encoding[charcode];
// b) Look up the character name in the Adobe Glyph List (see the
// Bibliography) to obtain the corresponding Unicode value.
if (glyphName === '') {
continue;
} else if (glyphsUnicodeMap[glyphName] === undefined) {
// (undocumented) c) Few heuristics to recognize unknown glyphs
// NOTE: Adobe Reader does not do this step, but OSX Preview does
var code = 0;
switch (glyphName[0]) {
case 'G': // Gxx glyph
if (glyphName.length === 3) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'g': // g00xx glyph
if (glyphName.length === 5) {
code = parseInt(glyphName.substr(1), 16);
}
break;
case 'C': // Cddd glyph
case 'c': // cddd glyph
if (glyphName.length >= 3) {
code = +glyphName.substr(1);
}
break;
default:
// 'uniXXXX'/'uXXXX{XX}' glyphs
var unicode = getUnicodeForGlyph(glyphName, glyphsUnicodeMap);
if (unicode !== -1) {
code = unicode;
}
}
if (code) {
// If |baseEncodingName| is one the predefined encodings,
// and |code| equals |charcode|, using the glyph defined in the
// baseEncoding seems to yield a better |toUnicode| mapping
// (fixes issue 5070).
if (baseEncodingName && code === +charcode) {
var baseEncoding = getEncoding(baseEncodingName);
if (baseEncoding && (glyphName = baseEncoding[charcode])) {
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
continue;
}
}
toUnicode[charcode] = String.fromCharCode(code);
}
continue;
}
toUnicode[charcode] =
String.fromCharCode(glyphsUnicodeMap[glyphName]);
}
return Promise.resolve(new ToUnicodeMap(toUnicode));
}
// If the font is a composite font that uses one of the predefined CMaps
// listed in Table 118 (except Identity–H and Identity–V) or whose
// descendant CIDFont uses the Adobe-GB1, Adobe-CNS1, Adobe-Japan1, or
// Adobe-Korea1 character collection:
if (properties.composite && (
(properties.cMap.builtInCMap &&
!(properties.cMap instanceof IdentityCMap)) ||
(properties.cidSystemInfo.registry === 'Adobe' &&
(properties.cidSystemInfo.ordering === 'GB1' ||
properties.cidSystemInfo.ordering === 'CNS1' ||
properties.cidSystemInfo.ordering === 'Japan1' ||
properties.cidSystemInfo.ordering === 'Korea1')))) {
// Then:
// a) Map the character code to a character identifier (CID) according
// to the font’s CMap.
// b) Obtain the registry and ordering of the character collection used
// by the font’s CMap (for example, Adobe and Japan1) from its
// CIDSystemInfo dictionary.
var registry = properties.cidSystemInfo.registry;
var ordering = properties.cidSystemInfo.ordering;
// c) Construct a second CMap name by concatenating the registry and
// ordering obtained in step (b) in the format registry–ordering–UCS2
// (for example, Adobe–Japan1–UCS2).
var ucs2CMapName = Name.get(registry + '-' + ordering + '-UCS2');
// d) Obtain the CMap with the name constructed in step (c) (available
// from the ASN Web site; see the Bibliography).
return CMapFactory.create({
encoding: ucs2CMapName,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function (ucs2CMap) {
var cMap = properties.cMap;
toUnicode = [];
cMap.forEach(function(charcode, cid) {
assert(cid <= 0xffff, 'Max size of CID is 65,535');
// e) Map the CID obtained in step (a) according to the CMap
// obtained in step (d), producing a Unicode value.
var ucs2 = ucs2CMap.lookup(cid);
if (ucs2) {
toUnicode[charcode] =
String.fromCharCode((ucs2.charCodeAt(0) << 8) +
ucs2.charCodeAt(1));
}
});
return new ToUnicodeMap(toUnicode);
});
}
// The viewer's choice, just use an identity map.
return Promise.resolve(new IdentityToUnicodeMap(properties.firstChar,
properties.lastChar));
},
readToUnicode: function PartialEvaluator_readToUnicode(toUnicode) {
var cmapObj = toUnicode;
if (isName(cmapObj)) {
return CMapFactory.create({
encoding: cmapObj,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function (cmap) {
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xFFFF);
}
return new ToUnicodeMap(cmap.getMap());
});
} else if (isStream(cmapObj)) {
return CMapFactory.create({
encoding: cmapObj,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function (cmap) {
if (cmap instanceof IdentityCMap) {
return new IdentityToUnicodeMap(0, 0xFFFF);
}
var map = new Array(cmap.length);
// Convert UTF-16BE
// NOTE: cmap can be a sparse array, so use forEach instead of for(;;)
// to iterate over all keys.
cmap.forEach(function(charCode, token) {
var str = [];
for (var k = 0; k < token.length; k += 2) {
var w1 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
if ((w1 & 0xF800) !== 0xD800) { // w1 < 0xD800 || w1 > 0xDFFF
str.push(w1);
continue;
}
k += 2;
var w2 = (token.charCodeAt(k) << 8) | token.charCodeAt(k + 1);
str.push(((w1 & 0x3ff) << 10) + (w2 & 0x3ff) + 0x10000);
}
map[charCode] = String.fromCharCode.apply(String, str);
});
return new ToUnicodeMap(map);
});
}
return Promise.resolve(null);
},
readCidToGidMap: function PartialEvaluator_readCidToGidMap(cidToGidStream) {
// Extract the encoding from the CIDToGIDMap
var glyphsData = cidToGidStream.getBytes();
// Set encoding 0 to later verify the font has an encoding
var result = [];
for (var j = 0, jj = glyphsData.length; j < jj; j++) {
var glyphID = (glyphsData[j++] << 8) | glyphsData[j];
if (glyphID === 0) {
continue;
}
var code = j >> 1;
result[code] = glyphID;
}
return result;
},
extractWidths: function PartialEvaluator_extractWidths(dict, descriptor,
properties) {
var xref = this.xref;
var glyphsWidths = [];
var defaultWidth = 0;
var glyphsVMetrics = [];
var defaultVMetrics;
var i, ii, j, jj, start, code, widths;
if (properties.composite) {
defaultWidth = dict.get('DW') || 1000;
widths = dict.get('W');
if (widths) {
for (i = 0, ii = widths.length; i < ii; i++) {
start = xref.fetchIfRef(widths[i++]);
code = xref.fetchIfRef(widths[i]);
if (isArray(code)) {
for (j = 0, jj = code.length; j < jj; j++) {
glyphsWidths[start++] = xref.fetchIfRef(code[j]);
}
} else {
var width = xref.fetchIfRef(widths[++i]);
for (j = start; j <= code; j++) {
glyphsWidths[j] = width;
}
}
}
}
if (properties.vertical) {
var vmetrics = dict.getArray('DW2') || [880, -1000];
defaultVMetrics = [vmetrics[1], defaultWidth * 0.5, vmetrics[0]];
vmetrics = dict.get('W2');
if (vmetrics) {
for (i = 0, ii = vmetrics.length; i < ii; i++) {
start = xref.fetchIfRef(vmetrics[i++]);
code = xref.fetchIfRef(vmetrics[i]);
if (isArray(code)) {
for (j = 0, jj = code.length; j < jj; j++) {
glyphsVMetrics[start++] = [
xref.fetchIfRef(code[j++]),
xref.fetchIfRef(code[j++]),
xref.fetchIfRef(code[j])
];
}
} else {
var vmetric = [
xref.fetchIfRef(vmetrics[++i]),
xref.fetchIfRef(vmetrics[++i]),
xref.fetchIfRef(vmetrics[++i])
];
for (j = start; j <= code; j++) {
glyphsVMetrics[j] = vmetric;
}
}
}
}
}
} else {
var firstChar = properties.firstChar;
widths = dict.get('Widths');
if (widths) {
j = firstChar;
for (i = 0, ii = widths.length; i < ii; i++) {
glyphsWidths[j++] = xref.fetchIfRef(widths[i]);
}
defaultWidth = (parseFloat(descriptor.get('MissingWidth')) || 0);
} else {
// Trying get the BaseFont metrics (see comment above).
var baseFontName = dict.get('BaseFont');
if (isName(baseFontName)) {
var metrics = this.getBaseFontMetrics(baseFontName.name);
glyphsWidths = this.buildCharCodeToWidth(metrics.widths,
properties);
defaultWidth = metrics.defaultWidth;
}
}
}
// Heuristic: detection of monospace font by checking all non-zero widths
var isMonospace = true;
var firstWidth = defaultWidth;
for (var glyph in glyphsWidths) {
var glyphWidth = glyphsWidths[glyph];
if (!glyphWidth) {
continue;
}
if (!firstWidth) {
firstWidth = glyphWidth;
continue;
}
if (firstWidth !== glyphWidth) {
isMonospace = false;
break;
}
}
if (isMonospace) {
properties.flags |= FontFlags.FixedPitch;
}
properties.defaultWidth = defaultWidth;
properties.widths = glyphsWidths;
properties.defaultVMetrics = defaultVMetrics;
properties.vmetrics = glyphsVMetrics;
},
isSerifFont: function PartialEvaluator_isSerifFont(baseFontName) {
// Simulating descriptor flags attribute
var fontNameWoStyle = baseFontName.split('-')[0];
return (fontNameWoStyle in getSerifFonts()) ||
(fontNameWoStyle.search(/serif/gi) !== -1);
},
getBaseFontMetrics: function PartialEvaluator_getBaseFontMetrics(name) {
var defaultWidth = 0;
var widths = [];
var monospace = false;
var stdFontMap = getStdFontMap();
var lookupName = (stdFontMap[name] || name);
var Metrics = getMetrics();
if (!(lookupName in Metrics)) {
// Use default fonts for looking up font metrics if the passed
// font is not a base font
if (this.isSerifFont(name)) {
lookupName = 'Times-Roman';
} else {
lookupName = 'Helvetica';
}
}
var glyphWidths = Metrics[lookupName];
if (isNum(glyphWidths)) {
defaultWidth = glyphWidths;
monospace = true;
} else {
widths = glyphWidths(); // expand lazy widths array
}
return {
defaultWidth,
monospace,
widths,
};
},
buildCharCodeToWidth:
function PartialEvaluator_bulildCharCodeToWidth(widthsByGlyphName,
properties) {
var widths = Object.create(null);
var differences = properties.differences;
var encoding = properties.defaultEncoding;
for (var charCode = 0; charCode < 256; charCode++) {
if (charCode in differences &&
widthsByGlyphName[differences[charCode]]) {
widths[charCode] = widthsByGlyphName[differences[charCode]];
continue;
}
if (charCode in encoding && widthsByGlyphName[encoding[charCode]]) {
widths[charCode] = widthsByGlyphName[encoding[charCode]];
continue;
}
}
return widths;
},
preEvaluateFont: function PartialEvaluator_preEvaluateFont(dict) {
var baseDict = dict;
var type = dict.get('Subtype');
assert(isName(type), 'invalid font Subtype');
var composite = false;
var uint8array;
if (type.name === 'Type0') {
// If font is a composite
// - get the descendant font
// - set the type according to the descendant font
// - get the FontDescriptor from the descendant font
var df = dict.get('DescendantFonts');
assert(df, 'Descendant fonts are not specified');
dict = (isArray(df) ? this.xref.fetchIfRef(df[0]) : df);
type = dict.get('Subtype');
assert(isName(type), 'invalid font Subtype');
composite = true;
}
var descriptor = dict.get('FontDescriptor');
if (descriptor) {
var hash = new MurmurHash3_64();
var encoding = baseDict.getRaw('Encoding');
if (isName(encoding)) {
hash.update(encoding.name);
} else if (isRef(encoding)) {
hash.update(encoding.toString());
} else if (isDict(encoding)) {
var keys = encoding.getKeys();
for (var i = 0, ii = keys.length; i < ii; i++) {
var entry = encoding.getRaw(keys[i]);
if (isName(entry)) {
hash.update(entry.name);
} else if (isRef(entry)) {
hash.update(entry.toString());
} else if (isArray(entry)) {
// 'Differences' array (fixes bug1157493.pdf).
var diffLength = entry.length, diffBuf = new Array(diffLength);
for (var j = 0; j < diffLength; j++) {
var diffEntry = entry[j];
if (isName(diffEntry)) {
diffBuf[j] = diffEntry.name;
} else if (isNum(diffEntry) || isRef(diffEntry)) {
diffBuf[j] = diffEntry.toString();
}
}
hash.update(diffBuf.join());
}
}
}
var toUnicode = dict.get('ToUnicode') || baseDict.get('ToUnicode');
if (isStream(toUnicode)) {
var stream = toUnicode.str || toUnicode;
uint8array = stream.buffer ?
new Uint8Array(stream.buffer.buffer, 0, stream.bufferLength) :
new Uint8Array(stream.bytes.buffer,
stream.start, stream.end - stream.start);
hash.update(uint8array);
} else if (isName(toUnicode)) {
hash.update(toUnicode.name);
}
var widths = dict.get('Widths') || baseDict.get('Widths');
if (widths) {
uint8array = new Uint8Array(new Uint32Array(widths).buffer);
hash.update(uint8array);
}
}
return {
descriptor,
dict,
baseDict,
composite,
type: type.name,
hash: hash ? hash.hexdigest() : ''
};
},
translateFont: function PartialEvaluator_translateFont(preEvaluatedFont) {
var baseDict = preEvaluatedFont.baseDict;
var dict = preEvaluatedFont.dict;
var composite = preEvaluatedFont.composite;
var descriptor = preEvaluatedFont.descriptor;
var type = preEvaluatedFont.type;
var maxCharIndex = (composite ? 0xFFFF : 0xFF);
var properties;
if (!descriptor) {
if (type === 'Type3') {
// FontDescriptor is only required for Type3 fonts when the document
// is a tagged pdf. Create a barbebones one to get by.
descriptor = new Dict(null);
descriptor.set('FontName', Name.get(type));
descriptor.set('FontBBox', dict.getArray('FontBBox'));
} else {
// Before PDF 1.5 if the font was one of the base 14 fonts, having a
// FontDescriptor was not required.
// This case is here for compatibility.
var baseFontName = dict.get('BaseFont');
assert(isName(baseFontName), 'Base font is not specified');
// Using base font name as a font name.
baseFontName = baseFontName.name.replace(/[,_]/g, '-');
var metrics = this.getBaseFontMetrics(baseFontName);
// Simulating descriptor flags attribute
var fontNameWoStyle = baseFontName.split('-')[0];
var flags =
(this.isSerifFont(fontNameWoStyle) ? FontFlags.Serif : 0) |
(metrics.monospace ? FontFlags.FixedPitch : 0) |
(getSymbolsFonts()[fontNameWoStyle] ? FontFlags.Symbolic :
FontFlags.Nonsymbolic);
properties = {
type,
name: baseFontName,
widths: metrics.widths,
defaultWidth: metrics.defaultWidth,
flags,
firstChar: 0,
lastChar: maxCharIndex
};
return this.extractDataStructures(dict, dict, properties).
then((properties) => {
properties.widths = this.buildCharCodeToWidth(metrics.widths,
properties);
return new Font(baseFontName, null, properties);
});
}
}
// According to the spec if 'FontDescriptor' is declared, 'FirstChar',
// 'LastChar' and 'Widths' should exist too, but some PDF encoders seem
// to ignore this rule when a variant of a standard font is used.
// TODO Fill the width array depending on which of the base font this is
// a variant.
var firstChar = (dict.get('FirstChar') || 0);
var lastChar = (dict.get('LastChar') || maxCharIndex);
var fontName = descriptor.get('FontName');
var baseFont = dict.get('BaseFont');
// Some bad PDFs have a string as the font name.
if (isString(fontName)) {
fontName = Name.get(fontName);
}
if (isString(baseFont)) {
baseFont = Name.get(baseFont);
}
if (type !== 'Type3') {
var fontNameStr = fontName && fontName.name;
var baseFontStr = baseFont && baseFont.name;
if (fontNameStr !== baseFontStr) {
info('The FontDescriptor\'s FontName is "' + fontNameStr +
'" but should be the same as the Font\'s BaseFont "' +
baseFontStr + '"');
// Workaround for cases where e.g. fontNameStr = 'Arial' and
// baseFontStr = 'Arial,Bold' (needed when no font file is embedded).
if (fontNameStr && baseFontStr &&
baseFontStr.indexOf(fontNameStr) === 0) {
fontName = baseFont;
}
}
}
fontName = (fontName || baseFont);
assert(isName(fontName), 'invalid font name');
var fontFile = descriptor.get('FontFile', 'FontFile2', 'FontFile3');
if (fontFile) {
if (fontFile.dict) {
var subtype = fontFile.dict.get('Subtype');
if (subtype) {
subtype = subtype.name;
}
var length1 = fontFile.dict.get('Length1');
var length2 = fontFile.dict.get('Length2');
var length3 = fontFile.dict.get('Length3');
}
}
properties = {
type,
name: fontName.name,
subtype,
file: fontFile,
length1,
length2,
length3,
loadedName: baseDict.loadedName,
composite,
wideChars: composite,
fixedPitch: false,
fontMatrix: (dict.getArray('FontMatrix') || FONT_IDENTITY_MATRIX),
firstChar: firstChar || 0,
lastChar: (lastChar || maxCharIndex),
bbox: descriptor.getArray('FontBBox'),
ascent: descriptor.get('Ascent'),
descent: descriptor.get('Descent'),
xHeight: descriptor.get('XHeight'),
capHeight: descriptor.get('CapHeight'),
flags: descriptor.get('Flags'),
italicAngle: descriptor.get('ItalicAngle'),
coded: false
};
var cMapPromise;
if (composite) {
var cidEncoding = baseDict.get('Encoding');
if (isName(cidEncoding)) {
properties.cidEncoding = cidEncoding.name;
}
cMapPromise = CMapFactory.create({
encoding: cidEncoding,
fetchBuiltInCMap: this.fetchBuiltInCMap,
useCMap: null,
}).then(function (cMap) {
properties.cMap = cMap;
properties.vertical = properties.cMap.vertical;
});
} else {
cMapPromise = Promise.resolve(undefined);
}
return cMapPromise.then(() => {
return this.extractDataStructures(dict, baseDict, properties);
}).then((properties) => {
this.extractWidths(dict, descriptor, properties);
if (type === 'Type3') {
properties.isType3Font = true;
}
return new Font(fontName.name, fontFile, properties);
});
}
};
return PartialEvaluator;
})();
var TranslatedFont = (function TranslatedFontClosure() {
function TranslatedFont(loadedName, font, dict) {
this.loadedName = loadedName;
this.font = font;
this.dict = dict;
this.type3Loaded = null;
this.sent = false;
}
TranslatedFont.prototype = {
send(handler) {
if (this.sent) {
return;
}
var fontData = this.font.exportData();
handler.send('commonobj', [
this.loadedName,
'Font',
fontData
]);
this.sent = true;
},
loadType3Data(evaluator, resources, parentOperatorList, task) {
assert(this.font.isType3Font);
if (this.type3Loaded) {
return this.type3Loaded;
}
// When parsing Type3 glyphs, always ignore them if there are errors.
// Compared to the parsing of e.g. an entire page, it doesn't really
// make sense to only be able to render a Type3 glyph partially.
var type3Options = Object.create(evaluator.options);
type3Options.ignoreErrors = false;
var type3Evaluator = evaluator.clone(type3Options);
var translatedFont = this.font;
var loadCharProcsPromise = Promise.resolve();
var charProcs = this.dict.get('CharProcs');
var fontResources = this.dict.get('Resources') || resources;
var charProcKeys = charProcs.getKeys();
var charProcOperatorList = Object.create(null);
for (var i = 0, n = charProcKeys.length; i < n; ++i) {
let key = charProcKeys[i];
loadCharProcsPromise = loadCharProcsPromise.then(function () {
var glyphStream = charProcs.get(key);
var operatorList = new OperatorList();
return type3Evaluator.getOperatorList({
stream: glyphStream,
task,
resources: fontResources,
operatorList,
}).then(function () {
charProcOperatorList[key] = operatorList.getIR();
// Add the dependencies to the parent operator list so they are
// resolved before sub operator list is executed synchronously.
parentOperatorList.addDependencies(operatorList.dependencies);
}).catch(function(reason) {
warn(`Type3 font resource "${key}" is not available.`);
var operatorList = new OperatorList();
charProcOperatorList[key] = operatorList.getIR();
});
});
}
this.type3Loaded = loadCharProcsPromise.then(function () {
translatedFont.charProcOperatorList = charProcOperatorList;
});
return this.type3Loaded;
}
};
return TranslatedFont;
})();
var OperatorList = (function OperatorListClosure() {
var CHUNK_SIZE = 1000;
var CHUNK_SIZE_ABOUT = CHUNK_SIZE - 5; // close to chunk size
function getTransfers(queue) {
var transfers = [];
var fnArray = queue.fnArray, argsArray = queue.argsArray;
for (var i = 0, ii = queue.length; i < ii; i++) {
switch (fnArray[i]) {
case OPS.paintInlineImageXObject:
case OPS.paintInlineImageXObjectGroup:
case OPS.paintImageMaskXObject:
var arg = argsArray[i][0]; // first param in imgData
if (!arg.cached) {
transfers.push(arg.data.buffer);
}
break;
}
}
return transfers;
}
function OperatorList(intent, messageHandler, pageIndex) {
this.messageHandler = messageHandler;
this.fnArray = [];
this.argsArray = [];
this.dependencies = Object.create(null);
this._totalLength = 0;
this.pageIndex = pageIndex;
this.intent = intent;
}
OperatorList.prototype = {
get length() {
return this.argsArray.length;
},
/**
* @returns {number} The total length of the entire operator list,
* since `this.length === 0` after flushing.
*/
get totalLength() {
return (this._totalLength + this.length);
},
addOp(fn, args) {
this.fnArray.push(fn);
this.argsArray.push(args);
if (this.messageHandler) {
if (this.fnArray.length >= CHUNK_SIZE) {
this.flush();
} else if (this.fnArray.length >= CHUNK_SIZE_ABOUT &&
(fn === OPS.restore || fn === OPS.endText)) {
// heuristic to flush on boundary of restore or endText
this.flush();
}
}
},
addDependency(dependency) {
if (dependency in this.dependencies) {
return;
}
this.dependencies[dependency] = true;
this.addOp(OPS.dependency, [dependency]);
},
addDependencies(dependencies) {
for (var key in dependencies) {
this.addDependency(key);
}
},
addOpList(opList) {
Util.extendObj(this.dependencies, opList.dependencies);
for (var i = 0, ii = opList.length; i < ii; i++) {
this.addOp(opList.fnArray[i], opList.argsArray[i]);
}
},
getIR() {
return {
fnArray: this.fnArray,
argsArray: this.argsArray,
length: this.length
};
},
flush(lastChunk) {
if (this.intent !== 'oplist') {
new QueueOptimizer().optimize(this);
}
var transfers = getTransfers(this);
var length = this.length;
this._totalLength += length;
this.messageHandler.send('RenderPageChunk', {
operatorList: {
fnArray: this.fnArray,
argsArray: this.argsArray,
lastChunk,
length,
},
pageIndex: this.pageIndex,
intent: this.intent
}, transfers);
this.dependencies = Object.create(null);
this.fnArray.length = 0;
this.argsArray.length = 0;
}
};
return OperatorList;
})();
var StateManager = (function StateManagerClosure() {
function StateManager(initialState) {
this.state = initialState;
this.stateStack = [];
}
StateManager.prototype = {
save() {
var old = this.state;
this.stateStack.push(this.state);
this.state = old.clone();
},
restore() {
var prev = this.stateStack.pop();
if (prev) {
this.state = prev;
}
},
transform(args) {
this.state.ctm = Util.transform(this.state.ctm, args);
}
};
return StateManager;
})();
var TextState = (function TextStateClosure() {
function TextState() {
this.ctm = new Float32Array(IDENTITY_MATRIX);
this.fontName = null;
this.fontSize = 0;
this.font = null;
this.fontMatrix = FONT_IDENTITY_MATRIX;
this.textMatrix = IDENTITY_MATRIX.slice();
this.textLineMatrix = IDENTITY_MATRIX.slice();
this.charSpacing = 0;
this.wordSpacing = 0;
this.leading = 0;
this.textHScale = 1;
this.textRise = 0;
}
TextState.prototype = {
setTextMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
var m = this.textMatrix;
m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
},
setTextLineMatrix: function TextState_setTextMatrix(a, b, c, d, e, f) {
var m = this.textLineMatrix;
m[0] = a; m[1] = b; m[2] = c; m[3] = d; m[4] = e; m[5] = f;
},
translateTextMatrix: function TextState_translateTextMatrix(x, y) {
var m = this.textMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
},
translateTextLineMatrix: function TextState_translateTextMatrix(x, y) {
var m = this.textLineMatrix;
m[4] = m[0] * x + m[2] * y + m[4];
m[5] = m[1] * x + m[3] * y + m[5];
},
calcTextLineMatrixAdvance:
function TextState_calcTextLineMatrixAdvance(a, b, c, d, e, f) {
var font = this.font;
if (!font) {
return null;
}
var m = this.textLineMatrix;
if (!(a === m[0] && b === m[1] && c === m[2] && d === m[3])) {
return null;
}
var txDiff = e - m[4], tyDiff = f - m[5];
if ((font.vertical && txDiff !== 0) || (!font.vertical && tyDiff !== 0)) {
return null;
}
var tx, ty, denominator = a * d - b * c;
if (font.vertical) {
tx = -tyDiff * c / denominator;
ty = tyDiff * a / denominator;
} else {
tx = txDiff * d / denominator;
ty = -txDiff * b / denominator;
}
return { width: tx, height: ty, value: (font.vertical ? ty : tx), };
},
calcRenderMatrix: function TextState_calcRendeMatrix(ctm) {
// 9.4.4 Text Space Details
var tsm = [this.fontSize * this.textHScale, 0,
0, this.fontSize,
0, this.textRise];
return Util.transform(ctm, Util.transform(this.textMatrix, tsm));
},
carriageReturn: function TextState_carriageReturn() {
this.translateTextLineMatrix(0, -this.leading);
this.textMatrix = this.textLineMatrix.slice();
},
clone: function TextState_clone() {
var clone = Object.create(this);
clone.textMatrix = this.textMatrix.slice();
clone.textLineMatrix = this.textLineMatrix.slice();
clone.fontMatrix = this.fontMatrix.slice();
return clone;
}
};
return TextState;
})();
var EvalState = (function EvalStateClosure() {
function EvalState() {
this.ctm = new Float32Array(IDENTITY_MATRIX);
this.font = null;
this.textRenderingMode = TextRenderingMode.FILL;
this.fillColorSpace = ColorSpace.singletons.gray;
this.strokeColorSpace = ColorSpace.singletons.gray;
}
EvalState.prototype = {
clone: function CanvasExtraState_clone() {
return Object.create(this);
},
};
return EvalState;
})();
var EvaluatorPreprocessor = (function EvaluatorPreprocessorClosure() {
// Specifies properties for each command
//
// If variableArgs === true: [0, `numArgs`] expected
// If variableArgs === false: exactly `numArgs` expected
var getOPMap = getLookupTableFactory(function (t) {
// Graphic state
t['w'] = { id: OPS.setLineWidth, numArgs: 1, variableArgs: false };
t['J'] = { id: OPS.setLineCap, numArgs: 1, variableArgs: false };
t['j'] = { id: OPS.setLineJoin, numArgs: 1, variableArgs: false };
t['M'] = { id: OPS.setMiterLimit, numArgs: 1, variableArgs: false };
t['d'] = { id: OPS.setDash, numArgs: 2, variableArgs: false };
t['ri'] = { id: OPS.setRenderingIntent, numArgs: 1, variableArgs: false };
t['i'] = { id: OPS.setFlatness, numArgs: 1, variableArgs: false };
t['gs'] = { id: OPS.setGState, numArgs: 1, variableArgs: false };
t['q'] = { id: OPS.save, numArgs: 0, variableArgs: false };
t['Q'] = { id: OPS.restore, numArgs: 0, variableArgs: false };
t['cm'] = { id: OPS.transform, numArgs: 6, variableArgs: false };
// Path
t['m'] = { id: OPS.moveTo, numArgs: 2, variableArgs: false };
t['l'] = { id: OPS.lineTo, numArgs: 2, variableArgs: false };
t['c'] = { id: OPS.curveTo, numArgs: 6, variableArgs: false };
t['v'] = { id: OPS.curveTo2, numArgs: 4, variableArgs: false };
t['y'] = { id: OPS.curveTo3, numArgs: 4, variableArgs: false };
t['h'] = { id: OPS.closePath, numArgs: 0, variableArgs: false };
t['re'] = { id: OPS.rectangle, numArgs: 4, variableArgs: false };
t['S'] = { id: OPS.stroke, numArgs: 0, variableArgs: false };
t['s'] = { id: OPS.closeStroke, numArgs: 0, variableArgs: false };
t['f'] = { id: OPS.fill, numArgs: 0, variableArgs: false };
t['F'] = { id: OPS.fill, numArgs: 0, variableArgs: false };
t['f*'] = { id: OPS.eoFill, numArgs: 0, variableArgs: false };
t['B'] = { id: OPS.fillStroke, numArgs: 0, variableArgs: false };
t['B*'] = { id: OPS.eoFillStroke, numArgs: 0, variableArgs: false };
t['b'] = { id: OPS.closeFillStroke, numArgs: 0, variableArgs: false };
t['b*'] = { id: OPS.closeEOFillStroke, numArgs: 0, variableArgs: false };
t['n'] = { id: OPS.endPath, numArgs: 0, variableArgs: false };
// Clipping
t['W'] = { id: OPS.clip, numArgs: 0, variableArgs: false };
t['W*'] = { id: OPS.eoClip, numArgs: 0, variableArgs: false };
// Text
t['BT'] = { id: OPS.beginText, numArgs: 0, variableArgs: false };
t['ET'] = { id: OPS.endText, numArgs: 0, variableArgs: false };
t['Tc'] = { id: OPS.setCharSpacing, numArgs: 1, variableArgs: false };
t['Tw'] = { id: OPS.setWordSpacing, numArgs: 1, variableArgs: false };
t['Tz'] = { id: OPS.setHScale, numArgs: 1, variableArgs: false };
t['TL'] = { id: OPS.setLeading, numArgs: 1, variableArgs: false };
t['Tf'] = { id: OPS.setFont, numArgs: 2, variableArgs: false };
t['Tr'] = { id: OPS.setTextRenderingMode, numArgs: 1, variableArgs: false };
t['Ts'] = { id: OPS.setTextRise, numArgs: 1, variableArgs: false };
t['Td'] = { id: OPS.moveText, numArgs: 2, variableArgs: false };
t['TD'] = { id: OPS.setLeadingMoveText, numArgs: 2, variableArgs: false };
t['Tm'] = { id: OPS.setTextMatrix, numArgs: 6, variableArgs: false };
t['T*'] = { id: OPS.nextLine, numArgs: 0, variableArgs: false };
t['Tj'] = { id: OPS.showText, numArgs: 1, variableArgs: false };
t['TJ'] = { id: OPS.showSpacedText, numArgs: 1, variableArgs: false };
t['\''] = { id: OPS.nextLineShowText, numArgs: 1, variableArgs: false };
t['"'] = { id: OPS.nextLineSetSpacingShowText, numArgs: 3,
variableArgs: false };
// Type3 fonts
t['d0'] = { id: OPS.setCharWidth, numArgs: 2, variableArgs: false };
t['d1'] = { id: OPS.setCharWidthAndBounds, numArgs: 6,
variableArgs: false };
// Color
t['CS'] = { id: OPS.setStrokeColorSpace, numArgs: 1, variableArgs: false };
t['cs'] = { id: OPS.setFillColorSpace, numArgs: 1, variableArgs: false };
t['SC'] = { id: OPS.setStrokeColor, numArgs: 4, variableArgs: true };
t['SCN'] = { id: OPS.setStrokeColorN, numArgs: 33, variableArgs: true };
t['sc'] = { id: OPS.setFillColor, numArgs: 4, variableArgs: true };
t['scn'] = { id: OPS.setFillColorN, numArgs: 33, variableArgs: true };
t['G'] = { id: OPS.setStrokeGray, numArgs: 1, variableArgs: false };
t['g'] = { id: OPS.setFillGray, numArgs: 1, variableArgs: false };
t['RG'] = { id: OPS.setStrokeRGBColor, numArgs: 3, variableArgs: false };
t['rg'] = { id: OPS.setFillRGBColor, numArgs: 3, variableArgs: false };
t['K'] = { id: OPS.setStrokeCMYKColor, numArgs: 4, variableArgs: false };
t['k'] = { id: OPS.setFillCMYKColor, numArgs: 4, variableArgs: false };
// Shading
t['sh'] = { id: OPS.shadingFill, numArgs: 1, variableArgs: false };
// Images
t['BI'] = { id: OPS.beginInlineImage, numArgs: 0, variableArgs: false };
t['ID'] = { id: OPS.beginImageData, numArgs: 0, variableArgs: false };
t['EI'] = { id: OPS.endInlineImage, numArgs: 1, variableArgs: false };
// XObjects
t['Do'] = { id: OPS.paintXObject, numArgs: 1, variableArgs: false };
t['MP'] = { id: OPS.markPoint, numArgs: 1, variableArgs: false };
t['DP'] = { id: OPS.markPointProps, numArgs: 2, variableArgs: false };
t['BMC'] = { id: OPS.beginMarkedContent, numArgs: 1, variableArgs: false };
t['BDC'] = { id: OPS.beginMarkedContentProps, numArgs: 2,
variableArgs: false };
t['EMC'] = { id: OPS.endMarkedContent, numArgs: 0, variableArgs: false };
// Compatibility
t['BX'] = { id: OPS.beginCompat, numArgs: 0, variableArgs: false };
t['EX'] = { id: OPS.endCompat, numArgs: 0, variableArgs: false };
// (reserved partial commands for the lexer)
t['BM'] = null;
t['BD'] = null;
t['true'] = null;
t['fa'] = null;
t['fal'] = null;
t['fals'] = null;
t['false'] = null;
t['nu'] = null;
t['nul'] = null;
t['null'] = null;
});
function EvaluatorPreprocessor(stream, xref, stateManager) {
this.opMap = getOPMap();
// TODO(mduan): pass array of knownCommands rather than this.opMap
// dictionary
this.parser = new Parser(new Lexer(stream, this.opMap), false, xref);
this.stateManager = stateManager;
this.nonProcessedArgs = [];
}
EvaluatorPreprocessor.prototype = {
get savedStatesDepth() {
return this.stateManager.stateStack.length;
},
// |operation| is an object with two fields:
//
// - |fn| is an out param.
//
// - |args| is an inout param. On entry, it should have one of two values.
//
// - An empty array. This indicates that the caller is providing the
// array in which the args will be stored in. The caller should use
// this value if it can reuse a single array for each call to read().
//
// - |null|. This indicates that the caller needs this function to create
// the array in which any args are stored in. If there are zero args,
// this function will leave |operation.args| as |null| (thus avoiding
// allocations that would occur if we used an empty array to represent
// zero arguments). Otherwise, it will replace |null| with a new array
// containing the arguments. The caller should use this value if it
// cannot reuse an array for each call to read().
//
// These two modes are present because this function is very hot and so
// avoiding allocations where possible is worthwhile.
//
read: function EvaluatorPreprocessor_read(operation) {
var args = operation.args;
while (true) {
var obj = this.parser.getObj();
if (isCmd(obj)) {
var cmd = obj.cmd;
// Check that the command is valid
var opSpec = this.opMap[cmd];
if (!opSpec) {
warn('Unknown command "' + cmd + '"');
continue;
}
var fn = opSpec.id;
var numArgs = opSpec.numArgs;
var argsLength = args !== null ? args.length : 0;
if (!opSpec.variableArgs) {
// Postscript commands can be nested, e.g. /F2 /GS2 gs 5.711 Tf
if (argsLength !== numArgs) {
var nonProcessedArgs = this.nonProcessedArgs;
while (argsLength > numArgs) {
nonProcessedArgs.push(args.shift());
argsLength--;
}
while (argsLength < numArgs && nonProcessedArgs.length !== 0) {
if (args === null) {
args = [];
}
args.unshift(nonProcessedArgs.pop());
argsLength++;
}
}
if (argsLength < numArgs) {
// If we receive too few arguments, it's not possible to execute
// the command, hence we skip the command.
warn('Skipping command ' + fn + ': expected ' + numArgs +
' args, but received ' + argsLength + ' args.');
if (args !== null) {
args.length = 0;
}
continue;
}
} else if (argsLength > numArgs) {
info('Command ' + fn + ': expected [0,' + numArgs +
'] args, but received ' + argsLength + ' args.');
}
// TODO figure out how to type-check vararg functions
this.preprocessCommand(fn, args);
operation.fn = fn;
operation.args = args;
return true;
}
if (isEOF(obj)) {
return false; // no more commands
}
// argument
if (obj !== null) {
if (args === null) {
args = [];
}
args.push(obj);
assert(args.length <= 33, 'Too many arguments');
}
}
},
preprocessCommand:
function EvaluatorPreprocessor_preprocessCommand(fn, args) {
switch (fn | 0) {
case OPS.save:
this.stateManager.save();
break;
case OPS.restore:
this.stateManager.restore();
break;
case OPS.transform:
this.stateManager.transform(args);
break;
}
}
};
return EvaluatorPreprocessor;
})();
var QueueOptimizer = (function QueueOptimizerClosure() {
function addState(parentState, pattern, fn) {
var state = parentState;
for (var i = 0, ii = pattern.length - 1; i < ii; i++) {
var item = pattern[i];
state = (state[item] || (state[item] = []));
}
state[pattern[pattern.length - 1]] = fn;
}
function handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
argsArray) {
// Handles special case of mainly LaTeX documents which use image masks to
// draw lines with the current fill style.
// 'count' groups of (save, transform, paintImageMaskXObject, restore)+
// have been found at iFirstSave.
var iFirstPIMXO = iFirstSave + 2;
for (var i = 0; i < count; i++) {
var arg = argsArray[iFirstPIMXO + 4 * i];
var imageMask = arg.length === 1 && arg[0];
if (imageMask && imageMask.width === 1 && imageMask.height === 1 &&
(!imageMask.data.length ||
(imageMask.data.length === 1 && imageMask.data[0] === 0))) {
fnArray[iFirstPIMXO + 4 * i] = OPS.paintSolidColorImageMask;
continue;
}
break;
}
return count - i;
}
var InitialState = [];
// This replaces (save, transform, paintInlineImageXObject, restore)+
// sequences with one |paintInlineImageXObjectGroup| operation.
addState(InitialState,
[OPS.save, OPS.transform, OPS.paintInlineImageXObject, OPS.restore],
function foundInlineImageGroup(context) {
var MIN_IMAGES_IN_INLINE_IMAGES_BLOCK = 10;
var MAX_IMAGES_IN_INLINE_IMAGES_BLOCK = 200;
var MAX_WIDTH = 1000;
var IMAGE_PADDING = 1;
var fnArray = context.fnArray, argsArray = context.argsArray;
var curr = context.iCurr;
var iFirstSave = curr - 3;
var iFirstTransform = curr - 2;
var iFirstPIIXO = curr - 1;
// Look for the quartets.
var i = iFirstSave + 4;
var ii = fnArray.length;
while (i + 3 < ii) {
if (fnArray[i] !== OPS.save ||
fnArray[i + 1] !== OPS.transform ||
fnArray[i + 2] !== OPS.paintInlineImageXObject ||
fnArray[i + 3] !== OPS.restore) {
break; // ops don't match
}
i += 4;
}
// At this point, i is the index of the first op past the last valid
// quartet.
var count = Math.min((i - iFirstSave) / 4,
MAX_IMAGES_IN_INLINE_IMAGES_BLOCK);
if (count < MIN_IMAGES_IN_INLINE_IMAGES_BLOCK) {
return i;
}
// assuming that heights of those image is too small (~1 pixel)
// packing as much as possible by lines
var maxX = 0;
var map = [], maxLineHeight = 0;
var currentX = IMAGE_PADDING, currentY = IMAGE_PADDING;
var q;
for (q = 0; q < count; q++) {
var transform = argsArray[iFirstTransform + (q << 2)];
var img = argsArray[iFirstPIIXO + (q << 2)][0];
if (currentX + img.width > MAX_WIDTH) {
// starting new line
maxX = Math.max(maxX, currentX);
currentY += maxLineHeight + 2 * IMAGE_PADDING;
currentX = 0;
maxLineHeight = 0;
}
map.push({
transform,
x: currentX, y: currentY,
w: img.width, h: img.height
});
currentX += img.width + 2 * IMAGE_PADDING;
maxLineHeight = Math.max(maxLineHeight, img.height);
}
var imgWidth = Math.max(maxX, currentX) + IMAGE_PADDING;
var imgHeight = currentY + maxLineHeight + IMAGE_PADDING;
var imgData = new Uint8Array(imgWidth * imgHeight * 4);
var imgRowSize = imgWidth << 2;
for (q = 0; q < count; q++) {
var data = argsArray[iFirstPIIXO + (q << 2)][0].data;
// Copy image by lines and extends pixels into padding.
var rowSize = map[q].w << 2;
var dataOffset = 0;
var offset = (map[q].x + map[q].y * imgWidth) << 2;
imgData.set(data.subarray(0, rowSize), offset - imgRowSize);
for (var k = 0, kk = map[q].h; k < kk; k++) {
imgData.set(data.subarray(dataOffset, dataOffset + rowSize), offset);
dataOffset += rowSize;
offset += imgRowSize;
}
imgData.set(data.subarray(dataOffset - rowSize, dataOffset), offset);
while (offset >= 0) {
data[offset - 4] = data[offset];
data[offset - 3] = data[offset + 1];
data[offset - 2] = data[offset + 2];
data[offset - 1] = data[offset + 3];
data[offset + rowSize] = data[offset + rowSize - 4];
data[offset + rowSize + 1] = data[offset + rowSize - 3];
data[offset + rowSize + 2] = data[offset + rowSize - 2];
data[offset + rowSize + 3] = data[offset + rowSize - 1];
offset -= imgRowSize;
}
}
// Replace queue items.
fnArray.splice(iFirstSave, count * 4, OPS.paintInlineImageXObjectGroup);
argsArray.splice(iFirstSave, count * 4,
[{ width: imgWidth, height: imgHeight, kind: ImageKind.RGBA_32BPP,
data: imgData }, map]);
return iFirstSave + 1;
});
// This replaces (save, transform, paintImageMaskXObject, restore)+
// sequences with one |paintImageMaskXObjectGroup| or one
// |paintImageMaskXObjectRepeat| operation.
addState(InitialState,
[OPS.save, OPS.transform, OPS.paintImageMaskXObject, OPS.restore],
function foundImageMaskGroup(context) {
var MIN_IMAGES_IN_MASKS_BLOCK = 10;
var MAX_IMAGES_IN_MASKS_BLOCK = 100;
var MAX_SAME_IMAGES_IN_MASKS_BLOCK = 1000;
var fnArray = context.fnArray, argsArray = context.argsArray;
var curr = context.iCurr;
var iFirstSave = curr - 3;
var iFirstTransform = curr - 2;
var iFirstPIMXO = curr - 1;
// Look for the quartets.
var i = iFirstSave + 4;
var ii = fnArray.length;
while (i + 3 < ii) {
if (fnArray[i] !== OPS.save ||
fnArray[i + 1] !== OPS.transform ||
fnArray[i + 2] !== OPS.paintImageMaskXObject ||
fnArray[i + 3] !== OPS.restore) {
break; // ops don't match
}
i += 4;
}
// At this point, i is the index of the first op past the last valid
// quartet.
var count = (i - iFirstSave) / 4;
count = handlePaintSolidColorImageMask(iFirstSave, count, fnArray,
argsArray);
if (count < MIN_IMAGES_IN_MASKS_BLOCK) {
return i;
}
var q;
var isSameImage = false;
var iTransform, transformArgs;
var firstPIMXOArg0 = argsArray[iFirstPIMXO][0];
if (argsArray[iFirstTransform][1] === 0 &&
argsArray[iFirstTransform][2] === 0) {
isSameImage = true;
var firstTransformArg0 = argsArray[iFirstTransform][0];
var firstTransformArg3 = argsArray[iFirstTransform][3];
iTransform = iFirstTransform + 4;
var iPIMXO = iFirstPIMXO + 4;
for (q = 1; q < count; q++, iTransform += 4, iPIMXO += 4) {
transformArgs = argsArray[iTransform];
if (argsArray[iPIMXO][0] !== firstPIMXOArg0 ||
transformArgs[0] !== firstTransformArg0 ||
transformArgs[1] !== 0 ||
transformArgs[2] !== 0 ||
transformArgs[3] !== firstTransformArg3) {
if (q < MIN_IMAGES_IN_MASKS_BLOCK) {
isSameImage = false;
} else {
count = q;
}
break; // different image or transform
}
}
}
if (isSameImage) {
count = Math.min(count, MAX_SAME_IMAGES_IN_MASKS_BLOCK);
var positions = new Float32Array(count * 2);
iTransform = iFirstTransform;
for (q = 0; q < count; q++, iTransform += 4) {
transformArgs = argsArray[iTransform];
positions[(q << 1)] = transformArgs[4];
positions[(q << 1) + 1] = transformArgs[5];
}
// Replace queue items.
fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectRepeat);
argsArray.splice(iFirstSave, count * 4,
[firstPIMXOArg0, firstTransformArg0, firstTransformArg3, positions]);
} else {
count = Math.min(count, MAX_IMAGES_IN_MASKS_BLOCK);
var images = [];
for (q = 0; q < count; q++) {
transformArgs = argsArray[iFirstTransform + (q << 2)];
var maskParams = argsArray[iFirstPIMXO + (q << 2)][0];
images.push({ data: maskParams.data, width: maskParams.width,
height: maskParams.height,
transform: transformArgs });
}
// Replace queue items.
fnArray.splice(iFirstSave, count * 4, OPS.paintImageMaskXObjectGroup);
argsArray.splice(iFirstSave, count * 4, [images]);
}
return iFirstSave + 1;
});
// This replaces (save, transform, paintImageXObject, restore)+ sequences
// with one paintImageXObjectRepeat operation, if the |transform| and
// |paintImageXObjectRepeat| ops are appropriate.
addState(InitialState,
[OPS.save, OPS.transform, OPS.paintImageXObject, OPS.restore],
function (context) {
var MIN_IMAGES_IN_BLOCK = 3;
var MAX_IMAGES_IN_BLOCK = 1000;
var fnArray = context.fnArray, argsArray = context.argsArray;
var curr = context.iCurr;
var iFirstSave = curr - 3;
var iFirstTransform = curr - 2;
var iFirstPIXO = curr - 1;
var iFirstRestore = curr;
if (argsArray[iFirstTransform][1] !== 0 ||
argsArray[iFirstTransform][2] !== 0) {
return iFirstRestore + 1; // transform has the wrong form
}
// Look for the quartets.
var firstPIXOArg0 = argsArray[iFirstPIXO][0];
var firstTransformArg0 = argsArray[iFirstTransform][0];
var firstTransformArg3 = argsArray[iFirstTransform][3];
var i = iFirstSave + 4;
var ii = fnArray.length;
while (i + 3 < ii) {
if (fnArray[i] !== OPS.save ||
fnArray[i + 1] !== OPS.transform ||
fnArray[i + 2] !== OPS.paintImageXObject ||
fnArray[i + 3] !== OPS.restore) {
break; // ops don't match
}
if (argsArray[i + 1][0] !== firstTransformArg0 ||
argsArray[i + 1][1] !== 0 ||
argsArray[i + 1][2] !== 0 ||
argsArray[i + 1][3] !== firstTransformArg3) {
break; // transforms don't match
}
if (argsArray[i + 2][0] !== firstPIXOArg0) {
break; // images don't match
}
i += 4;
}
// At this point, i is the index of the first op past the last valid
// quartet.
var count = Math.min((i - iFirstSave) / 4, MAX_IMAGES_IN_BLOCK);
if (count < MIN_IMAGES_IN_BLOCK) {
return i;
}
// Extract the (x,y) positions from all of the matching transforms.
var positions = new Float32Array(count * 2);
var iTransform = iFirstTransform;
for (var q = 0; q < count; q++, iTransform += 4) {
var transformArgs = argsArray[iTransform];
positions[(q << 1)] = transformArgs[4];
positions[(q << 1) + 1] = transformArgs[5];
}
// Replace queue items.
var args = [firstPIXOArg0, firstTransformArg0, firstTransformArg3,
positions];
fnArray.splice(iFirstSave, count * 4, OPS.paintImageXObjectRepeat);
argsArray.splice(iFirstSave, count * 4, args);
return iFirstSave + 1;
});
// This replaces (beginText, setFont, setTextMatrix, showText, endText)+
// sequences with (beginText, setFont, (setTextMatrix, showText)+, endText)+
// sequences, if the font for each one is the same.
addState(InitialState,
[OPS.beginText, OPS.setFont, OPS.setTextMatrix, OPS.showText, OPS.endText],
function (context) {
var MIN_CHARS_IN_BLOCK = 3;
var MAX_CHARS_IN_BLOCK = 1000;
var fnArray = context.fnArray, argsArray = context.argsArray;
var curr = context.iCurr;
var iFirstBeginText = curr - 4;
var iFirstSetFont = curr - 3;
var iFirstSetTextMatrix = curr - 2;
var iFirstShowText = curr - 1;
var iFirstEndText = curr;
// Look for the quintets.
var firstSetFontArg0 = argsArray[iFirstSetFont][0];
var firstSetFontArg1 = argsArray[iFirstSetFont][1];
var i = iFirstBeginText + 5;
var ii = fnArray.length;
while (i + 4 < ii) {
if (fnArray[i] !== OPS.beginText ||
fnArray[i + 1] !== OPS.setFont ||
fnArray[i + 2] !== OPS.setTextMatrix ||
fnArray[i + 3] !== OPS.showText ||
fnArray[i + 4] !== OPS.endText) {
break; // ops don't match
}
if (argsArray[i + 1][0] !== firstSetFontArg0 ||
argsArray[i + 1][1] !== firstSetFontArg1) {
break; // fonts don't match
}
i += 5;
}
// At this point, i is the index of the first op past the last valid
// quintet.
var count = Math.min(((i - iFirstBeginText) / 5), MAX_CHARS_IN_BLOCK);
if (count < MIN_CHARS_IN_BLOCK) {
return i;
}
// If the preceding quintet is (<something>, setFont, setTextMatrix,
// showText, endText), include that as well. (E.g. <something> might be
// |dependency|.)
var iFirst = iFirstBeginText;
if (iFirstBeginText >= 4 &&
fnArray[iFirstBeginText - 4] === fnArray[iFirstSetFont] &&
fnArray[iFirstBeginText - 3] === fnArray[iFirstSetTextMatrix] &&
fnArray[iFirstBeginText - 2] === fnArray[iFirstShowText] &&
fnArray[iFirstBeginText - 1] === fnArray[iFirstEndText] &&
argsArray[iFirstBeginText - 4][0] === firstSetFontArg0 &&
argsArray[iFirstBeginText - 4][1] === firstSetFontArg1) {
count++;
iFirst -= 5;
}
// Remove (endText, beginText, setFont) trios.
var iEndText = iFirst + 4;
for (var q = 1; q < count; q++) {
fnArray.splice(iEndText, 3);
argsArray.splice(iEndText, 3);
iEndText += 2;
}
return iEndText + 1;
});
function QueueOptimizer() {}
QueueOptimizer.prototype = {
optimize: function QueueOptimizer_optimize(queue) {
var fnArray = queue.fnArray, argsArray = queue.argsArray;
var context = {
iCurr: 0,
fnArray,
argsArray,
};
var state;
var i = 0, ii = fnArray.length;
while (i < ii) {
state = (state || InitialState)[fnArray[i]];
if (typeof state === 'function') { // we found some handler
context.iCurr = i;
// state() returns the index of the first non-matching op (if we
// didn't match) or the first op past the modified ops (if we did
// match and replace).
i = state(context);
state = undefined; // reset the state machine
ii = context.fnArray.length;
} else {
i++;
}
}
}
};
return QueueOptimizer;
})();
exports.OperatorList = OperatorList;
exports.PartialEvaluator = PartialEvaluator;
}));
|
import angular from 'angular';
import directive from './directive';
import './index.less';
const moduleName = 'cucCloudMonitoring';
angular.module(moduleName, []).directive('cucMonitoringChart', directive);
export default moduleName;
|
function validateForm() {
var nmlengkap = document.forms["myForm"]["nmlengkap"].value;
var notelp = document.forms["myForm"]["notelp"].value;
var tempat = document.forms["myForm"]["tempat"].value;
var tgllahir = document.forms["myForm"]["tgllahir"].value;
var umur = document.forms["myForm"]["umur"].value;
var alamat = document.forms["myForm"]["alamat"].value;
if (nmlengkap == "") {
validasi('Nama Lengkap wajib di isi!', 'warning');
return false;
} else if (tempat == '') {
validasi('Tempat Lahir wajib di isi!', 'warning');
return false;
} else if (notelp == '') {
validasi('NO.Telepon wajib di isi!', 'warning');
return false;
} else if (tgllahir == '') {
validasi('Tanggal Lahir wajib di isi!', 'warning');
return false;
} else if (umur == '') {
validasi('Umur wajib di isi!', 'warning');
return false;
} else if (alamat == '') {
validasi('Alamat wajib di isi!', 'warning');
return false;
}
}
function validasi(judul, status) {
swal.fire({
title: judul,
icon: status,
confirmButtonColor: '#4e73df',
});
}
function fileIsValid(fileName) {
var ext = fileName.match(/\.([^\.]+)$/)[1];
ext = ext.toLowerCase();
var isValid = true;
switch (ext) {
case 'png':
case 'jpeg':
case 'jpg':
case 'tiff':
case 'gif':
case 'tif':
case 'pdf':
break;
default:
this.value = '';
isValid = false;
}
return isValid;
}
function VerifyFileNameAndFileSize() {
var file = document.getElementById('GetFile').files[0];
if (file != null) {
var fileName = file.name;
if (fileIsValid(fileName) == false) {
validasi('Format bukan gambar!', 'warning');
document.getElementById('GetFile').value = null;
return false;
}
var content;
var size = file.size;
if ((size != null) && ((size / (1024 * 1024)) > 3)) {
validasi('Ukuran maximum 1024px', 'warning');
document.getElementById('GetFile').value = null;
return false;
}
var ext = fileName.match(/\.([^\.]+)$/)[1];
ext = ext.toLowerCase();
if (ext == 'pdf') {
$('#pdf').show();
$('#img').hide();
$(".custom-file-label").addClass("selected").html(file.name);
document.getElementById('outputPdf').src = window.URL.createObjectURL(file);
} else {
$('#pdf').hide();
$('#img').show();
$(".custom-file-label").addClass("selected").html(file.name);
document.getElementById('outputImg').src = window.URL.createObjectURL(file);
}
return true;
} else
return false;
}
|
import React,{Component} from 'react'
export default class AboutComponent extends Component{
render(){
return <div>
关...于
</div>
}
}
|
/**
* @name exports
* @summary ClaimInsurance Class
*/
module.exports = class ClaimInsurance {
constructor(opts) {
// Create an object to store all props
Object.defineProperty(this, '__data', { value: {} });
// Define getters and setters as enumerable
Object.defineProperty(this, '_id', {
enumerable: true,
get: () => this.__data._id,
set: value => {
if (value === undefined || value === null) {
return;
}
let Element = require('./element.js');
this.__data._id = new Element(value);
},
});
Object.defineProperty(this, 'id', {
enumerable: true,
get: () => this.__data.id,
set: value => {
if (value === undefined || value === null) {
return;
}
this.__data.id = value;
},
});
Object.defineProperty(this, 'extension', {
enumerable: true,
get: () => this.__data.extension,
set: value => {
if (value === undefined || value === null) {
return;
}
let Extension = require('./extension.js');
this.__data.extension = Array.isArray(value) ? value.map(v => new Extension(v)) : [new Extension(value)];
},
});
Object.defineProperty(this, 'modifierExtension', {
enumerable: true,
get: () => this.__data.modifierExtension,
set: value => {
if (value === undefined || value === null) {
return;
}
let Extension = require('./extension.js');
this.__data.modifierExtension = Array.isArray(value)
? value.map(v => new Extension(v))
: [new Extension(value)];
},
});
Object.defineProperty(this, '_sequence', {
enumerable: true,
get: () => this.__data._sequence,
set: value => {
if (value === undefined || value === null) {
return;
}
let Element = require('./element.js');
this.__data._sequence = new Element(value);
},
});
Object.defineProperty(this, 'sequence', {
enumerable: true,
get: () => this.__data.sequence,
set: value => {
if (value === undefined || value === null) {
return;
}
this.__data.sequence = value;
},
});
Object.defineProperty(this, '_focal', {
enumerable: true,
get: () => this.__data._focal,
set: value => {
if (value === undefined || value === null) {
return;
}
let Element = require('./element.js');
this.__data._focal = new Element(value);
},
});
Object.defineProperty(this, 'focal', {
enumerable: true,
get: () => this.__data.focal,
set: value => {
if (value === undefined || value === null) {
return;
}
this.__data.focal = value;
},
});
Object.defineProperty(this, 'coverage', {
enumerable: true,
get: () => this.__data.coverage,
set: value => {
if (value === undefined || value === null) {
return;
}
let Reference = require('./reference.js');
this.__data.coverage = new Reference(value);
},
});
Object.defineProperty(this, '_businessArrangement', {
enumerable: true,
get: () => this.__data._businessArrangement,
set: value => {
if (value === undefined || value === null) {
return;
}
let Element = require('./element.js');
this.__data._businessArrangement = new Element(value);
},
});
Object.defineProperty(this, 'businessArrangement', {
enumerable: true,
get: () => this.__data.businessArrangement,
set: value => {
if (value === undefined || value === null) {
return;
}
this.__data.businessArrangement = value;
},
});
Object.defineProperty(this, '_preAuthRef', {
enumerable: true,
get: () => this.__data._preAuthRef,
set: value => {
if (value === undefined || value === null) {
return;
}
let Element = require('./element.js');
this.__data._preAuthRef = new Element(value);
},
});
Object.defineProperty(this, 'preAuthRef', {
enumerable: true,
get: () => this.__data.preAuthRef,
set: value => {
if (value === undefined || value === null) {
return;
}
this.__data.preAuthRef = Array.isArray(value) ? value.map(v => v) : [value];
},
});
Object.defineProperty(this, 'claimResponse', {
enumerable: true,
get: () => this.__data.claimResponse,
set: value => {
if (value === undefined || value === null) {
return;
}
let Reference = require('./reference.js');
this.__data.claimResponse = new Reference(value);
},
});
// Merge in any defaults
Object.assign(this, opts);
// Define a default non-writable resourceType property
Object.defineProperty(this, 'resourceType', {
value: 'ClaimInsurance',
enumerable: true,
writable: false,
});
}
static get resourceType() {
return 'ClaimInsurance';
}
toJSON() {
return {
id: this.id,
extension: this.extension && this.extension.map(v => v.toJSON()),
modifierExtension: this.modifierExtension && this.modifierExtension.map(v => v.toJSON()),
_sequence: this._sequence && this._sequence.toJSON(),
sequence: this.sequence,
_focal: this._focal && this._focal.toJSON(),
focal: this.focal,
coverage: this.coverage && this.coverage.toJSON(),
_businessArrangement: this._businessArrangement && this._businessArrangement.toJSON(),
businessArrangement: this.businessArrangement,
_preAuthRef: this._preAuthRef && this._preAuthRef.toJSON(),
preAuthRef: this.preAuthRef,
claimResponse: this.claimResponse && this.claimResponse.toJSON(),
};
}
};
|
/**
* Auto-generated action file for "Microsoft Graph API" API.
*
* Generated at: 2019-08-07T14:53:11.402Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / microsoft-graph-api-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: flowground@telekom.de
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'me.onenote.sectionGroups.sections.parentNotebook.ListSectionGroups'
* Endpoint Path: '/me/onenote/sectionGroups/{sectionGroup-id}/sections/{onenoteSection-id}/parentNotebook/sectionGroups'
* Method: 'get'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"sectionGroup-id",
"onenoteSection-id",
"$top",
"$skip",
"$search",
"$filter",
"$count",
"$orderby",
"$select",
"$expand"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"sectionGroup_id": "sectionGroup-id",
"onenoteSection_id": "onenoteSection-id",
"_top": "$top",
"_skip": "$skip",
"_search": "$search",
"_filter": "$filter",
"_count": "$count",
"_orderby": "$orderby",
"_select": "$select",
"_expand": "$expand"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = undefined;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
let callParams = {
spec: spec,
operationId: 'me.onenote.sectionGroups.sections.parentNotebook.ListSectionGroups',
pathName: '/me/onenote/sectionGroups/{sectionGroup-id}/sections/{onenoteSection-id}/parentNotebook/sectionGroups',
method: 'get',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function mapFieldNames(obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
var book = {
"name": "Ruth",
"numChapters": 4,
"chapters": {
"1": {
"1": "<span class=\"chapternum\">1 </span>Du temps des juges, il y eut une famine dans le pays. Un homme de Bethléhem de Juda partit, avec sa femme et ses deux fils, pour faire un séjour dans le pays de Moab.",
"2": "<sup class=\"versenum\">2 </sup>Le nom de cet homme était Élimélec, celui de sa femme Naomi, et ses deux fils s'appelaient Machlon et Kiljon; ils étaient Éphratiens, de Bethléhem de Juda. Arrivés au pays de Moab, ils y fixèrent leur demeure.",
"3": "<sup class=\"versenum\">3 </sup>Élimélec, mari de Naomi, mourut, et elle resta avec ses deux fils.",
"4": "<sup class=\"versenum\">4 </sup>Ils prirent des femmes Moabites, dont l'une se nommait Orpa, et l'autre Ruth, et ils habitèrent là environ dix ans.",
"5": "<sup class=\"versenum\">5 </sup>Machlon et Kiljon moururent aussi tous les deux, et Naomi resta privée de ses deux fils et de son mari.",
"6": "<sup class=\"versenum\">6 </sup>Puis elle se leva, elle et ses belles-filles, afin de quitter le pays de Moab, car elle apprit au pays de Moab que l'Éternel avait visité son peuple et lui avait donné du pain.",
"7": "<sup class=\"versenum\">7 </sup>Elle sortit du lieu qu'elle habitait, accompagnée de ses deux belles-filles, et elle se mit en route pour retourner dans le pays de Juda.",
"8": "<sup class=\"versenum\">8 </sup>Naomi dit alors à ses deux belles-filles: Allez, retournez chacune à la maison de sa mère! Que l'Éternel use de bonté envers vous, comme vous l'avez fait envers ceux qui sont morts et envers moi!",
"9": "<sup class=\"versenum\">9 </sup>Que l'Éternel vous fasse trouver à chacune du repos dans la maison d'un mari! Et elle les baisa. Elles élevèrent la voix, et pleurèrent;",
"10": "<sup class=\"versenum\">10 </sup>et elles lui dirent: Non, nous irons avec toi vers ton peuple.",
"11": "<sup class=\"versenum\">11 </sup>Naomi, dit: Retournez, mes filles! Pourquoi viendriez-vous avec moi? Ai-je encore dans mon sein des fils qui puissent devenir vos maris?",
"12": "<sup class=\"versenum\">12 </sup>Retournez, mes filles, allez! Je suis trop vieille pour me remarier. Et quand je dirais: J'ai de l'espérance; quand cette nuit même je serais avec un mari, et que j'enfanterais des fils,",
"13": "<sup class=\"versenum\">13 </sup>attendriez-vous pour cela qu'ils eussent grandi, refuseriez-vous pour cela de vous marier? Non, mes filles! car à cause de vous je suis dans une grande affliction de ce que la main de l'Éternel s'est étendue contre moi.",
"14": "<sup class=\"versenum\">14 </sup>Et elles élevèrent la voix, et pleurèrent encore. Orpa baisa sa belle-mère, mais Ruth s'attacha à elle.",
"15": "<sup class=\"versenum\">15 </sup>Naomi dit à Ruth: Voici, ta belle-soeur est retournée vers son peuple et vers ses dieux; retourne, comme ta belle-soeur.",
"16": "<sup class=\"versenum\">16 </sup>Ruth répondit: Ne me presse pas de te laisser, de retourner loin de toi! Où tu iras j'irai, où tu demeureras je demeurerai; ton peuple sera mon peuple, et ton Dieu sera mon Dieu;",
"17": "<sup class=\"versenum\">17 </sup>où tu mourras je mourrai, et j'y serai enterrée. Que l'Éternel me traite dans toute sa rigueur, si autre chose que la mort vient à me séparer de toi!",
"18": "<sup class=\"versenum\">18 </sup>Naomi, la voyant décidée à aller avec elle, cessa ses instances.",
"19": "<sup class=\"versenum\">19 </sup>Elles firent ensemble le voyage jusqu'à leur arrivée à Bethléhem. Et lorsqu'elles entrèrent dans Bethléhem, toute la ville fut émue à cause d'elles, et les femmes disaient: Est-ce là Naomi?",
"20": "<sup class=\"versenum\">20 </sup>Elle leur dit: Ne m'appelez pas Naomi; appelez-moi Mara, car le Tout Puissant m'a remplie d'amertume.",
"21": "<sup class=\"versenum\">21 </sup>J'étais dans l'abondance à mon départ, et l'Éternel me ramène les mains vides. Pourquoi m'appelleriez-vous Naomi, après que l'Éternel s'est prononcé contre moi, et que le Tout Puissant m'a affligée?",
"22": "<sup class=\"versenum\">22 </sup>Ainsi revinrent du pays de Moab Naomi et sa belle-fille, Ruth la Moabite. Elles arrivèrent à Bethléhem au commencement de la moisson des orges."
},
"2": {
"1": "<span class=\"chapternum\">2 </span>Naomi avait un parent de son mari. C'était un homme puissant et riche, de la famille d'Élimélec, et qui se nommait Boaz.",
"2": "<sup class=\"versenum\">2 </sup>Ruth la Moabite dit à Naomi: Laisse-moi, je te prie, aller glaner des épis dans le champ de celui aux yeux duquel je trouverai grâce. Elle lui répondit: Va, ma fille.",
"3": "<sup class=\"versenum\">3 </sup>Elle alla glaner dans un champ, derrière les moissonneurs. Et il se trouva par hasard que la pièce de terre appartenait à Boaz, qui était de la famille d'Élimélec.",
"4": "<sup class=\"versenum\">4 </sup>Et voici, Boaz vint de Bethléhem, et il dit aux moissonneurs: Que l'Éternel soit avec vous! Ils lui répondirent: Que l'Éternel te bénisse!",
"5": "<sup class=\"versenum\">5 </sup>Et Boaz dit à son serviteur chargé de surveiller les moissonneurs: A qui est cette jeune femme?",
"6": "<sup class=\"versenum\">6 </sup>Le serviteur chargé de surveiller les moissonneurs répondit: C'est une jeune femme Moabite, qui est revenue avec Naomi du pays de Moab.",
"7": "<sup class=\"versenum\">7 </sup>Elle a dit: Permettez-moi de glaner et de ramasser des épis entre les gerbes, derrière les moissonneurs. Et depuis ce matin qu'elle est venue, elle a été debout jusqu'à présent, et ne s'est reposée qu'un moment dans la maison.",
"8": "<sup class=\"versenum\">8 </sup>Boaz dit à Ruth: Écoute, ma fille, ne va pas glaner dans un autre champ; ne t'éloigne pas d'ici, et reste avec mes servantes.",
"9": "<sup class=\"versenum\">9 </sup>Regarde où l'on moissonne dans le champ, et va après elles. J'ai défendu à mes serviteurs de te toucher. Et quand tu auras soif, tu iras aux vases, et tu boiras de ce que les serviteurs auront puisé.",
"10": "<sup class=\"versenum\">10 </sup>Alors elle tomba sur sa face et se prosterna contre terre, et elle lui dit: Comment ai-je trouvé grâce à tes yeux, pour que tu t'intéresses à moi, à moi qui suis une étrangère?",
"11": "<sup class=\"versenum\">11 </sup>Boaz lui répondit: On m'a rapporté tout ce que tu as fait pour ta belle-mère depuis la mort de ton mari, et comment tu as quitté ton père et ta mère et le pays de ta naissance, pour aller vers un peuple que tu ne connaissais point auparavant.",
"12": "<sup class=\"versenum\">12 </sup>Que l'Éternel te rende ce que tu as fait, et que ta récompense soit entière de la part de l'Éternel, le Dieu d'Israël, sous les ailes duquel tu es venue te réfugier!",
"13": "<sup class=\"versenum\">13 </sup>Et elle dit: Oh! que je trouve grâce à tes yeux, mon seigneur! Car tu m'as consolée, et tu as parlé au coeur de ta servante. Et pourtant je ne suis pas, moi, comme l'une de tes servantes.",
"14": "<sup class=\"versenum\">14 </sup>Au moment du repas, Boaz dit à Ruth: Approche, mange du pain, et trempe ton morceau dans le vinaigre. Elle s'assit à côté des moissonneurs. On lui donna du grain rôti; elle mangea et se rassasia, et elle garda le reste.",
"15": "<sup class=\"versenum\">15 </sup>Puis elle se leva pour glaner. Boaz donna cet ordre à ses serviteurs: Qu'elle glane aussi entre les gerbes, et ne l'inquiétez pas,",
"16": "<sup class=\"versenum\">16 </sup>et même vous ôterez pour elle des gerbes quelques épis, que vous la laisserez glaner, sans lui faire de reproches.",
"17": "<sup class=\"versenum\">17 </sup>Elle glana dans le champ jusqu'au soir, et elle battit ce qu'elle avait glané. Il y eut environ un épha d'orge.",
"18": "<sup class=\"versenum\">18 </sup>Elle l'emporta et rentra dans la ville, et sa belle-mère vit ce qu'elle avait glané. Elle sortit aussi les restes de son repas, et les lui donna.",
"19": "<sup class=\"versenum\">19 </sup>Sa belle-mère lui dit: Où as-tu glané aujourd'hui, et où as-tu travaillé? Béni soit celui qui s'est intéressé à toi! Et Ruth fit connaître à sa belle mère chez qui elle avait travaillé: L'homme chez qui j'ai travaillé aujourd'hui, dit-elle, s'appelle Boaz.",
"20": "<sup class=\"versenum\">20 </sup>Naomi dit à sa belle-fille: Qu'il soit béni de l'Éternel, qui se montre miséricordieux pour les vivants comme il le fut pour ceux qui sont morts! Cet homme est notre parent, lui dit encore Naomi, il est de ceux qui ont sur nous droit de rachat.",
"21": "<sup class=\"versenum\">21 </sup>Ruth la Moabite ajouta: Il m'a dit aussi: Reste avec mes serviteurs, jusqu'à ce qu'ils aient achevé toute ma moisson.",
"22": "<sup class=\"versenum\">22 </sup>Et Naomi dit à Ruth, sa belle-fille: Il est bon, ma fille, que tu sortes avec ses servantes, et qu'on ne te rencontre pas dans un autre champ.",
"23": "<sup class=\"versenum\">23 </sup>Elle resta donc avec les servantes de Boaz, pour glaner, jusqu'à la fin de la moisson des orges et de la moisson du froment. Et elle demeurait avec sa belle-mère."
},
"3": {
"1": "<span class=\"chapternum\">3 </span>Naomi, sa belle-mère, lui dit: Ma fille, je voudrais assurer ton repos, afin que tu fusses heureuse.",
"2": "<sup class=\"versenum\">2 </sup>Et maintenant Boaz, avec les servantes duquel tu as été, n'est-il pas notre parent? Voici, il doit vanner cette nuit les orges qui sont dans l'aire.",
"3": "<sup class=\"versenum\">3 </sup>Lave-toi et oins-toi, puis remets tes habits, et descends à l'aire. Tu ne te feras pas connaître à lui, jusqu'à ce qu'il ait achevé de manger et de boire.",
"4": "<sup class=\"versenum\">4 </sup>Et quand il ira se coucher, observe le lieu où il se couche. Ensuite va, découvre ses pieds, et couche-toi. Il te dira lui-même ce que tu as à faire.",
"5": "<sup class=\"versenum\">5 </sup>Elle lui répondit: Je ferai tout ce que tu as dit.",
"6": "<sup class=\"versenum\">6 </sup>Elle descendit à l'aire, et fit tout ce qu'avait ordonné sa belle-mère.",
"7": "<sup class=\"versenum\">7 </sup>Boaz mangea et but, et son coeur était joyeux. Il alla se coucher à l'extrémité d'un tas de gerbes. Ruth vint alors tout doucement, découvrit ses pieds, et se coucha.",
"8": "<sup class=\"versenum\">8 </sup>Au milieu de la nuit, cet homme eut une frayeur; il se pencha, et voici, une femme était couchée à ses pieds.",
"9": "<sup class=\"versenum\">9 </sup>Il dit: Qui es-tu? Elle répondit: Je suis Ruth, ta servante; étends ton aile sur ta servante, car tu as droit de rachat.",
"10": "<sup class=\"versenum\">10 </sup>Et il dit: Sois bénie de l'Éternel, ma fille! Ce dernier trait témoigne encore plus en ta faveur que le premier, car tu n'as pas recherché des jeunes gens, pauvres ou riches.",
"11": "<sup class=\"versenum\">11 </sup>Maintenant, ma fille, ne crains point; je ferai pour toi tout ce que tu diras; car toute la porte de mon peuple sait que tu es une femme vertueuse.",
"12": "<sup class=\"versenum\">12 </sup>Il est bien vrai que j'ai droit de rachat, mais il en existe un autre plus proche que moi.",
"13": "<sup class=\"versenum\">13 </sup>Passe ici la nuit. Et demain, s'il veut user envers toi du droit de rachat, à la bonne heure, qu'il le fasse; mais s'il ne lui plaît pas d'en user envers toi, j'en userai, moi, l'Éternel est vivant! Reste couchée jusqu'au matin.",
"14": "<sup class=\"versenum\">14 </sup>Elle resta couchée à ses pieds jusqu'au matin, et elle se leva avant qu'on pût se reconnaître l'un l'autre. Boaz dit: Qu'on ne sache pas qu'une femme est entrée dans l'aire.",
"15": "<sup class=\"versenum\">15 </sup>Et il ajouta: Donne le manteau qui est sur toi, et tiens-le. Elle le tint, et il mesura six mesures d'orge, qu'il chargea sur elle. Puis il rentra dans la ville.",
"16": "<sup class=\"versenum\">16 </sup>Ruth revint auprès de sa belle-mère, et Naomi dit: Est-ce toi, ma fille? Ruth lui raconta tout ce que cet homme avait fait pour elle.",
"17": "<sup class=\"versenum\">17 </sup>Elle dit: Il m'a donné ces six mesures d'orge, en disant: Tu ne retourneras pas à vide vers ta belle-mère.",
"18": "<sup class=\"versenum\">18 </sup>Et Naomi dit: Sois tranquille, ma fille, jusqu'à ce que tu saches comment finira la chose, car cet homme ne se donnera point de repos qu'il n'ait terminé cette affaire aujourd'hui."
},
"4": {
"1": "<span class=\"chapternum\">4 </span>Boaz monta à la porte, et s'y arrêta. Or voici, celui qui avait droit de rachat, et dont Boaz avait parlé, vint à passer. Boaz lui dit: Approche, reste ici, toi un tel. Et il s'approcha, et s'arrêta.",
"2": "<sup class=\"versenum\">2 </sup>Boaz prit alors dix hommes parmi les anciens de la ville, et il dit: Asseyez-vous ici. Et ils s'assirent.",
"3": "<sup class=\"versenum\">3 </sup>Puis il dit à celui qui avait le droit de rachat: Naomi, revenue du pays de Moab, a vendu la pièce de terre qui appartenait à notre frère Élimélec.",
"4": "<sup class=\"versenum\">4 </sup>J'ai cru devoir t'en informer, et te dire: Acquiers-la, en présence des habitants et en présence des anciens de mon peuple. Si tu veux racheter, rachète; mais si tu ne veux pas, déclare-le-moi, afin que je le sache. Car il n'y a personne avant toi qui ait le droit de rachat, et je l'ai après toi. Et il répondit: je rachèterai.",
"5": "<sup class=\"versenum\">5 </sup>Boaz dit: Le jour où tu acquerras le champ de la main de Naomi, tu l'acquerras en même temps de Ruth la Moabite, femme du défunt, pour relever le nom du défunt dans son héritage.",
"6": "<sup class=\"versenum\">6 </sup>Et celui qui avait le droit de rachat répondit: Je ne puis pas racheter pour mon compte, crainte de détruire mon héritage; prends pour toi mon droit de rachat, car je ne puis pas racheter.",
"7": "<sup class=\"versenum\">7 </sup>Autrefois en Israël, pour valider une affaire quelconque relative à un rachat ou à un échange, l'un ôtait son soulier et le donnait à l'autre: cela servait de témoignage en Israël.",
"8": "<sup class=\"versenum\">8 </sup>Celui qui avait le droit de rachat dit donc à Boaz: Acquiers pour ton compte! Et il ôta son soulier.",
"9": "<sup class=\"versenum\">9 </sup>Alors Boaz dit aux anciens et à tout le peuple: Vous êtes témoins aujourd'hui que j'ai acquis de la main de Naomi tout ce qui appartenait à Élimélec, à Kiljon et à Machlon,",
"10": "<sup class=\"versenum\">10 </sup>et que je me suis également acquis pour femme Ruth la Moabite, femme de Machlon, pour relever le nom du défunt dans son héritage, et afin que le nom du défunt ne soit point retranché d'entre ses frères et de la porte de son lieu. Vous en êtes témoins aujourd'hui!",
"11": "<sup class=\"versenum\">11 </sup>Tout le peuple qui était à la porte et les anciens dirent: Nous en sommes témoins! Que l'Éternel rende la femme qui entre dans ta maison semblable à Rachel et à Léa, qui toutes les deux ont bâti la maison d'Israël! Manifeste ta force dans Éphrata, et fais-toi un nom dans Bethléhem!",
"12": "<sup class=\"versenum\">12 </sup>Puisse la postérité que l'Éternel te donnera par cette jeune femme rendre ta maison semblable à la maison de Pérets, qui fut enfanté à Juda par Tamar!",
"13": "<sup class=\"versenum\">13 </sup>Boaz prit Ruth, qui devint sa femme, et il alla vers elle. L'Éternel permit à Ruth de concevoir, et elle enfanta un fils.",
"14": "<sup class=\"versenum\">14 </sup>Les femmes dirent à Naomi: Béni soit l'Éternel, qui ne t'a point laissé manquer aujourd'hui d'un homme ayant droit de rachat, et dont le nom sera célébré en Israël!",
"15": "<sup class=\"versenum\">15 </sup>Cet enfant restaurera ton âme, et sera le soutien de ta vieillesse; car ta belle-fille, qui t'aime, l'a enfanté, elle qui vaut mieux pour toi que sept fils.",
"16": "<sup class=\"versenum\">16 </sup>Naomi prit l'enfant et le mit sur son sein, et elle fut sa garde.",
"17": "<sup class=\"versenum\">17 </sup>Les voisines lui donnèrent un nom, en disant: Un fils est né à Naomi! Et elles l'appelèrent Obed. Ce fut le père d'Isaï père de David.",
"18": "<sup class=\"versenum\">18 </sup>Voici la postérité de Pérets.",
"19": "<sup class=\"versenum\">19 </sup>Pérets engendra Hetsron; Hetsron engendra Ram; Ram engendra Amminadab;",
"20": "<sup class=\"versenum\">20 </sup>Amminadab engendra Nachschon; Nachschon engendra Salmon;",
"21": "<sup class=\"versenum\">21 </sup>Salmon engendra Boaz; Boaz engendra Obed;",
"22": "<sup class=\"versenum\">22 </sup>Obed engendra Isaï; et Isaï engendra David."
}
}
};
module.exports = book;
|
$(function () {
$('#navbar-toggler').on('click', function () {
var nav = $('#ta-left-sidebar');
if (nav.hasClass('in')) {
nav.animate({ 'left': '-260px' }, 300);
nav.removeClass('in');
}
else {
nav.animate({ 'left': '0px' }, 300);
nav.addClass('in');
}
});
});
|
import React from 'react';
import { Chart } from "react-google-charts";
const GeoChart = () => {
const options = {
legend: {
position: "bottom",
alignment: "center",
textStyle: {
color: "#fff",
fontSize: 14
}
},
colorAxis: { colors: ['#00853f', 'black', '#e31b23'] },
animation: {
startup: true,
easing: 'linear',
duration: 1500,
},
tooltip: {
showColorCode: true
},
backgroundColor: '#1e2730',
fontName: "Roboto",
region: '034',
};
return(
<Chart
width={'300px'}
height={'300px'}
chartType="GeoChart"
options={options}
data={[
['Country', 'Popularity'],
['IN', 700],
['IN-TN', 100],
]}
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
mapsApiKey="AIzaSyApGSRs5COo6qvzuX1MO8n5N6VlbUzfiCo"
rootProps={{ 'data-testid': '1' }}
/>
)
}
export default GeoChart;
|
/**
* Demo.js
*
* Released under LGPL License.
* Copyright (c) 1999-2017 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*eslint no-console:0 */
define(
'tinymce.plugins.lists.demo.Demo',
[
'tinymce.core.EditorManager',
'tinymce.plugins.code.Plugin',
'tinymce.plugins.lists.Plugin',
'tinymce.themes.modern.Theme'
],
function (EditorManager, CodePlugin, ListPlugin, ModernTheme) {
return function () {
CodePlugin();
ListPlugin();
ModernTheme();
EditorManager.init({
selector: "textarea.tinymce",
theme: "modern",
skin_url: "../../../../../skins/lightgray/dist/lightgray",
plugins: "lists code",
toolbar: "numlist bullist | outdent indent | code",
height: 600
});
};
}
);
|
var alertType = "$var['jsalert']";
var alerts = new Array();
alerts['csv_import_bad_filetype'] = "$lang['lang_alerts_csv_import_bad_filetype']";
alerts['csv_import_file_oversize'] = "$lang['lang_alerts_csv_import_file_oversize']";
alerts['csv_import_failed'] = "$lang['lang_alerts_csv_import_failed']";
alerts['csv_import_file_empty'] = "$lang['lang_alerts_csv_import_file_empty']";
if (alertType) {
alert(alerts[alertType]);
}
|
import {
call,
put,
takeLatest,
takeEvery,
} from 'redux-saga/effects';
import * as API from '../utils/api';
import Reply from '../models/Reply';
// Actions
export const FETCH_REPLIES = 'FETCH_REPLIES';
export const FETCH_REPLIES_SUCCEEDED = 'FETCH_REPLIES_SUCCEEDED';
export const FETCH_REPLIES_FAILED = 'FETCH_REPLIES_FAILED';
export const FETCH_QUOTE = 'FETCH_QUOTE';
export const FETCH_QUOTE_SUCCEEDED = 'FETCH_QUOTE_SUCCEEDED';
export const FETCH_QUOTE_FAILED = 'FETCH_QUOTE_FAILED';
// Default state
export const defaultState = () => ({
status: 'DONE',
error: null,
totalPage: 0,
title: '',
replies: [],
like: 0,
dislike: 0,
quoteFetchingList: [],
});
// Action creator
export function fetchReplies(payload = {}, meta = {}) {
return ({ type: FETCH_REPLIES, payload, meta });
}
export function fetchQuote(payload = {}, meta = {}) {
return ({ type: FETCH_QUOTE, payload, meta });
}
// Worker
function* doFetchReplies(action) {
try {
const res = yield call(API.fetchReplies, action.payload);
yield put({
type: FETCH_REPLIES_SUCCEEDED,
payload: res,
meta: action.meta,
});
} catch (error) {
yield put({ type: FETCH_REPLIES_FAILED, error, meta: action.meta });
}
}
function* doFetchQuote(action) {
try {
const res = yield call(API.fetchQuote, action.payload);
yield put({
type: FETCH_QUOTE_SUCCEEDED,
payload: res,
meta: action.meta,
});
} catch (error) {
yield put({ type: FETCH_QUOTE_FAILED, error, meta: action.meta });
}
}
export const sagas = [
takeLatest(FETCH_REPLIES, doFetchReplies),
takeEvery(FETCH_QUOTE, doFetchQuote),
];
// Reducer
export default function reducer(state = defaultState(), action) {
switch (action.type) {
case FETCH_REPLIES:
return {
...state,
status: FETCH_REPLIES,
error: null,
replies: [],
};
case FETCH_REPLIES_SUCCEEDED:
return {
...state,
status: 'DONE',
...action.payload,
};
case FETCH_REPLIES_FAILED:
return {
...state,
status: 'ERROR',
error: action.error.message,
};
case FETCH_QUOTE:
return {
...state,
status: FETCH_QUOTE,
quoteFetchingList: [action.payload.quote].concat(state.quoteFetchingList),
error: null,
};
case FETCH_QUOTE_SUCCEEDED:
return {
...state,
status: 'DONE',
quoteFetchingList: state.quoteFetchingList.filter(a => a !== action.meta.quote),
replies: state.replies.map((r) => {
if (r.replyId === action.meta.replyId) {
return Reply({
...r,
content: r.content.replace(`<button data-quote-post-id="${action.meta.quote}" />`, action.payload),
});
}
return r;
}),
};
case FETCH_QUOTE_FAILED:
return {
...state,
status: 'ERROR',
quoteFetchingList: state.quoteFetchingList.filter(a => a !== action.meta.quote),
error: action.error.message,
};
default:
return state;
}
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const create_1 = require("../../../../../path/create");
function Create() {
return new create_1.default('/anggota/jabatan');
}
exports.default = Create;
|
import React from "react"
import siteStyle from './index.module.scss'
import { Helmet } from 'react-helmet'
import Contact from '../components/contactMe'
import About from '../components/about'
import Header from '../components/header'
import Projects from '../components/projects'
import Education from '../components/education'
const Index = () => {
return (
<div className={siteStyle}>
<Helmet title="Michaels-Portfolio">
<link href="https://fonts.googleapis.com/css?family=Blinker&display=swap" rel="stylesheet" />
<link href="https://fonts.googleapis.com/css?family=Carter+One&display=swap" rel="stylesheet" />
</Helmet>
<Header />
<About />
<Education />
<Projects />
<Contact />
</div>
)
}
export default Index
|
const { shim } = require('lib/shim.js');
const { GeolocationReact } = require('lib/geolocation-react.js');
const { PoorManIntervals } = require('lib/poor-man-intervals.js');
const RNFetchBlob = require('rn-fetch-blob').default;
const { generateSecureRandom } = require('react-native-securerandom');
const FsDriverRN = require('lib/fs-driver-rn.js').FsDriverRN;
const urlValidator = require('valid-url');
const { Buffer } = require('buffer');
const { Linking, Platform } = require('react-native');
const mimeUtils = require('lib/mime-utils.js').mime;
const { basename, fileExtension } = require('lib/path-utils.js');
const { uuid } = require('lib/uuid.js');
const Resource = require('lib/models/Resource');
const injectedJs = {
webviewLib: require('lib/rnInjectedJs/webviewLib'),
};
function shimInit() {
shim.Geolocation = GeolocationReact;
shim.setInterval = PoorManIntervals.setInterval;
shim.clearInterval = PoorManIntervals.clearInterval;
shim.sjclModule = require('lib/vendor/sjcl-rn.js');
shim.fsDriver = () => {
if (!shim.fsDriver_) shim.fsDriver_ = new FsDriverRN();
return shim.fsDriver_;
};
shim.randomBytes = async count => {
const randomBytes = await generateSecureRandom(count);
let temp = [];
for (let n in randomBytes) {
if (!randomBytes.hasOwnProperty(n)) continue;
temp.push(randomBytes[n]);
}
return temp;
};
shim.fetch = async function(url, options = null) {
// The native fetch() throws an uncatable error that crashes the app if calling it with an
// invalid URL such as '//.resource' or "http://ocloud. de" so detect if the URL is valid beforehand
// and throw a catchable error.
// Bug: https://github.com/facebook/react-native/issues/7436
const validatedUrl = urlValidator.isUri(url);
if (!validatedUrl) throw new Error(`Not a valid URL: ${url}`);
return shim.fetchWithRetry(() => {
return fetch(validatedUrl, options);
}, options);
};
shim.fetchBlob = async function(url, options) {
if (!options || !options.path) throw new Error('fetchBlob: target file path is missing');
let headers = options.headers ? options.headers : {};
let method = options.method ? options.method : 'GET';
const overwrite = 'overwrite' in options ? options.overwrite : true;
let dirs = RNFetchBlob.fs.dirs;
let localFilePath = options.path;
if (localFilePath.indexOf('/') !== 0) localFilePath = `${dirs.DocumentDir}/${localFilePath}`;
if (!overwrite) {
if (await shim.fsDriver().exists(localFilePath)) {
return { ok: true };
}
}
delete options.path;
delete options.overwrite;
const doFetchBlob = () => {
return RNFetchBlob.config({
path: localFilePath,
}).fetch(method, url, headers);
};
try {
const response = await shim.fetchWithRetry(doFetchBlob, options);
// Returns an object that's roughtly compatible with a standard Response object
let output = {
ok: response.respInfo.status < 400,
path: response.data,
text: response.text,
json: response.json,
status: response.respInfo.status,
headers: response.respInfo.headers,
};
return output;
} catch (error) {
throw new Error(`fetchBlob: ${method} ${url}: ${error.toString()}`);
}
};
shim.uploadBlob = async function(url, options) {
if (!options || !options.path) throw new Error('uploadBlob: source file path is missing');
const headers = options.headers ? options.headers : {};
const method = options.method ? options.method : 'POST';
try {
let response = await RNFetchBlob.fetch(method, url, headers, RNFetchBlob.wrap(options.path));
// Returns an object that's roughtly compatible with a standard Response object
return {
ok: response.respInfo.status < 400,
data: response.data,
text: response.text,
json: response.json,
status: response.respInfo.status,
headers: response.respInfo.headers,
};
} catch (error) {
throw new Error(`uploadBlob: ${method} ${url}: ${error.toString()}`);
}
};
shim.readLocalFileBase64 = async function(path) {
return RNFetchBlob.fs.readFile(path, 'base64');
};
shim.stringByteLength = function(string) {
return Buffer.byteLength(string, 'utf-8');
};
shim.Buffer = Buffer;
shim.openUrl = url => {
Linking.openURL(url);
};
shim.waitForFrame = () => {
return new Promise(function(resolve) {
requestAnimationFrame(function() {
resolve();
});
});
};
shim.mobilePlatform = () => {
return Platform.OS;
};
// NOTE: This is a limited version of createResourceFromPath - unlike the Node version, it
// only really works with images. It does not resize the image either.
shim.createResourceFromPath = async function(filePath, defaultProps = null) {
defaultProps = defaultProps ? defaultProps : {};
const resourceId = defaultProps.id ? defaultProps.id : uuid.create();
const ext = fileExtension(filePath);
let mimeType = mimeUtils.fromFileExtension(ext);
if (!mimeType) mimeType = 'image/jpeg';
let resource = Resource.new();
resource.id = resourceId;
resource.mime = mimeType;
resource.title = basename(filePath);
resource.file_extension = ext;
let targetPath = Resource.fullPath(resource);
await shim.fsDriver().copy(filePath, targetPath);
if (defaultProps) {
resource = Object.assign({}, resource, defaultProps);
}
const itDoes = await shim.fsDriver().waitTillExists(targetPath);
if (!itDoes) throw new Error(`Resource file was not created: ${targetPath}`);
const fileStat = await shim.fsDriver().stat(targetPath);
resource.size = fileStat.size;
resource = await Resource.save(resource, { isNew: true });
return resource;
};
shim.injectedJs = function(name) {
if (!(name in injectedJs)) throw new Error(`Cannot find injectedJs file (add it to "injectedJs" object): ${name}`);
return injectedJs[name];
};
}
module.exports = { shimInit };
|
// THIS FILE IS AUTO GENERATED
import { GenIcon } from '../lib';
export function IoLogoFacebook (props) {
return GenIcon({"tag":"svg","attr":{"viewBox":"0 0 512 512"},"child":[{"tag":"path","attr":{"fillRule":"evenodd","d":"M480 257.35c0-123.7-100.3-224-224-224s-224 100.3-224 224c0 111.8 81.9 204.47 189 221.29V322.12h-56.89v-64.77H221V208c0-56.13 33.45-87.16 84.61-87.16 24.51 0 50.15 4.38 50.15 4.38v55.13H327.5c-27.81 0-36.51 17.26-36.51 35v42h62.12l-9.92 64.77H291v156.54c107.1-16.81 189-109.48 189-221.31z"}}]})(props);
};
|
import {connect} from 'react-redux';
import ProfileView from './ProfileView';
export default connect(
state => {
return {
username: state.get('username'),
description: state.get('description'),
hours: state.get('hours'),
projects: state.get('projects')
};
}
)(ProfileView);
|
import { JSDOM } from 'jsdom';
import Enzyme from 'enzyme';
import Adapter from 'enzyme-adapter-react-16.2';
import { createElementMock } from './setup-canvas-jsdom';
Enzyme.configure({ adapter: new Adapter() });
const dom = new JSDOM('<!DOCTYPE html><html><head></head><body></body></html>', {
useAgent: 'node.js',
});
global.window = dom.window;
global.document = dom.window.document;
global.navigator = dom.window.navigator;
// needed by elements/functions using canvas:
// <Select />, <Axis />, filterTickValuesByWidth
global.document.createElement = createElementMock.bind(
null,
document.createElement.bind(document),
);
// needed by interact.js
global.Element = dom.window.Element;
// needed by <Autosizer />
global.getComputedStyle = dom.window.getComputedStyle.bind(dom.window);
global.HTMLElement = () => {};
|
require('dotenv').config();
const fs = require('fs');
const tough = require('tough-cookie');
const request = require('request-promise');
const Telegraf = require('telegraf');
const bot = new Telegraf(process.env.BOT_API);
const uuidv4 = require('uuid/v4');
const { Signale } = require('signale');
const del = require('del');
const logOptions = {
types: {
debug: {
color: 'blue',
label: 'debug'
}
}
};
const log = new Signale(logOptions);
bot.on('document', ctx => {
if (
ctx.message.document &&
ctx.message.document.mime_type === 'application/pdf'
) {
console.log(ctx.message.document);
let document = ctx.message.document;
bot.telegram.getFileLink(document.file_id).then(data => {
ctx.reply('Received your file.');
log.debug('File URL', data);
let options = {
method: 'GET',
uri: data,
resolveWithFullResponse: true
};
let uuid = uuidv4();
//create temp folder for pdf and pptx
if (!fs.existsSync('./temp/' + uuid)) {
fs.mkdirSync('./temp/' + uuid);
}
let fileName = document.file_name.slice(0,document.file_name.length-4);
//make request to download pdf file
request(options)
.pipe(fs.createWriteStream('./temp/' + uuid + '/' + fileName + '.pdf'))
.on('finish', () => {
//console.log('finish downloading pdf..');
log.success('finish downloading pdf...');
convert('./temp/' + uuid, fileName, ctx);
})
.on('error', error => {
console.log('Error in creating map', error);
//remove folder and tell user error.
});
});
}
});
const convert = (path, fileName, ctx) => {
request({
method: 'POST',
uri: 'https://simplypdf.com/api/convert',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data'
},
formData: {
DynamicFile: fs.createReadStream(path + '/' + fileName + '.pdf'),
OutputFormat: 'PowerPoint'
},
resolveWithFullResponse: true
})
.then(r => {
console.log('response', r.body);
ctx.reply('Converting your pdf.');
let id = JSON.parse(r.body).id;
let cookieValue = r.headers['set-cookie'][0]
.split('=', 2)[1]
.slice(0, 24);
let cookie = new tough.Cookie({
key: 'ASP.NET_SessionId',
value: cookieValue,
domain: 'simplypdf.com',
httpOnly: true
});
let cookiejar = request.jar();
cookiejar.setCookie(cookie, 'https://simplypdf.com');
let options = {
method: 'GET',
uri: 'https://simplypdf.com/api/status/' + id,
headers: {
Accept: 'application/json'
},
jar: cookiejar,
resolveWithFullResponse: true
};
checkStatusAndDownload(ctx, options, cookiejar, path, fileName);
})
.catch(err => {
log.err('error @ converting', err);
ctx.reply('There was an error uploading your file. Please try again.');
});
};
const checkStatusAndDownload = (ctx, options, cookiejar, path, fileName) => {
request(options).then(res => {
console.log('status', res.body);
let status = JSON.parse(res.body).status;
setTimeout(() => {
if (status === 'ready') {
log.success('ppt is ready for download...');
// console.log('ready for download...');
let id = JSON.parse(res.body).id;
let options = {
method: 'GET',
uri: 'https://simplypdf.com/api/download/' + id,
jar: cookiejar,
resolveWithFullResponse: true
};
request(options)
.pipe(fs.createWriteStream(path + '/' + fileName + '.pptx'))
.on('finish', () => {
log.success('finish downloading pptx...');
ctx.reply('finish downloading pptx.');
ctx.replyWithDocument({
source: path + '/' + fileName + '.pptx',
filename: fileName + '.pptx'
})
.then(() => {
del([path]).then(paths => {
log.debug('Deleted files and folders:\n', paths.join('\n'));
});
});
})
.on('error', function(error) {
console.log('Error in creating map', error);
});
} else {
log.error('ppt not ready');
checkStatusAndDownload(ctx, options, cookiejar, path, fileName);
}
}, 5000);
});
};
bot.command('start', ctx => {
ctx.reply(
'I convert PDF to PPTX. Simply drag and drop your PDF file 📎 and magically a PPTX will be sent to you.'
);
});
bot.command('help', ctx => {
ctx.reply(
'/help'
);
});
bot.startPolling();
|
"use strict";
angular.module('app.config', [
'app.metadata',
'app.config.error',
'app.config.http',
'app.config.router',
'app.config.cache',
'app.config.translate',
'app.config.ui'
]).run(function ($log, appRevision) {
$log.info("Application revision is", appRevision);
}).config(function ($compileProvider, isProductionEnvironment) {
// https://docs.angularjs.org/guide/production
$compileProvider.debugInfoEnabled(!isProductionEnvironment);
});
|
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './components'
import './registerServiceWorker'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
|
//! moment.js locale configuration
//! locale : Tunisian Arabic (ar-tn)
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['moment'], factory) :
factory(global.moment)
}(this, function (moment) { 'use strict';
var ar_tn = moment.defineLocale('ar-tn', {
months: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
monthsShort: 'جانفي_فيفري_مارس_أفريل_ماي_جوان_جويلية_أوت_سبتمبر_أكتوبر_نوفمبر_ديسمبر'.split('_'),
weekdays: 'الأحد_الإثنين_الثلاثاء_الأربعاء_الخميس_الجمعة_السبت'.split('_'),
weekdaysShort: 'أحد_إثنين_ثلاثاء_أربعاء_خميس_جمعة_سبت'.split('_'),
weekdaysMin: 'ح_ن_ث_ر_خ_ج_س'.split('_'),
longDateFormat: {
LT: 'HH:mm',
LTS: 'HH:mm:ss',
L: 'DD/MM/YYYY',
LL: 'D MMMM YYYY',
LLL: 'D MMMM YYYY HH:mm',
LLLL: 'dddd D MMMM YYYY HH:mm'
},
calendar: {
sameDay: '[اليوم على الساعة] LT',
nextDay: '[غدا على الساعة] LT',
nextWeek: 'dddd [على الساعة] LT',
lastDay: '[أمس على الساعة] LT',
lastWeek: 'dddd [على الساعة] LT',
sameElse: 'L'
},
relativeTime: {
future: 'في %s',
past: 'منذ %s',
s: 'ثوان',
m: 'دقيقة',
mm: '%d دقائق',
h: 'ساعة',
hh: '%d ساعات',
d: 'يوم',
dd: '%d أيام',
M: 'شهر',
MM: '%d أشهر',
y: 'سنة',
yy: '%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.
}
});
return ar_tn;
}));
|
import React from "react";
const TeamMemberBg = props => (
<svg width="1920.998" height="700" {...props}><defs><linearGradient id="team-bg" x1="0.205" y1="0.399" x2="0.672" y2="0.837" gradientUnits="objectBoundingBox"><stop offset="0" stopColor="#f9e9e3"/><stop offset="1" stopColor="#d0ddee"/></linearGradient></defs><path className="a" d="M18804,641.637l1.4-.767c-.268-3.5-.4-7.026-.4-10.548,0-199,429.8-360.323,960-360.323s960,161.323,960,360.323a138.463,138.463,0,0,1-1.436,19.874c.914.329,1.4.506,1.436.52V1596.4c-.053-.027-6.584-3.651-18.891-8.96a498.865,498.865,0,0,0-55.17-19.714,672.025,672.025,0,0,0-89.182-19.714,802.666,802.666,0,0,0-120.951-8.966c-88.428,0-180.838,13.659-274.664,40.594-26.715,7.669-53.928,16.538-80.885,26.362-28.232,10.283-56.971,21.906-85.416,34.534-29.705,13.189-59.914,27.848-89.779,43.559-31.115,16.37-62.729,34.345-93.961,53.427-20.5,12.525-40.846,24.267-60.465,34.891-19.053,10.321-37.99,19.9-56.289,28.463-17.727,8.3-35.379,15.9-52.461,22.587-16.508,6.46-32.986,12.266-48.975,17.256-15.391,4.8-30.812,8.993-45.84,12.465-14.387,3.327-28.861,6.1-43.035,8.231-13.477,2.031-27.129,3.559-40.574,4.537-12.682.924-25.623,1.393-38.469,1.393-14.3,0-28.529-.551-43.482-1.685-13.326-1.01-26.922-2.463-41.559-4.445-27.635-3.737-54.078-8.69-79.648-13.481h-.016l-1.311-.249c-25.465-4.769-51.789-9.7-78.279-13.33-14.252-1.95-27.432-3.381-40.3-4.375-14.439-1.118-28.123-1.658-41.834-1.658-45.105,0-89.041,6.087-134.318,18.612-12.441,3.44-25.184,7.432-37.881,11.871-13.1,4.575-26.568,9.765-40.029,15.425-13.846,5.822-28.1,12.325-42.379,19.319-14.652,7.178-29.773,15.1-44.951,23.554Z" transform="translate(20724.996 1916.903) rotate(180)"
fill = "url(#team-bg)"
opacity = {0.33}
/></svg>
);
export default TeamMemberBg;
|
'use strict';"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var lang_1 = require('angular2/src/facade/lang');
var exceptions_1 = require('angular2/src/facade/exceptions');
var intl_1 = require('angular2/src/facade/intl');
var core_1 = require('angular2/core');
var invalid_pipe_argument_exception_1 = require('./invalid_pipe_argument_exception');
var defaultLocale = 'en-US';
var _re = lang_1.RegExpWrapper.create('^(\\d+)?\\.((\\d+)(\\-(\\d+))?)?$');
/**
* Internal base class for numeric pipes.
*/
var NumberPipe = (function () {
function NumberPipe() {
}
/** @internal */
NumberPipe._format = function (value, style, digits, currency, currencyAsSymbol) {
if (currency === void 0) { currency = null; }
if (currencyAsSymbol === void 0) { currencyAsSymbol = false; }
if (lang_1.isBlank(value))
return null;
if (!lang_1.isNumber(value)) {
throw new invalid_pipe_argument_exception_1.InvalidPipeArgumentException(NumberPipe, value);
}
var minInt = 1, minFraction = 0, maxFraction = 3;
if (lang_1.isPresent(digits)) {
var parts = lang_1.RegExpWrapper.firstMatch(_re, digits);
if (lang_1.isBlank(parts)) {
throw new exceptions_1.BaseException(digits + " is not a valid digit info for number pipes");
}
if (lang_1.isPresent(parts[1])) {
minInt = lang_1.NumberWrapper.parseIntAutoRadix(parts[1]);
}
if (lang_1.isPresent(parts[3])) {
minFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[3]);
}
if (lang_1.isPresent(parts[5])) {
maxFraction = lang_1.NumberWrapper.parseIntAutoRadix(parts[5]);
}
}
return intl_1.NumberFormatter.format(value, defaultLocale, style, {
minimumIntegerDigits: minInt,
minimumFractionDigits: minFraction,
maximumFractionDigits: maxFraction,
currency: currency,
currencyAsSymbol: currencyAsSymbol
});
};
NumberPipe = __decorate([
lang_1.CONST(),
core_1.Injectable(),
__metadata('design:paramtypes', [])
], NumberPipe);
return NumberPipe;
}());
exports.NumberPipe = NumberPipe;
/**
* WARNING: this pipe uses the Internationalization API.
* Therefore it is only reliable in Chrome and Opera browsers.
*
* Formats a number as local text. i.e. group sizing and separator and other locale-specific
* configurations are based on the active locale.
*
* ### Usage
*
* expression | number[:digitInfo]
*
* where `expression` is a number and `digitInfo` has the following format:
*
* {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
*
* - minIntegerDigits is the minimum number of integer digits to use. Defaults to 1.
* - minFractionDigits is the minimum number of digits after fraction. Defaults to 0.
* - maxFractionDigits is the maximum number of digits after fraction. Defaults to 3.
*
* For more information on the acceptable range for each of these numbers and other
* details see your native internationalization library.
*
* ### Example
*
* {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='NumberPipe'}
*/
var DecimalPipe = (function (_super) {
__extends(DecimalPipe, _super);
function DecimalPipe() {
_super.apply(this, arguments);
}
DecimalPipe.prototype.transform = function (value, digits) {
if (digits === void 0) { digits = null; }
return NumberPipe._format(value, intl_1.NumberFormatStyle.Decimal, digits);
};
DecimalPipe = __decorate([
lang_1.CONST(),
core_1.Pipe({ name: 'number' }),
core_1.Injectable(),
__metadata('design:paramtypes', [])
], DecimalPipe);
return DecimalPipe;
}(NumberPipe));
exports.DecimalPipe = DecimalPipe;
/**
* WARNING: this pipe uses the Internationalization API.
* Therefore it is only reliable in Chrome and Opera browsers.
*
* Formats a number as local percent.
*
* ### Usage
*
* expression | percent[:digitInfo]
*
* For more information about `digitInfo` see {@link DecimalPipe}
*
* ### Example
*
* {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='PercentPipe'}
*/
var PercentPipe = (function (_super) {
__extends(PercentPipe, _super);
function PercentPipe() {
_super.apply(this, arguments);
}
PercentPipe.prototype.transform = function (value, digits) {
if (digits === void 0) { digits = null; }
return NumberPipe._format(value, intl_1.NumberFormatStyle.Percent, digits);
};
PercentPipe = __decorate([
lang_1.CONST(),
core_1.Pipe({ name: 'percent' }),
core_1.Injectable(),
__metadata('design:paramtypes', [])
], PercentPipe);
return PercentPipe;
}(NumberPipe));
exports.PercentPipe = PercentPipe;
/**
* WARNING: this pipe uses the Internationalization API.
* Therefore it is only reliable in Chrome and Opera browsers.
*
* Formats a number as local currency.
*
* ### Usage
*
* expression | currency[:currencyCode[:symbolDisplay[:digitInfo]]]
*
* where `currencyCode` is the ISO 4217 currency code, such as "USD" for the US dollar and
* "EUR" for the euro. `symbolDisplay` is a boolean indicating whether to use the currency
* symbol (e.g. $) or the currency code (e.g. USD) in the output. The default for this value
* is `false`.
* For more information about `digitInfo` see {@link DecimalPipe}
*
* ### Example
*
* {@example core/pipes/ts/number_pipe/number_pipe_example.ts region='CurrencyPipe'}
*/
var CurrencyPipe = (function (_super) {
__extends(CurrencyPipe, _super);
function CurrencyPipe() {
_super.apply(this, arguments);
}
CurrencyPipe.prototype.transform = function (value, currencyCode, symbolDisplay, digits) {
if (currencyCode === void 0) { currencyCode = 'USD'; }
if (symbolDisplay === void 0) { symbolDisplay = false; }
if (digits === void 0) { digits = null; }
return NumberPipe._format(value, intl_1.NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay);
};
CurrencyPipe = __decorate([
lang_1.CONST(),
core_1.Pipe({ name: 'currency' }),
core_1.Injectable(),
__metadata('design:paramtypes', [])
], CurrencyPipe);
return CurrencyPipe;
}(NumberPipe));
exports.CurrencyPipe = CurrencyPipe;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibnVtYmVyX3BpcGUuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJkaWZmaW5nX3BsdWdpbl93cmFwcGVyLW91dHB1dF9wYXRoLUJSSmVyMUo5LnRtcC9hbmd1bGFyMi9zcmMvY29tbW9uL3BpcGVzL251bWJlcl9waXBlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7Ozs7OztBQUFBLHFCQVNPLDBCQUEwQixDQUFDLENBQUE7QUFDbEMsMkJBQThDLGdDQUFnQyxDQUFDLENBQUE7QUFDL0UscUJBQWlELDBCQUEwQixDQUFDLENBQUE7QUFDNUUscUJBQTRELGVBQWUsQ0FBQyxDQUFBO0FBRTVFLGdEQUEyQyxtQ0FBbUMsQ0FBQyxDQUFBO0FBRS9FLElBQUksYUFBYSxHQUFXLE9BQU8sQ0FBQztBQUNwQyxJQUFJLEdBQUcsR0FBRyxvQkFBYSxDQUFDLE1BQU0sQ0FBQyxtQ0FBbUMsQ0FBQyxDQUFDO0FBRXBFOztHQUVHO0FBR0g7SUFBQTtJQWdDQSxDQUFDO0lBL0JDLGdCQUFnQjtJQUNULGtCQUFPLEdBQWQsVUFBZSxLQUFhLEVBQUUsS0FBd0IsRUFBRSxNQUFjLEVBQUUsUUFBdUIsRUFDaEYsZ0JBQWlDO1FBRHdCLHdCQUF1QixHQUF2QixlQUF1QjtRQUNoRixnQ0FBaUMsR0FBakMsd0JBQWlDO1FBQzlDLEVBQUUsQ0FBQyxDQUFDLGNBQU8sQ0FBQyxLQUFLLENBQUMsQ0FBQztZQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUM7UUFDaEMsRUFBRSxDQUFDLENBQUMsQ0FBQyxlQUFRLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQ3JCLE1BQU0sSUFBSSw4REFBNEIsQ0FBQyxVQUFVLEVBQUUsS0FBSyxDQUFDLENBQUM7UUFDNUQsQ0FBQztRQUNELElBQUksTUFBTSxHQUFHLENBQUMsRUFBRSxXQUFXLEdBQUcsQ0FBQyxFQUFFLFdBQVcsR0FBRyxDQUFDLENBQUM7UUFDakQsRUFBRSxDQUFDLENBQUMsZ0JBQVMsQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDdEIsSUFBSSxLQUFLLEdBQUcsb0JBQWEsQ0FBQyxVQUFVLENBQUMsR0FBRyxFQUFFLE1BQU0sQ0FBQyxDQUFDO1lBQ2xELEVBQUUsQ0FBQyxDQUFDLGNBQU8sQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUM7Z0JBQ25CLE1BQU0sSUFBSSwwQkFBYSxDQUFJLE1BQU0sZ0RBQTZDLENBQUMsQ0FBQztZQUNsRixDQUFDO1lBQ0QsRUFBRSxDQUFDLENBQUMsZ0JBQVMsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7Z0JBQ3hCLE1BQU0sR0FBRyxvQkFBYSxDQUFDLGlCQUFpQixDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO1lBQ3JELENBQUM7WUFDRCxFQUFFLENBQUMsQ0FBQyxnQkFBUyxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztnQkFDeEIsV0FBVyxHQUFHLG9CQUFhLENBQUMsaUJBQWlCLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7WUFDMUQsQ0FBQztZQUNELEVBQUUsQ0FBQyxDQUFDLGdCQUFTLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUN4QixXQUFXLEdBQUcsb0JBQWEsQ0FBQyxpQkFBaUIsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztZQUMxRCxDQUFDO1FBQ0gsQ0FBQztRQUNELE1BQU0sQ0FBQyxzQkFBZSxDQUFDLE1BQU0sQ0FBQyxLQUFLLEVBQUUsYUFBYSxFQUFFLEtBQUssRUFBRTtZQUN6RCxvQkFBb0IsRUFBRSxNQUFNO1lBQzVCLHFCQUFxQixFQUFFLFdBQVc7WUFDbEMscUJBQXFCLEVBQUUsV0FBVztZQUNsQyxRQUFRLEVBQUUsUUFBUTtZQUNsQixnQkFBZ0IsRUFBRSxnQkFBZ0I7U0FDbkMsQ0FBQyxDQUFDO0lBQ0wsQ0FBQztJQWpDSDtRQUFDLFlBQUssRUFBRTtRQUNQLGlCQUFVLEVBQUU7O2tCQUFBO0lBaUNiLGlCQUFDO0FBQUQsQ0FBQyxBQWhDRCxJQWdDQztBQWhDWSxrQkFBVSxhQWdDdEIsQ0FBQTtBQUVEOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBeUJHO0FBSUg7SUFBaUMsK0JBQVU7SUFBM0M7UUFBaUMsOEJBQVU7SUFJM0MsQ0FBQztJQUhDLCtCQUFTLEdBQVQsVUFBVSxLQUFVLEVBQUUsTUFBcUI7UUFBckIsc0JBQXFCLEdBQXJCLGFBQXFCO1FBQ3pDLE1BQU0sQ0FBQyxVQUFVLENBQUMsT0FBTyxDQUFDLEtBQUssRUFBRSx3QkFBaUIsQ0FBQyxPQUFPLEVBQUUsTUFBTSxDQUFDLENBQUM7SUFDdEUsQ0FBQztJQU5IO1FBQUMsWUFBSyxFQUFFO1FBQ1AsV0FBSSxDQUFDLEVBQUMsSUFBSSxFQUFFLFFBQVEsRUFBQyxDQUFDO1FBQ3RCLGlCQUFVLEVBQUU7O21CQUFBO0lBS2Isa0JBQUM7QUFBRCxDQUFDLEFBSkQsQ0FBaUMsVUFBVSxHQUkxQztBQUpZLG1CQUFXLGNBSXZCLENBQUE7QUFFRDs7Ozs7Ozs7Ozs7Ozs7O0dBZUc7QUFJSDtJQUFpQywrQkFBVTtJQUEzQztRQUFpQyw4QkFBVTtJQUkzQyxDQUFDO0lBSEMsK0JBQVMsR0FBVCxVQUFVLEtBQVUsRUFBRSxNQUFxQjtRQUFyQixzQkFBcUIsR0FBckIsYUFBcUI7UUFDekMsTUFBTSxDQUFDLFVBQVUsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLHdCQUFpQixDQUFDLE9BQU8sRUFBRSxNQUFNLENBQUMsQ0FBQztJQUN0RSxDQUFDO0lBTkg7UUFBQyxZQUFLLEVBQUU7UUFDUCxXQUFJLENBQUMsRUFBQyxJQUFJLEVBQUUsU0FBUyxFQUFDLENBQUM7UUFDdkIsaUJBQVUsRUFBRTs7bUJBQUE7SUFLYixrQkFBQztBQUFELENBQUMsQUFKRCxDQUFpQyxVQUFVLEdBSTFDO0FBSlksbUJBQVcsY0FJdkIsQ0FBQTtBQUVEOzs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBbUJHO0FBSUg7SUFBa0MsZ0NBQVU7SUFBNUM7UUFBa0MsOEJBQVU7SUFNNUMsQ0FBQztJQUxDLGdDQUFTLEdBQVQsVUFBVSxLQUFVLEVBQUUsWUFBNEIsRUFBRSxhQUE4QixFQUN4RSxNQUFxQjtRQURULDRCQUE0QixHQUE1QixvQkFBNEI7UUFBRSw2QkFBOEIsR0FBOUIscUJBQThCO1FBQ3hFLHNCQUFxQixHQUFyQixhQUFxQjtRQUM3QixNQUFNLENBQUMsVUFBVSxDQUFDLE9BQU8sQ0FBQyxLQUFLLEVBQUUsd0JBQWlCLENBQUMsUUFBUSxFQUFFLE1BQU0sRUFBRSxZQUFZLEVBQ3ZELGFBQWEsQ0FBQyxDQUFDO0lBQzNDLENBQUM7SUFSSDtRQUFDLFlBQUssRUFBRTtRQUNQLFdBQUksQ0FBQyxFQUFDLElBQUksRUFBRSxVQUFVLEVBQUMsQ0FBQztRQUN4QixpQkFBVSxFQUFFOztvQkFBQTtJQU9iLG1CQUFDO0FBQUQsQ0FBQyxBQU5ELENBQWtDLFVBQVUsR0FNM0M7QUFOWSxvQkFBWSxlQU14QixDQUFBIiwic291cmNlc0NvbnRlbnQiOlsiaW1wb3J0IHtcbiAgaXNOdW1iZXIsXG4gIGlzUHJlc2VudCxcbiAgaXNCbGFuayxcbiAgU3RyaW5nV3JhcHBlcixcbiAgTnVtYmVyV3JhcHBlcixcbiAgUmVnRXhwV3JhcHBlcixcbiAgQ09OU1QsXG4gIEZ1bmN0aW9uV3JhcHBlclxufSBmcm9tICdhbmd1bGFyMi9zcmMvZmFjYWRlL2xhbmcnO1xuaW1wb3J0IHtCYXNlRXhjZXB0aW9uLCBXcmFwcGVkRXhjZXB0aW9ufSBmcm9tICdhbmd1bGFyMi9zcmMvZmFjYWRlL2V4Y2VwdGlvbnMnO1xuaW1wb3J0IHtOdW1iZXJGb3JtYXR0ZXIsIE51bWJlckZvcm1hdFN0eWxlfSBmcm9tICdhbmd1bGFyMi9zcmMvZmFjYWRlL2ludGwnO1xuaW1wb3J0IHtJbmplY3RhYmxlLCBQaXBlVHJhbnNmb3JtLCBXcmFwcGVkVmFsdWUsIFBpcGV9IGZyb20gJ2FuZ3VsYXIyL2NvcmUnO1xuXG5pbXBvcnQge0ludmFsaWRQaXBlQXJndW1lbnRFeGNlcHRpb259IGZyb20gJy4vaW52YWxpZF9waXBlX2FyZ3VtZW50X2V4Y2VwdGlvbic7XG5cbnZhciBkZWZhdWx0TG9jYWxlOiBzdHJpbmcgPSAnZW4tVVMnO1xudmFyIF9yZSA9IFJlZ0V4cFdyYXBwZXIuY3JlYXRlKCdeKFxcXFxkKyk/XFxcXC4oKFxcXFxkKykoXFxcXC0oXFxcXGQrKSk/KT8kJyk7XG5cbi8qKlxuICogSW50ZXJuYWwgYmFzZSBjbGFzcyBmb3IgbnVtZXJpYyBwaXBlcy5cbiAqL1xuQENPTlNUKClcbkBJbmplY3RhYmxlKClcbmV4cG9ydCBjbGFzcyBOdW1iZXJQaXBlIHtcbiAgLyoqIEBpbnRlcm5hbCAqL1xuICBzdGF0aWMgX2Zvcm1hdCh2YWx1ZTogbnVtYmVyLCBzdHlsZTogTnVtYmVyRm9ybWF0U3R5bGUsIGRpZ2l0czogc3RyaW5nLCBjdXJyZW5jeTogc3RyaW5nID0gbnVsbCxcbiAgICAgICAgICAgICAgICAgY3VycmVuY3lBc1N5bWJvbDogYm9vbGVhbiA9IGZhbHNlKTogc3RyaW5nIHtcbiAgICBpZiAoaXNCbGFuayh2YWx1ZSkpIHJldHVybiBudWxsO1xuICAgIGlmICghaXNOdW1iZXIodmFsdWUpKSB7XG4gICAgICB0aHJvdyBuZXcgSW52YWxpZFBpcGVBcmd1bWVudEV4Y2VwdGlvbihOdW1iZXJQaXBlLCB2YWx1ZSk7XG4gICAgfVxuICAgIHZhciBtaW5JbnQgPSAxLCBtaW5GcmFjdGlvbiA9IDAsIG1heEZyYWN0aW9uID0gMztcbiAgICBpZiAoaXNQcmVzZW50KGRpZ2l0cykpIHtcbiAgICAgIHZhciBwYXJ0cyA9IFJlZ0V4cFdyYXBwZXIuZmlyc3RNYXRjaChfcmUsIGRpZ2l0cyk7XG4gICAgICBpZiAoaXNCbGFuayhwYXJ0cykpIHtcbiAgICAgICAgdGhyb3cgbmV3IEJhc2VFeGNlcHRpb24oYCR7ZGlnaXRzfSBpcyBub3QgYSB2YWxpZCBkaWdpdCBpbmZvIGZvciBudW1iZXIgcGlwZXNgKTtcbiAgICAgIH1cbiAgICAgIGlmIChpc1ByZXNlbnQocGFydHNbMV0pKSB7ICAvLyBtaW4gaW50ZWdlciBkaWdpdHNcbiAgICAgICAgbWluSW50ID0gTnVtYmVyV3JhcHBlci5wYXJzZUludEF1dG9SYWRpeChwYXJ0c1sxXSk7XG4gICAgICB9XG4gICAgICBpZiAoaXNQcmVzZW50KHBhcnRzWzNdKSkgeyAgLy8gbWluIGZyYWN0aW9uIGRpZ2l0c1xuICAgICAgICBtaW5GcmFjdGlvbiA9IE51bWJlcldyYXBwZXIucGFyc2VJbnRBdXRvUmFkaXgocGFydHNbM10pO1xuICAgICAgfVxuICAgICAgaWYgKGlzUHJlc2VudChwYXJ0c1s1XSkpIHsgIC8vIG1heCBmcmFjdGlvbiBkaWdpdHNcbiAgICAgICAgbWF4RnJhY3Rpb24gPSBOdW1iZXJXcmFwcGVyLnBhcnNlSW50QXV0b1JhZGl4KHBhcnRzWzVdKTtcbiAgICAgIH1cbiAgICB9XG4gICAgcmV0dXJuIE51bWJlckZvcm1hdHRlci5mb3JtYXQodmFsdWUsIGRlZmF1bHRMb2NhbGUsIHN0eWxlLCB7XG4gICAgICBtaW5pbXVtSW50ZWdlckRpZ2l0czogbWluSW50LFxuICAgICAgbWluaW11bUZyYWN0aW9uRGlnaXRzOiBtaW5GcmFjdGlvbixcbiAgICAgIG1heGltdW1GcmFjdGlvbkRpZ2l0czogbWF4RnJhY3Rpb24sXG4gICAgICBjdXJyZW5jeTogY3VycmVuY3ksXG4gICAgICBjdXJyZW5jeUFzU3ltYm9sOiBjdXJyZW5jeUFzU3ltYm9sXG4gICAgfSk7XG4gIH1cbn1cblxuLyoqXG4gKiBXQVJOSU5HOiB0aGlzIHBpcGUgdXNlcyB0aGUgSW50ZXJuYXRpb25hbGl6YXRpb24gQVBJLlxuICogVGhlcmVmb3JlIGl0IGlzIG9ubHkgcmVsaWFibGUgaW4gQ2hyb21lIGFuZCBPcGVyYSBicm93c2Vycy5cbiAqXG4gKiBGb3JtYXRzIGEgbnVtYmVyIGFzIGxvY2FsIHRleHQuIGkuZS4gZ3JvdXAgc2l6aW5nIGFuZCBzZXBhcmF0b3IgYW5kIG90aGVyIGxvY2FsZS1zcGVjaWZpY1xuICogY29uZmlndXJhdGlvbnMgYXJlIGJhc2VkIG9uIHRoZSBhY3RpdmUgbG9jYWxlLlxuICpcbiAqICMjIyBVc2FnZVxuICpcbiAqICAgICBleHByZXNzaW9uIHwgbnVtYmVyWzpkaWdpdEluZm9dXG4gKlxuICogd2hlcmUgYGV4cHJlc3Npb25gIGlzIGEgbnVtYmVyIGFuZCBgZGlnaXRJbmZvYCBoYXMgdGhlIGZvbGxvd2luZyBmb3JtYXQ6XG4gKlxuICogICAgIHttaW5JbnRlZ2VyRGlnaXRzfS57bWluRnJhY3Rpb25EaWdpdHN9LXttYXhGcmFjdGlvbkRpZ2l0c31cbiAqXG4gKiAtIG1pbkludGVnZXJEaWdpdHMgaXMgdGhlIG1pbmltdW0gbnVtYmVyIG9mIGludGVnZXIgZGlnaXRzIHRvIHVzZS4gRGVmYXVsdHMgdG8gMS5cbiAqIC0gbWluRnJhY3Rpb25EaWdpdHMgaXMgdGhlIG1pbmltdW0gbnVtYmVyIG9mIGRpZ2l0cyBhZnRlciBmcmFjdGlvbi4gRGVmYXVsdHMgdG8gMC5cbiAqIC0gbWF4RnJhY3Rpb25EaWdpdHMgaXMgdGhlIG1heGltdW0gbnVtYmVyIG9mIGRpZ2l0cyBhZnRlciBmcmFjdGlvbi4gRGVmYXVsdHMgdG8gMy5cbiAqXG4gKiBGb3IgbW9yZSBpbmZvcm1hdGlvbiBvbiB0aGUgYWNjZXB0YWJsZSByYW5nZSBmb3IgZWFjaCBvZiB0aGVzZSBudW1iZXJzIGFuZCBvdGhlclxuICogZGV0YWlscyBzZWUgeW91ciBuYXRpdmUgaW50ZXJuYXRpb25hbGl6YXRpb24gbGlicmFyeS5cbiAqXG4gKiAjIyMgRXhhbXBsZVxuICpcbiAqIHtAZXhhbXBsZSBjb3JlL3BpcGVzL3RzL251bWJlcl9waXBlL251bWJlcl9waXBlX2V4YW1wbGUudHMgcmVnaW9uPSdOdW1iZXJQaXBlJ31cbiAqL1xuQENPTlNUKClcbkBQaXBlKHtuYW1lOiAnbnVtYmVyJ30pXG5ASW5qZWN0YWJsZSgpXG5leHBvcnQgY2xhc3MgRGVjaW1hbFBpcGUgZXh0ZW5kcyBOdW1iZXJQaXBlIGltcGxlbWVudHMgUGlwZVRyYW5zZm9ybSB7XG4gIHRyYW5zZm9ybSh2YWx1ZTogYW55LCBkaWdpdHM6IHN0cmluZyA9IG51bGwpOiBzdHJpbmcge1xuICAgIHJldHVybiBOdW1iZXJQaXBlLl9mb3JtYXQodmFsdWUsIE51bWJlckZvcm1hdFN0eWxlLkRlY2ltYWwsIGRpZ2l0cyk7XG4gIH1cbn1cblxuLyoqXG4gKiBXQVJOSU5HOiB0aGlzIHBpcGUgdXNlcyB0aGUgSW50ZXJuYXRpb25hbGl6YXRpb24gQVBJLlxuICogVGhlcmVmb3JlIGl0IGlzIG9ubHkgcmVsaWFibGUgaW4gQ2hyb21lIGFuZCBPcGVyYSBicm93c2Vycy5cbiAqXG4gKiBGb3JtYXRzIGEgbnVtYmVyIGFzIGxvY2FsIHBlcmNlbnQuXG4gKlxuICogIyMjIFVzYWdlXG4gKlxuICogICAgIGV4cHJlc3Npb24gfCBwZXJjZW50WzpkaWdpdEluZm9dXG4gKlxuICogRm9yIG1vcmUgaW5mb3JtYXRpb24gYWJvdXQgYGRpZ2l0SW5mb2Agc2VlIHtAbGluayBEZWNpbWFsUGlwZX1cbiAqXG4gKiAjIyMgRXhhbXBsZVxuICpcbiAqIHtAZXhhbXBsZSBjb3JlL3BpcGVzL3RzL251bWJlcl9waXBlL251bWJlcl9waXBlX2V4YW1wbGUudHMgcmVnaW9uPSdQZXJjZW50UGlwZSd9XG4gKi9cbkBDT05TVCgpXG5AUGlwZSh7bmFtZTogJ3BlcmNlbnQnfSlcbkBJbmplY3RhYmxlKClcbmV4cG9ydCBjbGFzcyBQZXJjZW50UGlwZSBleHRlbmRzIE51bWJlclBpcGUgaW1wbGVtZW50cyBQaXBlVHJhbnNmb3JtIHtcbiAgdHJhbnNmb3JtKHZhbHVlOiBhbnksIGRpZ2l0czogc3RyaW5nID0gbnVsbCk6IHN0cmluZyB7XG4gICAgcmV0dXJuIE51bWJlclBpcGUuX2Zvcm1hdCh2YWx1ZSwgTnVtYmVyRm9ybWF0U3R5bGUuUGVyY2VudCwgZGlnaXRzKTtcbiAgfVxufVxuXG4vKipcbiAqIFdBUk5JTkc6IHRoaXMgcGlwZSB1c2VzIHRoZSBJbnRlcm5hdGlvbmFsaXphdGlvbiBBUEkuXG4gKiBUaGVyZWZvcmUgaXQgaXMgb25seSByZWxpYWJsZSBpbiBDaHJvbWUgYW5kIE9wZXJhIGJyb3dzZXJzLlxuICpcbiAqIEZvcm1hdHMgYSBudW1iZXIgYXMgbG9jYWwgY3VycmVuY3kuXG4gKlxuICogIyMjIFVzYWdlXG4gKlxuICogICAgIGV4cHJlc3Npb24gfCBjdXJyZW5jeVs6Y3VycmVuY3lDb2RlWzpzeW1ib2xEaXNwbGF5WzpkaWdpdEluZm9dXV1cbiAqXG4gKiB3aGVyZSBgY3VycmVuY3lDb2RlYCBpcyB0aGUgSVNPIDQyMTcgY3VycmVuY3kgY29kZSwgc3VjaCBhcyBcIlVTRFwiIGZvciB0aGUgVVMgZG9sbGFyIGFuZFxuICogXCJFVVJcIiBmb3IgdGhlIGV1cm8uIGBzeW1ib2xEaXNwbGF5YCBpcyBhIGJvb2xlYW4gaW5kaWNhdGluZyB3aGV0aGVyIHRvIHVzZSB0aGUgY3VycmVuY3lcbiAqIHN5bWJvbCAoZS5nLiAkKSBvciB0aGUgY3VycmVuY3kgY29kZSAoZS5nLiBVU0QpIGluIHRoZSBvdXRwdXQuIFRoZSBkZWZhdWx0IGZvciB0aGlzIHZhbHVlXG4gKiBpcyBgZmFsc2VgLlxuICogRm9yIG1vcmUgaW5mb3JtYXRpb24gYWJvdXQgYGRpZ2l0SW5mb2Agc2VlIHtAbGluayBEZWNpbWFsUGlwZX1cbiAqXG4gKiAjIyMgRXhhbXBsZVxuICpcbiAqIHtAZXhhbXBsZSBjb3JlL3BpcGVzL3RzL251bWJlcl9waXBlL251bWJlcl9waXBlX2V4YW1wbGUudHMgcmVnaW9uPSdDdXJyZW5jeVBpcGUnfVxuICovXG5AQ09OU1QoKVxuQFBpcGUoe25hbWU6ICdjdXJyZW5jeSd9KVxuQEluamVjdGFibGUoKVxuZXhwb3J0IGNsYXNzIEN1cnJlbmN5UGlwZSBleHRlbmRzIE51bWJlclBpcGUgaW1wbGVtZW50cyBQaXBlVHJhbnNmb3JtIHtcbiAgdHJhbnNmb3JtKHZhbHVlOiBhbnksIGN1cnJlbmN5Q29kZTogc3RyaW5nID0gJ1VTRCcsIHN5bWJvbERpc3BsYXk6IGJvb2xlYW4gPSBmYWxzZSxcbiAgICAgICAgICAgIGRpZ2l0czogc3RyaW5nID0gbnVsbCk6IHN0cmluZyB7XG4gICAgcmV0dXJuIE51bWJlclBpcGUuX2Zvcm1hdCh2YWx1ZSwgTnVtYmVyRm9ybWF0U3R5bGUuQ3VycmVuY3ksIGRpZ2l0cywgY3VycmVuY3lDb2RlLFxuICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgc3ltYm9sRGlzcGxheSk7XG4gIH1cbn1cbiJdfQ==
|
'use strict';
module.exports = function(app) {
// Root routing
var core = require('../../app/controllers/core.server.controller');
app.route('/').get(core.index);
app.route('/signin').get(core.signin);
app.route('/signup').get(core.signup);
};
|
/**
* Vietnamese translation for bootstrap-datepicker
* An Vo <https://github.com/anvoz/>
*/
;(function($){
$.fn.datepicker.dates['vi'] = {
days: ["Chủ nhật", "Thứ hai", "Thứ ba", "Thứ tư", "Thứ năm", "Thứ sáu", "Thứ bảy"],
daysShort: ["CN", "Thứ 2", "Thứ 3", "Thứ 4", "Thứ 5", "Thứ 6", "Thứ 7"],
daysMin: ["CN", "T2", "T3", "T4", "T5", "T6", "T7"],
months: ["Tháng 1", "Tháng 2", "Tháng 3", "Tháng 4", "Tháng 5", "Tháng 6", "Tháng 7", "Tháng 8", "Tháng 9", "Tháng 10", "Tháng 11", "Tháng 12"],
monthsShort: ["Th1", "Th2", "Th3", "Th4", "Th5", "Th6", "Th7", "Th8", "Th9", "Th10", "Th11", "Th12"],
today: "Hôm nay",
clear: "Xóa",
format: "dd/mm/yyyy"
};
}(jQuery));
|
var CodeList = {
};
CodeList.initGrid = function()
{
$("#codeFormContainer").kendoWindow({
actions: ["Close"],
draggable: false,
width: "400px",
height: "265px",
title: "Code Detail",
resizable: true,
modal: true,
visible: false
});
$( '#grid' ).kendoGrid(
{
toolbar: kendo.template( $( '#toolbarTemplate' ).html() ),
dataSource: CodeList.getDataSource(),
height: $( window ).height() - 160,
sortable: true,
selectable: 'single',
columns: [
{ field: 'batch_code', title: 'Batch' },
{ field: 'roll_code', title: 'Roll' },
{ field: 'full_code', title: 'Serial Number' },
{ field: 'disposition', title: 'Disposition' },
{ field: 'reseller', title: 'Reseller' },
{ field: 'updated_at', title: 'Updated' }],
change: function( e )
{
CodeList.setSelected( this.select() );
},
dataBound: function( e )
{
CodeList.setSelected( this.select() );
},
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
}
});
}
CodeList.getDataSource = function()
{
return new kendo.data.DataSource(
{
serverPaging: true,
serverSorting: true,
pageSize: 20,
transport:
{
read:
{
url: "/production-partner/getCodes",
dataType: 'json',
data:
{
filters: CodeList.getFilters()
}
}
},
schema:
{
model: CodeList.getModel(),
data: 'data',
total: 'total'
},
sort: { field: 'id', dir: 'desc' }
});
}
CodeList.getModel = function()
{
return kendo.data.Model.define(
{
id: 'id'
});
}
CodeList.getFilters = function()
{
var filters =
{
search: function()
{
return $( '#searchFilter' ).val();
}
}
return filters;
}
CodeList.filterGrid = function()
{
CodeList.getGrid().dataSource.filter({});
}
CodeList.filters = function()
{
var filters = [];
filters.push( { app: 'codes', grid: 'grid', filterName: 'search', filterValue: CodeList.getFilters().search() } );
return filters;
}
CodeList.editCode = function()
{
var uid = ( CodeList.getGrid().select().data() ) ? CodeList.getGrid().select().data().uid : null;
if( uid )
{
var selected = CodeList.getGrid().dataSource.getByUid( uid );
_code_id = selected.id;
CodeList.showCodeForm();
}
}
CodeList.addListeners = function()
{
$( 'table' ).dblclick( CodeList.editCode );
$( '#searchFilter' ).keyup( CodeList.filterGrid );
$( '#searchFilter' ).click( CodeList.filterGrid );
$( '#editButton' ).click( CodeList.editCode );
}
CodeList.setSelected = function( selectedRows )
{
if( selectedRows.length == 1 )
{
$( '#editButton' ).removeClass( 'k-state-disabled' );
}
else
{
$( '#editButton' ).addClass( 'k-state-disabled' );
}
}
CodeList.getGrid = function()
{
return $( '#grid' ).data( 'kendoGrid' );
}
CodeList.showCodeForm = function(){
$("#codeFormContainer").data("kendoWindow").center();
$("#codeFormContainer").data("kendoWindow").open();
$("#codeFormContainer").load( "/production-partner/getCodeForm");
}
CodeList.refreshCodeList = function() {
$( "#codeFormContainer" ).data("kendoWindow").close();
CodeList.filterGrid();
}
$( document ).ready( function()
{
CodeList.initGrid();
CodeList.addListeners();
});
|
import { createStore, applyMiddleware } from 'redux';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import { carToolReducer } from '../reducers/carToolReducers';
export const carToolStore = createStore(
carToolReducer,
composeWithDevTools(applyMiddleware(thunk)),
);
|
export { default as createColorblindFilters } from './createColorblindFilters'
export { colorblindFilterTypes } from './constants'
|
(function () {
"use strict";
$(".left-side").niceScroll({
styler: "fb",
cursorcolor: "#27cce4",
cursorwidth: '3',
cursorborderradius: '10px',
background: '#424f63',
spacebarenabled: false,
cursorborder: '0'
});
$(".left-side").getNiceScroll();
if ($('body').hasClass('left-side-collapsed')) {
$(".left-side").getNiceScroll().hide();
}
// Toggle Left Menu
jQuery('.menu-list > a').click(function () {
var parent = jQuery(this).parent();
var sub = parent.find('> ul');
if (!jQuery('body').hasClass('left-side-collapsed')) {
if (sub.is(':visible')) {
sub.slideUp(200, function () {
parent.removeClass('nav-active');
jQuery('.main-content').css({height: ''});
mainContentHeightAdjust();
});
} else {
visibleSubMenuClose();
parent.addClass('nav-active');
sub.slideDown(200, function () {
mainContentHeightAdjust();
});
}
}
return false;
});
function visibleSubMenuClose() {
jQuery('.menu-list').each(function () {
var t = jQuery(this);
if (t.hasClass('nav-active')) {
t.find('> ul').slideUp(200, function () {
t.removeClass('nav-active');
});
}
});
}
function mainContentHeightAdjust() {
// Adjust main content height
var docHeight = jQuery(document).height();
if (docHeight > jQuery('.main-content').height())
jQuery('.main-content').height(docHeight);
}
// class add mouse hover
jQuery('.custom-nav > li').hover(function () {
jQuery(this).addClass('nav-hover');
}, function () {
jQuery(this).removeClass('nav-hover');
});
// Menu Toggle
jQuery('.toggle-btn').click(function () {
$(".left-side").getNiceScroll().hide();
if ($('body').hasClass('left-side-collapsed')) {
$(".left-side").getNiceScroll().hide();
}
var body = jQuery('body');
var bodyposition = body.css('position');
if (bodyposition != 'relative') {
if (!body.hasClass('left-side-collapsed')) {
body.addClass('left-side-collapsed');
jQuery('.custom-nav ul').attr('style', '');
jQuery(this).addClass('menu-collapsed');
} else {
body.removeClass('left-side-collapsed chat-view');
jQuery('.custom-nav li.active ul').css({display: 'block'});
jQuery(this).removeClass('menu-collapsed');
}
} else {
if (body.hasClass('left-side-show'))
body.removeClass('left-side-show');
else
body.addClass('left-side-show');
mainContentHeightAdjust();
}
});
searchform_reposition();
jQuery(window).resize(function () {
if (jQuery('body').css('position') == 'relative') {
jQuery('body').removeClass('left-side-collapsed');
} else {
jQuery('body').css({left: '', marginRight: ''});
}
searchform_reposition();
});
function searchform_reposition() {
if (jQuery('.searchform').css('position') == 'relative') {
jQuery('.searchform').insertBefore('.left-side-inner .logged-user');
} else {
jQuery('.searchform').insertBefore('.menu-right');
}
}
})(jQuery);
// Dropdowns Script
$(document).ready(function () {
$(document).on('click', function (ev) {
ev.stopImmediatePropagation();
$(".dropdown-toggle").dropdown("active");
});
});
|
import * as React from 'react';
import { Typography } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import Inbox from '@material-ui/icons/Inbox';
import { useTranslate, useListContext, useResourceContext } from 'ra-core';
import inflection from 'inflection';
import { CreateButton } from '../button';
var useStyles = makeStyles(function (theme) { return ({
message: {
textAlign: 'center',
opacity: theme.palette.type === 'light' ? 0.5 : 0.8,
margin: '0 1em',
color: theme.palette.type === 'light'
? 'inherit'
: theme.palette.text.primary,
},
icon: {
width: '9em',
height: '9em',
},
toolbar: {
textAlign: 'center',
marginTop: '2em',
},
}); }, { name: 'RaEmpty' });
var Empty = function (props) {
var basePath = useListContext(props).basePath;
var resource = useResourceContext(props);
var classes = useStyles(props);
var translate = useTranslate();
var resourceName = translate("resources." + resource + ".forcedCaseName", {
smart_count: 0,
_: inflection.humanize(translate("resources." + resource + ".name", {
smart_count: 0,
_: inflection.pluralize(resource),
}), true),
});
var emptyMessage = translate('ra.page.empty', { name: resourceName });
var inviteMessage = translate('ra.page.invite');
return (React.createElement(React.Fragment, null,
React.createElement("div", { className: classes.message },
React.createElement(Inbox, { className: classes.icon }),
React.createElement(Typography, { variant: "h4", paragraph: true }, translate("resources." + resource + ".empty", {
_: emptyMessage,
})),
React.createElement(Typography, { variant: "body1" }, translate("resources." + resource + ".invite", {
_: inviteMessage,
}))),
React.createElement("div", { className: classes.toolbar },
React.createElement(CreateButton, { variant: "contained", basePath: basePath }))));
};
export default Empty;
|
/*************************************************************
*
* MathJax/localization/pl/TeX.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Localization.addTranslation("pl","TeX",{
version: "2.7.3",
isLoaded: true,
strings: {
ExtraOpenMissingClose: "Nadmiarowy nawias otwieraj\u0105cy lub brakuj\u0105cy nawias zamykaj\u0105cy",
ExtraCloseMissingOpen: "Nadmiarowy nawias zamykaj\u0105cy lub brakuj\u0105cy nawias otwieraj\u0105cy",
MissingLeftExtraRight: "Brakuj\u0105cy \\left lub nadmiarowy \\right",
MissingScript: "Brakuj\u0105cy argument dla indeksu dolnego lub g\u00F3rnego",
ExtraLeftMissingRight: "Nadmiarowy \\left lub brakuj\u0105cy \\right",
Misplaced: "\u0179le umiejscowiony %1",
MissingOpenForSub: "Brakuj\u0105cy nawias otwieraj\u0105cy dla indeksu dolnego",
MissingOpenForSup: "Brakuj\u0105cy nawias otwieraj\u0105cy dla indeksu g\u00F3rnego",
AmbiguousUseOf: "Niejednoznaczne u\u017Cycie %1",
EnvBadEnd: "\\begin{%1} zosta\u0142 zako\u0144czony \\end{%2}",
EnvMissingEnd: "Brakuj\u0105ce \\end{%1}",
MissingBoxFor: "Brakuj\u0105ce pude\u0142ko (box) dla %1",
MissingCloseBrace: "Brakuj\u0105cy nawias zamykaj\u0105cy",
UndefinedControlSequence: "Nieznana komenda steruj\u0105ca %1",
DoubleExponent: "Podw\u00F3jna pot\u0119ga: u\u017Cyj nawias\u00F3w, aby unikn\u0105\u0107 niejednoznaczno\u015Bci",
DoubleSubscripts: "Podw\u00F3jny indeks: u\u017Cyj nawias\u00F3w, aby unikn\u0105\u0107 niejednoznaczno\u015Bci",
DoubleExponentPrime: "Znak ' oznacza podw\u00F3jny wyk\u0142adnik: u\u017Cyj nawias\u00F3w, aby unikn\u0105\u0107 niejednoznaczno\u015Bci",
CantUseHash1: "Nie mo\u017Cesz u\u017Cywa\u0107 znaku parametru makra # w trybie matematycznym",
MisplacedMiddle: "%1 musi by\u0107 pomi\u0119dzy \\left i \\right",
MisplacedLimits: "%1 jest dozwolony tylko dla operator\u00F3w",
MisplacedMoveRoot: "%1 mo\u017Ce pojawi\u0107 si\u0119 tylko w ramach korzenia (root)",
MultipleCommand: "Wielokrotny %1",
IntegerArg: "Parametr dla %1 musi by\u0107 liczb\u0105 ca\u0142kowit\u0105",
NotMathMLToken: "%1 nie jest elementem typu token",
InvalidMathMLAttr: "Nieprawid\u0142owy atrybut MathML: %1",
UnknownAttrForElement: "%1 nie jest znanym atrybutem dla %2",
MaxMacroSub1: "Przekroczono maksymaln\u0105 liczb\u0119 wywo\u0142a\u0144 makra; czy wyst\u0119puje rekursywne makro?",
MaxMacroSub2: "Przekroczono maksymaln\u0105 liczb\u0119 zast\u0105pie\u0144 MathJax; czy wyst\u0119puje rekursywne \u015Brodowisko LaTeX?",
MissingArgFor: "Brakuje argumentu dla %1",
ExtraAlignTab: "Nadmiarowy tabulator w \\cases",
BracketMustBeDimension: "Argument w nawiasie dla %1 musi by\u0107 wymiarem",
InvalidEnv: "Nieznana nazwa \u015Brodowiska '%1'",
UnknownEnv: "Nieznane \u015Brodowisko '%1'",
ExtraCloseLooking: "Nadmiarowy nawias zamykaj\u0105cy napotkany w czasie poszukiwania %1",
MissingCloseBracket: "Nie odnaleziono zamykaj\u0105cego nawiasu ']' dla argumentu dla %1",
MissingOrUnrecognizedDelim: "Nieodnaleziony lub nierozpoznany separator dla %1",
MissingDimOrUnits: "Brakuje wymiaru lub jego jednostki dla %1",
TokenNotFoundForCommand: "Nie odnaleziono %1 dla %2",
MathNotTerminated: "Nie odnaleziono zako\u0144czenia w polu tekstowym",
IllegalMacroParam: "Nieprawid\u0142owa referencja do parametru makra",
MaxBufferSize: "Przekroczono rozmiar bufora MathJax, czy istnieje rekursywne wywo\u0142anie makra?",
CommandNotAllowedInEnv: "%1 nie jest dozwolony w \u015Brodowisku %2",
MultipleLabel: "Wielokrotna definicja etykiety '%1'",
CommandAtTheBeginingOfLine: "%1 musi znajdowa\u0107 si\u0119 na pocz\u0105tku linii",
IllegalAlign: "Nieprawid\u0142owy argument dla %1",
BadMathStyleFor: "B\u0142\u0119dny styl dla %1",
PositiveIntegerArg: "Argument dla %1 musi by\u0107 dodatni\u0105 liczb\u0105 ca\u0142kowit\u0105",
ErroneousNestingEq: "B\u0142\u0119dne zagnie\u017Cd\u017Cenie wyra\u017Ce\u0144",
MultlineRowsOneCol: "Wiersze w \u015Brodowisku %1 musz\u0105 mie\u0107 dok\u0142adnie jedn\u0105 kolumn\u0119",
MultipleBBoxProperty: "%1 okre\u015Blony dwa razy w %2",
InvalidBBoxProperty: "'%1' nie jest kolorem, wielko\u015Bci\u0105 odst\u0119pu, ani stylem",
ExtraEndMissingBegin: "Nadmiarowy %1 lub brakuj\u0105cy \\begingroup",
GlobalNotFollowedBy: "Po %1 nie wyst\u0119puje \\let, \\def, ani \\newcommand",
UndefinedColorModel: "Przestrze\u0144 barw '%1' nie jest zdefiniowana",
ModelArg1: "Warto\u015Bci kolor\u00F3w dla przestrzeni %1 wymagaj\u0105 3 liczb",
InvalidDecimalNumber: "Nieprawid\u0142owe liczba dziesi\u0119tna",
ModelArg2: "Warto\u015Bci kolor\u00F3w dla przestrzeni %1 musz\u0105 by\u0107 pomi\u0119dzy %2 i %3",
InvalidNumber: "B\u0142\u0119dna liczba",
NewextarrowArg1: "Pierwszy argument dla %1 musi by\u0107 nazw\u0105 sekwencji kontrolnej",
NewextarrowArg2: "Drugi argumentem dla %1 musz\u0105 by\u0107 dwie liczby ca\u0142kowite oddzielone przecinkiem",
NewextarrowArg3: "Trzeci argument dla %1 musi by\u0107 numerem znaku unicode",
NoClosingChar: "Nie mo\u017Cna odnale\u017A\u0107 zamykaj\u0105cego %1",
IllegalControlSequenceName: "Nieprawid\u0142owa nazwa sekwencji kontrolnej dla %1",
IllegalParamNumber: "Nieprawid\u0142owa liczba parametr\u00F3w dla %1",
MissingCS: "Po %1 musi wyst\u0105pi\u0107 sekwencja kontrolna",
CantUseHash2: "Nieprawid\u0142owe u\u017Cycie # w szablonie dla %1",
SequentialParam: "Parametry dla %1 musz\u0105 by\u0107 ponumerowane rosn\u0105co",
MissingReplacementString: "Brak \u0142a\u0144cucha zamiennego dla definicji %1",
MismatchUseDef: "U\u017Cycie %1 niezgodne z definicj\u0105",
RunawayArgument: "Zgin\u0105\u0142 argument dla %1?",
NoClosingDelim: "Nie mo\u017Cna znale\u017A\u0107\u00A0ko\u0144cz\u0105cego separatora dla %1"
}
});
MathJax.Ajax.loadComplete("[MathJax]/localization/pl/TeX.js");
|
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import expect from '@kbn/expect';
import { getHighlightRequest } from '../highlight_request';
describe('getHighlightRequest', () => {
let configMock;
const getConfig = (key) => configMock[key];
const queryStringQuery = { query_string: { query: 'foo' } };
beforeEach(function () {
configMock = {};
configMock['doc_table:highlight'] = true;
});
it('should be a function', () => {
expect(getHighlightRequest).to.be.a(Function);
});
it('should not modify the original query', () => {
getHighlightRequest(queryStringQuery, getConfig);
expect(queryStringQuery.query_string).to.not.have.property('highlight');
});
it('should return undefined if highlighting is turned off', () => {
configMock['doc_table:highlight'] = false;
const request = getHighlightRequest(queryStringQuery, getConfig);
expect(request).to.be(undefined);
});
it('should enable/disable highlighting if config is changed', () => {
let request = getHighlightRequest(queryStringQuery, getConfig);
expect(request).to.not.be(undefined);
configMock['doc_table:highlight'] = false;
request = getHighlightRequest(queryStringQuery, getConfig);
expect(request).to.be(undefined);
});
});
|
import { Enemy } from "./enemy.js";
import { Vector2 } from "./engine/vector.js";
//
// A spectral gem
//
// (c) 2019 Jani Nykänen
//
export class SpectralGem extends Enemy {
constructor(x, y) {
super(x, y, 0);
this.w = 8;
this.h = 8;
this.hitArea = new Vector2(6, 6);
this.acc.x = 0.010;
this.acc.y = 0.010;
this.maxHealth = 3;
this.health = this.maxHealth;
this.power = 2;
this.spr.setFrame(16, 0);
this.bounce = true;
this.bounceFactor = new Vector2(1, 1);
this.ignoreLadder = true;
this.preventLeaving = true;
this.spcAngle = (y*10 + x) * (Math.PI*2 / 10) % (Math.PI * 2);
this.offScreenKill = true;
}
// Update AI
updateAI(pl, ev) {
const FLY_SPEED = 0.5;
const ANGLE_MOD = 0.5;
this.spcAngle += 0.025 * ev.step;
this.spcAngle %= Math.PI * 2;
let angle = Math.atan2(
this.pos.y-pl.pos.y,
this.pos.x-pl.pos.x);
this.target.x = -Math.cos(angle) * FLY_SPEED +
Math.cos(this.spcAngle) * ANGLE_MOD;
this.target.y = -Math.sin(angle) * FLY_SPEED +
Math.sin(this.spcAngle) * ANGLE_MOD;
}
// Animate
animate(ev) {
let start = this.speed.x < 0 ? 0 : 4;
let end = this.speed.x < 0 ? 4 : 0;
let speed = 10 - 8 * Math.hypot(this.speed.x, this.speed.y);
this.spr.animate(16, start, end, speed, ev.step);
}
}
|
$(document).ready(function() {
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : sParameterName[1];
}
}
};
$("[data-content='pubDate']").html('<i class="fa fa-calendar" aria-hidden="true"></i> '+getUrlParameter('pubDate'));
$("[data-content='title']").html(getUrlParameter('title'));
$("[data-content='description']").html(getUrlParameter('description'));
var proxy = 'https://cors-anywhere.herokuapp.com/';
var relatedArticlesUrl = 'https://news.google.com/news?cf=all&hl=en&ned=us&output=rss&q='+getUrlParameter('title');
var relatedArticlesFeed = proxy + relatedArticlesUrl;
$.ajax(relatedArticlesFeed, {
accepts:{
xml:"application/rss+xml"
},
dataType:"xml",
success:function(data) {
$(data).find("item").each(function () {
$("#relatedArticles").append('<a href="article.html?title='+encodeURI($(this).find("title").text())+'&pubDate='+encodeURI($(this).find("pubDate").text())+'" class="list-group-item list-group-item-action flex-column align-items-start">\
<div class="d-flex w-100 justify-content-between">\
<h6 class="mb-1">'+$(this).find("title").text()+'</h6>\
</div>\
<small class="text-muted"><i class="fa fa-calendar" aria-hidden="true"></i> '+$(this).find("pubDate").text()+'</small>\
</a>');
});
}
});
var twitterSearchUrl = 'https://queryfeed.net/twitter?q='+getUrlParameter('title');
var twitterSearchFeed = proxy + twitterSearchUrl;
$.ajax(twitterSearchFeed, {
accepts:{
xml:"application/rss+xml"
},
dataType:"xml",
success:function(data) {
$(data).find("item").each(function () {
$("#twitterSearch").append('<li class="list-group-item flex-column align-items-start">\
<div class="d-flex w-100 justify-content-between">\
<h6 class="mb-1">'+$(this).find("title").text()+'</h6>\
</div>\
<p class="mb-1">'+$(this).find("description").text()+'</p>\
<small class="text-muted"><i class="fa fa-calendar" aria-hidden="true"></i> '+$(this).find("pubDate").text()+'</small>\
</li>');
});
}
});
});
|
import React from "react"
import { useStaticQuery, graphql, Link } from "gatsby"
import PropTypes from "prop-types"
import { HeaderWrapper, Image } from "./headerStyles/headerStyles"
import Menu from "./Menu"
const Header = ({ siteTitle }) => {
const { logo, wpcontent: { menuItems }} = useStaticQuery(graphql`
query {
logo: file(relativePath: { eq: "logo.png" }) {
childImageSharp {
fixed(quality: 100, width: 200) {
...GatsbyImageSharpFixed_withWebp
}
}
}
wpcontent {
menuItems {
edges {
node {
label
path
}
}
}
}
}`
);
return (
<HeaderWrapper>
<Link to="/">
<Image alt="logo top-games" fixed={logo.childImageSharp.fixed} />
</Link>
<Menu menuItems={menuItems.edges} />
</HeaderWrapper>
);
}
Header.propTypes = {
siteTitle: PropTypes.string,
}
Header.defaultProps = {
siteTitle: ``,
}
export default Header
|
"use strict"
// Default parameters
function greet($greeting = 'Hello world!'){
console.log($greeting);
}
greet();
// Spread operator
let args1 = [1,2,3];
let args2 = [4,5,6];
function test(){
console.log(args1+','+ args2);
}
// Using apply() method to pass an array as an argument
test.apply(null, args1);
// Using spread operator to pass an array as an argument
test(...args1, ...args2);
|
import createSvgIcon from './utils/createSvgIcon';
import { jsx as _jsx } from "react/jsx-runtime";
export default createSvgIcon( /*#__PURE__*/_jsx("path", {
d: "M12 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm5.95-4c.59 0 1.06.51 1 1.09-.02.15-.21 4.06-3.95 5.31V21c0 .55-.45 1-1 1s-1-.45-1-1v-5h-2v5c0 .55-.45 1-1 1s-1-.45-1-1V10.1c-.3.1-.5.2-.6.3-.46.36-1.17.87-1.36 2.67-.05.52-.47.93-1 .93-.58 0-1.05-.49-1-1.07.13-1.6.62-2.98 2.07-4.22C8.21 7.81 10 7 12 7s2.68-.46 3.48-1.06c.43-.34 1.28-.99 1.48-3.02.05-.52.47-.92.99-.92zM5 16h1c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1H5c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1z"
}), 'HailRounded');
|
const redis = require('redis')
const { REDIS_CONF } = require('../conf/db.js')
// 创建客户端
const redisClient = redis.createClient(REDIS_CONF.port, REDIS_CONF.host)
redisClient.on('error', err => {
console.error(err)
})
module.exports = redisClient
|
import * as React from "react";
function BookmarkIcon(props) {
return /*#__PURE__*/React.createElement("svg", Object.assign({
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
stroke: "currentColor"
}, props), /*#__PURE__*/React.createElement("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
strokeWidth: 2,
d: "M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"
}));
}
export default BookmarkIcon;
|
import React, { useState, useEffect } from 'react'
import PropTypes from 'prop-types'
import Radio from '@material-ui/core/Radio'
import RadioGroup from '@material-ui/core/RadioGroup'
import FormControlLabel from '@material-ui/core/FormControlLabel'
const Bool = props => {
const [value, setValue] = useState(props.dflt)
useEffect(() => {
if (props.value !== value) setValue(props.value)
}, [props.value])
const toggle = () => {
props.updateValue(props.name, !value)
setValue(!value)
}
return (
<RadioGroup onChange={toggle} value={JSON.stringify(value)}>
<FormControlLabel
control={<Radio color="primary" />}
value="false"
checked={value === 'true' || value === true || value === 1 ? false : true}
label={props.labels[0]}
className="po-list-item"
/>
<FormControlLabel
control={<Radio color="primary" />}
value="true"
checked={value === 'true' || value === true || value === 1 ? true : false}
label={props.labels[1]}
className="po-list-item"
/>
</RadioGroup>
)
}
Bool.propTypes = {
dflt: PropTypes.bool,
labels: PropTypes.array,
updateValue: PropTypes.func.isRequired,
name: PropTypes.string.isRequired
}
Bool.defaultProps = {
dflt: false,
labels: ['false', 'true']
}
export default Bool
|
import reducer from '../reducer';
describe('ADMIN | COMPONENTS | Permissions | reducer', () => {
describe('DEFAULT_ACTION', () => {
it('should return the initialState when the type is undefined', () => {
const initialState = { ok: true };
const action = { type: undefined };
expect(reducer(initialState, action)).toEqual(initialState);
});
});
describe('ON_CHANGE_COLLECTION_TYPE_GLOBAL_ACTION_CHECKBOX', () => {
it('should set all the leafs in each content type corresponding to the correct action and remove the applied conditions when the value is falsy', () => {
const initialState = {
modifiedData: {
collectionTypes: {
address: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: true,
},
},
},
'content-manager.explorer.update': {
properties: {
fields: {
f1: true,
},
},
},
},
restaurant: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: true,
f2: true,
services: {
name: true,
media: true,
closing: {
name: {
test: true,
},
},
},
dz: true,
relation: true,
},
locales: {
fr: true,
en: true,
},
},
conditions: {
test: true,
},
},
},
},
},
singleTypes: {
test: {
'content-manager.explorer.create': {
properties: {
fields: { f1: true },
},
},
},
},
};
const expected = {
modifiedData: {
collectionTypes: {
address: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: false,
},
},
},
'content-manager.explorer.update': {
properties: {
fields: {
f1: true,
},
},
},
},
restaurant: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: false,
f2: false,
services: {
name: false,
media: false,
closing: {
name: {
test: false,
},
},
},
dz: false,
relation: false,
},
locales: {
fr: false,
en: false,
},
},
conditions: {
test: false,
},
},
},
},
},
singleTypes: {
test: {
'content-manager.explorer.create': {
properties: {
fields: { f1: true },
},
},
},
},
};
const action = {
type: 'ON_CHANGE_COLLECTION_TYPE_GLOBAL_ACTION_CHECKBOX',
collectionTypeKind: 'collectionTypes',
actionId: 'content-manager.explorer.create',
value: false,
};
expect(reducer(initialState, action)).toEqual(expected);
});
it('should set all the leafs in each content type corresponding to the correct action and remove the applied conditions when the value is truthy', () => {
const initialState = {
modifiedData: {
collectionTypes: {
address: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: false,
},
},
conditions: {
creator: false,
roles: true,
},
},
'content-manager.explorer.update': {
properties: {
fields: {
f1: true,
},
},
},
},
restaurant: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: true,
f2: true,
},
locales: {
fr: false,
en: false,
},
},
conditions: {
test: true,
},
},
},
},
},
singleTypes: {
test: {
'content-manager.explorer.create': {
properties: {
fields: { f1: false },
},
},
},
},
};
const expected = {
modifiedData: {
collectionTypes: {
address: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: true,
},
},
conditions: {
creator: false,
roles: true,
},
},
'content-manager.explorer.update': {
properties: {
fields: {
f1: true,
},
},
},
},
restaurant: {
'content-manager.explorer.create': {
properties: {
fields: {
f1: true,
f2: true,
},
locales: {
fr: true,
en: true,
},
},
conditions: {
test: true,
},
},
},
},
},
singleTypes: {
test: {
'content-manager.explorer.create': {
properties: {
fields: { f1: false },
},
},
},
},
};
const action = {
type: 'ON_CHANGE_COLLECTION_TYPE_GLOBAL_ACTION_CHECKBOX',
collectionTypeKind: 'collectionTypes',
actionId: 'content-manager.explorer.create',
value: true,
};
expect(reducer(initialState, action)).toEqual(expected);
});
});
describe('ON_CHANGE_COLLECTION_TYPE_ROW_LEFT_CHECKBOX', () => {
it('should set all the leafs of a content type property to true when the value is truthy and not remove the applied conditions', () => {
const action = {
pathToCollectionType: 'collectionTypes..address',
propertyName: 'fields',
rowName: 'f2',
type: 'ON_CHANGE_COLLECTION_TYPE_ROW_LEFT_CHECKBOX',
value: true,
};
const initialState = {
initialData: { ok: true },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: false,
roles: true,
},
},
read: {
properties: {
fields: {
f1: false,
f2: false,
},
},
conditions: {
creator: false,
roles: false,
},
},
},
restaurant: {
delete: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: true,
},
},
},
},
plugins: { ok: true },
},
};
const expected = {
initialData: { ok: true },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: true,
f2: true,
},
},
conditions: {
creator: false,
roles: true,
},
},
read: {
properties: {
fields: {
f1: false,
f2: true,
},
},
conditions: {
creator: false,
roles: false,
},
},
},
restaurant: {
delete: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: true,
},
},
},
},
plugins: { ok: true },
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
it('should set all the leafs of a content type property to false when the value is falsy and remove the applied conditions', () => {
const action = {
pathToCollectionType: 'collectionTypes..address',
propertyName: 'fields',
rowName: 'f1',
type: 'ON_CHANGE_COLLECTION_TYPE_ROW_LEFT_CHECKBOX',
value: false,
};
const initialState = {
initialData: { ok: true },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: false,
roles: true,
},
},
read: {
properties: {
fields: {
f1: false,
f2: false,
},
},
conditions: {
creator: false,
roles: false,
},
},
},
restaurant: {
delete: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: true,
},
},
},
},
plugins: { ok: true },
},
};
const expected = {
initialData: { ok: true },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: false,
f2: false,
},
},
conditions: {
creator: false,
roles: false,
},
},
read: {
properties: {
fields: {
f1: false,
f2: false,
},
},
conditions: {
creator: false,
roles: false,
},
},
},
restaurant: {
delete: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: true,
},
},
},
},
plugins: { ok: true },
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
});
describe('ON_CHANGE_CONDITIONS', () => {
it('should apply the conditions only to the correct actions', () => {
const initialState = {
initialData: { ok: true },
layouts: { foo: 'bar' },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: false,
roles: true,
},
},
read: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: true,
roles: false,
},
},
},
},
plugins: {
ctb: {
general: {
read: {
properties: {
enabled: false,
},
conditions: {
creator: false,
roles: false,
},
},
},
},
doc: {
general: {
read: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: false,
},
},
},
settings: {
read: {
properties: {
enabled: false,
},
conditions: {
creator: false,
roles: false,
},
},
updated: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: false,
},
},
},
},
},
},
};
const conditions = {
'collectionTypes..address..create': {
creator: true,
roles: false,
},
'collectionTypes..address..read': {
creator: false,
roles: false,
},
'plugins..doc..settings..updated': {
creator: true,
roles: true,
},
};
const expected = {
initialData: { ok: true },
layouts: { foo: 'bar' },
modifiedData: {
collectionTypes: {
address: {
create: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: true,
roles: false,
},
},
read: {
properties: {
fields: {
f1: true,
f2: false,
},
},
conditions: {
creator: false,
roles: false,
},
},
},
},
plugins: {
ctb: {
general: {
read: {
properties: {
enabled: false,
},
conditions: {
creator: false,
roles: false,
},
},
},
},
doc: {
general: {
read: {
properties: {
enabled: true,
},
conditions: {
creator: false,
roles: false,
},
},
},
settings: {
read: {
properties: {
enabled: false,
},
conditions: {
creator: false,
roles: false,
},
},
updated: {
properties: {
enabled: true,
},
conditions: {
creator: true,
roles: true,
},
},
},
},
},
},
};
const action = { type: 'ON_CHANGE_CONDITIONS', conditions };
expect(reducer(initialState, action)).toEqual(expected);
});
});
describe('ON_CHANGE_SIMPLE_CHECKBOX', () => {
it('should set the modifiedData.test.enabled to false when the value is falsy and remove the applied conditions', () => {
const action = {
type: 'ON_CHANGE_SIMPLE_CHECKBOX',
keys: 'test..properties..enabled',
value: false,
};
const initialState = {
initialData: {
test: { properties: { enabled: true }, conditions: { creator: true, roles: true } },
},
modifiedData: {
test: { properties: { enabled: true }, conditions: { creator: true, roles: true } },
},
};
const expected = {
initialData: {
test: { properties: { enabled: true }, conditions: { creator: true, roles: true } },
},
modifiedData: {
test: { properties: { enabled: false }, conditions: { creator: false, roles: false } },
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
it('should set the modifiedData.test.enabled to true when the value is truthy and not remove the applied conditions', () => {
const action = {
type: 'ON_CHANGE_SIMPLE_CHECKBOX',
keys: 'test..properties..enabled',
value: true,
};
const initialState = {
initialData: {
test: { properties: { enabled: false }, conditions: { creator: true, roles: true } },
},
modifiedData: {
test: { properties: { enabled: false }, conditions: { creator: true, roles: true } },
},
};
const expected = {
initialData: {
test: { properties: { enabled: false }, conditions: { creator: true, roles: true } },
},
modifiedData: {
test: { properties: { enabled: true }, conditions: { creator: true, roles: true } },
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
});
describe('ON_CHANGE_TOGGLE_PARENT_CHECKBOX', () => {
it('should set all the leafs of the create action to true and not remove the applied conditions when the value is truthy', () => {
const action = {
type: 'ON_CHANGE_TOGGLE_PARENT_CHECKBOX',
keys: 'restaurant..create',
value: true,
};
const initialState = {
initialData: {},
modifiedData: {
restaurant: {
create: {
properties: {
fields: { f1: false, f2: { f1: false } },
locales: { en: false },
},
conditions: {
test: 'test',
},
},
update: {
properties: {
test: true,
},
},
},
},
};
const expected = {
initialData: {},
modifiedData: {
restaurant: {
create: {
properties: {
fields: { f1: true, f2: { f1: true } },
locales: { en: true },
},
conditions: {
test: 'test',
},
},
update: {
properties: {
test: true,
},
},
},
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
it('should set all the leafs of the create action to true and remove the applied conditions when the value is falsy', () => {
const action = {
type: 'ON_CHANGE_TOGGLE_PARENT_CHECKBOX',
keys: 'restaurant..create',
value: false,
};
const initialState = {
initialData: {},
modifiedData: {
restaurant: {
create: {
properties: {
fields: { f1: true, f2: { f1: false } },
locales: { en: false },
},
conditions: {
test: true,
},
},
update: {
properties: {
test: true,
},
},
},
},
};
const expected = {
initialData: {},
modifiedData: {
restaurant: {
create: {
properties: {
fields: { f1: false, f2: { f1: false } },
locales: { en: false },
},
conditions: {
test: false,
},
},
update: {
properties: {
test: true,
},
},
},
},
};
expect(reducer(initialState, action)).toEqual(expected);
});
});
});
|
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
System.config({
paths: {
// paths serve as alias
'npm:': 'lib/'
},
// map tells the System loader where to look for things
map: {
// our app is within the app folder
app: 'app',
// angular bundles
'@angular/core': 'npm:@angular/core/bundles/core.umd.js',
'@angular/common': 'npm:@angular/common/bundles/common.umd.js',
'@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
'@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
'@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
'@angular/http': 'npm:@angular/http/bundles/http.umd.js',
'@angular/router': 'npm:@angular/router/bundles/router.umd.js',
'@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
// other libraries
'rxjs': 'npm:rxjs',
'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
},
// packages tells the System loader how to load when no filename and/or no extension
packages: {
app: {
main: './main.js',
defaultExtension: 'js'
},
rxjs: {
defaultExtension: 'js'
},
'angular2-in-memory-web-api': {
main: './index.js',
defaultExtension: 'js'
}
}
});
})(this);
|
/**
* Created by arunsharma on 12/2/16.
*/
'use strict';
angular.module('users').directive('userMenuIcon',['Authentication',function(Authentication){
return {
restrict : 'E',
replace : true,
scope: true,
templateUrl : '/modules/users/client/views/user-menu-icon.client.view.html',
link : function(scope, elements, attrs) {
// check if need to enable drop down menu
scope.enablemenu = attrs.enablemenu;
scope.authentication = Authentication;
}
};
}]);
|
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A streaming pending request.
*/
class PendingRequest {
}
/**
* Orchestrates and manages pending streaming requests.
*/
class RequestManager {
constructor() {
this._pendingRequests = {};
}
pendingRequestCount() {
return Object.keys(this._pendingRequests).length;
}
signalResponse(requestId, response) {
return __awaiter(this, void 0, void 0, function* () {
let pendingRequest = this._pendingRequests[requestId];
if (pendingRequest) {
pendingRequest.resolve(response);
delete this._pendingRequests[requestId];
return true;
}
return false;
});
}
getResponse(requestId) {
let pendingRequest = this._pendingRequests[requestId];
if (pendingRequest) {
return Promise.reject(`requestId '${requestId}' already exists in RequestManager`);
}
pendingRequest = new PendingRequest();
pendingRequest.requestId = requestId;
let promise = new Promise((resolve, reject) => {
pendingRequest.resolve = resolve;
pendingRequest.reject = reject;
});
this._pendingRequests[requestId] = pendingRequest;
return promise;
}
}
exports.RequestManager = RequestManager;
//# sourceMappingURL=requestManager.js.map
|
var PlayModule = {
name: "Play",
bigicon: "imgs/tabicon-player.png",
state: "stop",
preferences_panel: [{name:"play", title:"Play", icon:null }],
max_delta_time: 1/15,
inplayer: false,
icons: {
play: "►",
stop: "∎",
pause: "❚❚",
stoprecord: "∎✔",
eject: "⏏",
reload: "↻"
},
preferences: { //persistent settings
tint_interface_when_playing: true,
render_play_border: true,
restore_state_after_play: true
},
init: function()
{
LiteGUI.addCSS("\
#play-tools { position: fixed; top: 2px; right: 300px; font-size: 1.4em; padding-right: 3px; z-index: 10; } \
#play-tools button { padding: 0 0.5em; overflow: hidden; height: 1.25em; } \
#play-tools button.enabled { background: #AEE !important;} \
#restore-button { background: #944 !important;} \
");
//Register in CanvasManager to render the border on playmode
RenderModule.canvas_manager.addWidget( PlayModule, 10 );
//If the scene is cleared be sure to change mode to stop
LEvent.bind( LS.GlobalScene, "clear", this.onSceneStop, this );
LEvent.bind( LS.GlobalScene, "code_error", this.onSceneError, this );
//play tools panel
var container = document.createElement("div");
container.id = "play-tools";
container.className = "big-buttons";
container.innerHTML = "<button class='litebutton' id='play-button' title='Play'>"+this.icons.play+"</button><button class='litebutton' id='pause-button' title='Pause' disabled>"+this.icons.pause+"</button><button class='litebutton' id='stopkeep-button' disabled title='Stop And Save'>"+this.icons.stoprecord+"</button><button class='litebutton' id='restore-button' title='restore'>"+this.icons.reload+"</button><button class='litebutton' id='launch-button' title='launch'>"+this.icons.eject+"</button>";
this.play_button = container.querySelector("#play-button");
this.pause_button = container.querySelector("#pause-button");
this.stopkeep_button = container.querySelector("#stopkeep-button");
this.restore_button = container.querySelector("#restore-button");
this.restore_button.style.display = "none";
this.launch_button = container.querySelector("#launch-button");
this.play_button.addEventListener("click", this.onPlay.bind(this) );
this.pause_button.addEventListener("click", this.onPause.bind(this) );
this.stopkeep_button.addEventListener("click", this.onStopKeep.bind(this) );
this.launch_button.addEventListener("click", this.launch.bind(this) );
this.restore_button.addEventListener("click", this.restore.bind(this) );
setTimeout( function() { //timeout because some weird glitch
document.getElementById("mainmenubar").appendChild( container );
}, 1000);
this.tab = LiteGUI.main_tabs.addTab("Player", {id:"ingametab", bigicon: this.bigicon, size: "full", module: EditorModule, callback: function() {
//get the canvas
var canvas = RenderModule.appendViewportTo( PlayModule.tab.content );
RenderModule.render_settings.in_player = true;
PlayModule.inplayer = true;
LS.GUI._allow_change_cursor = true;
},
callback_leave: function() {
PlayModule.inplayer = false;
LS.GUI._allow_change_cursor = false;
RenderModule.appendViewportTo(null);
}});
//overwrite method to add the module to the right place
var GUIgetRoot = LS.GUI.getHTMLRoot.bind(LS.GUI);
LS.GUI.getHTMLRoot = function()
{
var gui = GUIgetRoot();
if( gui.parentNode != PlayModule.tab.content)
PlayModule.tab.content.appendChild( gui );
return gui;
},
this.tab.content.style.overflow = "hidden";
},
//play clicked
onPlay: function()
{
if(this.state == "stop") //play
{
//send ready signal
var result = LEvent.trigger( LS.GlobalScene, "prepare_play" );
if( result === true )
{
console.log("Play aborted");
return;
}
//serialize before launching
this._backup = LS.GlobalScene.serialize();
var selected_node = SelectionModule.getSelectedNode();
this._selected_node_uid = selected_node ? selected_node.uid : null;
this.play_button.innerHTML = this.icons.stop;
this.pause_button.removeAttribute('disabled');
this.pause_button.classList.remove("enabled");
this.stopkeep_button.removeAttribute('disabled');
this.changeState("play");
}
else //stop
{
this.play_button.innerHTML = this.icons.play;
this.pause_button.setAttribute('disabled','disabled');
this.pause_button.classList.remove("enabled");
this.stopkeep_button.setAttribute('disabled','disabled');
this.changeState("stop");
//restore old scene
if(this.preferences.restore_state_after_play)
this.restore();
}
},
onPause: function() {
if( this.state == "play" )
this.changeState("pause");
else if( this.state == "pause" )
this.changeState("unpause");
else
return;
//LEvent.trigger( LS.GlobalScene, this.state == "pause" ? "pause" : "unpause" );
if( this.state == 'pause' )
this.pause_button.classList.add("enabled");
else
this.pause_button.classList.remove("enabled");
},
onStopKeep: function() {
if(this.state != "play")
return;
this.changeState("stop");
this.play_button.innerHTML = "Play";
this.pause_button.setAttribute('disabled','disabled');
this.pause_button.classList.remove("enabled");
},
launch: function()
{
var that = this;
DriveModule.checkResourcesSaved( true, inner_ready );
function inner_ready()
{
//pass current scene
var scene_info = LS.GlobalScene.serialize();
//open window
var demo_window = that.demo_window;
if(!demo_window)
{
demo_window = window.open("player.html?preview", "", "width=800, height=600")
demo_window.onload = launch;
var console = window.console;
//helps debugging
demo_window.console._log = demo_window.console.log;
demo_window.console.log = function(){
var args = Array.prototype.slice.call(arguments);
demo_window.console._log.apply( console, args );
args.unshift("WINDOW:");
console.log.apply( console, args );
}
demo_window.console._warn = demo_window.console.warn;
demo_window.console.warn = function(){
var args = Array.prototype.slice.call(arguments);
demo_window.console._warn.apply( console, args );
args.unshift("WINDOW:");
console.warn.apply( console, args );
}
demo_window.console._error = demo_window.console.error;
demo_window.console.error = function(){
var args = Array.prototype.slice.call(arguments);
demo_window.console._error.apply( console, args );
args.unshift("WINDOW:");
console.error.apply( console, args );
}
demo_window.onbeforeunload = function(){
that.demo_window = null;
}
that.demo_window = demo_window;
}
else
launch();
//play
function launch()
{
if(!demo_window.player)
return LiteGUI.alert("Error loading player window");
demo_window.player.autoplay = true;
demo_window.player.setScene( scene_info, inner_launched, inner_before_play );
};
function inner_before_play( scene )
{
//console.log("scene ready to be played in window");
}
function inner_launched( scene )
{
//console.log("scene launched in window");
}
}
},
play: function()
{
this.changeState("play");
},
stop: function()
{
this.changeState("stop");
},
restore: function()
{
this.restore_button.style.display = "none";
var scene = LS.GlobalScene;
LEvent.trigger(scene,"beforeReload");
scene.clear();
scene.configure(this._backup);
LEvent.trigger(scene,"reload");
if(this._selected_node_uid)
{
var old_selected_node = scene.getNodeByUId( this._selected_node_uid );
if(old_selected_node)
SelectionModule.setSelection( old_selected_node );
}
EditorModule.refreshAttributes();
},
changeState: function(state)
{
if(state == this.state)
return;
var scene = LS.GlobalScene;
if(state == "play")
{
this.state = "play";
console.log("%c + START ", 'background: #222; color: #AFA; font-size: 1.4em');
if(this.preferences.tint_interface_when_playing)
LiteGUI.root.classList.add("playing");
LEvent.bind( scene,"finish", this.onSceneStop, this );
LS.Input.reset(); //this force some events to be sent
LS.GUI.reset();
scene.start();
EditorModule.render_debug_info = false;
EditorModule.refreshAttributes();
RenderModule.requestFrame();
}
else if(state == "pause")
{
this.state = "pause";
console.log("%c + PAUSE", 'background: #222; color: #AFA; font-size: 1.4em');
scene.pause();
}
else if(state == "unpause")
{
this.state = "play";
console.log("%c + UNPAUSE", 'background: #222; color: #AFA; font-size: 1.4em');
scene.unpause();
}
else if(state == "stop")
{
this.state = "stop";
console.log("%c + FINISH ", 'background: #222; color: #AAF; font-size: 1.4em');
LiteGUI.root.classList.remove("playing");
scene.finish();
LS.Tween.reset();
EditorModule.render_debug_info = true;
RenderModule.requestFrame();
LEvent.unbind( scene,"finish", this.onSceneStop, this );
LS.GUI.reset();
}
},
//ensures that if we are using an external file it has been loaded
reloadScripts: function( callback )
{
var to_reload = [];
var res = LS.GlobalScene.getResources();
for(var i in res)
{
if(i.indexOf("://") == -1)
continue;
to_reload.push(i);
LS.ResourcesManager.unregisterResource( i );
}
if(callback)
callback();
},
onSceneStop: function()
{
this.changeState("stop");
this.play_button.innerHTML = this.icons.play;
},
onSceneError: function()
{
if(this.state != "play")
return;
this.restore_button.style.display = "";
},
//called from CanvasManager with every user event
onevent: function(e)
{
if(!this.inplayer)
return;
//dont know where to put this
var r = RenderModule.passEventToLiteScene(e);
//block propagation (mousemove should be propagated so when dragging panels works)
if(e.type != "mousemove")
e.stopPropagation();
e.preventDefault();
return true;
},
//file (or item) dropped over the Player
onItemDrop: function(e)
{
if(!this.inplayer)
return;
var r = false;
if( e.dataTransfer.files.length )
{
for(var i = 0; i < e.dataTransfer.files.length; ++i )
{
var file = e.dataTransfer.files[i];
var r = LEvent.trigger( LS.GlobalScene, "fileDrop", { file: file, event: e } );
if(r === false)
{
e.stopPropagation();
e.stopImmediatePropagation();
r = true;
}
}
}
return r;
},
render: function()
{
if(!RenderModule.frame_updated || this.inplayer || LS.GlobalScene._state == LS.STOPPED || !this.preferences.render_play_border)
return;
//render inplayer border
var ctx = gl;
ctx.start2D();
ctx.strokeColor = [0,1,1,0.8];
ctx.strokeRect(1,1,gl.canvas.width-2,gl.canvas.height-2);
ctx.finish2D();
},
update: function(dt)
{
if(dt > PlayModule.max_delta_time)
dt = PlayModule.max_delta_time;
if( this.state == 'play' )
{
LS.Tween.update(dt);
LS.Input.update(dt);
LS.GlobalScene.update(dt);
this.checkErrors();
}
},
checkErrors: function()
{
if( vec3.distance(LS.ZEROS,[0,0,0]) > 0 ||
vec3.distance(LS.ONES,[1,1,1]) > 0 ||
vec3.distance(LS.RIGHT,[1,0,0]) > 0 ||
vec3.distance(LS.LEFT,[-1,0,0]) > 0 ||
vec3.distance(LS.TOP,[0,1,0]) > 0 ||
vec3.distance(LS.BOTTOM,[0,-1,0]) > 0 ||
vec3.distance(LS.FRONT,[0,0,-1]) > 0 ||
vec3.distance(LS.BACK,[0,0,1]) > 0 )
console.error("LS base vectors have been modifyed!, you never should change LS.FRONT,LS.BACK,LS.RIGHT,LS.LEFT,LS.TOP,LS.BOTTOM,LS.ZEROS or LS.ONES");
},
onShowPreferencesPanel: function(name,widgets)
{
if(name != "play")
return;
widgets.addCheckbox("Reset scene after play",PlayModule.preferences.restore_state_after_play, { callback: function(value) {
PlayModule.preferences.restore_state_after_play = value;
}});
widgets.addCheckbox("Show Play window border",PlayModule.preferences.render_play_border, { callback: function(value) {
PlayModule.preferences.render_play_border = value;
}});
widgets.addCheckbox("Tint Interface while playing",PlayModule.preferences.tint_interface_when_playing, { callback: function(value) {
PlayModule.preferences.tint_interface_when_playing = value;
}});
}
};
CORE.registerModule( PlayModule );
|
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'id', {
button: {
title: 'Properti Tombol',
text: 'Teks (Nilai)',
type: 'Tipe',
typeBtn: 'Tombol',
typeSbm: 'Menyerahkan',
typeRst: 'Atur Ulang'
},
checkboxAndRadio: {
checkboxTitle: 'Checkbox Properties', // MISSING
radioTitle: 'Radio Button Properties', // MISSING
value: 'Nilai',
selected: 'Terpilih',
required: 'Wajib'
},
form: {
title: 'Form Properties', // MISSING
menu: 'Form Properties', // MISSING
action: 'Aksi',
method: 'Metode',
encoding: 'Encoding' // MISSING
},
hidden: {
title: 'Hidden Field Properties', // MISSING
name: 'Nama',
value: 'Nilai'
},
select: {
title: 'Selection Field Properties', // MISSING
selectInfo: 'Select Info', // MISSING
opAvail: 'Available Options', // MISSING
value: 'Nilai',
size: 'Ukuran',
lines: 'garis',
chkMulti: 'Izinkan pemilihan ganda',
required: 'Wajib',
opText: 'Teks',
opValue: 'Nilai',
btnAdd: 'Tambah',
btnModify: 'Modifikasi',
btnUp: 'Atas',
btnDown: 'Bawah',
btnSetValue: 'Atur sebagai nilai yang dipilih',
btnDelete: 'Hapus'
},
textarea: {
title: 'Textarea Properties', // MISSING
cols: 'Kolom',
rows: 'Baris'
},
textfield: {
title: 'Text Field Properties', // MISSING
name: 'Name',
value: 'Nilai',
charWidth: 'Character Width', // MISSING
maxChars: 'Maximum Characters', // MISSING
required: 'Wajib',
type: 'Tipe',
typeText: 'Teks',
typePass: 'Kata kunci',
typeEmail: 'Surel',
typeSearch: 'Cari',
typeTel: 'Nomor Telepon',
typeUrl: 'URL'
}
} );
|
import {
ADD_VENDOR_SUCCESS,
RESET_VENDORS,
} from "../actions/vendorsActionTypes";
import {
GET_VENDORS_BY_WORKSPACE_ID_SUCCESS,
RESET_WORKSPACE,
} from "../../workspaces/actions/workspacesActionTypes";
const initialState = {
vendors: [],
};
export default (state = initialState, action) => {
switch (action.type) {
case GET_VENDORS_BY_WORKSPACE_ID_SUCCESS:
return {
...state,
vendors: action.payload.vendors,
};
case ADD_VENDOR_SUCCESS:
return {
...state,
vendors: [...state.vendors, action.payload],
};
case RESET_VENDORS:
return {
...state,
vendors: [],
};
case RESET_WORKSPACE:
return {
...state,
vendors: [],
};
default:
return state;
}
};
|
const express = require('express');
const config = require('../config/config');
const logger = require('../config/logger');
const axios = require('axios');
const { writeToJsonFile, readFromJsonFile } = require('../utils/jsonUtils');
const router = express.Router();
require('dotenv').config();
// Global fields
let parsedJsonTokens = readFromJsonFile('src/temp/', 'tokens.json');
const TWITCH_AUTHORIZE_URL = `https://id.twitch.tv/oauth2/authorize?client_id=${config.env.TWITCH_CLIENT_ID}&redirect_uri=${config.REDIRECT_URI}&response_type=code&scope=${config.env.SCOPES}`;
const authorize = (async (req, res) => {
logger.info('Incoming login request, redirecting to twitch authorization');
logger.info(`Redirecting to twitch authorize url: ${TWITCH_AUTHORIZE_URL}`)
// TODO: Here we need to verify whether the user wants to authenticate or not.
res.redirect(TWITCH_AUTHORIZE_URL);
});
const unauthorize = (async (req, res) => {
try {
if (parsedJsonTokens.TWITCH_ACCESS_TOKEN == undefined) {
logger.error('Twitch Access Token is undefined')
}
let response = await axios({
url: 'https://id.twitch.tv/oauth2/revoke',
method: 'post',
timeout: 8000,
headers: {
'Content-Type': 'application/json'
},
params: {
client_id: config.env.TWITCH_CLIENT_ID,
token: parsedJsonTokens.TWITCH_ACCESS_TOKEN
}
})
if (response.status == 200) {
logger.info(`👍 Successfully revoked oauth token, redirecting to homepage...`)
res.redirect('/');
};
} catch (error) {
logger.error(`🔥 Error when revoking OAuth Token: ${JSON.stringify(error.response.status)}`)
logger.error(`Error Headers: ${JSON.stringify(error.response.headers)}`)
logger.error(`Error Data: ${JSON.stringify(error.response.data)}`)
return;
}
});
/**
* This redirect route will call the generateAuthToken route with the oauthCode it gets from the request query.
* It also sets the tokens to the global environment variables.
*
*/
const redirect = (async (req, res) => {
let oauthCode = req.query.code;
if (oauthCode != undefined) {
// We have a valid oauthCode after the user logs in. So fetch the open token.
console.log(`OAuth code: ${oauthCode}`)
let response = await generateAuthToken(oauthCode);
writeTokensToJson(response);
}
// This endpoint handles getting the token and then we redirect again to the homepage.
res.redirect('/');
});
/**
* Generates user access token and refresh token with the provided OAuth code.
*
* @param {string} oauthCode OAuth code
* @returns {object} Response token
*/
const generateAuthToken = async (oauthCode) => {
try {
let response = await axios({
url: 'https://id.twitch.tv/oauth2/token',
method: 'post',
timeout: 8000,
headers: {
'Content-Type': 'application/json'
},
params: {
client_id: config.env.TWITCH_CLIENT_ID,
client_secret: config.env.TWITCH_CLIENT_SECRET,
code: oauthCode,
grant_type: 'authorization_code',
redirect_uri: config.REDIRECT_URI
}
})
logger.info(`👍 Successfully retrieved oauth code`)
return response;
} catch (error) {
logger.error(`🔥 Error when generating OAuth Token: ${JSON.stringify(error.response.status)}`)
logger.error(`Error Headers: ${JSON.stringify(error.response.headers)}`)
logger.error(`Error Data: ${JSON.stringify(error.response.data)}`)
return;
}
};
const refreshAuthToken = (async (req, res) => {
try {
let response = await axios({
url: 'https://id.twitch.tv/oauth2/token',
method: 'post',
timeout: 8000,
headers: {
'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
},
params: {
grant_type: 'refresh_token',
refresh_token: parsedJsonTokens.TWITCH_REFRESH_TOKEN,
client_id: config.env.TWITCH_CLIENT_ID,
client_secret: config.env.TWITCH_CLIENT_SECRET
}
})
if (response.status == 200) {
logger.info(`👍 Successfully refreshed oauth token, redirecting to homepage`)
writeTokensToJson(response);
res.redirect('/')
}
} catch (error) {
logger.error(error.response.url)
logger.error(`🔥 Error when revoking OAuth Token: ${JSON.stringify(error.response.status)}`)
logger.error(`Error Headers: ${JSON.stringify(error.response.headers)}`)
logger.error(`Error Data: ${JSON.stringify(error.response.data)}`)
return false;
}
});
const writeTokensToJson = async (response) => {
if (response != undefined) {
let tokens = {
TWITCH_ACCESS_TOKEN: response.data.access_token,
TWITCH_REFRESH_TOKEN: response.data.refresh_token
}
logger.info(`Writing tokens to temp JSON file`);
writeToJsonFile('src/temp/', 'tokens.json', tokens);
}
}
router.get('/authorize', authorize);
router.get('/refresh', refreshAuthToken);
router.get('/unauthorize', unauthorize);
router.get('/redirect', redirect);
module.exports = router;
|
import ContestsService from "services/contests.service";
import PhotosService from "services/photos.service";
import UsersService from "services/users.service";
import ArticlesService from "services/articles.service";
import { apiService } from "services/api.service";
import { appConfigsService } from "services/app-configs.service";
import { isDataValid } from "utils/data.util";
import {
setContests,
setContestsPrizesSuccess,
setContestsCategoriesSuccess,
} from "./contests.actions";
import { setTranslations, setAppLanguage } from "./ui.actions";
import { setPhotosSubmittionsSuccess } from "./photos.actions";
import { setJudlesSuccess, setUsersSuccess } from "./users.actions";
import { setArticlesSuccess } from "./articles.actions";
import { checkExistedAccountAndSignIn } from "./auth.actions";
import enTranslations from 'mocks/translations/en';
import uaTranslations from 'mocks/translations/ua';
export const initAppData = (dispatch) => {
ContestsService.getContets().then((contestsResponse) => {
if (isDataValid(contestsResponse)) {
dispatch(setContests(contestsResponse.data));
}
});
ContestsService.getContestsPrizes().then((contestsPrizes) => {
if (isDataValid(contestsPrizes)) {
dispatch(setContestsPrizesSuccess(contestsPrizes.data));
}
});
ContestsService.getContestsCategories().then((contestsCategories) => {
if (isDataValid(contestsCategories)) {
dispatch(setContestsCategoriesSuccess(contestsCategories.data));
}
});
PhotosService.getPhotosSubmittions().then((photosSubmittionsData) => {
if (isDataValid(photosSubmittionsData)) {
dispatch(setPhotosSubmittionsSuccess(photosSubmittionsData.data));
}
});
UsersService.getJudles().then((judlesData) => {
if (isDataValid(judlesData)) {
dispatch(setJudlesSuccess(judlesData.data));
}
});
ArticlesService.getArticles().then((articlesData) => {
if (isDataValid(articlesData)) {
dispatch(setArticlesSuccess(articlesData.data));
}
});
UsersService.getUsers().then((usersResponse) => {
if (isDataValid(usersResponse)) {
dispatch(setUsersSuccess(usersResponse.data));
}
});
apiService.getAppTranslations().then((translationsData) => {
const newTranslationData = translationsData.data?.reduce((acc, tr) => {
acc[`${tr.key}.${tr.lang}`] = tr.value;
return acc;
}, {})
if (newTranslationData) {
Object.keys(uaTranslations).forEach(_key => {
newTranslationData[`${_key}.ua`] = uaTranslations[_key];
});
Object.keys(enTranslations).forEach(_key => {
newTranslationData[`${_key}.en`] = enTranslations[_key];
});
dispatch(setTranslations(newTranslationData));
}
});
const type = "[COMMON] INIT_APP_DATA";
dispatch(checkExistedAccountAndSignIn());
dispatch(setAppLanguage(appConfigsService.activeLang));
return {
type,
};
};
|
const responseSheet = document.getElementById('response-sheet');
const sheetDoc = document.implementation.createHTMLDocument("Response-Sheet").documentElement;
responseSheet.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
var reader = new FileReader();
reader.onload = (evt) => {
var text = evt.target.result;
sheetDoc.innerHTML = text;
}
reader.readAsText(file);
} else {
document.querySelector(".response-sheet-content").textContent = "Failed to load response-sheet";
}
});
const answerKey = document.getElementById('answer-key');
const keyDoc = document.implementation.createHTMLDocument("Answer-Key").documentElement;
answerKey.addEventListener('change', (event) => {
const file = event.target.files[0];
if (file) {
var reader = new FileReader();
reader.onload = (evt) => {
var text = evt.target.result;
keyDoc.innerHTML = text;
}
reader.readAsText(file);
} else {
document.querySelector(".answer-key-content").textContent = "Failed to load answer-key";
}
});
const doTheMath = () => {
var scores = new Map();
["Physics", "Chemistry", "Mathematics", "total-score"].forEach((subject) => { scores.set(subject, 0); } );
var answerKeyRows = keyDoc.getRootNode().getElementById("ctl00_LoginContent_grAnswerKey").getElementsByTagName("tr")
var i = 1;
var count = 0;
var answerMap = new Map();
while (count < 90) {
if(answerKeyRows[i].getElementsByTagName("span").length > 0) {
var answerDetails = answerKeyRows[i].getElementsByTagName("span");
var quesType = answerDetails[1].textContent;
var questionNo = answerDetails[2].textContent;
var correctAnswer = answerDetails[3].textContent;
answerMap.set(questionNo, { type : quesType, answer : correctAnswer });
if(quesType === "Objective") i++;
}
i++;
count++;
}
var sections = sheetDoc.getElementsByClassName("section-cntnr");
for(var i = 0 ; i < sections.length ; i++) {
var section = sections[i];
var sectionName = section.getElementsByClassName("section-lbl")[0].children[1].textContent;
var subject = sectionName.split(" ")[0];
var questions = section.getElementsByClassName("questionPnlTbl");
for(var j = 0 ; j < questions.length ; j++) {
var question = questions[j];
var questionRowDetails = question.getElementsByClassName("questionRowTbl")[0].getElementsByTagName("tr")
var questionLabel = questionRowDetails[1].children[0].textContent
var questionDetails = question.getElementsByClassName("menu-tbl")[0].getElementsByTagName("tr")
var questionType = questionDetails[0].children[1].textContent
var questionId = questionDetails[1].children[1].textContent
var status = questionType == "MCQ" ? questionDetails[6].children[1].textContent : questionDetails[2].children[1].textContent;
var markedAnswer = questionType == "MCQ" ? questionDetails[7].children[1].textContent : questionRowDetails[4].children[1].textContent
var correctAnswer = getCorrectAnswer(questionDetails, answerMap.get(questionId).answer);
var scoreForThisQuestion = 0;
if(correctAnswer === markedAnswer) scoreForThisQuestion = 4;
else if(questionType === "MCQ" && !isNaN(markedAnswer) && !isNaN(correctAnswer)) scoreForThisQuestion--;
scores.set("total-score", scores.get("total-score") + scoreForThisQuestion);
scores.set(subject, scores.get(subject) + scoreForThisQuestion);
appendToTable([sectionName + " " + questionLabel, status, correctAnswer, markedAnswer]);
}
}
scores.forEach((value, key) => {
document.querySelector("#" + key).textContent = value;
});
}
const getCorrectAnswer = (questionDetails, answer) => {
if(questionDetails[0].children[1].textContent == "SA") return answer;
for(var i = 2 ; i < 6 ; i++) {
if(answer === questionDetails[i].children[1].textContent) return (i - 1).toString();
}
return answer;
}
const appendToTable = (tableRowContents) => {
var newRow = document.getElementById("responses-table-body").insertRow()
for(var i = 0 ; i < 4 ; i++) {
var newCell = newRow.insertCell();
newCell.appendChild(document.createTextNode(tableRowContents[i]));
}
newRow.setAttribute('class', findCorrectness(tableRowContents.slice(1, 4)));
}
const findCorrectness = (answerDetails) => {
if(answerDetails[0] === "Answered") {
if(answerDetails[1] === answerDetails[2]) return "table-success";
return "table-danger";
}
return "";
}
|
/* eslint-disable func-names, no-new, promise/catch-or-return */
import $ from 'jquery';
import axios from '~/lib/utils/axios_utils';
import _ from 'underscore';
import CreateLabelDropdown from '../../create_label';
import boardsStore from '../stores/boards_store';
$(document)
.off('created.label')
.on('created.label', (e, label) => {
boardsStore.new({
title: label.title,
position: boardsStore.state.lists.length - 2,
list_type: 'label',
label: {
id: label.id,
title: label.title,
color: label.color,
},
});
});
export default function initNewListDropdown() {
$('.js-new-board-list').each(function() {
const $this = $(this);
new CreateLabelDropdown(
$this.closest('.dropdown').find('.dropdown-new-label'),
$this.data('namespacePath'),
$this.data('projectPath'),
);
$this.glDropdown({
data(term, callback) {
axios.get($this.attr('data-list-labels-path')).then(({ data }) => {
callback(data);
});
},
renderRow(label) {
const active = boardsStore.findList('title', label.title);
const $li = $('<li />');
const $a = $('<a />', {
class: active ? `is-active js-board-list-${active.id}` : '',
text: label.title,
href: '#',
});
const $labelColor = $('<span />', {
class: 'dropdown-label-box',
style: `background-color: ${label.color}`,
});
return $li.append($a.prepend($labelColor));
},
search: {
fields: ['title'],
},
filterable: true,
selectable: true,
multiSelect: true,
containerSelector: '.js-tab-container-labels .dropdown-page-one .dropdown-content',
clicked(options) {
const { e } = options;
const label = options.selectedObj;
e.preventDefault();
if (!boardsStore.findList('title', label.title)) {
boardsStore.new({
title: label.title,
position: boardsStore.state.lists.length - 2,
list_type: 'label',
label: {
id: label.id,
title: label.title,
color: label.color,
},
});
boardsStore.state.lists = _.sortBy(boardsStore.state.lists, 'position');
}
},
});
});
}
|
import ViewContact from './my-accounts.component'
import { compose } from 'recompose'
import { connect } from 'react-redux'
import { withRouter } from 'react-router-dom'
import { accountsWithSendEtherInfoSelector } from '../../../../selectors/selectors'
const mapStateToProps = (state) => {
const myAccounts = accountsWithSendEtherInfoSelector(state)
return {
myAccounts,
}
}
export default compose(withRouter, connect(mapStateToProps))(ViewContact)
|
import '@vaadin/vaadin-material-styles/color.js';
import { menuOverlay } from '@vaadin/vaadin-material-styles/mixins/menu-overlay.js';
import { css, registerStyles } from '@vaadin/vaadin-themable-mixin/vaadin-themable-mixin.js';
const avatarGroupOverlay = css`
[part='overlay'] {
outline: none;
}
`;
registerStyles('vaadin-avatar-group-overlay', [menuOverlay, avatarGroupOverlay], {
moduleId: 'material-avatar-group-overlay'
});
registerStyles(
'vaadin-avatar-group-list-box',
css`
[part='items'] ::slotted(vaadin-item[theme='avatar-group-item']) {
padding: 8px;
padding-right: 24px;
}
:host([dir='rtl']) [part='items'] ::slotted(vaadin-item[theme='avatar-group-item']) {
padding: 8px;
padding-left: 24px;
}
`,
{ moduleId: 'material-avatar-group-list-box' }
);
registerStyles(
'vaadin-item',
css`
:host([theme='avatar-group-item']) [part='content'] {
display: flex;
align-items: center;
}
:host([theme='avatar-group-item']) [part='checkmark']::before {
display: none;
}
:host([theme='avatar-group-item']:not([dir='rtl'])) ::slotted(vaadin-avatar) {
margin-right: 8px;
}
:host([theme='avatar-group-item'][dir='rtl']) ::slotted(vaadin-avatar) {
margin-left: 8px;
}
`,
{ moduleId: 'material-avatar-group-item' }
);
|
import React from 'react';
import { CodeComponent } from './CodeComponent';
import { bemClasses } from '../../../../../helpers/misc';
import { TRIGGER_SCHEMA } from '../../../../../constants';
const classes = {
schemaExample: bemClasses.element(`schema-example`),
schemaHeader: bemClasses.element(`schema-example-header`),
schemaHeaderTitle: bemClasses.element(`schema-example-header-title`),
};
export const SchemaExample = ({ schema = {} }) => {
const example = JSON.stringify(schema.example || {}, null, 2);
if (!example || !Object.keys(example).length) {
return null;
}
const renderedTitle = (
<header className={classes.schemaHeader}>
<span className={classes.schemaHeaderTitle}>
{TRIGGER_SCHEMA.EXAMPLE_TEXT}
</span>
</header>
);
return (
<div className={classes.schemaExample}>
<CodeComponent code={example} title={renderedTitle} />
</div>
);
};
|
var callbackArguments = [];
var argument1 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument1[2.1869172855352885e+307] = 122
return a+b-c-d
};
var argument2 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument2[9] = {"25":1.3580484526687759e+308,"157":"","655":"","843":82,"":"","5e-324":5.034160658305139e+307,"8.462627616720447e+307":1.1315952725967238e+308,"1.537448068198547e+308":""}
return a+b+c+d
};
var argument3 = false;
var argument4 = {"460":"N","595":-100,"":3.4203197471313544e+307,"T":655,"MEg%>^[c_<;":"q)","9G":9.645797075099021e+307};
var argument5 = 1.517678662922813e+308;
var argument6 = false;
var argument7 = r_0;
var argument8 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument6[3] = null
base_2[1][3] = null
return a+b*c+d
};
var argument9 = function callback(a,b,c,d) {
callbackArguments.push(JSON.stringify(arguments))
argument9[8] = {"49":"F","714":"","8.67486099559871e+307":"g","":"0sdwj","2L+":893}
return a-b-c/d
};
var base_0 = ["X","#3"]
var r_0= undefined
try {
r_0 = base_0.reduce(argument1)
}
catch(e) {
r_0= "Error"
}
var base_1 = ["X","#3"]
var r_1= undefined
try {
r_1 = base_1.reduce(argument2,argument3,argument4)
}
catch(e) {
r_1= "Error"
}
var base_2 = ["X","#3"]
var r_2= undefined
try {
r_2 = base_2.reduce(argument5,argument6,argument7,argument8)
}
catch(e) {
r_2= "Error"
}
var base_3 = ["X","#3"]
var r_3= undefined
try {
r_3 = base_3.reduce(argument9)
}
catch(e) {
r_3= "Error"
}
function serialize(array){
return array.map(function(a){
if (a === null || a == undefined) return a;
var name = a.constructor.name;
if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String')
return JSON.stringify(a);
return name;
});
}
setTimeout(function(){
require("fs").writeFileSync("./experiments/reduce/reduceGen/test402.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments}))
},300)
|
import React from 'react';
import AppBtn from "./AppBtn";
import { CompLev } from '../helpers/survey';
import { ReactComponent as ShareIcon } from "../icons/share.svg";
import { ReactComponent as EditIcon } from "../icons/edit.svg";
import { ReactComponent as TrashIcon } from "../icons/trash.svg";
import "./SurveyItem.css";
const SurveyItem = ({ surveyMeta, onShare, onEdit, onDelete }) => {
//Derive proper color for indicator
const cL = surveyMeta.compLev; //shorter
const statusNameSuffix = surveyMeta.ongoing ? (
(cL === CompLev.TOO_FEW ? "ongoing-too-few" : "ongoing-some")
) : (
(cL === CompLev.ALL ? "complete" :
(cL === CompLev.SOME ? "complete-some" : "terminated")
)
);
const statusName = `SurveyItem-indicator SurveyItem-${statusNameSuffix}`;
//Text versions of meta
const dateStr = new Date(surveyMeta.createTime).toLocaleDateString();
return (
<div className="SurveyItem">
<div className="SurveyItem-info">
<div className={statusName}>+</div>
<div className="SurveyItem-info-details">
<h4>{dateStr}</h4>
<p>{`${cL} (${surveyMeta.numResponders})`}</p>
</div>
</div>
<div className="SurveyItem-edit">
{ onShare ?
<AppBtn onClick={() => onShare(surveyMeta)}>
<ShareIcon />
</AppBtn> : null }
{ onEdit ?
<AppBtn onClick={() => onEdit(surveyMeta)}>
<EditIcon />
</AppBtn> : null }
{ onDelete ?
<AppBtn onClick={() => onDelete(surveyMeta)}>
<TrashIcon />
</AppBtn> : null }
</div>
</div>
);
};
export default SurveyItem;
|
/*! bootstrap3-wysihtml5-bower 2014-09-26 */
var wysihtml5,Base,Handlebars;Object.defineProperty&&Object.getOwnPropertyDescriptor&&Object.getOwnPropertyDescriptor(Element.prototype,"textContent")&&!Object.getOwnPropertyDescriptor(Element.prototype,"textContent").get&&!function(){var a=Object.getOwnPropertyDescriptor(Element.prototype,"innerText");Object.defineProperty(Element.prototype,"textContent",{get:function(){return a.get.call(this)},set:function(b){return a.set.call(this,b)}})}(),Array.isArray||(Array.isArray=function(a){return"[object Array]"===Object.prototype.toString.call(a)}),wysihtml5={version:"0.4.15",commands:{},dom:{},quirks:{},toolbar:{},lang:{},selection:{},views:{},INVISIBLE_SPACE:"",EMPTY_FUNCTION:function(){},ELEMENT_NODE:1,TEXT_NODE:3,BACKSPACE_KEY:8,ENTER_KEY:13,ESCAPE_KEY:27,SPACE_KEY:32,DELETE_KEY:46},function(a,b){"function"==typeof define&&define.amd?define(a):b.rangy=a()}(function(){function a(a,b){var c=typeof a[b];return c==x||!(c!=w||!a[b])||"unknown"==c}function b(a,b){return!(typeof a[b]!=w||!a[b])}function c(a,b){return typeof a[b]!=y}function d(a){return function(b,c){for(var d=c.length;d--;)if(!a(b,c[d]))return!1;return!0}}function e(a){return a&&D(a,C)&&F(a,B)}function f(a){return b(a,"body")?a.body:a.getElementsByTagName("body")[0]}function g(c){b(window,"console")&&a(window.console,"log")&&window.console.log(c)}function h(a,b){b?window.alert(a):g(a)}function i(a){H.initialized=!0,H.supported=!1,h("Rangy is not supported on this page in your browser. Reason: "+a,H.config.alertOnFail)}function j(a){h("Rangy warning: "+a,H.config.alertOnWarn)}function k(a){return a.message||a.description||a+""}function l(){var b,c,d,h,j,l,m,o,p;if(!H.initialized){if(c=!1,d=!1,a(document,"createRange")&&(b=document.createRange(),D(b,A)&&F(b,z)&&(c=!0)),h=f(document),!h||"body"!=h.nodeName.toLowerCase())return i("No body element found"),void 0;if(h&&a(h,"createTextRange")&&(b=h.createTextRange(),e(b)&&(d=!0)),!c&&!d)return i("Neither Range nor TextRange are available"),void 0;H.initialized=!0,H.features={implementsDomRange:c,implementsTextRange:d};for(m in G)(j=G[m])instanceof n&&j.init(j,H);for(o=0,p=s.length;p>o;++o)try{s[o](H)}catch(q){l="Rangy init listener threw an exception. Continuing. Detail: "+k(q),g(l)}}}function m(a){a=a||window,l();for(var b=0,c=t.length;c>b;++b)t[b](a)}function n(a,b,c){this.name=a,this.dependencies=b,this.initialized=!1,this.supported=!1,this.initializer=c}function o(a,b,c,d){var e=new n(b,c,function(a){if(!a.initialized){a.initialized=!0;try{d(H,a),a.supported=!0}catch(c){var e="Module '"+b+"' failed to load: "+k(c);g(e)}}});G[b]=e}function p(){}function q(){}var r,s,t,u,v,w="object",x="function",y="undefined",z=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],A=["setStart","setStartBefore","setStartAfter","setEnd","setEndBefore","setEndAfter","collapse","selectNode","selectNodeContents","compareBoundaryPoints","deleteContents","extractContents","cloneContents","insertNode","surroundContents","cloneRange","toString","detach"],B=["boundingHeight","boundingLeft","boundingTop","boundingWidth","htmlText","text"],C=["collapse","compareEndPoints","duplicate","moveToElementText","parentElement","select","setEndPoint","getBoundingClientRect"],D=d(a),E=d(b),F=d(c),G={},H={version:"1.3alpha.20140804",initialized:!1,supported:!0,util:{isHostMethod:a,isHostObject:b,isHostProperty:c,areHostMethods:D,areHostObjects:E,areHostProperties:F,isTextRange:e,getBody:f},features:{},modules:G,config:{alertOnFail:!0,alertOnWarn:!1,preferTextRange:!1,autoInitialize:typeof rangyAutoInitialize==y?!0:rangyAutoInitialize}};return H.fail=i,H.warn=j,{}.hasOwnProperty?H.util.extend=function(a,b,c){var d,e,f;for(f in b)b.hasOwnProperty(f)&&(d=a[f],e=b[f],c&&null!==d&&"object"==typeof d&&null!==e&&"object"==typeof e&&H.util.extend(d,e,!0),a[f]=e);return b.hasOwnProperty("toString")&&(a.toString=b.toString),a}:i("hasOwnProperty not supported"),function(){var a,b,c=document.createElement("div");c.appendChild(document.createElement("span")),a=[].slice;try{1==a.call(c.childNodes,0)[0].nodeType&&(b=function(b){return a.call(b,0)})}catch(d){}b||(b=function(a){var b,c,d=[];for(b=0,c=a.length;c>b;++b)d[b]=a[b];return d}),H.util.toArray=b}(),a(document,"addEventListener")?r=function(a,b,c){a.addEventListener(b,c,!1)}:a(document,"attachEvent")?r=function(a,b,c){a.attachEvent("on"+b,c)}:i("Document does not have required addEventListener or attachEvent method"),H.util.addListener=r,s=[],H.init=l,H.addInitListener=function(a){H.initialized?a(H):s.push(a)},t=[],H.addShimListener=function(a){t.push(a)},H.shim=H.createMissingNativeApi=m,n.prototype={init:function(){var a,b,c,d,e=this.dependencies||[];for(a=0,b=e.length;b>a;++a){if(d=e[a],c=G[d],!(c&&c instanceof n))throw Error("required module '"+d+"' not found");if(c.init(),!c.supported)throw Error("required module '"+d+"' not supported")}this.initializer(this)},fail:function(a){throw this.initialized=!0,this.supported=!1,Error("Module '"+this.name+"' failed to load: "+a)},warn:function(a){H.warn("Module "+this.name+": "+a)},deprecationNotice:function(a,b){H.warn("DEPRECATED: "+a+" in module "+this.name+"is deprecated. Please use "+b+" instead")},createError:function(a){return Error("Error in Rangy "+this.name+" module: "+a)}},H.createModule=function(a){var b,c,d;2==arguments.length?(b=arguments[1],c=[]):(b=arguments[2],c=arguments[1]),d=o(!1,a,c,b),H.initialized&&d.init()},H.createCoreModule=function(a,b,c){o(!0,a,b,c)},H.RangePrototype=p,H.rangePrototype=new p,H.selectionPrototype=new q,u=!1,v=function(){u||(u=!0,!H.initialized&&H.config.autoInitialize&&l())},typeof window==y?(i("No window found"),void 0):typeof document==y?(i("No document found"),void 0):(a(document,"addEventListener")&&document.addEventListener("DOMContentLoaded",v,!1),r(window,"load",v),H.createCoreModule("DomUtil",[],function(a,b){function c(a){var b;return typeof a.namespaceURI==I||null===(b=a.namespaceURI)||"http://www.w3.org/1999/xhtml"==b}function d(a){var b=a.parentNode;return 1==b.nodeType?b:null}function e(a){for(var b=0;a=a.previousSibling;)++b;return b}function f(a){switch(a.nodeType){case 7:case 10:return 0;case 3:case 8:return a.length;default:return a.childNodes.length}}function g(a,b){var c,d=[];for(c=a;c;c=c.parentNode)d.push(c);for(c=b;c;c=c.parentNode)if(F(d,c))return c;return null}function h(a,b,c){for(var d=c?b:b.parentNode;d;){if(d===a)return!0;d=d.parentNode}return!1}function i(a,b){return h(a,b,!0)}function j(a,b,c){for(var d,e=c?a:a.parentNode;e;){if(d=e.parentNode,d===b)return e;e=d}return null}function k(a){var b=a.nodeType;return 3==b||4==b||8==b}function l(a){if(!a)return!1;var b=a.nodeType;return 3==b||8==b}function m(a,b){var c=b.nextSibling,d=b.parentNode;return c?d.insertBefore(a,c):d.appendChild(a),a}function n(a,b,c){var d,f,g=a.cloneNode(!1);if(g.deleteData(0,b),a.deleteData(b,a.length-b),m(g,a),c)for(d=0;f=c[d++];)f.node==a&&f.offset>b?(f.node=g,f.offset-=b):f.node==a.parentNode&&f.offset>e(a)&&++f.offset;return g}function o(a){if(9==a.nodeType)return a;if(typeof a.ownerDocument!=I)return a.ownerDocument;if(typeof a.document!=I)return a.document;if(a.parentNode)return o(a.parentNode);throw b.createError("getDocument: no document found for node")}function p(a){var c=o(a);if(typeof c.defaultView!=I)return c.defaultView;if(typeof c.parentWindow!=I)return c.parentWindow;throw b.createError("Cannot get a window object for node")}function q(a){if(typeof a.contentDocument!=I)return a.contentDocument;if(typeof a.contentWindow!=I)return a.contentWindow.document;throw b.createError("getIframeDocument: No Document object found for iframe element")}function r(a){if(typeof a.contentWindow!=I)return a.contentWindow;if(typeof a.contentDocument!=I)return a.contentDocument.defaultView;throw b.createError("getIframeWindow: No Window object found for iframe element")}function s(a){return a&&J.isHostMethod(a,"setTimeout")&&J.isHostObject(a,"document")}function t(a,b,c){var d;if(a?J.isHostProperty(a,"nodeType")?d=1==a.nodeType&&"iframe"==a.tagName.toLowerCase()?q(a):o(a):s(a)&&(d=a.document):d=document,!d)throw b.createError(c+"(): Parameter must be a Window object or DOM node");return d}function u(a){for(var b;b=a.parentNode;)a=b;return a}function v(a,c,d,f){var h,i,k,l,m;if(a==d)return c===f?0:f>c?-1:1;if(h=j(d,a,!0))return c<=e(h)?-1:1;if(h=j(a,d,!0))return e(h)<f?-1:1;if(i=g(a,d),!i)throw Error("comparePoints error: nodes have no common ancestor");if(k=a===i?i:j(a,i,!0),l=d===i?i:j(d,i,!0),k===l)throw b.createError("comparePoints got to case 4 and childA and childB are the same!");for(m=i.firstChild;m;){if(m===k)return-1;if(m===l)return 1;m=m.nextSibling}}function w(a){var b;try{return b=a.parentNode,!1}catch(c){return!0}}function x(a){if(!a)return"[No node]";if(G&&w(a))return"[Broken node]";if(k(a))return'"'+a.data+'"';if(1==a.nodeType){var b=a.id?' id="'+a.id+'"':"";return"<"+a.nodeName+b+">[index:"+e(a)+",length:"+a.childNodes.length+"]["+(a.innerHTML||"[innerHTML not supported]").slice(0,25)+"]"}return a.nodeName}function y(a){for(var b,c=o(a).createDocumentFragment();b=a.firstChild;)c.appendChild(b);return c}function z(a){this.root=a,this._next=a}function A(a){return new z(a)}function B(a,b){this.node=a,this.offset=b}function C(a){this.code=this[a],this.codeName=a,this.message="DOMException: "+this.codeName}var D,E,F,G,H,I="undefined",J=a.util;J.areHostMethods(document,["createDocumentFragment","createElement","createTextNode"])||b.fail("document missing a Node creation method"),J.isHostMethod(document,"getElementsByTagName")||b.fail("document missing getElementsByTagName method"),D=document.createElement("div"),J.areHostMethods(D,["insertBefore","appendChild","cloneNode"]||!J.areHostObjects(D,["previousSibling","nextSibling","childNodes","parentNode"]))||b.fail("Incomplete Element implementation"),J.isHostProperty(D,"innerHTML")||b.fail("Element is missing innerHTML property"),E=document.createTextNode("test"),J.areHostMethods(E,["splitText","deleteData","insertData","appendData","cloneNode"]||!J.areHostObjects(D,["previousSibling","nextSibling","childNodes","parentNode"])||!J.areHostProperties(E,["data"]))||b.fail("Incomplete Text Node implementation"),F=function(a,b){for(var c=a.length;c--;)if(a[c]===b)return!0;return!1},G=!1,function(){var b,c=document.createElement("b");c.innerHTML="1",b=c.firstChild,c.innerHTML="<br>",G=w(b),a.features.crashyTextNodes=G}(),typeof window.getComputedStyle!=I?H=function(a,b){return p(a).getComputedStyle(a,null)[b]}:typeof document.documentElement.currentStyle!=I?H=function(a,b){return a.currentStyle[b]}:b.fail("No means of obtaining computed style properties found"),z.prototype={_current:null,hasNext:function(){return!!this._next},next:function(){var a,b,c=this._current=this._next;if(this._current)if(a=c.firstChild,a)this._next=a;else{for(b=null;c!==this.root&&!(b=c.nextSibling);)c=c.parentNode;this._next=b}return this._current},detach:function(){this._current=this._next=this.root=null}},B.prototype={equals:function(a){return!!a&&this.node===a.node&&this.offset==a.offset},inspect:function(){return"[DomPosition("+x(this.node)+":"+this.offset+")]"},toString:function(){return this.inspect()}},C.prototype={INDEX_SIZE_ERR:1,HIERARCHY_REQUEST_ERR:3,WRONG_DOCUMENT_ERR:4,NO_MODIFICATION_ALLOWED_ERR:7,NOT_FOUND_ERR:8,NOT_SUPPORTED_ERR:9,INVALID_STATE_ERR:11,INVALID_NODE_TYPE_ERR:24},C.prototype.toString=function(){return this.message},a.dom={arrayContains:F,isHtmlNamespace:c,parentElement:d,getNodeIndex:e,getNodeLength:f,getCommonAncestor:g,isAncestorOf:h,isOrIsAncestorOf:i,getClosestAncestorIn:j,isCharacterDataNode:k,isTextOrCommentNode:l,insertAfter:m,splitDataNode:n,getDocument:o,getWindow:p,getIframeWindow:r,getIframeDocument:q,getBody:J.getBody,isWindow:s,getContentDocument:t,getRootContainer:u,comparePoints:v,isBrokenNode:w,inspectNode:x,getComputedStyleProperty:H,fragmentFromNodeChildren:y,createIterator:A,DomPosition:B},a.DOMException=C}),H.createCoreModule("DomRange",["DomUtil"],function(a){function b(a,b){return 3!=a.nodeType&&(gb(a,b.startContainer)||gb(a,b.endContainer))}function c(a){return a.document||hb(a.startContainer)}function d(a){return new cb(a.parentNode,fb(a))}function e(a){return new cb(a.parentNode,fb(a)+1)}function f(a,b,c){var d=11==a.nodeType?a.firstChild:a;return eb(b)?c==b.length?ab.insertAfter(a,b):b.parentNode.insertBefore(a,0==c?b:jb(b,c)):c>=b.childNodes.length?b.appendChild(a):b.insertBefore(a,b.childNodes[c]),d}function g(a,b,d){if(y(a),y(b),c(b)!=c(a))throw new db("WRONG_DOCUMENT_ERR");var e=ib(a.startContainer,a.startOffset,b.endContainer,b.endOffset),f=ib(a.endContainer,a.endOffset,b.startContainer,b.startOffset);return d?0>=e&&f>=0:0>e&&f>0}function h(a){var b,d,e,f;for(e=c(a.range).createDocumentFragment();d=a.next();){if(b=a.isPartiallySelectedSubtree(),d=d.cloneNode(!b),b&&(f=a.getSubtreeIterator(),d.appendChild(h(f)),f.detach()),10==d.nodeType)throw new db("HIERARCHY_REQUEST_ERR");e.appendChild(d)}return e}function i(a,b,c){var d,e,f,g;for(c=c||{stop:!1};f=a.next();)if(a.isPartiallySelectedSubtree()){if(b(f)===!1)return c.stop=!0,void 0;if(g=a.getSubtreeIterator(),i(g,b,c),g.detach(),c.stop)return}else for(d=ab.createIterator(f);e=d.next();)if(b(e)===!1)return c.stop=!0,void 0}function j(a){for(var b;a.next();)a.isPartiallySelectedSubtree()?(b=a.getSubtreeIterator(),j(b),b.detach()):a.remove()}function k(a){for(var b,d,e=c(a.range).createDocumentFragment();b=a.next();){if(a.isPartiallySelectedSubtree()?(b=b.cloneNode(!1),d=a.getSubtreeIterator(),b.appendChild(k(d)),d.detach()):a.remove(),10==b.nodeType)throw new db("HIERARCHY_REQUEST_ERR");e.appendChild(b)}return e}function l(a,b,c){var d,e,f=!(!b||!b.length),g=!!c;return f&&(d=RegExp("^("+b.join("|")+")$")),e=[],i(new n(a,!1),function(b){var h,i;(!f||d.test(b.nodeType))&&(!g||c(b))&&(h=a.startContainer,b==h&&eb(h)&&a.startOffset==h.length||(i=a.endContainer,b==i&&eb(i)&&0==a.endOffset||e.push(b)))}),e}function m(a){var b=void 0===a.getName?"Range":a.getName();return"["+b+"("+ab.inspectNode(a.startContainer)+":"+a.startOffset+", "+ab.inspectNode(a.endContainer)+":"+a.endOffset+")]"}function n(a,b){if(this.range=a,this.clonePartiallySelectedTextNodes=b,!a.collapsed){this.sc=a.startContainer,this.so=a.startOffset,this.ec=a.endContainer,this.eo=a.endOffset;var c=a.commonAncestorContainer;this.sc===this.ec&&eb(this.sc)?(this.isSingleCharacterDataNode=!0,this._first=this._last=this._next=this.sc):(this._first=this._next=this.sc!==c||eb(this.sc)?kb(this.sc,c,!0):this.sc.childNodes[this.so],this._last=this.ec!==c||eb(this.ec)?kb(this.ec,c,!0):this.ec.childNodes[this.eo-1])}}function o(a){return function(b,c){for(var d,e=c?b:b.parentNode;e;){if(d=e.nodeType,mb(a,d))return e;e=e.parentNode}return null}}function p(a,b){if(P(a,b))throw new db("INVALID_NODE_TYPE_ERR")}function q(a,b){if(!mb(b,a.nodeType))throw new db("INVALID_NODE_TYPE_ERR")}function r(a,b){if(0>b||b>(eb(a)?a.length:a.childNodes.length))throw new db("INDEX_SIZE_ERR")}function s(a,b){if(N(a,!0)!==N(b,!0))throw new db("WRONG_DOCUMENT_ERR")}function t(a){if(O(a,!0))throw new db("NO_MODIFICATION_ALLOWED_ERR")}function u(a,b){if(!a)throw new db(b)}function v(a){return ob&&ab.isBrokenNode(a)||!mb(J,a.nodeType)&&!N(a,!0)}function w(a,b){return b<=(eb(a)?a.length:a.childNodes.length)}function x(a){return!!a.startContainer&&!!a.endContainer&&!v(a.startContainer)&&!v(a.endContainer)&&w(a.startContainer,a.startOffset)&&w(a.endContainer,a.endOffset)}function y(a){if(!x(a))throw Error("Range error: Range is no longer valid after DOM mutation ("+a.inspect()+")")}function z(a,b){var c,d,e,f,g;y(a),c=a.startContainer,d=a.startOffset,e=a.endContainer,f=a.endOffset,g=c===e,eb(e)&&f>0&&f<e.length&&jb(e,f,b),eb(c)&&d>0&&d<c.length&&(c=jb(c,d,b),g?(f-=d,e=c):e==c.parentNode&&f>=fb(c)&&f++,d=0),a.setStartAndEnd(c,d,e,f)}function A(a){y(a);var b=a.commonAncestorContainer.parentNode.cloneNode(!1);return b.appendChild(a.cloneContents()),b.innerHTML}function B(a){a.START_TO_START=U,a.START_TO_END=V,a.END_TO_END=W,a.END_TO_START=X,a.NODE_BEFORE=Y,a.NODE_AFTER=Z,a.NODE_BEFORE_AND_AFTER=$,a.NODE_INSIDE=_}function C(a){B(a),B(a.prototype)}function D(a,b){return function(){var c,d,f,g,h,j,k;return y(this),c=this.startContainer,d=this.startOffset,f=this.commonAncestorContainer,g=new n(this,!0),c!==f&&(h=kb(c,f,!0),j=e(h),c=j.node,d=j.offset),i(g,t),g.reset(),k=a(g),g.detach(),b(this,c,d,c,d),k}}function E(c,f){function g(a,b){return function(c){q(c,I),q(nb(c),J);var f=(a?d:e)(c);(b?h:i)(this,f.node,f.offset)}}function h(a,b,c){var d=a.endContainer,e=a.endOffset;(b!==a.startContainer||c!==a.startOffset)&&((nb(b)!=nb(d)||1==ib(b,c,d,e))&&(d=b,e=c),f(a,b,c,d,e))}function i(a,b,c){var d=a.startContainer,e=a.startOffset;(b!==a.endContainer||c!==a.endOffset)&&((nb(b)!=nb(d)||-1==ib(b,c,d,e))&&(d=b,e=c),f(a,d,e,b,c))}var l=function(){};l.prototype=a.rangePrototype,c.prototype=new l,bb.extend(c.prototype,{setStart:function(a,b){p(a,!0),r(a,b),h(this,a,b)},setEnd:function(a,b){p(a,!0),r(a,b),i(this,a,b)},setStartAndEnd:function(){var a=arguments,b=a[0],c=a[1],d=b,e=c;switch(a.length){case 3:e=a[2];break;case 4:d=a[2],e=a[3]}f(this,b,c,d,e)},setBoundary:function(a,b,c){this["set"+(c?"Start":"End")](a,b)},setStartBefore:g(!0,!0),setStartAfter:g(!1,!0),setEndBefore:g(!0,!1),setEndAfter:g(!1,!1),collapse:function(a){y(this),a?f(this,this.startContainer,this.startOffset,this.startContainer,this.startOffset):f(this,this.endContainer,this.endOffset,this.endContainer,this.endOffset)},selectNodeContents:function(a){p(a,!0),f(this,a,0,a,lb(a))},selectNode:function(a){p(a,!1),q(a,I);var b=d(a),c=e(a);f(this,b.node,b.offset,c.node,c.offset)},extractContents:D(k,f),deleteContents:D(j,f),canSurroundContents:function(){var a,c;return y(this),t(this.startContainer),t(this.endContainer),a=new n(this,!0),c=a._first&&b(a._first,this)||a._last&&b(a._last,this),a.detach(),!c},splitBoundaries:function(){z(this)},splitBoundariesPreservingPositions:function(a){z(this,a)},normalizeBoundaries:function(){var a,b,c,d,e,g,h,i,j;y(this),a=this.startContainer,b=this.startOffset,c=this.endContainer,d=this.endOffset,e=function(a){var b=a.nextSibling;b&&b.nodeType==a.nodeType&&(c=a,d=a.length,a.appendData(b.data),b.parentNode.removeChild(b))},g=function(e){var f,g,h=e.previousSibling;h&&h.nodeType==e.nodeType&&(a=e,f=e.length,b=h.length,e.insertData(0,h.data),h.parentNode.removeChild(h),a==c?(d+=b,c=a):c==e.parentNode&&(g=fb(e),d==g?(c=e,d=f):d>g&&d--))},h=!0,eb(c)?c.length==d&&e(c):(d>0&&(i=c.childNodes[d-1],i&&eb(i)&&e(i)),h=!this.collapsed),h?eb(a)?0==b&&g(a):b<a.childNodes.length&&(j=a.childNodes[b],j&&eb(j)&&g(j)):(a=c,b=d),f(this,a,b,c,d)},collapseToPoint:function(a,b){p(a,!0),r(a,b),this.setStartAndEnd(a,b)}}),C(c)}function F(a){a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset,a.commonAncestorContainer=a.collapsed?a.startContainer:ab.getCommonAncestor(a.startContainer,a.endContainer)}function G(a,b,c,d,e){a.startContainer=b,a.startOffset=c,a.endContainer=d,a.endOffset=e,a.document=ab.getDocument(b),F(a)}function H(a){this.startContainer=a,this.startOffset=0,this.endContainer=a,this.endOffset=0,this.document=a,F(this)}var I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,$,_,ab=a.dom,bb=a.util,cb=ab.DomPosition,db=a.DOMException,eb=ab.isCharacterDataNode,fb=ab.getNodeIndex,gb=ab.isOrIsAncestorOf,hb=ab.getDocument,ib=ab.comparePoints,jb=ab.splitDataNode,kb=ab.getClosestAncestorIn,lb=ab.getNodeLength,mb=ab.arrayContains,nb=ab.getRootContainer,ob=a.features.crashyTextNodes;n.prototype={_current:null,_next:null,_first:null,_last:null,isSingleCharacterDataNode:!1,reset:function(){this._current=null,this._next=this._first},hasNext:function(){return!!this._next},next:function(){var a=this._current=this._next;return a&&(this._next=a!==this._last?a.nextSibling:null,eb(a)&&this.clonePartiallySelectedTextNodes&&(a===this.ec&&(a=a.cloneNode(!0)).deleteData(this.eo,a.length-this.eo),this._current===this.sc&&(a=a.cloneNode(!0)).deleteData(0,this.so))),a},remove:function(){var a,b,c=this._current;!eb(c)||c!==this.sc&&c!==this.ec?c.parentNode&&c.parentNode.removeChild(c):(a=c===this.sc?this.so:0,b=c===this.ec?this.eo:c.length,a!=b&&c.deleteData(a,b-a))},isPartiallySelectedSubtree:function(){var a=this._current;return b(a,this.range)},getSubtreeIterator:function(){var a,b,d,e,f,g;return this.isSingleCharacterDataNode?(a=this.range.cloneRange(),a.collapse(!1)):(a=new H(c(this.range)),b=this._current,d=b,e=0,f=b,g=lb(b),gb(b,this.sc)&&(d=this.sc,e=this.so),gb(b,this.ec)&&(f=this.ec,g=this.eo),G(a,d,e,f,g)),new n(a,this.clonePartiallySelectedTextNodes)},detach:function(){this.range=this._current=this._next=this._first=this._last=this.sc=this.so=this.ec=this.eo=null}},I=[1,3,4,5,7,8,10],J=[2,9,11],K=[5,6,10,12],L=[1,3,4,5,7,8,10,11],M=[1,3,4,5,7,8],N=o([9,11]),O=o(K),P=o([6,10,12]),Q=document.createElement("style"),R=!1;try{Q.innerHTML="<b>x</b>",R=3==Q.firstChild.nodeType}catch(pb){}a.features.htmlParsingConforms=R,S=R?function(a){var b,c=this.startContainer,d=hb(c);if(!c)throw new db("INVALID_STATE_ERR");return b=null,1==c.nodeType?b=c:eb(c)&&(b=ab.parentElement(c)),b=null===b||"HTML"==b.nodeName&&ab.isHtmlNamespace(hb(b).documentElement)&&ab.isHtmlNamespace(b)?d.createElement("body"):b.cloneNode(!1),b.innerHTML=a,ab.fragmentFromNodeChildren(b)}:function(a){var b=c(this),d=b.createElement("body");return d.innerHTML=a,ab.fragmentFromNodeChildren(d)},T=["startContainer","startOffset","endContainer","endOffset","collapsed","commonAncestorContainer"],U=0,V=1,W=2,X=3,Y=0,Z=1,$=2,_=3,bb.extend(a.rangePrototype,{compareBoundaryPoints:function(a,b){var c,d,e,f,g,h;return y(this),s(this.startContainer,b.startContainer),g=a==X||a==U?"start":"end",h=a==V||a==U?"start":"end",c=this[g+"Container"],d=this[g+"Offset"],e=b[h+"Container"],f=b[h+"Offset"],ib(c,d,e,f)},insertNode:function(a){if(y(this),q(a,L),t(this.startContainer),gb(a,this.startContainer))throw new db("HIERARCHY_REQUEST_ERR");var b=f(a,this.startContainer,this.startOffset);this.setStartBefore(b)},cloneContents:function(){var a,b,d;return y(this),this.collapsed?c(this).createDocumentFragment():this.startContainer===this.endContainer&&eb(this.startContainer)?(a=this.startContainer.cloneNode(!0),a.data=a.data.slice(this.startOffset,this.endOffset),b=c(this).createDocumentFragment(),b.appendChild(a),b):(d=new n(this,!0),a=h(d),d.detach(),a)},canSurroundContents:function(){var a,c;return y(this),t(this.startContainer),t(this.endContainer),a=new n(this,!0),c=a._first&&b(a._first,this)||a._last&&b(a._last,this),a.detach(),!c},surroundContents:function(a){if(q(a,M),!this.canSurroundContents())throw new db("INVALID_STATE_ERR");var b=this.extractContents();if(a.hasChildNodes())for(;a.lastChild;)a.removeChild(a.lastChild);f(a,this.startContainer,this.startOffset),a.appendChild(b),this.selectNode(a)},cloneRange:function(){var a,b,d;for(y(this),a=new H(c(this)),b=T.length;b--;)d=T[b],a[d]=this[d];return a},toString:function(){var a,b,c;return y(this),a=this.startContainer,a===this.endContainer&&eb(a)?3==a.nodeType||4==a.nodeType?a.data.slice(this.startOffset,this.endOffset):"":(b=[],c=new n(this,!0),i(c,function(a){(3==a.nodeType||4==a.nodeType)&&b.push(a.data)}),c.detach(),b.join(""))},compareNode:function(a){var b,c,d,e;if(y(this),b=a.parentNode,c=fb(a),!b)throw new db("NOT_FOUND_ERR");return d=this.comparePoint(b,c),e=this.comparePoint(b,c+1),0>d?e>0?$:Y:e>0?Z:_},comparePoint:function(a,b){return y(this),u(a,"HIERARCHY_REQUEST_ERR"),s(a,this.startContainer),ib(a,b,this.startContainer,this.startOffset)<0?-1:ib(a,b,this.endContainer,this.endOffset)>0?1:0},createContextualFragment:S,toHtml:function(){return A(this)},intersectsNode:function(a,b){var d,e,f,g;return y(this),u(a,"NOT_FOUND_ERR"),hb(a)!==c(this)?!1:(d=a.parentNode,e=fb(a),u(d,"NOT_FOUND_ERR"),f=ib(d,e,this.endContainer,this.endOffset),g=ib(d,e+1,this.startContainer,this.startOffset),b?0>=f&&g>=0:0>f&&g>0)},isPointInRange:function(a,b){return y(this),u(a,"HIERARCHY_REQUEST_ERR"),s(a,this.startContainer),ib(a,b,this.startContainer,this.startOffset)>=0&&ib(a,b,this.endContainer,this.endOffset)<=0},intersectsRange:function(a){return g(this,a,!1)},intersectsOrTouchesRange:function(a){return g(this,a,!0)},intersection:function(a){var b,c,d;return this.intersectsRange(a)?(b=ib(this.startContainer,this.startOffset,a.startContainer,a.startOffset),c=ib(this.endContainer,this.endOffset,a.endContainer,a.endOffset),d=this.cloneRange(),-1==b&&d.setStart(a.startContainer,a.startOffset),1==c&&d.setEnd(a.endContainer,a.endOffset),d):null},union:function(a){if(this.intersectsOrTouchesRange(a)){var b=this.cloneRange();return-1==ib(a.startContainer,a.startOffset,this.startContainer,this.startOffset)&&b.setStart(a.startContainer,a.startOffset),1==ib(a.endContainer,a.endOffset,this.endContainer,this.endOffset)&&b.setEnd(a.endContainer,a.endOffset),b}throw new db("Ranges do not intersect")},containsNode:function(a,b){return b?this.intersectsNode(a,!1):this.compareNode(a)==_},containsNodeContents:function(a){return this.comparePoint(a,0)>=0&&this.comparePoint(a,lb(a))<=0},containsRange:function(a){var b=this.intersection(a);return null!==b&&a.equals(b)},containsNodeText:function(a){var b,c,d=this.cloneRange();return d.selectNode(a),b=d.getNodes([3]),b.length>0?(d.setStart(b[0],0),c=b.pop(),d.setEnd(c,c.length),this.containsRange(d)):this.containsNodeContents(a)},getNodes:function(a,b){return y(this),l(this,a,b)},getDocument:function(){return c(this)},collapseBefore:function(a){this.setEndBefore(a),this.collapse(!1)},collapseAfter:function(a){this.setStartAfter(a),this.collapse(!0)},getBookmark:function(b){var d,e,f,g=c(this),h=a.createRange(g);return b=b||ab.getBody(g),h.selectNodeContents(b),d=this.intersection(h),e=0,f=0,d&&(h.setEnd(d.startContainer,d.startOffset),e=(""+h).length,f=e+(""+d).length),{start:e,end:f,containerNode:b}},moveToBookmark:function(a){var b,c,d,e,f,g,h,i=a.containerNode,j=0;for(this.setStart(i,0),this.collapse(!0),b=[i],d=!1,e=!1;!e&&(c=b.pop());)if(3==c.nodeType)f=j+c.length,!d&&a.start>=j&&a.start<=f&&(this.setStart(c,a.start-j),d=!0),d&&a.end>=j&&a.end<=f&&(this.setEnd(c,a.end-j),e=!0),j=f;else for(h=c.childNodes,g=h.length;g--;)b.push(h[g])},getName:function(){return"DomRange"},equals:function(a){return H.rangesEqual(this,a)},isValid:function(){return x(this)},inspect:function(){return m(this)},detach:function(){}}),E(H,G),bb.extend(H,{rangeProperties:T,RangeIterator:n,copyComparisonConstants:C,createPrototypeRange:E,inspect:m,toHtml:A,getRangeDocument:c,rangesEqual:function(a,b){return a.startContainer===b.startContainer&&a.startOffset===b.startOffset&&a.endContainer===b.endContainer&&a.endOffset===b.endOffset}}),a.DomRange=H}),H.createCoreModule("WrappedRange",["DomRange"],function(a,b){var c,d,e,f,g,h,i,j,k=a.dom,l=a.util,m=k.DomPosition,n=a.DomRange,o=k.getBody,p=k.getContentDocument,q=k.isCharacterDataNode;a.features.implementsDomRange&&!function(){function d(a){for(var b,c=s.length;c--;)b=s[c],a[b]=a.nativeRange[b];a.collapsed=a.startContainer===a.endContainer&&a.startOffset===a.endOffset}function e(a,b,c,d,e){var f=a.startContainer!==b||a.startOffset!=c,g=a.endContainer!==d||a.endOffset!=e,h=!a.equals(a.nativeRange);(f||g||h)&&(a.setEnd(d,e),a.setStart(b,c))}var f,g,h,i,j,m,q,r,s=n.rangeProperties;c=function(a){if(!a)throw b.createError("WrappedRange: Range must be specified");this.nativeRange=a,d(this)},n.createPrototypeRange(c,e),f=c.prototype,f.selectNode=function(a){this.nativeRange.selectNode(a),d(this)},f.cloneContents=function(){return this.nativeRange.cloneContents()},f.surroundContents=function(a){this.nativeRange.surroundContents(a),d(this)},f.collapse=function(a){this.nativeRange.collapse(a),d(this)},f.cloneRange=function(){return new c(this.nativeRange.cloneRange())},f.refresh=function(){d(this)},f.toString=function(){return""+this.nativeRange},h=document.createTextNode("test"),o(document).appendChild(h),i=document.createRange(),i.setStart(h,0),i.setEnd(h,0);try{i.setStart(h,1),f.setStart=function(a,b){this.nativeRange.setStart(a,b),d(this)},f.setEnd=function(a,b){this.nativeRange.setEnd(a,b),d(this)},g=function(a){return function(b){this.nativeRange[a](b),d(this)}}}catch(t){f.setStart=function(a,b){try{this.nativeRange.setStart(a,b)}catch(c){this.nativeRange.setEnd(a,b),this.nativeRange.setStart(a,b)}d(this)},f.setEnd=function(a,b){try{this.nativeRange.setEnd(a,b)}catch(c){this.nativeRange.setStart(a,b),this.nativeRange.setEnd(a,b)}d(this)},g=function(a,b){return function(c){try{this.nativeRange[a](c)}catch(e){this.nativeRange[b](c),this.nativeRange[a](c)}d(this)}}}f.setStartBefore=g("setStartBefore","setEndBefore"),f.setStartAfter=g("setStartAfter","setEndAfter"),f.setEndBefore=g("setEndBefore","setStartBefore"),f.setEndAfter=g("setEndAfter","setStartAfter"),f.selectNodeContents=function(a){this.setStartAndEnd(a,0,k.getNodeLength(a))},i.selectNodeContents(h),i.setEnd(h,3),j=document.createRange(),j.selectNodeContents(h),j.setEnd(h,4),j.setStart(h,2),f.compareBoundaryPoints=-1==i.compareBoundaryPoints(i.START_TO_END,j)&&1==i.compareBoundaryPoints(i.END_TO_START,j)?function(a,b){return b=b.nativeRange||b,a==b.START_TO_END?a=b.END_TO_START:a==b.END_TO_START&&(a=b.START_TO_END),this.nativeRange.compareBoundaryPoints(a,b)}:function(a,b){return this.nativeRange.compareBoundaryPoints(a,b.nativeRange||b)},m=document.createElement("div"),m.innerHTML="123",q=m.firstChild,r=o(document),r.appendChild(m),i.setStart(q,1),i.setEnd(q,2),i.deleteContents(),"13"==q.data&&(f.deleteContents=function(){this.nativeRange.deleteContents(),d(this)},f.extractContents=function(){var a=this.nativeRange.extractContents();return d(this),a}),r.removeChild(m),r=null,l.isHostMethod(i,"createContextualFragment")&&(f.createContextualFragment=function(a){return this.nativeRange.createContextualFragment(a)}),o(document).removeChild(h),f.getName=function(){return"WrappedRange"},a.WrappedRange=c,a.createNativeRange=function(a){return a=p(a,b,"createNativeRange"),a.createRange()}}(),a.features.implementsTextRange&&(e=function(a){var b,c,d,e=a.parentElement(),f=a.duplicate();return f.collapse(!0),b=f.parentElement(),f=a.duplicate(),f.collapse(!1),c=f.parentElement(),d=b==c?b:k.getCommonAncestor(b,c),d==e?d:k.getCommonAncestor(e,d)},f=function(a){return 0==a.compareEndPoints("StartToEnd",a)},g=function(a,b,c,d,e){var f,g,h,i,j,l,n,o,p,r,s,t,u,v,w,x,y=a.duplicate();if(y.collapse(c),f=y.parentElement(),k.isOrIsAncestorOf(b,f)||(f=b),!f.canHaveHTML)return g=new m(f.parentNode,k.getNodeIndex(f)),{boundaryPosition:g,nodeInfo:{nodeIndex:g.offset,containerElement:g.node}};for(h=k.getDocument(f).createElement("span"),h.parentNode&&h.parentNode.removeChild(h),j=c?"StartToStart":"StartToEnd",r=e&&e.containerElement==f?e.nodeIndex:0,s=f.childNodes.length,t=s,u=t;;){if(u==s?f.appendChild(h):f.insertBefore(h,f.childNodes[u]),y.moveToElementText(h),i=y.compareEndPoints(j,a),0==i||r==t)break;if(-1==i){if(t==r+1)break;r=u}else t=t==r+1?r:u;u=Math.floor((r+t)/2),f.removeChild(h)}if(p=h.nextSibling,-1==i&&p&&q(p)){if(y.setEndPoint(c?"EndToStart":"EndToEnd",a),/[\r\n]/.test(p.data))for(w=y.duplicate(),x=w.text.replace(/\r\n/g,"\r").length,v=w.moveStart("character",x);-1==(i=w.compareEndPoints("StartToEnd",w));)v++,w.moveStart("character",1);else v=y.text.length;o=new m(p,v)}else l=(d||!c)&&h.previousSibling,n=(d||c)&&h.nextSibling,o=n&&q(n)?new m(n,0):l&&q(l)?new m(l,l.data.length):new m(f,k.getNodeIndex(h));return h.parentNode.removeChild(h),{boundaryPosition:o,nodeInfo:{nodeIndex:u,containerElement:f}}},h=function(a,b){var c,d,e,f,g=a.offset,h=k.getDocument(a.node),i=o(h).createTextRange(),j=q(a.node);return j?(c=a.node,d=c.parentNode):(f=a.node.childNodes,c=g<f.length?f[g]:null,d=a.node),e=h.createElement("span"),e.innerHTML="&#feff;",c?d.insertBefore(e,c):d.appendChild(e),i.moveToElementText(e),i.collapse(!b),d.removeChild(e),j&&i[b?"moveStart":"moveEnd"]("character",g),i},d=function(a){this.textRange=a,this.refresh()},d.prototype=new n(document),d.prototype.refresh=function(){var a,b,c,d=e(this.textRange);
f(this.textRange)?b=a=g(this.textRange,d,!0,!0).boundaryPosition:(c=g(this.textRange,d,!0,!1),a=c.boundaryPosition,b=g(this.textRange,d,!1,!1,c.nodeInfo).boundaryPosition),this.setStart(a.node,a.offset),this.setEnd(b.node,b.offset)},d.prototype.getName=function(){return"WrappedTextRange"},n.copyComparisonConstants(d),i=function(a){var b,c,d;return a.collapsed?h(new m(a.startContainer,a.startOffset),!0):(b=h(new m(a.startContainer,a.startOffset),!0),c=h(new m(a.endContainer,a.endOffset),!1),d=o(n.getRangeDocument(a)).createTextRange(),d.setEndPoint("StartToStart",b),d.setEndPoint("EndToEnd",c),d)},d.rangeToTextRange=i,d.prototype.toTextRange=function(){return i(this)},a.WrappedTextRange=d,(!a.features.implementsDomRange||a.config.preferTextRange)&&(j=function(){return this}(),void 0===j.Range&&(j.Range=d),a.createNativeRange=function(a){return a=p(a,b,"createNativeRange"),o(a).createTextRange()},a.WrappedRange=d)),a.createRange=function(c){return c=p(c,b,"createRange"),new a.WrappedRange(a.createNativeRange(c))},a.createRangyRange=function(a){return a=p(a,b,"createRangyRange"),new n(a)},a.createIframeRange=function(c){return b.deprecationNotice("createIframeRange()","createRange(iframeEl)"),a.createRange(c)},a.createIframeRangyRange=function(c){return b.deprecationNotice("createIframeRangyRange()","createRangyRange(iframeEl)"),a.createRangyRange(c)},a.addShimListener(function(b){var c=b.document;void 0===c.createRange&&(c.createRange=function(){return a.createRange(c)}),c=b=null})}),H.createCoreModule("WrappedSelection",["DomRange","WrappedRange"],function(a,b){function c(a){return"string"==typeof a?/^backward(s)?$/i.test(a):!!a}function d(a,c){if(a){if(A.isWindow(a))return a;if(a instanceof r)return a.win;var d=A.getContentDocument(a,b,c);return A.getWindow(d)}return window}function e(a){return d(a,"getWinSelection").getSelection()}function f(a){return d(a,"getDocSelection").document.selection}function g(a){var b=!1;return a.anchorNode&&(b=1==A.comparePoints(a.anchorNode,a.anchorOffset,a.focusNode,a.focusOffset)),b}function h(a,b,c){var d=c?"end":"start",e=c?"start":"end";a.anchorNode=b[d+"Container"],a.anchorOffset=b[d+"Offset"],a.focusNode=b[e+"Container"],a.focusOffset=b[e+"Offset"]}function i(a){var b=a.nativeSelection;a.anchorNode=b.anchorNode,a.anchorOffset=b.anchorOffset,a.focusNode=b.focusNode,a.focusOffset=b.focusOffset}function j(a){a.anchorNode=a.focusNode=null,a.anchorOffset=a.focusOffset=0,a.rangeCount=0,a.isCollapsed=!0,a._ranges.length=0}function k(b){var c;return b instanceof D?(c=a.createNativeRange(b.getDocument()),c.setEnd(b.endContainer,b.endOffset),c.setStart(b.startContainer,b.startOffset)):b instanceof E?c=b.nativeRange:J.implementsDomRange&&b instanceof A.getWindow(b.startContainer).Range&&(c=b),c}function l(a){if(!a.length||1!=a[0].nodeType)return!1;for(var b=1,c=a.length;c>b;++b)if(!A.isAncestorOf(a[0],a[b]))return!1;return!0}function m(a){var c=a.getNodes();if(!l(c))throw b.createError("getSingleElementFromRange: range "+a.inspect()+" did not consist of a single element");return c[0]}function n(a){return!!a&&void 0!==a.text}function o(a,b){var c=new E(b);a._ranges=[c],h(a,c,!1),a.rangeCount=1,a.isCollapsed=c.collapsed}function p(b){var c,d,e,f;if(b._ranges.length=0,"None"==b.docSelection.type)j(b);else if(c=b.docSelection.createRange(),n(c))o(b,c);else{for(b.rangeCount=c.length,e=L(c.item(0)),f=0;f<b.rangeCount;++f)d=a.createRange(e),d.selectNode(c.item(f)),b._ranges.push(d);b.isCollapsed=1==b.rangeCount&&b._ranges[0].collapsed,h(b,b._ranges[b.rangeCount-1],!1)}}function q(a,c){var d,e,f=a.docSelection.createRange(),g=m(c),h=L(f.item(0)),i=M(h).createControlRange();for(d=0,e=f.length;e>d;++d)i.add(f.item(d));try{i.add(g)}catch(j){throw b.createError("addRange(): Element within the specified Range could not be added to control selection (does it have layout?)")}i.select(),p(a)}function r(a,b,c){this.nativeSelection=a,this.docSelection=b,this._ranges=[],this.win=c,this.refresh()}function s(a){a.win=a.anchorNode=a.focusNode=a._ranges=null,a.rangeCount=a.anchorOffset=a.focusOffset=0,a.detached=!0}function t(a,b){for(var c,d,e=bb.length;e--;)if(c=bb[e],d=c.selection,"deleteAll"==b)s(d);else if(c.win==a)return"delete"==b?(bb.splice(e,1),!0):d;return"deleteAll"==b&&(bb.length=0),null}function u(a,c){var d,e,f,g=L(c[0].startContainer),h=M(g).createControlRange();for(d=0,f=c.length;f>d;++d){e=m(c[d]);try{h.add(e)}catch(i){throw b.createError("setRanges(): Element within one of the specified Ranges could not be added to control selection (does it have layout?)")}}h.select(),p(a)}function v(a,b){if(a.win.document!=L(b))throw new F("WRONG_DOCUMENT_ERR")}function w(b){return function(c,d){var e;this.rangeCount?(e=this.getRangeAt(0),e["set"+(b?"Start":"End")](c,d)):(e=a.createRange(this.win.document),e.setStartAndEnd(c,d)),this.setSingleRange(e,this.isBackward())}}function x(a){var b,c,d=[],e=new G(a.anchorNode,a.anchorOffset),f=new G(a.focusNode,a.focusOffset),g="function"==typeof a.getName?a.getName():"Selection";if(void 0!==a.rangeCount)for(b=0,c=a.rangeCount;c>b;++b)d[b]=D.inspect(a.getRangeAt(b));return"["+g+"(Ranges: "+d.join(", ")+")(anchor: "+e.inspect()+", focus: "+f.inspect()+"]"}var y,z,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,$,_,ab,bb,cb,db,eb,fb,gb,hb;if(a.config.checkSelectionRanges=!0,y="boolean",z="number",A=a.dom,B=a.util,C=B.isHostMethod,D=a.DomRange,E=a.WrappedRange,F=a.DOMException,G=A.DomPosition,J=a.features,K="Control",L=A.getDocument,M=A.getBody,N=D.rangesEqual,O=C(window,"getSelection"),P=B.isHostObject(document,"selection"),J.implementsWinGetSelection=O,J.implementsDocSelection=P,Q=P&&(!O||a.config.preferTextRange),Q?(H=f,a.isSelectionValid=function(a){var b=d(a,"isSelectionValid").document,c=b.selection;return"None"!=c.type||L(c.createRange().parentElement())==b}):O?(H=e,a.isSelectionValid=function(){return!0}):b.fail("Neither document.selection or window.getSelection() detected."),a.getNativeSelection=H,R=H(),S=a.createNativeRange(document),T=M(document),U=B.areHostProperties(R,["anchorNode","focusNode","anchorOffset","focusOffset"]),J.selectionHasAnchorAndFocus=U,V=C(R,"extend"),J.selectionHasExtend=V,W=typeof R.rangeCount==z,J.selectionHasRangeCount=W,X=!1,Y=!0,Z=V?function(b,c){var d=D.getRangeDocument(c),e=a.createRange(d);e.collapseToPoint(c.endContainer,c.endOffset),b.addRange(k(e)),b.extend(c.startContainer,c.startOffset)}:null,B.areHostMethods(R,["addRange","getRangeAt","removeAllRanges"])&&typeof R.rangeCount==z&&J.implementsDomRange&&!function(){var b,c,d,e,f,h,i,j,k,l,m,n=window.getSelection();if(n){for(b=n.rangeCount,c=b>1,d=[],e=g(n),f=0;b>f;++f)d[f]=n.getRangeAt(f);for(h=M(document),i=h.appendChild(document.createElement("div")),i.contentEditable="false",j=i.appendChild(document.createTextNode(" ")),k=document.createRange(),k.setStart(j,1),k.collapse(!0),n.addRange(k),Y=1==n.rangeCount,n.removeAllRanges(),c||(l=window.navigator.appVersion.match(/Chrome\/(.*?) /),l&&parseInt(l[1])>=36?X=!1:(m=k.cloneRange(),k.setStart(j,0),m.setEnd(j,3),m.setStart(j,2),n.addRange(k),n.addRange(m),X=2==n.rangeCount)),h.removeChild(i),n.removeAllRanges(),f=0;b>f;++f)0==f&&e?Z?Z(n,d[f]):(a.warn("Rangy initialization: original selection was backwards but selection has been restored forwards because the browser does not support Selection.extend"),n.addRange(d[f])):n.addRange(d[f])}}(),J.selectionSupportsMultipleRanges=X,J.collapsedNonEditableSelectionsSupported=Y,$=!1,T&&C(T,"createControlRange")&&(_=T.createControlRange(),B.areHostProperties(_,["item","add"])&&($=!0)),J.implementsControlRange=$,I=U?function(a){return a.anchorNode===a.focusNode&&a.anchorOffset===a.focusOffset}:function(a){return a.rangeCount?a.getRangeAt(a.rangeCount-1).collapsed:!1},C(R,"getRangeAt")?ab=function(a,b){try{return a.getRangeAt(b)}catch(c){return null}}:U&&(ab=function(b){var c=L(b.anchorNode),d=a.createRange(c);return d.setStartAndEnd(b.anchorNode,b.anchorOffset,b.focusNode,b.focusOffset),d.collapsed!==this.isCollapsed&&d.setStartAndEnd(b.focusNode,b.focusOffset,b.anchorNode,b.anchorOffset),d}),r.prototype=a.selectionPrototype,bb=[],cb=function(a){var b,c,e;return a&&a instanceof r?(a.refresh(),a):(a=d(a,"getNativeSelection"),b=t(a),c=H(a),e=P?f(a):null,b?(b.nativeSelection=c,b.docSelection=e,b.refresh()):(b=new r(c,e,a),bb.push({win:a,selection:b})),b)},a.getSelection=cb,a.getIframeSelection=function(c){return b.deprecationNotice("getIframeSelection()","getSelection(iframeEl)"),a.getSelection(A.getIframeWindow(c))},db=r.prototype,!Q&&U&&B.areHostMethods(R,["removeAllRanges","addRange"]))db.removeAllRanges=function(){this.nativeSelection.removeAllRanges(),j(this)},eb=function(a,b){Z(a.nativeSelection,b),a.refresh()},db.addRange=W?function(b,d){var e,f;$&&P&&this.docSelection.type==K?q(this,b):c(d)&&V?eb(this,b):(X?e=this.rangeCount:(this.removeAllRanges(),e=0),this.nativeSelection.addRange(k(b).cloneRange()),this.rangeCount=this.nativeSelection.rangeCount,this.rangeCount==e+1?(a.config.checkSelectionRanges&&(f=ab(this.nativeSelection,this.rangeCount-1),f&&!N(f,b)&&(b=new E(f))),this._ranges[this.rangeCount-1]=b,h(this,b,hb(this.nativeSelection)),this.isCollapsed=I(this)):this.refresh())}:function(a,b){c(b)&&V?eb(this,a):(this.nativeSelection.addRange(k(a)),this.refresh())},db.setRanges=function(a){if($&&P&&a.length>1)u(this,a);else{this.removeAllRanges();for(var b=0,c=a.length;c>b;++b)this.addRange(a[b])}};else{if(!(C(R,"empty")&&C(S,"select")&&$&&Q))return b.fail("No means of selecting a Range or TextRange was found"),!1;db.removeAllRanges=function(){var a,b,c;try{this.docSelection.empty(),"None"!=this.docSelection.type&&(this.anchorNode?a=L(this.anchorNode):this.docSelection.type==K&&(b=this.docSelection.createRange(),b.length&&(a=L(b.item(0)))),a&&(c=M(a).createTextRange(),c.select(),this.docSelection.empty()))}catch(d){}j(this)},db.addRange=function(b){this.docSelection.type==K?q(this,b):(a.WrappedTextRange.rangeToTextRange(b).select(),this._ranges[0]=b,this.rangeCount=1,this.isCollapsed=this._ranges[0].collapsed,h(this,b,!1))},db.setRanges=function(a){this.removeAllRanges();var b=a.length;b>1?u(this,a):b&&this.addRange(a[0])}}if(db.getRangeAt=function(a){if(0>a||a>=this.rangeCount)throw new F("INDEX_SIZE_ERR");return this._ranges[a].cloneRange()},Q)fb=function(b){var c;a.isSelectionValid(b.win)?c=b.docSelection.createRange():(c=M(b.win.document).createTextRange(),c.collapse(!0)),b.docSelection.type==K?p(b):n(c)?o(b,c):j(b)};else if(C(R,"getRangeAt")&&typeof R.rangeCount==z)fb=function(b){if($&&P&&b.docSelection.type==K)p(b);else if(b._ranges.length=b.rangeCount=b.nativeSelection.rangeCount,b.rangeCount){for(var c=0,d=b.rangeCount;d>c;++c)b._ranges[c]=new a.WrappedRange(b.nativeSelection.getRangeAt(c));h(b,b._ranges[b.rangeCount-1],hb(b.nativeSelection)),b.isCollapsed=I(b)}else j(b)};else{if(!U||typeof R.isCollapsed!=y||typeof S.collapsed!=y||!J.implementsDomRange)return b.fail("No means of obtaining a Range or TextRange from the user's selection was found"),!1;fb=function(a){var b,c=a.nativeSelection;c.anchorNode?(b=ab(c,0),a._ranges=[b],a.rangeCount=1,i(a),a.isCollapsed=I(a)):j(a)}}db.refresh=function(a){var b,c=a?this._ranges.slice(0):null,d=this.anchorNode,e=this.anchorOffset;if(fb(this),a){if(b=c.length,b!=this._ranges.length)return!0;if(this.anchorNode!=d||this.anchorOffset!=e)return!0;for(;b--;)if(!N(c[b],this._ranges[b]))return!0;return!1}},gb=function(a,b){var c,d,e=a.getAllRanges();for(a.removeAllRanges(),c=0,d=e.length;d>c;++c)N(b,e[c])||a.addRange(e[c]);a.rangeCount||j(a)},db.removeRange=$&&P?function(a){var b,c,d,e,f,g,h,i;if(this.docSelection.type==K){for(b=this.docSelection.createRange(),c=m(a),d=L(b.item(0)),e=M(d).createControlRange(),g=!1,h=0,i=b.length;i>h;++h)f=b.item(h),f!==c||g?e.add(b.item(h)):g=!0;e.select(),p(this)}else gb(this,a)}:function(a){gb(this,a)},!Q&&U&&J.implementsDomRange?(hb=g,db.isBackward=function(){return hb(this)}):hb=db.isBackward=function(){return!1},db.isBackwards=db.isBackward,db.toString=function(){var a,b,c=[];for(a=0,b=this.rangeCount;b>a;++a)c[a]=""+this._ranges[a];return c.join("")},db.collapse=function(b,c){v(this,b);var d=a.createRange(b);d.collapseToPoint(b,c),this.setSingleRange(d),this.isCollapsed=!0},db.collapseToStart=function(){if(!this.rangeCount)throw new F("INVALID_STATE_ERR");var a=this._ranges[0];this.collapse(a.startContainer,a.startOffset)},db.collapseToEnd=function(){if(!this.rangeCount)throw new F("INVALID_STATE_ERR");var a=this._ranges[this.rangeCount-1];this.collapse(a.endContainer,a.endOffset)},db.selectAllChildren=function(b){v(this,b);var c=a.createRange(b);c.selectNodeContents(b),this.setSingleRange(c)},db.deleteFromDocument=function(){var a,b,c,d,e;if($&&P&&this.docSelection.type==K){for(a=this.docSelection.createRange();a.length;)b=a.item(0),a.remove(b),b.parentNode.removeChild(b);this.refresh()}else if(this.rangeCount&&(c=this.getAllRanges(),c.length)){for(this.removeAllRanges(),d=0,e=c.length;e>d;++d)c[d].deleteContents();this.addRange(c[e-1])}},db.eachRange=function(a,b){for(var c=0,d=this._ranges.length;d>c;++c)if(a(this.getRangeAt(c)))return b},db.getAllRanges=function(){var a=[];return this.eachRange(function(b){a.push(b)}),a},db.setSingleRange=function(a,b){this.removeAllRanges(),this.addRange(a,b)},db.callMethodOnEachRange=function(a,b){var c=[];return this.eachRange(function(d){c.push(d[a].apply(d,b))}),c},db.setStart=w(!0),db.setEnd=w(!1),a.rangePrototype.select=function(a){cb(this.getDocument()).setSingleRange(this,a)},db.changeEachRange=function(a){var b=[],c=this.isBackward();this.eachRange(function(c){a(c),b.push(c)}),this.removeAllRanges(),c&&1==b.length?this.addRange(b[0],"backward"):this.setRanges(b)},db.containsNode=function(a,b){return this.eachRange(function(c){return c.containsNode(a,b)},!0)||!1},db.getBookmark=function(a){return{backward:this.isBackward(),rangeBookmarks:this.callMethodOnEachRange("getBookmark",[a])}},db.moveToBookmark=function(b){var c,d,e,f=[];for(c=0;d=b.rangeBookmarks[c++];)e=a.createRange(this.win),e.moveToBookmark(d),f.push(e);b.backward?this.setSingleRange(f[0],"backward"):this.setRanges(f)},db.toHtml=function(){var a=[];return this.eachRange(function(b){a.push(D.toHtml(b))}),a.join("")},J.implementsTextRange&&(db.getNativeTextRange=function(){var c,d;if(c=this.docSelection){if(d=c.createRange(),n(d))return d;throw b.createError("getNativeTextRange: selection is a control selection")}if(this.rangeCount>0)return a.WrappedTextRange.rangeToTextRange(this.getRangeAt(0));throw b.createError("getNativeTextRange: selection contains no range")}),db.getName=function(){return"WrappedSelection"},db.inspect=function(){return x(this)},db.detach=function(){t(this.win,"delete"),s(this)},r.detachAll=function(){t(null,"deleteAll")},r.inspect=x,r.isDirectionBackward=c,a.Selection=r,a.selectionPrototype=db,a.addShimListener(function(a){void 0===a.getSelection&&(a.getSelection=function(){return cb(a)}),a=null})}),H)},this),function(a,b){"function"==typeof define&&define.amd?define(["rangy"],a):a(b.rangy)}(function(a){a.createModule("SaveRestore",["WrappedRange"],function(a,b){function c(a,b){return(b||document).getElementById(a)}function d(a,b){var c,d="selectionBoundary_"+ +new Date+"_"+(""+Math.random()).slice(2),e=o.getDocument(a.startContainer),f=a.cloneRange();return f.collapse(b),c=e.createElement("span"),c.id=d,c.style.lineHeight="0",c.style.display="none",c.className="rangySelectionBoundary",c.appendChild(e.createTextNode(p)),f.insertNode(c),c}function e(a,d,e,f){var g=c(e,a);g?(d[f?"setStartBefore":"setEndBefore"](g),g.parentNode.removeChild(g)):b.warn("Marker element has been removed. Cannot restore selection.")}function f(a,b){return b.compareBoundaryPoints(a.START_TO_START,a)}function g(b,c){var e,f,g=a.DomRange.getRangeDocument(b),h=""+b;return b.collapsed?(f=d(b,!1),{document:g,markerId:f.id,collapsed:!0}):(f=d(b,!1),e=d(b,!0),{document:g,startMarkerId:e.id,endMarkerId:f.id,collapsed:!1,backward:c,toString:function(){return"original text: '"+h+"', new text: '"+b+"'"}})}function h(d,f){var g,h,i,j=d.document;return void 0===f&&(f=!0),g=a.createRange(j),d.collapsed?(h=c(d.markerId,j),h?(h.style.display="inline",i=h.previousSibling,i&&3==i.nodeType?(h.parentNode.removeChild(h),g.collapseToPoint(i,i.length)):(g.collapseBefore(h),h.parentNode.removeChild(h))):b.warn("Marker element has been removed. Cannot restore selection.")):(e(j,g,d.startMarkerId,!0),e(j,g,d.endMarkerId,!1)),f&&g.normalizeBoundaries(),g}function i(b,d){var e,h,i,j,k=[];for(b=b.slice(0),b.sort(f),i=0,j=b.length;j>i;++i)k[i]=g(b[i],d);for(i=j-1;i>=0;--i)e=b[i],h=a.DomRange.getRangeDocument(e),e.collapsed?e.collapseAfter(c(k[i].markerId,h)):(e.setEndBefore(c(k[i].endMarkerId,h)),e.setStartAfter(c(k[i].startMarkerId,h)));return k}function j(c){var d,e,f,g;return a.isSelectionValid(c)?(d=a.getSelection(c),e=d.getAllRanges(),f=1==e.length&&d.isBackward(),g=i(e,f),f?d.setSingleRange(e[0],"backward"):d.setRanges(e),{win:c,rangeInfos:g,restored:!1}):(b.warn("Cannot save selection. This usually happens when the selection is collapsed and the selection document has lost focus."),null)}function k(a){var b,c=[],d=a.length;for(b=d-1;b>=0;b--)c[b]=h(a[b],!0);return c}function l(b,c){var d,e,f,g;b.restored||(d=b.rangeInfos,e=a.getSelection(b.win),f=k(d),g=d.length,1==g&&c&&a.features.selectionHasExtend&&d[0].backward?(e.removeAllRanges(),e.addRange(f[0],!0)):e.setRanges(f),b.restored=!0)}function m(a,b){var d=c(b,a);d&&d.parentNode.removeChild(d)}function n(a){var b,c,d,e=a.rangeInfos;for(b=0,c=e.length;c>b;++b)d=e[b],d.collapsed?m(a.doc,d.markerId):(m(a.doc,d.startMarkerId),m(a.doc,d.endMarkerId))}var o=a.dom,p="";a.util.extend(a,{saveRange:g,restoreRange:h,saveRanges:i,restoreRanges:k,saveSelection:j,restoreSelection:l,removeMarkerElement:m,removeMarkers:n})})},this),Base=function(){},Base.extend=function(a,b){var c,d,e,f=Base.prototype.extend;return Base._prototyping=!0,c=new this,f.call(c,a),c.base=function(){},delete Base._prototyping,d=c.constructor,e=c.constructor=function(){if(!Base._prototyping)if(this._constructing||this.constructor==e)this._constructing=!0,d.apply(this,arguments),delete this._constructing;else if(null!=arguments[0])return(arguments[0].extend||f).call(arguments[0],c)},e.ancestor=this,e.extend=this.extend,e.forEach=this.forEach,e.implement=this.implement,e.prototype=c,e.toString=this.toString,e.valueOf=function(a){return"object"==a?e:d.valueOf()},f.call(e,b),"function"==typeof e.init&&e.init(),e},Base.prototype={extend:function(a,b){var c,d,e,f,g,h,i;if(arguments.length>1)c=this[a],!c||"function"!=typeof b||c.valueOf&&c.valueOf()==b.valueOf()||!/\bbase\b/.test(b)||(d=b.valueOf(),b=function(){var a,b=this.base||Base.prototype.base;return this.base=c,a=d.apply(this,arguments),this.base=b,a},b.valueOf=function(a){return"object"==a?b:d},b.toString=Base.toString),this[a]=b;else if(a){for(e=Base.prototype.extend,Base._prototyping||"function"==typeof this||(e=this.extend||e),f={toSource:null},g=["constructor","toString","valueOf"],h=Base._prototyping?0:1;i=g[h++];)a[i]!=f[i]&&e.call(this,i,a[i]);for(i in a)f[i]||e.call(this,i,a[i])}return this}},Base=Base.extend({constructor:function(){this.extend(arguments[0])}},{ancestor:Object,version:"1.1",forEach:function(a,b,c){for(var d in a)void 0===this.prototype[d]&&b.call(c,a[d],d,a)},implement:function(){for(var a=0;a<arguments.length;a++)"function"==typeof arguments[a]?arguments[a](this.prototype):this.prototype.extend(arguments[a]);return this},toString:function(){return this.valueOf()+""}}),wysihtml5.browser=function(){function a(a){return+(/ipad|iphone|ipod/.test(a)&&a.match(/ os (\d+).+? like mac os x/)||[void 0,0])[1]}function b(a){return+(a.match(/android (\d+)/)||[void 0,0])[1]}function c(a,b){var c,d=-1;return"Microsoft Internet Explorer"==navigator.appName?c=RegExp("MSIE ([0-9]{1,}[.0-9]{0,})"):"Netscape"==navigator.appName&&(c=RegExp("Trident/.*rv:([0-9]{1,}[.0-9]{0,})")),c&&null!=c.exec(navigator.userAgent)&&(d=parseFloat(RegExp.$1)),-1===d?!1:a?b?"<"===b?d>a:">"===b?a>d:"<="===b?d>=a:">="===b?a>=d:void 0:a===d:!0}var d=navigator.userAgent,e=document.createElement("div"),f=-1!==d.indexOf("Gecko")&&-1===d.indexOf("KHTML"),g=-1!==d.indexOf("AppleWebKit/"),h=-1!==d.indexOf("Chrome/"),i=-1!==d.indexOf("Opera/");return{USER_AGENT:d,supported:function(){var c=this.USER_AGENT.toLowerCase(),d="contentEditable"in e,f=document.execCommand&&document.queryCommandSupported&&document.queryCommandState,g=document.querySelector&&document.querySelectorAll,h=this.isIos()&&a(c)<5||this.isAndroid()&&b(c)<4||-1!==c.indexOf("opera mobi")||-1!==c.indexOf("hpwos/");return d&&f&&g&&!h},isTouchDevice:function(){return this.supportsEvent("touchmove")},isIos:function(){return/ipad|iphone|ipod/i.test(this.USER_AGENT)},isAndroid:function(){return-1!==this.USER_AGENT.indexOf("Android")},supportsSandboxedIframes:function(){return c()},throwsMixedContentWarningWhenIframeSrcIsEmpty:function(){return!("querySelector"in document)},displaysCaretInEmptyContentEditableCorrectly:function(){return c()},hasCurrentStyleProperty:function(){return"currentStyle"in e},hasHistoryIssue:function(){return f&&"Mac"===navigator.platform.substr(0,3)},insertsLineBreaksOnReturn:function(){return f},supportsPlaceholderAttributeOn:function(a){return"placeholder"in a},supportsEvent:function(a){return"on"+a in e||function(){return e.setAttribute("on"+a,"return;"),"function"==typeof e["on"+a]}()},supportsEventsInIframeCorrectly:function(){return!i},supportsHTML5Tags:function(a){var b=a.createElement("div"),c="<article>foo</article>";return b.innerHTML=c,b.innerHTML.toLowerCase()===c},supportsCommand:function(){var a={formatBlock:c(10,"<="),insertUnorderedList:c(),insertOrderedList:c()},b={insertHTML:f};return function(c,d){var e=a[d];if(!e){try{return c.queryCommandSupported(d)}catch(f){}try{return c.queryCommandEnabled(d)}catch(g){return!!b[d]}}return!1}}(),doesAutoLinkingInContentEditable:function(){return c()},canDisableAutoLinking:function(){return this.supportsCommand(document,"AutoUrlDetect")},clearsContentEditableCorrectly:function(){return f||i||g},supportsGetAttributeCorrectly:function(){var a=document.createElement("td");return"1"!=a.getAttribute("rowspan")},canSelectImagesInContentEditable:function(){return f||c()||i},autoScrollsToCaret:function(){return!g},autoClosesUnclosedTags:function(){var a,b,c=e.cloneNode(!1);return c.innerHTML="<p><div></div>",b=c.innerHTML.toLowerCase(),a="<p></p><div></div>"===b||"<p><div></div></p>"===b,this.autoClosesUnclosedTags=function(){return a},a},supportsNativeGetElementsByClassName:function(){return-1!==(document.getElementsByClassName+"").indexOf("[native code]")},supportsSelectionModify:function(){return"getSelection"in window&&"modify"in window.getSelection()},needsSpaceAfterLineBreak:function(){return i},supportsSpeechApiOn:function(a){var b=d.match(/Chrome\/(\d+)/)||[void 0,0];return b[1]>=11&&("onwebkitspeechchange"in a||"speech"in a)},crashesWhenDefineProperty:function(a){return c(9)&&("XMLHttpRequest"===a||"XDomainRequest"===a)},doesAsyncFocus:function(){return c()},hasProblemsSettingCaretAfterImg:function(){return c()},hasUndoInContextMenu:function(){return f||h||i},hasInsertNodeIssue:function(){return i},hasIframeFocusIssue:function(){return c()},createsNestedInvalidMarkupAfterPaste:function(){return g},supportsMutationEvents:function(){return"MutationEvent"in window},supportsModenPaste:function(){return!("clipboardData"in window)}}}(),wysihtml5.lang.array=function(a){return{contains:function(b){if(Array.isArray(b)){for(var c=b.length;c--;)if(-1!==wysihtml5.lang.array(a).indexOf(b[c]))return!0;return!1}return-1!==wysihtml5.lang.array(a).indexOf(b)},indexOf:function(b){if(a.indexOf)return a.indexOf(b);for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1},without:function(b){b=wysihtml5.lang.array(b);for(var c=[],d=0,e=a.length;e>d;d++)b.contains(a[d])||c.push(a[d]);return c},get:function(){for(var b=0,c=a.length,d=[];c>b;b++)d.push(a[b]);return d},map:function(b,c){if(Array.prototype.map)return a.map(b,c);for(var d=a.length>>>0,e=Array(d),f=0;d>f;f++)e[f]=b.call(c,a[f],f,a);return e},unique:function(){for(var b=[],c=a.length,d=0;c>d;)wysihtml5.lang.array(b).contains(a[d])||b.push(a[d]),d++;return b}}},wysihtml5.lang.Dispatcher=Base.extend({on:function(a,b){return this.events=this.events||{},this.events[a]=this.events[a]||[],this.events[a].push(b),this},off:function(a,b){this.events=this.events||{};var c,d,e=0;if(a){for(c=this.events[a]||[],d=[];e<c.length;e++)c[e]!==b&&b&&d.push(c[e]);this.events[a]=d}else this.events={};return this},fire:function(a,b){this.events=this.events||{};for(var c=this.events[a]||[],d=0;d<c.length;d++)c[d].call(this,b);return this},observe:function(){return this.on.apply(this,arguments)},stopObserving:function(){return this.off.apply(this,arguments)}}),wysihtml5.lang.object=function(a){return{merge:function(b){for(var c in b)a[c]=b[c];return this},get:function(){return a},clone:function(b){var c,d={};if(null===a||!wysihtml5.lang.object(a).isPlainObject())return a;for(c in a)a.hasOwnProperty(c)&&(d[c]=b?wysihtml5.lang.object(a[c]).clone(b):a[c]);return d},isArray:function(){return"[object Array]"===Object.prototype.toString.call(a)},isFunction:function(){return"[object Function]"===Object.prototype.toString.call(a)},isPlainObject:function(){return"[object Object]"===Object.prototype.toString.call(a)}}},function(){var a=/^\s+/,b=/\s+$/,c=/[&<>\t"]/g,d={"&":"&","<":"<",">":">",'"':"""," ":" "};wysihtml5.lang.string=function(e){return e+="",{trim:function(){return e.replace(a,"").replace(b,"")},interpolate:function(a){for(var b in a)e=this.replace("#{"+b+"}").by(a[b]);return e},replace:function(a){return{by:function(b){return e.split(a).join(b)}}},escapeHTML:function(a,b){var f=e.replace(c,function(a){return d[a]});return a&&(f=f.replace(/(?:\r\n|\r|\n)/g,"<br />")),b&&(f=f.replace(/ /gi," ")),f}}}}(),function(a){function b(a,b){return f(a,b)?a:(a===a.ownerDocument.documentElement&&(a=a.ownerDocument.body),g(a,b))}function c(a){return a.replace(i,function(a,b){var c,d,e=(b.match(j)||[])[1]||"",f=l[e];return b=b.replace(j,""),b.split(f).length>b.split(e).length&&(b+=e,e=""),c=b,d=b,b.length>k&&(d=d.substr(0,k)+"..."),"www."===c.substr(0,4)&&(c="http://"+c),'<a href="'+c+'">'+d+"</a>"+e})}function d(a){var b=a._wysihtml5_tempElement;return b||(b=a._wysihtml5_tempElement=a.createElement("div")),b}function e(b){var e=b.parentNode,f=a.lang.string(b.data).escapeHTML(),g=d(e.ownerDocument);for(g.innerHTML="<span></span>"+c(f),g.removeChild(g.firstChild);g.firstChild;)e.insertBefore(g.firstChild,b);e.removeChild(b)}function f(b,c){for(var d;b.parentNode;){if(b=b.parentNode,d=b.nodeName,b.className&&a.lang.array(b.className.split(" ")).contains(c))return!0;if(h.contains(d))return!0;if("body"===d)return!1}return!1}function g(b,c){if(!(h.contains(b.nodeName)||b.className&&a.lang.array(b.className.split(" ")).contains(c))){if(b.nodeType===a.TEXT_NODE&&b.data.match(i))return e(b),void 0;for(var d=a.lang.array(b.childNodes).get(),f=d.length,j=0;f>j;j++)g(d[j],c);return b}}var h=a.lang.array(["CODE","PRE","A","SCRIPT","HEAD","TITLE","STYLE"]),i=/((https?:\/\/|www\.)[^\s<]{3,})/gi,j=/([^\w\/\-](,?))$/i,k=100,l={")":"(","]":"[","}":"{"};a.dom.autoLink=b,a.dom.autoLink.URL_REG_EXP=i}(wysihtml5),function(a){var b=a.dom;b.addClass=function(a,c){var d=a.classList;return d?d.add(c):(b.hasClass(a,c)||(a.className+=" "+c),void 0)},b.removeClass=function(a,b){var c=a.classList;return c?c.remove(b):(a.className=a.className.replace(RegExp("(^|\\s+)"+b+"(\\s+|$)")," "),void 0)},b.hasClass=function(a,b){var c,d=a.classList;return d?d.contains(b):(c=a.className,c.length>0&&(c==b||RegExp("(^|\\s)"+b+"(\\s|$)").test(c)))}}(wysihtml5),wysihtml5.dom.contains=function(){var a=document.documentElement;return a.contains?function(a,b){return b.nodeType!==wysihtml5.ELEMENT_NODE&&(b=b.parentNode),a!==b&&a.contains(b)}:a.compareDocumentPosition?function(a,b){return!!(16&a.compareDocumentPosition(b))}:void 0}(),wysihtml5.dom.convertToList=function(){function a(a,b){var c=a.createElement("li");return b.appendChild(c),c}function b(a,b){return a.createElement(b)}function c(c,d,e){if("UL"===c.nodeName||"OL"===c.nodeName||"MENU"===c.nodeName)return c;var f,g,h,i,j,k,l,m,n,o=c.ownerDocument,p=b(o,d),q=c.querySelectorAll("br"),r=q.length;for(n=0;r>n;n++)for(i=q[n];(j=i.parentNode)&&j!==c&&j.lastChild===i;){if("block"===wysihtml5.dom.getStyle("display").from(j)){j.removeChild(i);break}wysihtml5.dom.insert(i).after(i.parentNode)}for(f=wysihtml5.lang.array(c.childNodes).get(),g=f.length,n=0;g>n;n++)m=m||a(o,p),h=f[n],k="block"===wysihtml5.dom.getStyle("display").from(h),l="BR"===h.nodeName,!k||e&&wysihtml5.dom.hasClass(h,e)?l?m=m.firstChild?null:m:m.appendChild(h):(m=m.firstChild?a(o,p):m,m.appendChild(h),m=null);return 0===f.length&&a(o,p),c.parentNode.replaceChild(p,c),p}return c}(),wysihtml5.dom.copyAttributes=function(a){return{from:function(b){return{to:function(c){for(var d,e=0,f=a.length;f>e;e++)d=a[e],void 0!==b[d]&&""!==b[d]&&(c[d]=b[d]);return{andTo:arguments.callee}}}}}},function(a){var b=["-webkit-box-sizing","-moz-box-sizing","-ms-box-sizing","box-sizing"],c=function(b){return d(b)?parseInt(a.getStyle("width").from(b),10)<b.offsetWidth:!1},d=function(c){for(var d=0,e=b.length;e>d;d++)if("border-box"===a.getStyle(b[d]).from(c))return b[d]};a.copyStyles=function(d){return{from:function(e){c(e)&&(d=wysihtml5.lang.array(d).without(b));for(var f,g="",h=d.length,i=0;h>i;i++)f=d[i],g+=f+":"+a.getStyle(f).from(e)+";";return{to:function(b){return a.setStyles(g).on(b),{andTo:arguments.callee}}}}}}}(wysihtml5.dom),function(a){a.dom.delegate=function(b,c,d,e){return a.dom.observe(b,d,function(d){for(var f=d.target,g=a.lang.array(b.querySelectorAll(c));f&&f!==b;){if(g.contains(f)){e.call(f,d);break}f=f.parentNode}})}}(wysihtml5),function(a){a.dom.domNode=function(b){var c=[a.ELEMENT_NODE,a.TEXT_NODE],d=function(b){return b.nodeType===a.TEXT_NODE&&/^\s*$/g.test(b.data)};return{prev:function(e){var f=b.previousSibling,g=e&&e.nodeTypes?e.nodeTypes:c;return f?!a.lang.array(g).contains(f.nodeType)||e&&e.ignoreBlankTexts&&d(f)?a.dom.domNode(f).prev(e):f:null},next:function(e){var f=b.nextSibling,g=e&&e.nodeTypes?e.nodeTypes:c;return f?!a.lang.array(g).contains(f.nodeType)||e&&e.ignoreBlankTexts&&d(f)?a.dom.domNode(f).next(e):f:null}}}}(wysihtml5),wysihtml5.dom.getAsDom=function(){var a=function(a,b){var c=b.createElement("div");c.style.display="none",b.body.appendChild(c);try{c.innerHTML=a}catch(d){}return b.body.removeChild(c),c},b=function(a){if(!a._wysihtml5_supportsHTML5Tags){for(var b=0,d=c.length;d>b;b++)a.createElement(c[b]);a._wysihtml5_supportsHTML5Tags=!0}},c=["abbr","article","aside","audio","bdi","canvas","command","datalist","details","figcaption","figure","footer","header","hgroup","keygen","mark","meter","nav","output","progress","rp","rt","ruby","svg","section","source","summary","time","track","video","wbr"];return function(c,d){d=d||document;var e;return"object"==typeof c&&c.nodeType?(e=d.createElement("div"),e.appendChild(c)):wysihtml5.browser.supportsHTML5Tags(d)?(e=d.createElement("div"),e.innerHTML=c):(b(d),e=a(c,d)),e}}(),wysihtml5.dom.getParentElement=function(){function a(a,b){return b&&b.length?"string"==typeof b?a===b:wysihtml5.lang.array(b).contains(a):!0}function b(a){return a.nodeType===wysihtml5.ELEMENT_NODE}function c(a,b,c){var d=(a.className||"").match(c)||[];return b?d[d.length-1]===b:!!d.length}function d(a,b,c){var d=(a.getAttribute("style")||"").match(c)||[];return b?d[d.length-1]===b:!!d.length}return function(e,f,g,h){var i=f.cssStyle||f.styleRegExp,j=f.className||f.classRegExp;for(g=g||50;g--&&e&&"BODY"!==e.nodeName&&(!h||e!==h);){if(b(e)&&a(e.nodeName,f.nodeName)&&(!i||d(e,f.cssStyle,f.styleRegExp))&&(!j||c(e,f.className,f.classRegExp)))return e;e=e.parentNode}return null}}(),wysihtml5.dom.getStyle=function(){function a(a){return a.replace(c,function(a){return a.charAt(1).toUpperCase()
})}var b={"float":"styleFloat"in document.createElement("div").style?"styleFloat":"cssFloat"},c=/\-[a-z]/g;return function(c){return{from:function(d){var e,f,g,h,i,j,k,l,m;if(d.nodeType===wysihtml5.ELEMENT_NODE){if(e=d.ownerDocument,f=b[c]||a(c),g=d.style,h=d.currentStyle,i=g[f],i)return i;if(h)try{return h[f]}catch(n){}return j=e.defaultView||e.parentWindow,k=("height"===c||"width"===c)&&"TEXTAREA"===d.nodeName,j.getComputedStyle?(k&&(l=g.overflow,g.overflow="hidden"),m=j.getComputedStyle(d,null).getPropertyValue(c),k&&(g.overflow=l||""),m):void 0}}}}}(),wysihtml5.dom.getTextNodes=function(a,b){var c=[];for(a=a.firstChild;a;a=a.nextSibling)3==a.nodeType?b&&/^\s*$/.test(a.innerText||a.textContent)||c.push(a):c=c.concat(wysihtml5.dom.getTextNodes(a,b));return c},wysihtml5.dom.hasElementWithTagName=function(){function a(a){return a._wysihtml5_identifier||(a._wysihtml5_identifier=c++)}var b={},c=1;return function(c,d){var e=a(c)+":"+d,f=b[e];return f||(f=b[e]=c.getElementsByTagName(d)),f.length>0}}(),function(a){function b(a){return a._wysihtml5_identifier||(a._wysihtml5_identifier=d++)}var c={},d=1;a.dom.hasElementWithClassName=function(d,e){if(!a.browser.supportsNativeGetElementsByClassName())return!!d.querySelector("."+e);var f=b(d)+":"+e,g=c[f];return g||(g=c[f]=d.getElementsByClassName(e)),g.length>0}}(wysihtml5),wysihtml5.dom.insert=function(a){return{after:function(b){b.parentNode.insertBefore(a,b.nextSibling)},before:function(b){b.parentNode.insertBefore(a,b)},into:function(b){b.appendChild(a)}}},wysihtml5.dom.insertCSS=function(a){return a=a.join("\n"),{into:function(b){var c,d,e=b.createElement("style");return e.type="text/css",e.styleSheet?e.styleSheet.cssText=a:e.appendChild(b.createTextNode(a)),c=b.querySelector("head link"),c?(c.parentNode.insertBefore(e,c),void 0):(d=b.querySelector("head"),d&&d.appendChild(e),void 0)}}},function(a){a.dom.lineBreaks=function(b){function c(a){return"BR"===a.nodeName}function d(b){return c(b)?!0:"block"===a.dom.getStyle("display").from(b)?!0:!1}return{add:function(){var c=b.ownerDocument,e=a.dom.domNode(b).next({ignoreBlankTexts:!0}),f=a.dom.domNode(b).prev({ignoreBlankTexts:!0});e&&!d(e)&&a.dom.insert(c.createElement("br")).after(b),f&&!d(f)&&a.dom.insert(c.createElement("br")).before(b)},remove:function(){var d=a.dom.domNode(b).next({ignoreBlankTexts:!0}),e=a.dom.domNode(b).prev({ignoreBlankTexts:!0});d&&c(d)&&d.parentNode.removeChild(d),e&&c(e)&&e.parentNode.removeChild(e)}}}}(wysihtml5),wysihtml5.dom.observe=function(a,b,c){b="string"==typeof b?[b]:b;for(var d,e,f=0,g=b.length;g>f;f++)e=b[f],a.addEventListener?a.addEventListener(e,c,!1):(d=function(b){"target"in b||(b.target=b.srcElement),b.preventDefault=b.preventDefault||function(){this.returnValue=!1},b.stopPropagation=b.stopPropagation||function(){this.cancelBubble=!0},c.call(a,b)},a.attachEvent("on"+e,d));return{stop:function(){for(var e,f=0,g=b.length;g>f;f++)e=b[f],a.removeEventListener?a.removeEventListener(e,c,!1):a.detachEvent("on"+e,d)}}},wysihtml5.dom.parse=function(a,b){function c(a,b){var c,f,g,h,i,j,k,l,m;for(wysihtml5.lang.object(t).merge(s).merge(b.rules).get(),c=b.context||a.ownerDocument||document,f=c.createDocumentFragment(),g="string"==typeof a,h=!1,b.clearInternals===!0&&(h=!0),i=g?wysihtml5.dom.getAsDom(a,c):a,t.selectors&&e(i,t.selectors);i.firstChild;)k=i.firstChild,j=d(k,b.cleanUp,h,b.uneditableClass),j&&f.appendChild(j),k!==j&&i.removeChild(k);if(b.unjoinNbsps)for(l=wysihtml5.dom.getTextNodes(f),m=l.length;m--;)l[m].nodeValue=l[m].nodeValue.replace(/([\S\u00A0])\u00A0/gi,"$1 ");return i.innerHTML="",i.appendChild(f),g?wysihtml5.quirks.getCorrectInnerHTML(i):i}function d(a,b,c,e){var f,g,h,i=a.nodeType,j=a.childNodes,k=j.length,l=p[i],m=0;if(e&&1===i&&wysihtml5.dom.hasClass(a,e))return a;if(g=l&&l(a,c),!g){if(g===!1){for(f=a.ownerDocument.createDocumentFragment(),m=k;m--;)j[m]&&(h=d(j[m],b,c,e),h&&(j[m]===h&&m--,f.insertBefore(h,f.firstChild)));return"block"===wysihtml5.dom.getStyle("display").from(a)&&f.appendChild(a.ownerDocument.createElement("br")),wysihtml5.lang.array(["div","pre","p","table","td","th","ul","ol","li","dd","dl","footer","header","section","h1","h2","h3","h4","h5","h6"]).contains(a.nodeName.toLowerCase())&&a.parentNode.lastChild!==a&&(a.nextSibling&&3===a.nextSibling.nodeType&&/^\s/.test(a.nextSibling.nodeValue)||f.appendChild(a.ownerDocument.createTextNode(" "))),f.normalize&&f.normalize(),f}return null}for(m=0;k>m;m++)j[m]&&(h=d(j[m],b,c,e),h&&(j[m]===h&&m--,g.appendChild(h)));if(b&&g.nodeName.toLowerCase()===q&&(!g.childNodes.length||/^\s*$/gi.test(g.innerHTML)&&(c||"_wysihtml5-temp-placeholder"!==a.className&&"rangySelectionBoundary"!==a.className)||!g.attributes.length)){for(f=g.ownerDocument.createDocumentFragment();g.firstChild;)f.appendChild(g.firstChild);return f.normalize&&f.normalize(),f}return g.normalize&&g.normalize(),g}function e(a,b){var c,d,e,f;for(c in b)if(b.hasOwnProperty(c))for(wysihtml5.lang.object(b[c]).isFunction()?d=b[c]:"string"==typeof b[c]&&z[b[c]]&&(d=z[b[c]]),e=a.querySelectorAll(c),f=e.length;f--;)d(e[f])}function f(a,b){var c,d,e,f=t.tags,h=a.nodeName.toLowerCase(),j=a.scopeName;if(a._wysihtml5)return null;if(a._wysihtml5=1,"wysihtml5-temp"===a.className)return null;if(j&&"HTML"!=j&&(h=j+":"+h),"outerHTML"in a&&(wysihtml5.browser.autoClosesUnclosedTags()||"P"!==a.nodeName||"</p>"===a.outerHTML.slice(-4).toLowerCase()||(h="div")),h in f){if(c=f[h],!c||c.remove)return null;if(c.unwrap)return!1;c="string"==typeof c?{rename_tag:c}:c}else{if(!a.firstChild)return null;c={rename_tag:q}}if(c.one_of_type&&!g(a,t,c.one_of_type,b)){if(!c.remove_action)return null;if("unwrap"===c.remove_action)return!1;if("rename"!==c.remove_action)return null;e=c.remove_action_rename_to||q}return d=a.ownerDocument.createElement(e||c.rename_tag||h),m(a,d,c,b),i(a,d,c),a=null,d.normalize&&d.normalize(),d}function g(a,b,c,d){var e,f;if("SPAN"===a.nodeName&&!d&&("_wysihtml5-temp-placeholder"===a.className||"rangySelectionBoundary"===a.className))return!0;for(f in c)if(c.hasOwnProperty(f)&&b.type_definitions&&b.type_definitions[f]&&(e=b.type_definitions[f],h(a,e)))return!0;return!1}function h(a,b){var c,d,e,f,g,h,i,j,k=a.getAttribute("class"),l=a.getAttribute("style");if(b.methods)for(h in b.methods)if(b.methods.hasOwnProperty(h)&&y[h]&&y[h](a))return!0;if(k&&b.classes)for(k=k.replace(/^\s+/g,"").replace(/\s+$/g,"").split(r),c=k.length,i=0;c>i;i++)if(b.classes[k[i]])return!0;if(l&&b.styles){l=l.split(";");for(d in b.styles)if(b.styles.hasOwnProperty(d))for(j=l.length;j--;)if(g=l[j].split(":"),g[0].replace(/\s/g,"").toLowerCase()===d&&(b.styles[d]===!0||1===b.styles[d]||wysihtml5.lang.array(b.styles[d]).contains(g[1].replace(/\s/g,"").toLowerCase())))return!0}if(b.attrs)for(e in b.attrs)if(b.attrs.hasOwnProperty(e)&&(f=wysihtml5.dom.getAttribute(a,e),"string"==typeof f&&f.search(b.attrs[e])>-1))return!0;return!1}function i(a,b,c){var d,e;if(c&&c.keep_styles)for(d in c.keep_styles)if(c.keep_styles.hasOwnProperty(d)){if(e="float"===d?a.style.styleFloat||a.style.cssFloat:a.style[d],c.keep_styles[d]instanceof RegExp&&!c.keep_styles[d].test(e))continue;"float"===d?b.style[a.style.styleFloat?"styleFloat":"cssFloat"]=e:a.style[d]&&(b.style[d]=e)}}function j(a,b){var c,d=[];for(c in b)b.hasOwnProperty(c)&&0===c.indexOf(a)&&d.push(c);return d}function k(a,b,c,d){var e,f=v[c];return f&&(b||"alt"===a&&"IMG"==d)&&(e=f(b),"string"==typeof e)?e:!1}function l(a,b){var c,d,e,f,g,h=wysihtml5.lang.object(t.attributes||{}).clone(),i=wysihtml5.lang.object(h).merge(wysihtml5.lang.object(b||{}).clone()).get(),l={},m=wysihtml5.dom.getAttributes(a);for(c in i)if(/\*$/.test(c))for(e=j(c.slice(0,-1),m),f=0,g=e.length;g>f;f++)d=k(e[f],m[e[f]],i[c],a.nodeName),d!==!1&&(l[e[f]]=d);else d=k(c,m[c],i[c],a.nodeName),d!==!1&&(l[c]=d);return l}function m(a,b,c,d){var e,f,g,h,i,j={},k=c.set_class,m=c.add_class,n=c.add_style,o=c.set_attributes,p=t.classes,q=0,s=[],u=[],v=[],y=[];if(o&&(j=wysihtml5.lang.object(o).clone()),j=wysihtml5.lang.object(j).merge(l(a,c.check_attributes)).get(),k&&s.push(k),m)for(h in m)i=x[m[h]],i&&(g=i(wysihtml5.dom.getAttribute(a,h)),"string"==typeof g&&s.push(g));if(n)for(h in n)i=w[n[h]],i&&(newStyle=i(wysihtml5.dom.getAttribute(a,h)),"string"==typeof newStyle&&u.push(newStyle));if("string"==typeof p&&"any"===p&&a.getAttribute("class"))if(t.classes_blacklist){for(y=a.getAttribute("class"),y&&(s=s.concat(y.split(r))),e=s.length;e>q;q++)f=s[q],t.classes_blacklist[f]||v.push(f);v.length&&(j["class"]=wysihtml5.lang.array(v).unique().join(" "))}else j["class"]=a.getAttribute("class");else{for(d||(p["_wysihtml5-temp-placeholder"]=1,p._rangySelectionBoundary=1,p["wysiwyg-tmp-selected-cell"]=1),y=a.getAttribute("class"),y&&(s=s.concat(y.split(r))),e=s.length;e>q;q++)f=s[q],p[f]&&v.push(f);v.length&&(j["class"]=wysihtml5.lang.array(v).unique().join(" "))}j["class"]&&d&&(j["class"]=j["class"].replace("wysiwyg-tmp-selected-cell",""),/^\s*$/g.test(j["class"])&&delete j["class"]),u.length&&(j.style=wysihtml5.lang.array(u).unique().join(" "));for(h in j)try{b.setAttribute(h,j[h])}catch(z){}j.src&&(void 0!==j.width&&b.setAttribute("width",j.width),void 0!==j.height&&b.setAttribute("height",j.height))}function n(a){var b,c=a.nextSibling;return c&&c.nodeType===wysihtml5.TEXT_NODE?(c.data=a.data.replace(u,"")+c.data.replace(u,""),void 0):(b=a.data.replace(u,""),a.ownerDocument.createTextNode(b))}function o(a){return t.comments?a.ownerDocument.createComment(a.nodeValue):void 0}var p={1:f,3:n,8:o},q="span",r=/\s+/,s={tags:{},classes:{}},t={},u=/\uFEFF/g,v={url:function(){var a=/^https?:\/\//i;return function(b){return b&&b.match(a)?b.replace(a,function(a){return a.toLowerCase()}):null}}(),src:function(){var a=/^(\/|https?:\/\/)/i;return function(b){return b&&b.match(a)?b.replace(a,function(a){return a.toLowerCase()}):null}}(),href:function(){var a=/^(#|\/|https?:\/\/|mailto:)/i;return function(b){return b&&b.match(a)?b.replace(a,function(a){return a.toLowerCase()}):null}}(),alt:function(){var a=/[^ a-z0-9_\-]/gi;return function(b){return b?b.replace(a,""):""}}(),numbers:function(){var a=/\D/g;return function(b){return b=(b||"").replace(a,""),b||null}}(),any:function(){return function(a){return a}}()},w={align_text:function(){var a={left:"text-align: left;",right:"text-align: right;",center:"text-align: center;"};return function(b){return a[(b+"").toLowerCase()]}}()},x={align_img:function(){var a={left:"wysiwyg-float-left",right:"wysiwyg-float-right"};return function(b){return a[(b+"").toLowerCase()]}}(),align_text:function(){var a={left:"wysiwyg-text-align-left",right:"wysiwyg-text-align-right",center:"wysiwyg-text-align-center",justify:"wysiwyg-text-align-justify"};return function(b){return a[(b+"").toLowerCase()]}}(),clear_br:function(){var a={left:"wysiwyg-clear-left",right:"wysiwyg-clear-right",both:"wysiwyg-clear-both",all:"wysiwyg-clear-both"};return function(b){return a[(b+"").toLowerCase()]}}(),size_font:function(){var a={1:"wysiwyg-font-size-xx-small",2:"wysiwyg-font-size-small",3:"wysiwyg-font-size-medium",4:"wysiwyg-font-size-large",5:"wysiwyg-font-size-x-large",6:"wysiwyg-font-size-xx-large",7:"wysiwyg-font-size-xx-large","-":"wysiwyg-font-size-smaller","+":"wysiwyg-font-size-larger"};return function(b){return a[(b+"").charAt(0)]}}()},y={has_visible_contet:function(){var a,b=["img","video","picture","br","script","noscript","style","table","iframe","object","embed","audio","svg","input","button","select","textarea","canvas"];return function(c){if(a=(c.innerText||c.textContent).replace(/\s/g,""),a&&a.length>0)return!0;for(var d=b.length;d--;)if(c.querySelector(b[d]))return!0;return c.offsetWidth&&c.offsetWidth>0&&c.offsetHeight&&c.offsetHeight>0?!0:!1}}()},z={unwrap:function(a){wysihtml5.dom.unwrap(a)},remove:function(a){a.parentNode.removeChild(a)}};return c(a,b)},wysihtml5.dom.removeEmptyTextNodes=function(a){for(var b,c=wysihtml5.lang.array(a.childNodes).get(),d=c.length,e=0;d>e;e++)b=c[e],b.nodeType===wysihtml5.TEXT_NODE&&""===b.data&&b.parentNode.removeChild(b)},wysihtml5.dom.renameElement=function(a,b){for(var c,d=a.ownerDocument.createElement(b);c=a.firstChild;)d.appendChild(c);return wysihtml5.dom.copyAttributes(["align","className"]).from(a).to(d),a.parentNode.replaceChild(d,a),d},wysihtml5.dom.replaceWithChildNodes=function(a){if(a.parentNode){if(!a.firstChild)return a.parentNode.removeChild(a),void 0;for(var b=a.ownerDocument.createDocumentFragment();a.firstChild;)b.appendChild(a.firstChild);a.parentNode.replaceChild(b,a),a=b=null}},function(a){function b(b){return"block"===a.getStyle("display").from(b)}function c(a){return"BR"===a.nodeName}function d(a){var b=a.ownerDocument.createElement("br");a.appendChild(b)}function e(a,e){if(a.nodeName.match(/^(MENU|UL|OL)$/)){var f,g,h,i,j,k,l=a.ownerDocument,m=l.createDocumentFragment(),n=wysihtml5.dom.domNode(a).prev({ignoreBlankTexts:!0});if(e)for(!n||b(n)||c(n)||d(m);k=a.firstElementChild||a.firstChild;){for(g=k.lastChild;f=k.firstChild;)h=f===g,i=h&&!b(f)&&!c(f),m.appendChild(f),i&&d(m);k.parentNode.removeChild(k)}else for(;k=a.firstElementChild||a.firstChild;){if(k.querySelector&&k.querySelector("div, p, ul, ol, menu, blockquote, h1, h2, h3, h4, h5, h6"))for(;f=k.firstChild;)m.appendChild(f);else{for(j=l.createElement("p");f=k.firstChild;)j.appendChild(f);m.appendChild(j)}k.parentNode.removeChild(k)}a.parentNode.replaceChild(m,a)}}a.resolveList=e}(wysihtml5.dom),function(a){var b=document,c=["parent","top","opener","frameElement","frames","localStorage","globalStorage","sessionStorage","indexedDB"],d=["open","close","openDialog","showModalDialog","alert","confirm","prompt","openDatabase","postMessage","XMLHttpRequest","XDomainRequest"],e=["referrer","write","open","close"];a.dom.Sandbox=Base.extend({constructor:function(b,c){this.callback=b||a.EMPTY_FUNCTION,this.config=a.lang.object({}).merge(c).get(),this.editableArea=this._createIframe()},insertInto:function(a){"string"==typeof a&&(a=b.getElementById(a)),a.appendChild(this.editableArea)},getIframe:function(){return this.editableArea},getWindow:function(){this._readyError()},getDocument:function(){this._readyError()},destroy:function(){var a=this.getIframe();a.parentNode.removeChild(a)},_readyError:function(){throw Error("wysihtml5.Sandbox: Sandbox iframe isn't loaded yet")},_createIframe:function(){var c=this,d=b.createElement("iframe");return d.className="wysihtml5-sandbox",a.dom.setAttributes({security:"restricted",allowtransparency:"true",frameborder:0,width:0,height:0,marginwidth:0,marginheight:0}).on(d),a.browser.throwsMixedContentWarningWhenIframeSrcIsEmpty()&&(d.src="javascript:'<html></html>'"),d.onload=function(){d.onreadystatechange=d.onload=null,c._onLoadIframe(d)},d.onreadystatechange=function(){/loaded|complete/.test(d.readyState)&&(d.onreadystatechange=d.onload=null,c._onLoadIframe(d))},d},_onLoadIframe:function(f){var g,h,i,j,k,l,m;if(a.dom.contains(b.documentElement,f)){if(g=this,h=f.contentWindow,i=f.contentWindow.document,j=b.characterSet||b.charset||"utf-8",k=this._getHtml({charset:j,stylesheets:this.config.stylesheets}),i.open("text/html","replace"),i.write(k),i.close(),this.getWindow=function(){return f.contentWindow},this.getDocument=function(){return f.contentWindow.document},h.onerror=function(a,b,c){throw Error("wysihtml5.Sandbox: "+a,b,c)},!a.browser.supportsSandboxedIframes()){for(l=0,m=c.length;m>l;l++)this._unset(h,c[l]);for(l=0,m=d.length;m>l;l++)this._unset(h,d[l],a.EMPTY_FUNCTION);for(l=0,m=e.length;m>l;l++)this._unset(i,e[l]);this._unset(i,"cookie","",!0)}this.loaded=!0,setTimeout(function(){g.callback(g)},0)}},_getHtml:function(b){var c,d=b.stylesheets,e="",f=0;if(d="string"==typeof d?[d]:d,d)for(c=d.length;c>f;f++)e+='<link rel="stylesheet" href="'+d[f]+'">';return b.stylesheets=e,a.lang.string('<!DOCTYPE html><html><head><meta charset="#{charset}">#{stylesheets}</head><body></body></html>').interpolate(b)},_unset:function(b,c,d,e){try{b[c]=d}catch(f){}try{b.__defineGetter__(c,function(){return d})}catch(f){}if(e)try{b.__defineSetter__(c,function(){})}catch(f){}if(!a.browser.crashesWhenDefineProperty(c))try{var g={get:function(){return d}};e&&(g.set=function(){}),Object.defineProperty(b,c,g)}catch(f){}}})}(wysihtml5),function(a){var b=document;a.dom.ContentEditableArea=Base.extend({getContentEditable:function(){return this.element},getWindow:function(){return this.element.ownerDocument.defaultView},getDocument:function(){return this.element.ownerDocument},constructor:function(b,c,d){this.callback=b||a.EMPTY_FUNCTION,this.config=a.lang.object({}).merge(c).get(),this.element=d?this._bindElement(d):this._createElement()},_createElement:function(){var a=b.createElement("div");return a.className="wysihtml5-sandbox",this._loadElement(a),a},_bindElement:function(a){return a.className=a.className&&""!=a.className?a.className+" wysihtml5-sandbox":"wysihtml5-sandbox",this._loadElement(a,!0),a},_loadElement:function(a,b){var c,d=this;b||(c=this._getHtml(),a.innerHTML=c),this.getWindow=function(){return a.ownerDocument.defaultView},this.getDocument=function(){return a.ownerDocument},this.loaded=!0,setTimeout(function(){d.callback(d)},0)},_getHtml:function(){return""}})}(wysihtml5),function(){var a={className:"class"};wysihtml5.dom.setAttributes=function(b){return{on:function(c){for(var d in b)c.setAttribute(a[d]||d,b[d])}}}}(),wysihtml5.dom.setStyles=function(a){return{on:function(b){var c,d=b.style;if("string"==typeof a)return d.cssText+=";"+a,void 0;for(c in a)"float"===c?(d.cssFloat=a[c],d.styleFloat=a[c]):d[c]=a[c]}}},function(a){a.simulatePlaceholder=function(b,c,d){var e="placeholder",f=function(){var b=c.element.offsetWidth>0&&c.element.offsetHeight>0;c.hasPlaceholderSet()&&(c.clear(),c.element.focus(),b&&setTimeout(function(){var a=c.selection.getSelection();a.focusNode&&a.anchorNode||c.selection.selectNode(c.element.firstChild||c.element)},0)),c.placeholderSet=!1,a.removeClass(c.element,e)},g=function(){c.isEmpty()&&(c.placeholderSet=!0,c.setValue(d),a.addClass(c.element,e))};b.on("set_placeholder",g).on("unset_placeholder",f).on("focus:composer",f).on("paste:composer",f).on("blur:composer",g),g()}}(wysihtml5.dom),function(a){var b=document.documentElement;"textContent"in b?(a.setTextContent=function(a,b){a.textContent=b},a.getTextContent=function(a){return a.textContent}):"innerText"in b?(a.setTextContent=function(a,b){a.innerText=b},a.getTextContent=function(a){return a.innerText}):(a.setTextContent=function(a,b){a.nodeValue=b},a.getTextContent=function(a){return a.nodeValue})}(wysihtml5.dom),wysihtml5.dom.getAttribute=function(a,b){var c,d,e,f=!wysihtml5.browser.supportsGetAttributeCorrectly();return b=b.toLowerCase(),c=a.nodeName,"IMG"==c&&"src"==b&&wysihtml5.dom.isLoadedImage(a)===!0?a.src:f&&"outerHTML"in a?(d=a.outerHTML.toLowerCase(),e=-1!=d.indexOf(" "+b+"="),e?a.getAttribute(b):null):a.getAttribute(b)},wysihtml5.dom.getAttributes=function(a){var b,c=!wysihtml5.browser.supportsGetAttributeCorrectly(),d=a.nodeName,e=[];for(b in a.attributes)(a.attributes.hasOwnProperty&&a.attributes.hasOwnProperty(b)||!a.attributes.hasOwnProperty&&Object.prototype.hasOwnProperty.call(a.attributes,b))&&a.attributes[b].specified&&("IMG"==d&&"src"==a.attributes[b].name.toLowerCase()&&wysihtml5.dom.isLoadedImage(a)===!0?e.src=a.src:wysihtml5.lang.array(["rowspan","colspan"]).contains(a.attributes[b].name.toLowerCase())&&c?1!==a.attributes[b].value&&(e[a.attributes[b].name]=a.attributes[b].value):e[a.attributes[b].name]=a.attributes[b].value);return e},wysihtml5.dom.isLoadedImage=function(a){try{return a.complete&&!a.mozMatchesSelector(":-moz-broken")}catch(b){if(a.complete&&"complete"===a.readyState)return!0}},function(a){function b(a,b){var c,d,e,f,g=[];for(d=0,e=a.length;e>d;d++)if(c=a[d].querySelectorAll(b),c)for(f=c.length;f--;g.unshift(c[f]));return g}function d(a){a.parentNode.removeChild(a)}function e(a,b){a.parentNode.insertBefore(b,a.nextSibling)}function f(a,b){for(var c=a.nextSibling;1!=c.nodeType;)if(c=c.nextSibling,!b||b==c.tagName.toLowerCase())return c;return null}var g=a.dom,h=function(a){this.el=a,this.isColspan=!1,this.isRowspan=!1,this.firstCol=!0,this.lastCol=!0,this.firstRow=!0,this.lastRow=!0,this.isReal=!0,this.spanCollection=[],this.modified=!1},i=function(a,b){a?(this.cell=a,this.table=g.getParentElement(a,{nodeName:["TABLE"]})):b&&(this.table=b,this.cell=this.table.querySelectorAll("th, td")[0])};i.prototype={addSpannedCellToMap:function(a,b,c,d,e,f){var g,i,j=[],k=c+(f?parseInt(f,10)-1:0),l=d+(e?parseInt(e,10)-1:0);for(g=c;k>=g;g++)for(void 0===b[g]&&(b[g]=[]),i=d;l>=i;i++)b[g][i]=new h(a),b[g][i].isColspan=e&&parseInt(e,10)>1,b[g][i].isRowspan=f&&parseInt(f,10)>1,b[g][i].firstCol=i==d,b[g][i].lastCol=i==l,b[g][i].firstRow=g==c,b[g][i].lastRow=g==k,b[g][i].isReal=i==d&&g==c,b[g][i].spanCollection=j,j.push(b[g][i])},setCellAsModified:function(a){if(a.modified=!0,a.spanCollection.length>0)for(var b=0,c=a.spanCollection.length;c>b;b++)a.spanCollection[b].modified=!0},setTableMap:function(){var a,b,c,d,e,f,i,j,k=[],l=this.getTableRows();for(a=0;a<l.length;a++)for(b=l[a],c=this.getRowCells(b),f=0,void 0===k[a]&&(k[a]=[]),d=0;d<c.length;d++){for(e=c[d];void 0!==k[a][f];)f++;i=g.getAttribute(e,"colspan"),j=g.getAttribute(e,"rowspan"),i||j?(this.addSpannedCellToMap(e,k,a,f,i,j),f+=i?parseInt(i,10):1):(k[a][f]=new h(e),f++)}return this.map=k,k},getRowCells:function(c){var d=this.table.querySelectorAll("table"),e=d?b(d,"th, td"):[],f=c.querySelectorAll("th, td"),g=e.length>0?a.lang.array(f).without(e):f;return g},getTableRows:function(){var c=this.table.querySelectorAll("table"),d=c?b(c,"tr"):[],e=this.table.querySelectorAll("tr"),f=d.length>0?a.lang.array(e).without(d):e;return f},getMapIndex:function(a){var b,c,d=this.map.length,e=this.map&&this.map[0]?this.map[0].length:0;for(b=0;d>b;b++)for(c=0;e>c;c++)if(this.map[b][c].el===a)return{row:b,col:c};return!1},getElementAtIndex:function(a){return this.setTableMap(),this.map[a.row]&&this.map[a.row][a.col]&&this.map[a.row][a.col].el?this.map[a.row][a.col].el:null},getMapElsTo:function(a){var b,c,d,e,f,g,h=[];if(this.setTableMap(),this.idx_start=this.getMapIndex(this.cell),this.idx_end=this.getMapIndex(a),(this.idx_start.row>this.idx_end.row||this.idx_start.row==this.idx_end.row&&this.idx_start.col>this.idx_end.col)&&(b=this.idx_start,this.idx_start=this.idx_end,this.idx_end=b),this.idx_start.col>this.idx_end.col&&(c=this.idx_start.col,this.idx_start.col=this.idx_end.col,this.idx_end.col=c),null!=this.idx_start&&null!=this.idx_end)for(d=this.idx_start.row,e=this.idx_end.row;e>=d;d++)for(f=this.idx_start.col,g=this.idx_end.col;g>=f;f++)h.push(this.map[d][f].el);return h},orderSelectionEnds:function(a){var b,c;return this.setTableMap(),this.idx_start=this.getMapIndex(this.cell),this.idx_end=this.getMapIndex(a),(this.idx_start.row>this.idx_end.row||this.idx_start.row==this.idx_end.row&&this.idx_start.col>this.idx_end.col)&&(b=this.idx_start,this.idx_start=this.idx_end,this.idx_end=b),this.idx_start.col>this.idx_end.col&&(c=this.idx_start.col,this.idx_start.col=this.idx_end.col,this.idx_end.col=c),{start:this.map[this.idx_start.row][this.idx_start.col].el,end:this.map[this.idx_end.row][this.idx_end.col].el}},createCells:function(a,b,c){var d,e,f,g=this.table.ownerDocument,h=g.createDocumentFragment();for(e=0;b>e;e++){if(d=g.createElement(a),c)for(f in c)c.hasOwnProperty(f)&&d.setAttribute(f,c[f]);d.appendChild(document.createTextNode(" ")),h.appendChild(d)}return h},correctColIndexForUnreals:function(a,b){var c,d,e=this.map[b],f=-1;for(c=0,d=a;a>c;c++)e[c].isReal&&f++;return f},getLastNewCellOnRow:function(a,b){var c,d,e,f,g=this.getRowCells(a);for(e=0,f=g.length;f>e;e++)if(c=g[e],d=this.getMapIndex(c),d===!1||void 0!==b&&d.row!=b)return c;return null},removeEmptyTable:function(){var a=this.table.querySelectorAll("td, th");return a&&0!=a.length?!1:(d(this.table),!0)},splitRowToCells:function(a){var b,c,d;a.isColspan&&(b=parseInt(g.getAttribute(a.el,"colspan")||1,10),c=a.el.tagName.toLowerCase(),b>1&&(d=this.createCells(c,b-1),e(a.el,d)),a.el.removeAttribute("colspan"))},getRealRowEl:function(a,b){var c,d,e=null,f=null;for(b=b||this.idx,c=0,d=this.map[b.row].length;d>c;c++)if(f=this.map[b.row][c],f.isReal&&(e=g.getParentElement(f.el,{nodeName:["TR"]}),e))return e;return null===e&&a&&(e=g.getParentElement(this.map[b.row][b.col].el,{nodeName:["TR"]})||null),e},injectRowAt:function(a,b,c,d,f){var h,i,j=this.getRealRowEl(!1,{row:a,col:b}),k=this.createCells(d,c);j?(h=this.correctColIndexForUnreals(b,a),h>=0?e(this.getRowCells(j)[h],k):j.insertBefore(k,j.firstChild)):(i=this.table.ownerDocument.createElement("tr"),i.appendChild(k),e(g.getParentElement(f.el,{nodeName:["TR"]}),i))},canMerge:function(a){var b,c,d,e,f,g;for(this.to=a,this.setTableMap(),this.idx_start=this.getMapIndex(this.cell),this.idx_end=this.getMapIndex(this.to),(this.idx_start.row>this.idx_end.row||this.idx_start.row==this.idx_end.row&&this.idx_start.col>this.idx_end.col)&&(b=this.idx_start,this.idx_start=this.idx_end,this.idx_end=b),this.idx_start.col>this.idx_end.col&&(c=this.idx_start.col,this.idx_start.col=this.idx_end.col,this.idx_end.col=c),d=this.idx_start.row,e=this.idx_end.row;e>=d;d++)for(f=this.idx_start.col,g=this.idx_end.col;g>=f;f++)if(this.map[d][f].isColspan||this.map[d][f].isRowspan)return!1;return!0},decreaseCellSpan:function(a,b){var c=parseInt(g.getAttribute(a.el,b),10)-1;c>=1?a.el.setAttribute(b,c):(a.el.removeAttribute(b),"colspan"==b&&(a.isColspan=!1),"rowspan"==b&&(a.isRowspan=!1),a.firstCol=!0,a.lastCol=!0,a.firstRow=!0,a.lastRow=!0,a.isReal=!0)},removeSurplusLines:function(){var a,b,c,e,f,h,i,j;if(this.setTableMap(),this.map){for(c=0,e=this.map.length;e>c;c++){for(a=this.map[c],i=!0,f=0,h=a.length;h>f;f++)if(b=a[f],!(g.getAttribute(b.el,"rowspan")&&parseInt(g.getAttribute(b.el,"rowspan"),10)>1&&b.firstRow!==!0)){i=!1;break}if(i)for(f=0;h>f;f++)this.decreaseCellSpan(a[f],"rowspan")}for(j=this.getTableRows(),c=0,e=j.length;e>c;c++)a=j[c],0==a.childNodes.length&&/^\s*$/.test(a.textContent||a.innerText)&&d(a)}},fillMissingCells:function(){var a,b,c,d=0,f=0,g=null;if(this.setTableMap(),this.map){for(d=this.map.length,a=0;d>a;a++)this.map[a].length>f&&(f=this.map[a].length);for(b=0;d>b;b++)for(c=0;f>c;c++)this.map[b]&&!this.map[b][c]&&c>0&&(this.map[b][c]=new h(this.createCells("td",1)),g=this.map[b][c-1],g&&g.el&&g.el.parent&&e(this.map[b][c-1].el,this.map[b][c].el))}},rectify:function(){return this.removeEmptyTable()?!1:(this.removeSurplusLines(),this.fillMissingCells(),!0)},unmerge:function(){var a,b,c,d,e,f;if(this.rectify()&&(this.setTableMap(),this.idx=this.getMapIndex(this.cell),this.idx)){if(a=this.map[this.idx.row][this.idx.col],b=g.getAttribute(a.el,"colspan")?parseInt(g.getAttribute(a.el,"colspan"),10):1,c=a.el.tagName.toLowerCase(),a.isRowspan){if(d=parseInt(g.getAttribute(a.el,"rowspan"),10),d>1)for(e=1,f=d-1;f>=e;e++)this.injectRowAt(this.idx.row+e,this.idx.col,b,c,a);a.el.removeAttribute("rowspan")}this.splitRowToCells(a)}},merge:function(a){var b,c,e,f,g,h;if(this.rectify())if(this.canMerge(a)){for(b=this.idx_end.row-this.idx_start.row+1,c=this.idx_end.col-this.idx_start.col+1,e=this.idx_start.row,f=this.idx_end.row;f>=e;e++)for(g=this.idx_start.col,h=this.idx_end.col;h>=g;g++)e==this.idx_start.row&&g==this.idx_start.col?(b>1&&this.map[e][g].el.setAttribute("rowspan",b),c>1&&this.map[e][g].el.setAttribute("colspan",c)):(/^\s*<br\/?>\s*$/.test(this.map[e][g].el.innerHTML.toLowerCase())||(this.map[this.idx_start.row][this.idx_start.col].el.innerHTML+=" "+this.map[e][g].el.innerHTML),d(this.map[e][g].el));this.rectify()}else window.console&&void 0},collapseCellToNextRow:function(a){var b,c,d,f=this.getMapIndex(a.el),h=f.row+1,i={row:h,col:f.col};h<this.map.length&&(b=this.getRealRowEl(!1,i),null!==b&&(c=this.correctColIndexForUnreals(i.col,i.row),c>=0?e(this.getRowCells(b)[c],a.el):(d=this.getLastNewCellOnRow(b,h),null!==d?e(d,a.el):b.insertBefore(a.el,b.firstChild)),parseInt(g.getAttribute(a.el,"rowspan"),10)>2?a.el.setAttribute("rowspan",parseInt(g.getAttribute(a.el,"rowspan"),10)-1):a.el.removeAttribute("rowspan")))},removeRowCell:function(a){a.isReal?a.isRowspan?this.collapseCellToNextRow(a):d(a.el):parseInt(g.getAttribute(a.el,"rowspan"),10)>2?a.el.setAttribute("rowspan",parseInt(g.getAttribute(a.el,"rowspan"),10)-1):a.el.removeAttribute("rowspan")},getRowElementsByCell:function(){var a,b,c,d=[];if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),this.idx!==!1)for(a=this.map[this.idx.row],b=0,c=a.length;c>b;b++)a[b].isReal&&d.push(a[b].el);return d},getColumnElementsByCell:function(){var a,b,c=[];if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),this.idx!==!1)for(a=0,b=this.map.length;b>a;a++)this.map[a][this.idx.col]&&this.map[a][this.idx.col].isReal&&c.push(this.map[a][this.idx.col].el);return c},removeRow:function(){var a,b,c,e=g.getParentElement(this.cell,{nodeName:["TR"]});if(e){if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),this.idx!==!1)for(a=this.map[this.idx.row],b=0,c=a.length;c>b;b++)a[b].modified||(this.setCellAsModified(a[b]),this.removeRowCell(a[b]));d(e)}},removeColCell:function(a){a.isColspan?parseInt(g.getAttribute(a.el,"colspan"),10)>2?a.el.setAttribute("colspan",parseInt(g.getAttribute(a.el,"colspan"),10)-1):a.el.removeAttribute("colspan"):a.isReal&&d(a.el)},removeColumn:function(){if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),this.idx!==!1)for(var a=0,b=this.map.length;b>a;a++)this.map[a][this.idx.col].modified||(this.setCellAsModified(this.map[a][this.idx.col]),this.removeColCell(this.map[a][this.idx.col]))},remove:function(a){if(this.rectify()){switch(a){case"row":this.removeRow();break;case"column":this.removeColumn()}this.rectify()}},addRow:function(a){var b,c,d,f,h,i=this.table.ownerDocument;if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),"below"==a&&g.getAttribute(this.cell,"rowspan")&&(this.idx.row=this.idx.row+parseInt(g.getAttribute(this.cell,"rowspan"),10)-1),this.idx!==!1){for(b=this.map[this.idx.row],c=i.createElement("tr"),d=0,f=b.length;f>d;d++)b[d].modified||(this.setCellAsModified(b[d]),this.addRowCell(b[d],c,a));switch(a){case"below":e(this.getRealRowEl(!0),c);break;case"above":h=g.getParentElement(this.map[this.idx.row][this.idx.col].el,{nodeName:["TR"]}),h&&h.parentNode.insertBefore(c,h)}}},addRowCell:function(a,b,d){var e=a.isColspan?{colspan:g.getAttribute(a.el,"colspan")}:null;a.isReal?"above"!=d&&a.isRowspan?a.el.setAttribute("rowspan",parseInt(g.getAttribute(a.el,"rowspan"),10)+1):b.appendChild(this.createCells("td",1,e)):"above"!=d&&a.isRowspan&&a.lastRow?b.appendChild(this.createCells("td",1,e)):c.isRowspan&&a.el.attr("rowspan",parseInt(g.getAttribute(a.el,"rowspan"),10)+1)},add:function(a){this.rectify()&&(("below"==a||"above"==a)&&this.addRow(a),("before"==a||"after"==a)&&this.addColumn(a))},addColCell:function(a,b,d){var f,h=a.el.tagName.toLowerCase();switch(d){case"before":f=!a.isColspan||a.firstCol;break;case"after":f=!a.isColspan||a.lastCol||a.isColspan&&c.el==this.cell}if(f){switch(d){case"before":a.el.parentNode.insertBefore(this.createCells(h,1),a.el);break;case"after":e(a.el,this.createCells(h,1))}a.isRowspan&&this.handleCellAddWithRowspan(a,b+1,d)}else a.el.setAttribute("colspan",parseInt(g.getAttribute(a.el,"colspan"),10)+1)},addColumn:function(a){var b,c,d,e;if(this.setTableMap(),this.idx=this.getMapIndex(this.cell),"after"==a&&g.getAttribute(this.cell,"colspan")&&(this.idx.col=this.idx.col+parseInt(g.getAttribute(this.cell,"colspan"),10)-1),this.idx!==!1)for(d=0,e=this.map.length;e>d;d++)b=this.map[d],b[this.idx.col]&&(c=b[this.idx.col],c.modified||(this.setCellAsModified(c),this.addColCell(c,d,a)))},handleCellAddWithRowspan:function(a,b,c){var d,h,i,j,k=parseInt(g.getAttribute(this.cell,"rowspan"),10)-1,l=g.getParentElement(a.el,{nodeName:["TR"]}),m=a.el.tagName.toLowerCase(),n=this.table.ownerDocument;for(j=0;k>j;j++)if(d=this.correctColIndexForUnreals(this.idx.col,b+j),l=f(l,"tr"),l)if(d>0)switch(c){case"before":h=this.getRowCells(l),d>0&&this.map[b+j][this.idx.col].el!=h[d]&&d==h.length-1?e(h[d],this.createCells(m,1)):h[d].parentNode.insertBefore(this.createCells(m,1),h[d]);
break;case"after":e(this.getRowCells(l)[d],this.createCells(m,1))}else l.insertBefore(this.createCells(m,1),l.firstChild);else i=n.createElement("tr"),i.appendChild(this.createCells(m,1)),this.table.appendChild(i)}},g.table={getCellsBetween:function(a,b){var c=new i(a);return c.getMapElsTo(b)},addCells:function(a,b){var c=new i(a);c.add(b)},removeCells:function(a,b){var c=new i(a);c.remove(b)},mergeCellsBetween:function(a,b){var c=new i(a);c.merge(b)},unmergeCell:function(a){var b=new i(a);b.unmerge()},orderSelectionEnds:function(a,b){var c=new i(a);return c.orderSelectionEnds(b)},indexOf:function(a){var b=new i(a);return b.setTableMap(),b.getMapIndex(a)},findCell:function(a,b){var c=new i(null,a);return c.getElementAtIndex(b)},findRowByCell:function(a){var b=new i(a);return b.getRowElementsByCell()},findColumnByCell:function(a){var b=new i(a);return b.getColumnElementsByCell()},canMerge:function(a,b){var c=new i(a);return c.canMerge(b)}}}(wysihtml5),wysihtml5.dom.query=function(a,b){var c,d,e,f,g=[];for(a.nodeType&&(a=[a]),d=0,e=a.length;e>d;d++)if(c=a[d].querySelectorAll(b),c)for(f=c.length;f--;g.unshift(c[f]));return g},wysihtml5.dom.compareDocumentPosition=function(){var a=document.documentElement;return a.compareDocumentPosition?function(a,b){return a.compareDocumentPosition(b)}:function(a,b){var c,d,e,f,g,h,i,j,k;if(c=9===a.nodeType?a:a.ownerDocument,d=9===b.nodeType?b:b.ownerDocument,a===b)return 0;if(a===b.ownerDocument)return 20;if(a.ownerDocument===b)return 10;if(c!==d)return 1;if(2===a.nodeType&&a.childNodes&&-1!==wysihtml5.lang.array(a.childNodes).indexOf(b))return 20;if(2===b.nodeType&&b.childNodes&&-1!==wysihtml5.lang.array(b.childNodes).indexOf(a))return 10;for(e=a,f=[],g=null;e;){if(e==b)return 10;f.push(e),e=e.parentNode}for(e=b,g=null;e;){if(e==a)return 20;if(h=wysihtml5.lang.array(f).indexOf(e),-1!==h)return i=f[h],j=wysihtml5.lang.array(i.childNodes).indexOf(f[h-1]),k=wysihtml5.lang.array(i.childNodes).indexOf(g),j>k?2:4;g=e,e=e.parentNode}return 1}}(),wysihtml5.dom.unwrap=function(a){if(a.parentNode){for(;a.lastChild;)wysihtml5.dom.insert(a.lastChild).after(a);a.parentNode.removeChild(a)}},wysihtml5.dom.getPastedHtml=function(a){var b;return a.clipboardData&&(wysihtml5.lang.array(a.clipboardData.types).contains("text/html")?b=a.clipboardData.getData("text/html"):wysihtml5.lang.array(a.clipboardData.types).contains("text/plain")&&(b=wysihtml5.lang.string(a.clipboardData.getData("text/plain")).escapeHTML(!0,!0))),b},wysihtml5.dom.getPastedHtmlWithDiv=function(a,b){var c=a.selection.getBookmark(),d=a.element.ownerDocument,e=d.createElement("DIV");d.body.appendChild(e),e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",e.setAttribute("contenteditable","true"),e.focus(),setTimeout(function(){a.selection.setBookmark(c),b(e.innerHTML),e.parentNode.removeChild(e)},0)},wysihtml5.quirks.cleanPastedHTML=function(){var a=function(a){var b=wysihtml5.lang.string(a).trim(),c=b.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");return RegExp("^((?!^"+c+"$).)*$","i")},b=function(b,c){var d,e,f=wysihtml5.lang.object(b).clone(!0);for(d in f.tags)if(f.tags.hasOwnProperty(d)&&f.tags[d].keep_styles)for(e in f.tags[d].keep_styles)f.tags[d].keep_styles.hasOwnProperty(e)&&c[e]&&(f.tags[d].keep_styles[e]=a(c[e]));return f},c=function(a,b){var c,d,e;if(!a)return null;for(d=0,e=a.length;e>d;d++)if(a[d].condition||(c=a[d].set),a[d].condition&&a[d].condition.test(b))return a[d].set;return c};return function(a,d){var e,f={color:wysihtml5.dom.getStyle("color").from(d.referenceNode),fontSize:wysihtml5.dom.getStyle("font-size").from(d.referenceNode)},g=b(c(d.rules,a)||{},f);return e=wysihtml5.dom.parse(a,{rules:g,cleanUp:!0,context:d.referenceNode.ownerDocument,uneditableClass:d.uneditableClass,clearInternals:!0,unjoinNbsps:!0}),e}}(),wysihtml5.quirks.ensureProperClearing=function(){var a=function(){var a=this;setTimeout(function(){var b=a.innerHTML.toLowerCase();("<p> </p>"==b||"<p> </p><p> </p>"==b)&&(a.innerHTML="")},0)};return function(b){wysihtml5.dom.observe(b.element,["cut","keydown"],a)}}(),function(a){var b="%7E";a.quirks.getCorrectInnerHTML=function(c){var d,e,f,g,h,i=c.innerHTML;if(-1===i.indexOf(b))return i;for(d=c.querySelectorAll("[href*='~'], [src*='~']"),h=0,g=d.length;g>h;h++)e=d[h].href||d[h].src,f=a.lang.string(e).replace("~").by(b),i=a.lang.string(i).replace(f).by(e);return i}}(wysihtml5),function(a){var b="wysihtml5-quirks-redraw";a.quirks.redraw=function(c){a.dom.addClass(c,b),a.dom.removeClass(c,b);try{var d=c.ownerDocument;d.execCommand("italic",!1,null),d.execCommand("italic",!1,null)}catch(e){}}}(wysihtml5),wysihtml5.quirks.tableCellsSelection=function(a,b){function c(){return k.observe(a,"mousedown",function(a){var b=wysihtml5.dom.getParentElement(a.target,{nodeName:["TD","TH"]});b&&d(b)}),l}function d(c){l.start=c,l.end=c,l.cells=[c],l.table=k.getParentElement(l.start,{nodeName:["TABLE"]}),l.table&&(e(),k.addClass(c,m),n=k.observe(a,"mousemove",g),o=k.observe(a,"mouseup",h),b.fire("tableselectstart").fire("tableselectstart:composer"))}function e(){var b,c;if(a&&(b=a.querySelectorAll("."+m),b.length>0))for(c=0;c<b.length;c++)k.removeClass(b[c],m)}function f(a){for(var b=0;b<a.length;b++)k.addClass(a[b],m)}function g(a){var c,d=null,g=k.getParentElement(a.target,{nodeName:["TD","TH"]});g&&l.table&&l.start&&(d=k.getParentElement(g,{nodeName:["TABLE"]}),d&&d===l.table&&(e(),c=l.end,l.end=g,l.cells=k.table.getCellsBetween(l.start,g),l.cells.length>1&&b.composer.selection.deselect(),f(l.cells),l.end!==c&&b.fire("tableselectchange").fire("tableselectchange:composer")))}function h(){n.stop(),o.stop(),b.fire("tableselect").fire("tableselect:composer"),setTimeout(function(){i()},0)}function i(){var c=k.observe(a.ownerDocument,"click",function(a){c.stop(),k.getParentElement(a.target,{nodeName:["TABLE"]})!=l.table&&(e(),l.table=null,l.start=null,l.end=null,b.fire("tableunselect").fire("tableunselect:composer"))})}function j(a,c){l.start=a,l.end=c,l.table=k.getParentElement(l.start,{nodeName:["TABLE"]}),selectedCells=k.table.getCellsBetween(l.start,l.end),f(selectedCells),i(),b.fire("tableselect").fire("tableselect:composer")}var k=wysihtml5.dom,l={table:null,start:null,end:null,cells:null,select:j},m="wysiwyg-tmp-selected-cell",n=null,o=null;return c()},function(a){var b=/^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*([\d\.]+)\s*\)/i,c=/^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/i,d=/^#([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])([0-9a-f][0-9a-f])/i,e=/^#([0-9a-f])([0-9a-f])([0-9a-f])/i,f=function(a){return RegExp("(^|\\s|;)"+a+"\\s*:\\s*[^;$]+","gi")};a.quirks.styleParser={parseColor:function(g,h){var i,j,k,l=f(h),m=g.match(l),n=10;if(m){for(k=m.length;k--;)m[k]=a.lang.string(m[k].split(":")[1]).trim();if(i=m[m.length-1],b.test(i))j=i.match(b);else if(c.test(i))j=i.match(c);else if(d.test(i))j=i.match(d),n=16;else if(e.test(i))return j=i.match(e),j.shift(),j.push(1),a.lang.array(j).map(function(a,b){return 3>b?16*parseInt(a,16)+parseInt(a,16):parseFloat(a)});if(j)return j.shift(),j[3]||j.push(1),a.lang.array(j).map(function(a,b){return 3>b?parseInt(a,n):parseFloat(a)})}return!1},unparseColor:function(a,b){if(b){if("hex"==b)return a[0].toString(16).toUpperCase()+a[1].toString(16).toUpperCase()+a[2].toString(16).toUpperCase();if("hash"==b)return"#"+a[0].toString(16).toUpperCase()+a[1].toString(16).toUpperCase()+a[2].toString(16).toUpperCase();if("rgb"==b)return"rgb("+a[0]+","+a[1]+","+a[2]+")";if("rgba"==b)return"rgba("+a[0]+","+a[1]+","+a[2]+","+a[3]+")";if("csv"==b)return a[0]+","+a[1]+","+a[2]+","+a[3]}return a[3]&&1!==a[3]?"rgba("+a[0]+","+a[1]+","+a[2]+","+a[3]+")":"rgb("+a[0]+","+a[1]+","+a[2]+")"},parseFontSize:function(b){var c=b.match(f("font-size"));return c?a.lang.string(c[c.length-1].split(":")[1]).trim():!1}}}(wysihtml5),function(a){function b(a){var b=0;if(a.parentNode)do b+=a.offsetTop||0,a=a.offsetParent;while(a);return b}function c(a,b){for(var c=0;b!==a;)if(c++,b=b.parentNode,!b)throw Error("not a descendant of ancestor!");return c}function d(a){if(!a.canSurroundContents())for(var b=a.commonAncestorContainer,d=c(b,a.startContainer),e=c(b,a.endContainer);!a.canSurroundContents();)d>e?(a.setStartBefore(a.startContainer),d=c(b,a.startContainer)):(a.setEndAfter(a.endContainer),e=c(b,a.endContainer))}var e=a.dom;a.Selection=Base.extend({constructor:function(a,b,c){window.rangy.init(),this.editor=a,this.composer=a.composer,this.doc=this.composer.doc,this.contain=b,this.unselectableClass=c||!1},getBookmark:function(){var a=this.getRange();return a&&d(a),a&&a.cloneRange()},setBookmark:function(a){a&&this.setSelection(a)},setBefore:function(a){var b=rangy.createRange(this.doc);return b.setStartBefore(a),b.setEndBefore(a),this.setSelection(b)},setAfter:function(a){var b=rangy.createRange(this.doc);return b.setStartAfter(a),b.setEndAfter(a),this.setSelection(b)},selectNode:function(b,c){var d=rangy.createRange(this.doc),f=b.nodeType===a.ELEMENT_NODE,g="canHaveHTML"in b?b.canHaveHTML:"IMG"!==b.nodeName,h=f?b.innerHTML:b.data,i=""===h||h===a.INVISIBLE_SPACE,j=e.getStyle("display").from(b),k="block"===j||"list-item"===j;if(i&&f&&g&&!c)try{b.innerHTML=a.INVISIBLE_SPACE}catch(l){}g?d.selectNodeContents(b):d.selectNode(b),g&&i&&f?d.collapse(k):g&&i&&(d.setStartAfter(b),d.setEndAfter(b)),this.setSelection(d)},getSelectedNode:function(a){var b,c;return a&&this.doc.selection&&"Control"===this.doc.selection.type&&(c=this.doc.selection.createRange(),c&&c.length)?c.item(0):(b=this.getSelection(this.doc),b.focusNode===b.anchorNode?b.focusNode:(c=this.getRange(this.doc),c?c.commonAncestorContainer:this.doc.body))},fixSelBorders:function(){var a=this.getRange();d(a),this.setSelection(a)},getSelectedOwnNodes:function(){var a,b,c=this.getOwnRanges(),d=[];for(a=0,b=c.length;b>a;a++)d.push(c[a].commonAncestorContainer||this.doc.body);return d},findNodesInSelection:function(b){var c,d,e,f=this.getOwnRanges(),g=[];for(d=0,e=f.length;e>d;d++)c=f[d].getNodes([1],function(c){return a.lang.array(b).contains(c.nodeName)}),g=g.concat(c);return g},containsUneditable:function(){var a,b,c=this.getOwnUneditables(),d=this.getSelection();for(a=0,b=c.length;b>a;a++)if(d.containsNode(c[a]))return!0;return!1},deleteContents:function(){var a,b=this.getOwnRanges();for(a=b.length;a--;)b[a].deleteContents();this.setSelection(b[0])},getPreviousNode:function(b,c){var d,e,f;return b||(d=this.getSelection(),b=d.anchorNode),b===this.contain?!1:(e=b.previousSibling,e===this.contain?!1:(e&&3!==e.nodeType&&1!==e.nodeType?e=this.getPreviousNode(e,c):e&&3===e.nodeType&&/^\s*$/.test(e.textContent)?e=this.getPreviousNode(e,c):c&&e&&1===e.nodeType&&!a.lang.array(["BR","HR","IMG"]).contains(e.nodeName)&&/^[\s]*$/.test(e.innerHTML)?e=this.getPreviousNode(e,c):e||b===this.contain||(f=b.parentNode,f!==this.contain&&(e=this.getPreviousNode(f,c))),e!==this.contain?e:!1))},getSelectionParentsByTag:function(){var b,c,d,e=this.getSelectedOwnNodes(),f=[];for(c=0,d=e.length;d>c;c++)b=e[c].nodeName&&"LI"===e[c].nodeName?e[c]:a.dom.getParentElement(e[c],{nodeName:["LI"]},!1,this.contain),b&&f.push(b);return f.length?f:null},getRangeToNodeEnd:function(){if(this.isCollapsed()){var a=this.getRange(),b=a.startContainer,c=a.startOffset,d=rangy.createRange(this.doc);return d.selectNodeContents(b),d.setStart(b,c),d}},caretIsLastInSelection:function(){var a=(rangy.createRange(this.doc),this.getSelection(),this.getRangeToNodeEnd().cloneContents()),b=a.textContent;return/^\s*$/.test(b)},caretIsFirstInSelection:function(){var b=rangy.createRange(this.doc),c=this.getSelection(),d=this.getRange(),e=d.startContainer;return e.nodeType===a.TEXT_NODE?this.isCollapsed()&&e.nodeType===a.TEXT_NODE&&/^\s*$/.test(e.data.substr(0,d.startOffset)):(b.selectNodeContents(this.getRange().commonAncestorContainer),b.collapse(!0),this.isCollapsed()&&(b.startContainer===c.anchorNode||b.endContainer===c.anchorNode)&&b.startOffset===c.anchorOffset)},caretIsInTheBeginnig:function(b){var c=this.getSelection(),d=c.anchorNode,e=c.anchorOffset;return b?0===e&&(d.nodeName&&d.nodeName===b.toUpperCase()||a.dom.getParentElement(d.parentNode,{nodeName:b},1)):0===e&&!this.getPreviousNode(d,!0)},caretIsBeforeUneditable:function(){var a,b,c,d,e=this.getSelection(),f=e.anchorNode,g=e.anchorOffset;if(0===g&&(a=this.getPreviousNode(f,!0),a))for(b=this.getOwnUneditables(),c=0,d=b.length;d>c;c++)if(a===b[c])return b[c];return!1},executeAndRestoreRangy:function(a){var b=this.doc.defaultView||this.doc.parentWindow,c=rangy.saveSelection(b);if(c)try{a()}catch(d){setTimeout(function(){throw d},0)}else a();rangy.restoreSelection(c)},executeAndRestore:function(b,c){var d,f,g,h,i,j,k,l,m,n=this.doc.body,o=c&&n.scrollTop,p=c&&n.scrollLeft,q="_wysihtml5-temp-placeholder",r='<span class="'+q+'">'+a.INVISIBLE_SPACE+"</span>",s=this.getRange(!0);if(!s)return b(n,n),void 0;s.collapsed||(k=s.cloneRange(),j=k.createContextualFragment(r),k.collapse(!1),k.insertNode(j),k.detach()),i=s.createContextualFragment(r),s.insertNode(i),j&&(d=this.contain.querySelectorAll("."+q),s.setStartBefore(d[0]),s.setEndAfter(d[d.length-1])),this.setSelection(s);try{b(s.startContainer,s.endContainer)}catch(t){setTimeout(function(){throw t},0)}if(d=this.contain.querySelectorAll("."+q),d&&d.length)for(l=rangy.createRange(this.doc),g=d[0].nextSibling,d.length>1&&(h=d[d.length-1].previousSibling),h&&g?(l.setStartBefore(g),l.setEndAfter(h)):(f=this.doc.createTextNode(a.INVISIBLE_SPACE),e.insert(f).after(d[0]),l.setStartBefore(f),l.setEndAfter(f)),this.setSelection(l),m=d.length;m--;)d[m].parentNode.removeChild(d[m]);else this.contain.focus();c&&(n.scrollTop=o,n.scrollLeft=p);try{d.parentNode.removeChild(d)}catch(u){}},set:function(a,b){var c=rangy.createRange(this.doc);c.setStart(a,b||0),this.setSelection(c)},insertHTML:function(a){var b,c=(rangy.createRange(this.doc),this.doc.createElement("DIV")),d=this.doc.createDocumentFragment();for(c.innerHTML=a,b=c.lastChild;c.firstChild;)d.appendChild(c.firstChild);this.insertNode(d),b&&this.setAfter(b)},insertNode:function(a){var b=this.getRange();b&&b.insertNode(a)},surround:function(a){var b,c,d=this.getOwnRanges(),e=[];if(0==d.length)return e;for(c=d.length;c--;){b=this.doc.createElement(a.nodeName),e.push(b),a.className&&(b.className=a.className),a.cssStyle&&b.setAttribute("style",a.cssStyle);try{d[c].surroundContents(b),this.selectNode(b)}catch(f){b.appendChild(d[c].extractContents()),d[c].insertNode(b)}}return e},deblockAndSurround:function(b){var c,d,e,f=this.doc.createElement("div"),g=rangy.createRange(this.doc);if(f.className=b.className,this.composer.commands.exec("formatBlock",b.nodeName,b.className),c=this.contain.querySelectorAll("."+b.className),c[0])for(c[0].parentNode.insertBefore(f,c[0]),g.setStartBefore(c[0]),g.setEndAfter(c[c.length-1]),d=g.extractContents();d.firstChild;)if(e=d.firstChild,1==e.nodeType&&a.dom.hasClass(e,b.className)){for(;e.firstChild;)f.appendChild(e.firstChild);"BR"!==e.nodeName&&f.appendChild(this.doc.createElement("br")),d.removeChild(e)}else f.appendChild(e);else f=null;return f},scrollIntoView:function(){var c,d=this.doc,e=5,f=d.documentElement.scrollHeight>d.documentElement.offsetHeight,g=d._wysihtml5ScrollIntoViewElement=d._wysihtml5ScrollIntoViewElement||function(){var b=d.createElement("span");return b.innerHTML=a.INVISIBLE_SPACE,b}();f&&(this.insertNode(g),c=b(g),g.parentNode.removeChild(g),c>=d.body.scrollTop+d.documentElement.offsetHeight-e&&(d.body.scrollTop=c))},selectLine:function(){a.browser.supportsSelectionModify()?this._selectLine_W3C():this.doc.selection&&this._selectLine_MSIE()},_selectLine_W3C:function(){var a=this.doc.defaultView,b=a.getSelection();b.modify("move","left","lineboundary"),b.modify("extend","right","lineboundary")},_selectLine_MSIE:function(){var a,b,c,d,e,f=this.doc.selection.createRange(),g=f.boundingTop,h=this.doc.body.scrollWidth;if(f.moveToPoint){for(0===g&&(c=this.doc.createElement("span"),this.insertNode(c),g=c.offsetTop,c.parentNode.removeChild(c)),g+=1,d=-10;h>d;d+=2)try{f.moveToPoint(d,g);break}catch(i){}for(a=g,b=this.doc.selection.createRange(),e=h;e>=0;e--)try{b.moveToPoint(e,a);break}catch(j){}f.setEndPoint("EndToEnd",b),f.select()}},getText:function(){var a=this.getSelection();return a?""+a:""},getNodes:function(a,b){var c=this.getRange();return c?c.getNodes([a],b):[]},fixRangeOverflow:function(a){var b,c;this.contain&&this.contain.firstChild&&a&&(b=a.compareNode(this.contain),2!==b?(1===b&&a.setStartBefore(this.contain.firstChild),0===b&&a.setEndAfter(this.contain.lastChild),3===b&&(a.setStartBefore(this.contain.firstChild),a.setEndAfter(this.contain.lastChild))):this._detectInlineRangeProblems(a)&&(c=a.endContainer.previousElementSibling,c&&a.setEnd(c,this._endOffsetForNode(c))))},_endOffsetForNode:function(a){var b=document.createRange();return b.selectNodeContents(a),b.endOffset},_detectInlineRangeProblems:function(a){var b=e.compareDocumentPosition(a.startContainer,a.endContainer);return 0==a.endOffset&&4&b},getRange:function(a){var b=this.getSelection(),c=b&&b.rangeCount&&b.getRangeAt(0);return a!==!0&&this.fixRangeOverflow(c),c},getOwnUneditables:function(){var b=e.query(this.contain,"."+this.unselectableClass),c=e.query(b,"."+this.unselectableClass);return a.lang.array(b).without(c)},getOwnRanges:function(){var a,b,c,d,e,f,g,h=[],i=this.getRange();if(i&&h.push(i),this.unselectableClass&&this.contain&&i&&(b=this.getOwnUneditables(),b.length>0))for(d=0,e=b.length;e>d;d++)for(a=[],f=0,g=h.length;g>f;f++){if(h[f])switch(h[f].compareNode(b[d])){case 2:break;case 3:c=h[f].cloneRange(),c.setEndBefore(b[d]),a.push(c),c=h[f].cloneRange(),c.setStartAfter(b[d]),a.push(c);break;default:a.push(h[f])}h=a}return h},getSelection:function(){return rangy.getSelection(this.doc.defaultView||this.doc.parentWindow)},setSelection:function(a){var b=this.doc.defaultView||this.doc.parentWindow,c=rangy.getSelection(b);return c.setSingleRange(a)},createRange:function(){return rangy.createRange(this.doc)},isCollapsed:function(){return this.getSelection().isCollapsed},getHtml:function(){return this.getSelection().toHtml()},isEndToEndInNode:function(b){var c=this.getRange(),d=c.commonAncestorContainer,e=c.startContainer,f=c.endContainer;if(d.nodeType===a.TEXT_NODE&&(d=d.parentNode),e.nodeType===a.TEXT_NODE&&!/^\s*$/.test(e.data.substr(c.startOffset)))return!1;if(f.nodeType===a.TEXT_NODE&&!/^\s*$/.test(f.data.substr(c.endOffset)))return!1;for(;e&&e!==d;){if(e.nodeType!==a.TEXT_NODE&&!a.dom.contains(d,e))return!1;if(a.dom.domNode(e).prev({ignoreBlankTexts:!0}))return!1;e=e.parentNode}for(;f&&f!==d;){if(f.nodeType!==a.TEXT_NODE&&!a.dom.contains(d,f))return!1;if(a.dom.domNode(f).next({ignoreBlankTexts:!0}))return!1;f=f.parentNode}return a.lang.array(b).contains(d.nodeName)?d:!1},deselect:function(){var a=this.getSelection();a&&a.removeAllRanges()}})}(wysihtml5),function(a,b){function c(a,b,c){if(!a.className)return!1;var d=a.className.match(c)||[];return d[d.length-1]===b}function d(a,b){if(!a.getAttribute||!a.getAttribute("style"))return!1;a.getAttribute("style").match(b);return a.getAttribute("style").match(b)?!0:!1}function e(a,b,c){a.getAttribute("style")?(h(a,c),a.getAttribute("style")&&!/^\s*$/.test(a.getAttribute("style"))?a.setAttribute("style",b+";"+a.getAttribute("style")):a.setAttribute("style",b)):a.setAttribute("style",b)}function f(a,b,c){a.className?(g(a,c),a.className+=" "+b):a.className=b}function g(a,b){a.className&&(a.className=a.className.replace(b,""))}function h(a,b){var c,d,e=[];if(a.getAttribute("style")){for(c=a.getAttribute("style").split(";"),d=c.length;d--;)c[d].match(b)||/^\s*$/.test(c[d])||e.push(c[d]);e.length?a.setAttribute("style",e.join(";")):a.removeAttribute("style")}}function i(a,b){var c,d,e,f=[],g=b.split(";"),h=a.getAttribute("style");if(h){for(h=h.replace(/\s/gi,"").toLowerCase(),f.push(RegExp("(^|\\s|;)"+b.replace(/\s/gi,"").replace(/([\(\)])/gi,"\\$1").toLowerCase().replace(";",";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi,"\\s?rgb\\($1,\\s?$2,\\s?$3\\)"),"gi")),c=g.length;c-->0;)/^\s*$/.test(g[c])||f.push(RegExp("(^|\\s|;)"+g[c].replace(/\s/gi,"").replace(/([\(\)])/gi,"\\$1").toLowerCase().replace(";",";?").replace(/rgb\\\((\d+),(\d+),(\d+)\\\)/gi,"\\s?rgb\\($1,\\s?$2,\\s?$3\\)"),"gi"));for(d=0,e=f.length;e>d;d++)if(h.match(f[d]))return f[d]}return!1}function j(c,d,e,f){return e?i(c,e):f?a.dom.hasClass(c,f):b.dom.arrayContains(d,c.tagName.toLowerCase())}function k(a,b,c,d){for(var e=a.length;e--;)if(!j(a[e],b,c,d))return!1;return a.length?!0:!1}function l(a,b,c){var d=i(a,b);return d?(h(a,d),"remove"):(e(a,b,c),"change")}function m(a,b){return a.className.replace(u," ")==b.className.replace(u," ")}function n(a){for(var b=a.parentNode;a.firstChild;)b.insertBefore(a.firstChild,a);b.removeChild(a)}function o(a,b){if(a.attributes.length!=b.attributes.length)return!1;for(var c,d,e,f=0,g=a.attributes.length;g>f;++f)if(c=a.attributes[f],e=c.name,"class"!=e){if(d=b.attributes.getNamedItem(e),c.specified!=d.specified)return!1;if(c.specified&&c.nodeValue!==d.nodeValue)return!1}return!0}function p(a,c){return b.dom.isCharacterDataNode(a)?0==c?!!a.previousSibling:c==a.length?!!a.nextSibling:!0:c>0&&c<a.childNodes.length}function q(a,c,d,e){var f,g;if(b.dom.isCharacterDataNode(c)&&(0==d?(d=b.dom.getNodeIndex(c),c=c.parentNode):d==c.length?(d=b.dom.getNodeIndex(c)+1,c=c.parentNode):f=b.dom.splitDataNode(c,d)),!(f||e&&c===e)){for(f=c.cloneNode(!1),f.id&&f.removeAttribute("id");g=c.childNodes[d];)f.appendChild(g);b.dom.insertAfter(f,c)}return c==a?f:q(a,f.parentNode,b.dom.getNodeIndex(f),e)}function r(b){this.isElementMerge=b.nodeType==a.ELEMENT_NODE,this.firstTextNode=this.isElementMerge?b.lastChild:b,this.textNodes=[this.firstTextNode]}function s(a,b,c,d,e,f,g){this.tagNames=a||[t],this.cssClass=b||(b===!1?!1:""),this.similarClassRegExp=c,this.cssStyle=e||"",this.similarStyleRegExp=f,this.normalize=d,this.applyToAnyTagName=!1,this.container=g}var t="span",u=/\s+/g;r.prototype={doMerge:function(){var a,b,c,d,e,f=[];for(d=0,e=this.textNodes.length;e>d;++d)a=this.textNodes[d],b=a.parentNode,f[d]=a.data,d&&(b.removeChild(a),b.hasChildNodes()||b.parentNode.removeChild(b));return this.firstTextNode.data=c=f.join(""),c},getLength:function(){for(var a=this.textNodes.length,b=0;a--;)b+=this.textNodes[a].length;return b},toString:function(){var a,b,c=[];for(a=0,b=this.textNodes.length;b>a;++a)c[a]="'"+this.textNodes[a].data+"'";return"[Merge("+c.join(",")+")]"}},s.prototype={getAncestorWithClass:function(d){for(var e;d;){if(e=this.cssClass?c(d,this.cssClass,this.similarClassRegExp):""!==this.cssStyle?!1:!0,d.nodeType==a.ELEMENT_NODE&&"false"!=d.getAttribute("contenteditable")&&b.dom.arrayContains(this.tagNames,d.tagName.toLowerCase())&&e)return d;d=d.parentNode}return!1},getAncestorWithStyle:function(c){for(var e;c;){if(e=this.cssStyle?d(c,this.similarStyleRegExp):!1,c.nodeType==a.ELEMENT_NODE&&"false"!=c.getAttribute("contenteditable")&&b.dom.arrayContains(this.tagNames,c.tagName.toLowerCase())&&e)return c;c=c.parentNode}return!1},getMatchingAncestor:function(a){var b=this.getAncestorWithClass(a),c=!1;return b?this.cssStyle&&(c="class"):(b=this.getAncestorWithStyle(a),b&&(c="style")),{element:b,type:c}},postApply:function(a,b){var c,d,e,f,g,h,i=a[0],j=a[a.length-1],k=[],l=i,m=j,n=0,o=j.length;for(f=0,g=a.length;g>f;++f)d=a[f],e=null,d&&d.parentNode&&(e=this.getAdjacentMergeableTextNode(d.parentNode,!1)),e?(c||(c=new r(e),k.push(c)),c.textNodes.push(d),d===i&&(l=c.firstTextNode,n=l.length),d===j&&(m=c.firstTextNode,o=c.getLength())):c=null;if(j&&j.parentNode&&(h=this.getAdjacentMergeableTextNode(j.parentNode,!0),h&&(c||(c=new r(j),k.push(c)),c.textNodes.push(h))),k.length){for(f=0,g=k.length;g>f;++f)k[f].doMerge();b.setStart(l,n),b.setEnd(m,o)}},getAdjacentMergeableTextNode:function(b,c){var d,e=b.nodeType==a.TEXT_NODE,f=e?b.parentNode:b,g=c?"nextSibling":"previousSibling";if(e){if(d=b[g],d&&d.nodeType==a.TEXT_NODE)return d}else if(d=f[g],d&&this.areElementsMergeable(b,d))return d[c?"firstChild":"lastChild"];return null},areElementsMergeable:function(a,c){return b.dom.arrayContains(this.tagNames,(a.tagName||"").toLowerCase())&&b.dom.arrayContains(this.tagNames,(c.tagName||"").toLowerCase())&&m(a,c)&&o(a,c)},createContainer:function(a){var b=a.createElement(this.tagNames[0]);return this.cssClass&&(b.className=this.cssClass),this.cssStyle&&b.setAttribute("style",this.cssStyle),b},applyToTextNode:function(a){var c,d=a.parentNode;1==d.childNodes.length&&b.dom.arrayContains(this.tagNames,d.tagName.toLowerCase())?(this.cssClass&&f(d,this.cssClass,this.similarClassRegExp),this.cssStyle&&e(d,this.cssStyle,this.similarStyleRegExp)):(c=this.createContainer(b.dom.getDocument(a)),a.parentNode.insertBefore(c,a),c.appendChild(a))},isRemovable:function(c){return b.dom.arrayContains(this.tagNames,c.tagName.toLowerCase())&&""===a.lang.string(c.className).trim()&&(!c.getAttribute("style")||""===a.lang.string(c.getAttribute("style")).trim())},undoToTextNode:function(a,b,c,d){var e,f=c?!1:!0,h=c||d,i=!1;b.containsNode(h)||(e=b.cloneRange(),e.selectNode(h),e.isPointInRange(b.endContainer,b.endOffset)&&p(b.endContainer,b.endOffset)&&(q(h,b.endContainer,b.endOffset,this.container),b.setEndAfter(h)),e.isPointInRange(b.startContainer,b.startOffset)&&p(b.startContainer,b.startOffset)&&(h=q(h,b.startContainer,b.startOffset,this.container))),!f&&this.similarClassRegExp&&g(h,this.similarClassRegExp),f&&this.similarStyleRegExp&&(i="change"===l(h,this.cssStyle,this.similarStyleRegExp)),this.isRemovable(h)&&!i&&n(h)},applyToRange:function(b){var c,d,e,f,g,h;for(d=b.length;d--;){if(c=b[d].getNodes([a.TEXT_NODE]),!c.length)try{return e=this.createContainer(b[d].endContainer.ownerDocument),b[d].surroundContents(e),this.selectNode(b[d],e),void 0}catch(i){}if(b[d].splitBoundaries(),c=b[d].getNodes([a.TEXT_NODE]),c.length){for(g=0,h=c.length;h>g;++g)f=c[g],this.getMatchingAncestor(f).element||this.applyToTextNode(f);b[d].setStart(c[0],0),f=c[c.length-1],b[d].setEnd(f,f.length),this.normalize&&this.postApply(c,b[d])}}},undoToRange:function(b){var c,d,e,f,g,h,i,j;for(f=b.length;f--;){for(c=b[f].getNodes([a.TEXT_NODE]),c.length?(b[f].splitBoundaries(),c=b[f].getNodes([a.TEXT_NODE])):(g=b[f].endContainer.ownerDocument,h=g.createTextNode(a.INVISIBLE_SPACE),b[f].insertNode(h),b[f].selectNode(h),c=[h]),i=0,j=c.length;j>i;++i)b[f].isValid()&&(d=c[i],e=this.getMatchingAncestor(d),"style"===e.type?this.undoToTextNode(d,b[f],!1,e.element):e.element&&this.undoToTextNode(d,b[f],e.element));1==j?this.selectNode(b[f],c[0]):(b[f].setStart(c[0],0),d=c[c.length-1],b[f].setEnd(d,d.length),this.normalize&&this.postApply(c,b[f]))}},selectNode:function(b,c){var d=c.nodeType===a.ELEMENT_NODE,e="canHaveHTML"in c?c.canHaveHTML:!0,f=d?c.innerHTML:c.data,g=""===f||f===a.INVISIBLE_SPACE;if(g&&d&&e)try{c.innerHTML=a.INVISIBLE_SPACE}catch(h){}b.selectNodeContents(c),g&&d?b.collapse(!1):g&&(b.setStartAfter(c),b.setEndAfter(c))},getTextSelectedByRange:function(a,b){var c,d,e=b.cloneRange();return e.selectNodeContents(a),c=e.intersection(b),d=c?""+c:"",e.detach(),d},isAppliedToRange:function(b){var c,d,e,f,g,h,i=[],j="full";for(e=b.length;e--;){if(d=b[e].getNodes([a.TEXT_NODE]),!d.length)return c=this.getMatchingAncestor(b[e].startContainer).element,c?{elements:[c],coverage:j}:!1;for(f=0,g=d.length;g>f;++f)h=this.getTextSelectedByRange(d[f],b[e]),c=this.getMatchingAncestor(d[f]).element,c&&""!=h?(i.push(c),1===a.dom.getTextNodes(c,!0).length?j="full":"full"===j&&(j="inline")):c||(j="partial")}return i.length?{elements:i,coverage:j}:!1},toggleRange:function(a){var b,c=this.isAppliedToRange(a);c?"full"===c.coverage?this.undoToRange(a):"inline"===c.coverage?(b=k(c.elements,this.tagNames,this.cssStyle,this.cssClass),this.undoToRange(a),b||this.applyToRange(a)):(k(c.elements,this.tagNames,this.cssStyle,this.cssClass)||this.undoToRange(a),this.applyToRange(a)):this.applyToRange(a)}},a.selection.HTMLApplier=s}(wysihtml5,rangy),wysihtml5.Commands=Base.extend({constructor:function(a){this.editor=a,this.composer=a.composer,this.doc=this.composer.doc},support:function(a){return wysihtml5.browser.supportsCommand(this.doc,a)},exec:function(a,b){var c=wysihtml5.commands[a],d=wysihtml5.lang.array(arguments).get(),e=c&&c.exec,f=null;if(this.editor.fire("beforecommand:composer"),e)d.unshift(this.composer),f=e.apply(c,d);else try{f=this.doc.execCommand(a,!1,b)}catch(g){}return this.editor.fire("aftercommand:composer"),f},state:function(a){var b=wysihtml5.commands[a],c=wysihtml5.lang.array(arguments).get(),d=b&&b.state;if(d)return c.unshift(this.composer),d.apply(b,c);try{return this.doc.queryCommandState(a)}catch(e){return!1}},stateValue:function(a){var b=wysihtml5.commands[a],c=wysihtml5.lang.array(arguments).get(),d=b&&b.stateValue;return d?(c.unshift(this.composer),d.apply(b,c)):!1}}),wysihtml5.commands.bold={exec:function(a,b){wysihtml5.commands.formatInline.execWithToggle(a,b,"b")},state:function(a,b){return wysihtml5.commands.formatInline.state(a,b,"b")}},function(a){function b(b,c){var g,h,i,j,k,l,m,n,o,p=b.doc,q="_wysihtml5-temp-"+ +new Date,r=/non-matching-class/g,s=0;for(a.commands.formatInline.exec(b,d,e,q,r,d,d,!0,!0),h=p.querySelectorAll(e+"."+q),g=h.length;g>s;s++){i=h[s],i.removeAttribute("class");for(o in c)"text"!==o&&i.setAttribute(o,c[o])}l=i,1===g&&(m=f.getTextContent(i),j=!!i.querySelector("*"),k=""===m||m===a.INVISIBLE_SPACE,!j&&k&&(f.setTextContent(i,c.text||i.href),n=p.createTextNode(" "),b.selection.setAfter(i),f.insert(n).after(i),l=n)),b.selection.setAfter(l)}function c(a,b,c){var d,e,f,g;for(e=b.length;e--;){for(d=b[e].attributes,f=d.length;f--;)b[e].removeAttribute(d.item(f).name);for(g in c)c.hasOwnProperty(g)&&b[e].setAttribute(g,c[g])}}var d,e="A",f=a.dom;a.commands.createLink={exec:function(a,d,e){var f=this.state(a,d);f?a.selection.executeAndRestore(function(){c(a,f,e)}):(e="object"==typeof e?e:{href:e},b(a,e))},state:function(b,c){return a.commands.formatInline.state(b,c,"A")}}}(wysihtml5),function(a){function b(a,b){for(var d,e,f,g=b.length,h=0;g>h;h++)d=b[h],e=c.getParentElement(d,{nodeName:"code"}),f=c.getTextContent(d),f.match(c.autoLink.URL_REG_EXP)&&!e?e=c.renameElement(d,"code"):c.replaceWithChildNodes(d)}var c=a.dom;a.commands.removeLink={exec:function(a,c){var d=this.state(a,c);d&&a.selection.executeAndRestore(function(){b(a,d)})},state:function(b,c){return a.commands.formatInline.state(b,c,"A")}}}(wysihtml5),function(a){var b=/wysiwyg-font-size-[0-9a-z\-]+/g;a.commands.fontSize={exec:function(c,d,e){a.commands.formatInline.execWithToggle(c,d,"span","wysiwyg-font-size-"+e,b)},state:function(c,d,e){return a.commands.formatInline.state(c,d,"span","wysiwyg-font-size-"+e,b)}}}(wysihtml5),function(a){var b=/(\s|^)font-size\s*:\s*[^;\s]+;?/gi;a.commands.fontSizeStyle={exec:function(c,d,e){e="object"==typeof e?e.size:e,/^\s*$/.test(e)||a.commands.formatInline.execWithToggle(c,d,"span",!1,!1,"font-size:"+e,b)},state:function(c,d){return a.commands.formatInline.state(c,d,"span",!1,!1,"font-size",b)},stateValue:function(b,c){var d,e=this.state(b,c);return e&&a.lang.object(e).isArray()&&(e=e[0]),e&&(d=e.getAttribute("style"),d)?a.quirks.styleParser.parseFontSize(d):!1}}}(wysihtml5),function(a){var b=/wysiwyg-color-[0-9a-z]+/g;a.commands.foreColor={exec:function(c,d,e){a.commands.formatInline.execWithToggle(c,d,"span","wysiwyg-color-"+e,b)},state:function(c,d,e){return a.commands.formatInline.state(c,d,"span","wysiwyg-color-"+e,b)}}}(wysihtml5),function(a){var b=/(\s|^)color\s*:\s*[^;\s]+;?/gi;a.commands.foreColorStyle={exec:function(c,d,e){var f,g=a.quirks.styleParser.parseColor("object"==typeof e?"color:"+e.color:"color:"+e,"color");g&&(f="color: rgb("+g[0]+","+g[1]+","+g[2]+");",1!==g[3]&&(f+="color: rgba("+g[0]+","+g[1]+","+g[2]+","+g[3]+");"),a.commands.formatInline.execWithToggle(c,d,"span",!1,!1,f,b))},state:function(c,d){return a.commands.formatInline.state(c,d,"span",!1,!1,"color",b)},stateValue:function(b,c,d){var e,f=this.state(b,c);return f&&a.lang.object(f).isArray()&&(f=f[0]),f&&(e=f.getAttribute("style"),e&&e)?(val=a.quirks.styleParser.parseColor(e,"color"),a.quirks.styleParser.unparseColor(val,d)):!1
}}}(wysihtml5),function(a){var b=/(\s|^)background-color\s*:\s*[^;\s]+;?/gi;a.commands.bgColorStyle={exec:function(c,d,e){var f,g=a.quirks.styleParser.parseColor("object"==typeof e?"background-color:"+e.color:"background-color:"+e,"background-color");g&&(f="background-color: rgb("+g[0]+","+g[1]+","+g[2]+");",1!==g[3]&&(f+="background-color: rgba("+g[0]+","+g[1]+","+g[2]+","+g[3]+");"),a.commands.formatInline.execWithToggle(c,d,"span",!1,!1,f,b))},state:function(c,d){return a.commands.formatInline.state(c,d,"span",!1,!1,"background-color",b)},stateValue:function(b,c,d){var e,f=this.state(b,c),g=!1;return f&&a.lang.object(f).isArray()&&(f=f[0]),f&&(e=f.getAttribute("style"),e)?(g=a.quirks.styleParser.parseColor(e,"background-color"),a.quirks.styleParser.unparseColor(g,d)):!1}}}(wysihtml5),function(a){function b(b,c,e){b.className?(d(b,e),b.className=a.lang.string(b.className+" "+c).trim()):b.className=c}function c(b,c,d){e(b,d),b.getAttribute("style")?b.setAttribute("style",a.lang.string(b.getAttribute("style")+" "+c).trim()):b.setAttribute("style",c)}function d(b,c){var d=c.test(b.className);return b.className=b.className.replace(c,""),""==a.lang.string(b.className).trim()&&b.removeAttribute("class"),d}function e(b,c){var d=c.test(b.getAttribute("style"));return b.setAttribute("style",(b.getAttribute("style")||"").replace(c,"")),""==a.lang.string(b.getAttribute("style")||"").trim()&&b.removeAttribute("style"),d}function f(a){var b=a.lastChild;b&&g(b)&&b.parentNode.removeChild(b)}function g(a){return"BR"===a.nodeName}function h(b,c){var d,e,g;for(b.selection.isCollapsed()&&b.selection.selectLine(),d=b.selection.surround(c),e=0,g=d.length;g>e;e++)a.dom.lineBreaks(d[e]).remove(),f(d[e])}function i(b){return!!a.lang.string(b.className).trim()}function j(b){return!!a.lang.string(b.getAttribute("style")||"").trim()}var k=a.dom,l=["H1","H2","H3","H4","H5","H6","P","PRE","DIV"];a.commands.formatBlock={exec:function(f,g,m,n,o,p,q){var r,s,t,u,v,w=(f.doc,this.state(f,g,m,n,o,p,q)),x=f.config.useLineBreaks,y=x?"DIV":"P";return m="string"==typeof m?m.toUpperCase():m,w.length?(f.selection.executeAndRestoreRangy(function(){var b,c,f;for(b=w.length;b--;){if(o&&(s=d(w[b],o)),q&&(u=e(w[b],q)),(u||s)&&null===m&&w[b].nodeName!=y)return;c=i(w[b]),f=j(w[b]),c||f||!x&&"P"!==m?k.renameElement(w[b],"P"===m?"DIV":y):(a.dom.lineBreaks(w[b]).add(),k.replaceWithChildNodes(w[b]))}}),void 0):((null!==m&&!a.lang.array(l).contains(m)||(r=f.selection.findNodesInSelection(l).concat(f.selection.getSelectedOwnNodes()),f.selection.executeAndRestoreRangy(function(){for(var a=r.length;a--;)v=k.getParentElement(r[a],{nodeName:l}),v==f.element&&(v=null),v&&(m&&(v=k.renameElement(v,m)),n&&b(v,n,o),p&&c(v,p,q),t=!0)}),!t))&&h(f,{nodeName:m||y,className:n||null,cssStyle:p||null}),void 0)},state:function(b,c,d,e,f,g,h){var i,j,l,m=b.selection.getSelectedOwnNodes(),n=[];for(d="string"==typeof d?d.toUpperCase():d,j=0,l=m.length;l>j;j++)i=k.getParentElement(m[j],{nodeName:d,className:e,classRegExp:f,cssStyle:g,styleRegExp:h}),i&&-1==a.lang.array(n).indexOf(i)&&n.push(i);return 0==n.length?!1:n}}}(wysihtml5),wysihtml5.commands.formatCode={exec:function(a,b,c){var d,e,f,g=this.state(a);g?a.selection.executeAndRestore(function(){d=g.querySelector("code"),wysihtml5.dom.replaceWithChildNodes(g),d&&wysihtml5.dom.replaceWithChildNodes(d)}):(e=a.selection.getRange(),f=e.extractContents(),g=a.doc.createElement("pre"),d=a.doc.createElement("code"),c&&(d.className=c),g.appendChild(d),d.appendChild(f),e.insertNode(g),a.selection.selectNode(g))},state:function(a){var b=a.selection.getSelectedNode();return b&&b.nodeName&&"PRE"==b.nodeName&&b.firstChild&&b.firstChild.nodeName&&"CODE"==b.firstChild.nodeName?b:wysihtml5.dom.getParentElement(b,{nodeName:"CODE"})&&wysihtml5.dom.getParentElement(b,{nodeName:"PRE"})}},function(a){function b(a){var b=d[a];return b?[a.toLowerCase(),b.toLowerCase()]:[a.toLowerCase()]}function c(c,d,f,g,h,i){var j=c;return d&&(j+=":"+d),g&&(j+=":"+g),e[j]||(e[j]=new a.selection.HTMLApplier(b(c),d,f,!0,g,h,i)),e[j]}var d={strong:"b",em:"i",b:"strong",i:"em"},e={};a.commands.formatInline={exec:function(a,b,d,e,f,g,h,i,j){var k=a.selection.createRange(),l=a.selection.getOwnRanges();return l&&0!=l.length?(a.selection.getSelection().removeAllRanges(),c(d,e,f,g,h,a.element).toggleRange(l),i?j||a.cleanUp():(k.setStart(l[0].startContainer,l[0].startOffset),k.setEnd(l[l.length-1].endContainer,l[l.length-1].endOffset),a.selection.setSelection(k),a.selection.executeAndRestore(function(){j||a.cleanUp()},!0,!0)),void 0):!1},execWithToggle:function(b,c,d,e,f,g,h){var i,j=this;this.state(b,c,d,e,f,g,h)&&b.selection.isCollapsed()&&!b.selection.caretIsLastInSelection()&&!b.selection.caretIsFirstInSelection()?(i=j.state(b,c,d,e,f)[0],b.selection.executeAndRestoreRangy(function(){i.parentNode;b.selection.selectNode(i,!0),a.commands.formatInline.exec(b,c,d,e,f,g,h,!0,!0)})):this.state(b,c,d,e,f,g,h)&&!b.selection.isCollapsed()?b.selection.executeAndRestoreRangy(function(){a.commands.formatInline.exec(b,c,d,e,f,g,h,!0,!0)}):a.commands.formatInline.exec(b,c,d,e,f,g,h)},state:function(b,e,f,g,h,i,j){var k,l,m=b.doc,n=d[f]||f;return a.dom.hasElementWithTagName(m,f)||a.dom.hasElementWithTagName(m,n)?g&&!a.dom.hasElementWithClassName(m,g)?!1:(k=b.selection.getOwnRanges(),k&&0!==k.length?(l=c(f,g,h,i,j,b.element).isAppliedToRange(k),l&&l.elements?l.elements:!1):!1):!1}}}(wysihtml5),function(a){a.commands.insertBlockQuote={exec:function(b,c){var d=this.state(b,c),e=b.selection.isEndToEndInNode(["H1","H2","H3","H4","H5","H6","P"]);b.selection.executeAndRestore(function(){if(d)b.config.useLineBreaks&&a.dom.lineBreaks(d).add(),a.dom.unwrap(d);else if(b.selection.isCollapsed()&&b.selection.selectLine(),e){var c=e.ownerDocument.createElement("blockquote");a.dom.insert(c).after(e),c.appendChild(e)}else b.selection.surround({nodeName:"blockquote"})})},state:function(b){var c=b.selection.getSelectedNode(),d=a.dom.getParentElement(c,{nodeName:"BLOCKQUOTE"},!1,b.element);return d?d:!1}}}(wysihtml5),wysihtml5.commands.insertHTML={exec:function(a,b,c){a.commands.support(b)?a.doc.execCommand(b,!1,c):a.selection.insertHTML(c)},state:function(){return!1}},function(a){var b="IMG";a.commands.insertImage={exec:function(c,d,e){var f,g,h,i,j;if(e="object"==typeof e?e:{src:e},f=c.doc,g=this.state(c),g)return c.selection.setBefore(g),i=g.parentNode,i.removeChild(g),a.dom.removeEmptyTextNodes(i),"A"!==i.nodeName||i.firstChild||(c.selection.setAfter(i),i.parentNode.removeChild(i)),a.quirks.redraw(c.element),void 0;g=f.createElement(b);for(j in e)g.setAttribute("className"===j?"class":j,e[j]);c.selection.insertNode(g),a.browser.hasProblemsSettingCaretAfterImg()?(h=f.createTextNode(a.INVISIBLE_SPACE),c.selection.insertNode(h),c.selection.setAfter(h)):c.selection.setAfter(g)},state:function(c){var d,e,f,g=c.doc;return a.dom.hasElementWithTagName(g,b)?(d=c.selection.getSelectedNode(),d?d.nodeName===b?d:d.nodeType!==a.ELEMENT_NODE?!1:(e=c.selection.getText(),e=a.lang.string(e).trim(),e?!1:(f=c.selection.getNodes(a.ELEMENT_NODE,function(a){return"IMG"===a.nodeName}),1!==f.length?!1:f[0])):!1):!1}}}(wysihtml5),function(a){var b="<br>"+(a.browser.needsSpaceAfterLineBreak()?" ":"");a.commands.insertLineBreak={exec:function(c,d){c.commands.support(d)?(c.doc.execCommand(d,!1,null),a.browser.autoScrollsToCaret()||c.selection.scrollIntoView()):c.commands.exec("insertHTML",b)},state:function(){return!1}}}(wysihtml5),wysihtml5.commands.insertOrderedList={exec:function(a,b){wysihtml5.commands.insertList.exec(a,b,"OL")},state:function(a,b){return wysihtml5.commands.insertList.state(a,b,"OL")}},wysihtml5.commands.insertUnorderedList={exec:function(a,b){wysihtml5.commands.insertList.exec(a,b,"UL")},state:function(a,b){return wysihtml5.commands.insertList.state(a,b,"UL")}},wysihtml5.commands.insertList=function(a){var b=function(a,b){if(a&&a.nodeName){"string"==typeof b&&(b=[b]);for(var c=b.length;c--;)if(a.nodeName===b[c])return!0}return!1},c=function(c,d,e){var f,g,h={el:null,other:!1};return c&&(f=a.dom.getParentElement(c,{nodeName:"LI"}),g="UL"===d?"OL":"UL",b(c,d)?h.el=c:b(c,g)?h={el:c,other:!0}:f&&(b(f.parentNode,d)?h.el=f.parentNode:b(f.parentNode,g)&&(h={el:f.parentNode,other:!0}))),h.el&&!e.element.contains(h.el)&&(h.el=null),h},d=function(b,c,d){var e,g="UL"===c?"OL":"UL";d.selection.executeAndRestore(function(){var h,i,j=f(g,d);if(j.length)for(h=j.length;h--;)a.dom.renameElement(j[h],c.toLowerCase());else{for(e=f(["OL","UL"],d),i=e.length;i--;)a.dom.resolveList(e[i],d.config.useLineBreaks);a.dom.resolveList(b,d.config.useLineBreaks)}})},e=function(b,c,d){var e="UL"===c?"OL":"UL";d.selection.executeAndRestore(function(){var g,h=[b].concat(f(e,d));for(g=h.length;g--;)a.dom.renameElement(h[g],c.toLowerCase())})},f=function(a,c){var d,e=c.selection.getOwnRanges(),f=[];for(d=e.length;d--;)f=f.concat(e[d].getNodes([1],function(c){return b(c,a)}));return f},g=function(b,c){c.selection.executeAndRestoreRangy(function(){var d,e,f="_wysihtml5-temp-"+(new Date).getTime(),g=c.selection.deblockAndSurround({nodeName:"div",className:f}),h=/\uFEFF/g;g.innerHTML=g.innerHTML.replace(h,""),g&&(d=a.lang.array(["","<br>",a.INVISIBLE_SPACE]).contains(g.innerHTML),e=a.dom.convertToList(g,b.toLowerCase(),c.parent.config.uneditableContainerClassname),d&&c.selection.selectNode(e.querySelector("li"),!0))})};return{exec:function(a,b,f){var h=a.doc,i="OL"===f?"insertOrderedList":"insertUnorderedList",j=a.selection.getSelectedNode(),k=c(j,f,a);k.el?k.other?e(k.el,f,a):d(k.el,f,a):a.commands.support(i)?h.execCommand(i,!1,null):g(f,a)},state:function(a,b,d){var e=a.selection.getSelectedNode(),f=c(e,d,a);return f.el&&!f.other?f.el:!1}}}(wysihtml5),wysihtml5.commands.italic={exec:function(a,b){wysihtml5.commands.formatInline.execWithToggle(a,b,"i")},state:function(a,b){return wysihtml5.commands.formatInline.state(a,b,"i")}},function(a){var b="wysiwyg-text-align-center",c=/wysiwyg-text-align-[0-9a-z]+/g;a.commands.justifyCenter={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,b,c)}}}(wysihtml5),function(a){var b="wysiwyg-text-align-left",c=/wysiwyg-text-align-[0-9a-z]+/g;a.commands.justifyLeft={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,b,c)}}}(wysihtml5),function(a){var b="wysiwyg-text-align-right",c=/wysiwyg-text-align-[0-9a-z]+/g;a.commands.justifyRight={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,b,c)}}}(wysihtml5),function(a){var b="wysiwyg-text-align-justify",c=/wysiwyg-text-align-[0-9a-z]+/g;a.commands.justifyFull={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,b,c)}}}(wysihtml5),function(a){var b="text-align: right;",c=/(\s|^)text-align\s*:\s*[^;\s]+;?/gi;a.commands.alignRightStyle={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,null,null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,null,null,b,c)}}}(wysihtml5),function(a){var b="text-align: left;",c=/(\s|^)text-align\s*:\s*[^;\s]+;?/gi;a.commands.alignLeftStyle={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,null,null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,null,null,b,c)}}}(wysihtml5),function(a){var b="text-align: center;",c=/(\s|^)text-align\s*:\s*[^;\s]+;?/gi;a.commands.alignCenterStyle={exec:function(d){return a.commands.formatBlock.exec(d,"formatBlock",null,null,null,b,c)},state:function(d){return a.commands.formatBlock.state(d,"formatBlock",null,null,null,b,c)}}}(wysihtml5),wysihtml5.commands.redo={exec:function(a){return a.undoManager.redo()},state:function(){return!1}},wysihtml5.commands.underline={exec:function(a,b){wysihtml5.commands.formatInline.execWithToggle(a,b,"u")},state:function(a,b){return wysihtml5.commands.formatInline.state(a,b,"u")}},wysihtml5.commands.undo={exec:function(a){return a.undoManager.undo()},state:function(){return!1}},wysihtml5.commands.createTable={exec:function(a,b,c){var d,e,f;if(c&&c.cols&&c.rows&&parseInt(c.cols,10)>0&&parseInt(c.rows,10)>0){for(f=c.tableStyle?'<table style="'+c.tableStyle+'">':"<table>",f+="<tbody>",e=0;e<c.rows;e++){for(f+="<tr>",d=0;d<c.cols;d++)f+="<td> </td>";f+="</tr>"}f+="</tbody></table>",a.commands.exec("insertHTML",f)}},state:function(){return!1}},wysihtml5.commands.mergeTableCells={exec:function(a,b){a.tableSelection&&a.tableSelection.start&&a.tableSelection.end&&(this.state(a,b)?wysihtml5.dom.table.unmergeCell(a.tableSelection.start):wysihtml5.dom.table.mergeCellsBetween(a.tableSelection.start,a.tableSelection.end))},state:function(a){if(a.tableSelection){var b=a.tableSelection.start,c=a.tableSelection.end;if(b&&c&&b==c&&(wysihtml5.dom.getAttribute(b,"colspan")&&parseInt(wysihtml5.dom.getAttribute(b,"colspan"),10)>1||wysihtml5.dom.getAttribute(b,"rowspan")&&parseInt(wysihtml5.dom.getAttribute(b,"rowspan"),10)>1))return[b]}return!1}},wysihtml5.commands.addTableCells={exec:function(a,b,c){if(a.tableSelection&&a.tableSelection.start&&a.tableSelection.end){var d=wysihtml5.dom.table.orderSelectionEnds(a.tableSelection.start,a.tableSelection.end);"before"==c||"above"==c?wysihtml5.dom.table.addCells(d.start,c):("after"==c||"below"==c)&&wysihtml5.dom.table.addCells(d.end,c),setTimeout(function(){a.tableSelection.select(d.start,d.end)},0)}},state:function(){return!1}},wysihtml5.commands.deleteTableCells={exec:function(a,b,c){if(a.tableSelection&&a.tableSelection.start&&a.tableSelection.end){var d,e=wysihtml5.dom.table.orderSelectionEnds(a.tableSelection.start,a.tableSelection.end),f=wysihtml5.dom.table.indexOf(e.start),g=a.tableSelection.table;wysihtml5.dom.table.removeCells(e.start,c),setTimeout(function(){d=wysihtml5.dom.table.findCell(g,f),d||("row"==c&&(d=wysihtml5.dom.table.findCell(g,{row:f.row-1,col:f.col})),"column"==c&&(d=wysihtml5.dom.table.findCell(g,{row:f.row,col:f.col-1}))),d&&a.tableSelection.select(d,d)},0)}},state:function(){return!1}},wysihtml5.commands.indentList={exec:function(a){var b=a.selection.getSelectionParentsByTag("LI");return b?this.tryToPushLiLevel(b,a.selection):!1},state:function(){return!1},tryToPushLiLevel:function(a,b){var c,d,e,f,g,h=!1;return b.executeAndRestoreRangy(function(){for(var b=a.length;b--;)f=a[b],c="OL"===f.parentNode.nodeName?"OL":"UL",d=f.ownerDocument.createElement(c),e=wysihtml5.dom.domNode(f).prev({nodeTypes:[wysihtml5.ELEMENT_NODE]}),g=e?e.querySelector("ul, ol"):null,e&&(g?g.appendChild(f):(d.appendChild(f),e.appendChild(d)),h=!0)}),h}},wysihtml5.commands.outdentList={exec:function(a){var b=a.selection.getSelectionParentsByTag("LI");return b?this.tryToPullLiLevel(b,a):!1},state:function(){return!1},tryToPullLiLevel:function(a,b){var c,d,e,f,g,h=!1,i=this;return b.selection.executeAndRestoreRangy(function(){var j,k;for(j=a.length;j--;)if(f=a[j],f.parentNode&&(c=f.parentNode,"OL"===c.tagName||"UL"===c.tagName)){if(h=!0,d=wysihtml5.dom.getParentElement(c.parentNode,{nodeName:["OL","UL"]},!1,b.element),e=wysihtml5.dom.getParentElement(c.parentNode,{nodeName:["LI"]},!1,b.element),d&&e)f.nextSibling&&(g=i.getAfterList(c,f),f.appendChild(g)),d.insertBefore(f,e.nextSibling);else{for(f.nextSibling&&(g=i.getAfterList(c,f),f.appendChild(g)),k=f.childNodes.length;k--;)c.parentNode.insertBefore(f.childNodes[k],c.nextSibling);c.parentNode.insertBefore(document.createElement("br"),c.nextSibling),f.parentNode.removeChild(f)}0===c.childNodes.length&&c.parentNode.removeChild(c)}}),h},getAfterList:function(a,b){for(var c=a.nodeName,d=document.createElement(c);b.nextSibling;)d.appendChild(b.nextSibling);return d}},function(a){var b=90,c=89,d=8,e=46,f=25,g="data-wysihtml5-selection-node",h="data-wysihtml5-selection-offset",i=('<span id="_wysihtml5-undo" class="_wysihtml5-temp">'+a.INVISIBLE_SPACE+"</span>",'<span id="_wysihtml5-redo" class="_wysihtml5-temp">'+a.INVISIBLE_SPACE+"</span>",a.dom);a.UndoManager=a.lang.Dispatcher.extend({constructor:function(a){this.editor=a,this.composer=a.composer,this.element=this.composer.element,this.position=0,this.historyStr=[],this.historyDom=[],this.transact(),this._observe()},_observe:function(){{var a,f=this;this.composer.sandbox.getDocument()}i.observe(this.element,"keydown",function(a){if(!a.altKey&&(a.ctrlKey||a.metaKey)){var d=a.keyCode,e=d===b&&!a.shiftKey,g=d===b&&a.shiftKey||d===c;e?(f.undo(),a.preventDefault()):g&&(f.redo(),a.preventDefault())}}),i.observe(this.element,"keydown",function(b){var c=b.keyCode;c!==a&&(a=c,(c===d||c===e)&&f.transact())}),this.editor.on("newword:composer",function(){f.transact()}).on("beforecommand:composer",function(){f.transact()})},transact:function(){var b,c,d,e,i,j,k,l=this.historyStr[this.position-1],m=this.composer.getValue(!1,!1),n=this.element.offsetWidth>0&&this.element.offsetHeight>0;m!==l&&(j=this.historyStr.length=this.historyDom.length=this.position,j>f&&(this.historyStr.shift(),this.historyDom.shift(),this.position--),this.position++,n&&(b=this.composer.selection.getRange(),c=b&&b.startContainer?b.startContainer:this.element,d=b&&b.startOffset?b.startOffset:0,c.nodeType===a.ELEMENT_NODE?e=c:(e=c.parentNode,i=this.getChildNodeIndex(e,c)),e.setAttribute(h,d),void 0!==i&&e.setAttribute(g,i)),k=this.element.cloneNode(!!m),this.historyDom.push(k),this.historyStr.push(m),e&&(e.removeAttribute(h),e.removeAttribute(g)))},undo:function(){this.transact(),this.undoPossible()&&(this.set(this.historyDom[--this.position-1]),this.editor.fire("undo:composer"))},redo:function(){this.redoPossible()&&(this.set(this.historyDom[++this.position-1]),this.editor.fire("redo:composer"))},undoPossible:function(){return this.position>1},redoPossible:function(){return this.position<this.historyStr.length},set:function(a){var b,c,d,e,f,i;for(this.element.innerHTML="",b=0,c=a.childNodes,d=a.childNodes.length;d>b;b++)this.element.appendChild(c[b].cloneNode(!0));a.hasAttribute(h)?(e=a.getAttribute(h),i=a.getAttribute(g),f=this.element):(f=this.element.querySelector("["+h+"]")||this.element,e=f.getAttribute(h),i=f.getAttribute(g),f.removeAttribute(h),f.removeAttribute(g)),null!==i&&(f=this.getChildNodeByIndex(f,+i)),this.composer.selection.set(f,e)},getChildNodeIndex:function(a,b){for(var c=0,d=a.childNodes,e=d.length;e>c;c++)if(d[c]===b)return c},getChildNodeByIndex:function(a,b){return a.childNodes[b]}})}(wysihtml5),wysihtml5.views.View=Base.extend({constructor:function(a,b,c){this.parent=a,this.element=b,this.config=c,this.config.noTextarea||this._observeViewChange()},_observeViewChange:function(){var a=this;this.parent.on("beforeload",function(){a.parent.on("change_view",function(b){b===a.name?(a.parent.currentView=a,a.show(),setTimeout(function(){a.focus()},0)):a.hide()})})},focus:function(){if(this.element.ownerDocument.querySelector(":focus")!==this.element)try{this.element.focus()}catch(a){}},hide:function(){this.element.style.display="none"},show:function(){this.element.style.display=""},disable:function(){this.element.setAttribute("disabled","disabled")},enable:function(){this.element.removeAttribute("disabled")}}),function(a){var b=a.dom,c=a.browser;a.views.Composer=a.views.View.extend({name:"composer",CARET_HACK:"<br>",constructor:function(a,b,c){this.base(a,b,c),this.config.noTextarea?this.editableArea=b:this.textarea=this.parent.textarea,this.config.contentEditableMode?this._initContentEditableArea():this._initSandbox()},clear:function(){this.element.innerHTML=c.displaysCaretInEmptyContentEditableCorrectly()?"":this.CARET_HACK},getValue:function(b,c){var d=this.isEmpty()?"":a.quirks.getCorrectInnerHTML(this.element);return b!==!1&&(d=this.parent.parse(d,c===!1?!1:!0)),d},setValue:function(a,b){b&&(a=this.parent.parse(a));try{this.element.innerHTML=a}catch(c){this.element.innerText=a}},cleanUp:function(){this.parent.parse(this.element)},show:function(){this.editableArea.style.display=this._displayStyle||"",this.config.noTextarea||this.textarea.element.disabled||(this.disable(),this.enable())},hide:function(){this._displayStyle=b.getStyle("display").from(this.editableArea),"none"===this._displayStyle&&(this._displayStyle=null),this.editableArea.style.display="none"},disable:function(){this.parent.fire("disable:composer"),this.element.removeAttribute("contentEditable")},enable:function(){this.parent.fire("enable:composer"),this.element.setAttribute("contentEditable","true")},focus:function(b){a.browser.doesAsyncFocus()&&this.hasPlaceholderSet()&&this.clear(),this.base();var c=this.element.lastChild;b&&c&&this.selection&&("BR"===c.nodeName?this.selection.setBefore(this.element.lastChild):this.selection.setAfter(this.element.lastChild))},getTextContent:function(){return b.getTextContent(this.element)},hasPlaceholderSet:function(){return this.getTextContent()==(this.config.noTextarea?this.editableArea.getAttribute("data-placeholder"):this.textarea.element.getAttribute("placeholder"))&&this.placeholderSet},isEmpty:function(){var a=this.element.innerHTML.toLowerCase();return/^(\s|<br>|<\/br>|<p>|<\/p>)*$/i.test(a)||""===a||"<br>"===a||"<p></p>"===a||"<p><br></p>"===a||this.hasPlaceholderSet()},_initContentEditableArea:function(){var a=this;this.config.noTextarea?this.sandbox=new b.ContentEditableArea(function(){a._create()},{},this.editableArea):(this.sandbox=new b.ContentEditableArea(function(){a._create()}),this.editableArea=this.sandbox.getContentEditable(),b.insert(this.editableArea).after(this.textarea.element),this._createWysiwygFormField())},_initSandbox:function(){var a,c=this;this.sandbox=new b.Sandbox(function(){c._create()},{stylesheets:this.config.stylesheets}),this.editableArea=this.sandbox.getIframe(),a=this.textarea.element,b.insert(this.editableArea).after(a),this._createWysiwygFormField()},_createWysiwygFormField:function(){if(this.textarea.element.form){var a=document.createElement("input");a.type="hidden",a.name="_wysihtml5_mode",a.value=1,b.insert(a).after(this.textarea.element)}},_create:function(){var d,e,f=this;this.doc=this.sandbox.getDocument(),this.element=this.config.contentEditableMode?this.sandbox.getContentEditable():this.doc.body,this.config.noTextarea?this.cleanUp():(this.textarea=this.parent.textarea,this.element.innerHTML=this.textarea.getValue(!0,!1)),this.selection=new a.Selection(this.parent,this.element,this.config.uneditableContainerClassname),this.commands=new a.Commands(this.parent),this.config.noTextarea||b.copyAttributes(["className","spellcheck","title","lang","dir","accessKey"]).from(this.textarea.element).to(this.element),b.addClass(this.element,this.config.composerClassName),this.config.style&&!this.config.contentEditableMode&&this.style(),this.observe(),d=this.config.name,d&&(b.addClass(this.element,d),this.config.contentEditableMode||b.addClass(this.editableArea,d)),this.enable(),!this.config.noTextarea&&this.textarea.element.disabled&&this.disable(),e="string"==typeof this.config.placeholder?this.config.placeholder:this.config.noTextarea?this.editableArea.getAttribute("data-placeholder"):this.textarea.element.getAttribute("placeholder"),e&&b.simulatePlaceholder(this.parent,this,e),this.commands.exec("styleWithCSS",!1),this._initAutoLinking(),this._initObjectResizing(),this._initUndoManager(),this._initLineBreaking(),this.config.noTextarea||!this.textarea.element.hasAttribute("autofocus")&&document.querySelector(":focus")!=this.textarea.element||c.isIos()||setTimeout(function(){f.focus(!0)},100),c.clearsContentEditableCorrectly()||a.quirks.ensureProperClearing(this),this.initSync&&this.config.sync&&this.initSync(),this.config.noTextarea||this.textarea.hide(),this.parent.fire("beforeload").fire("load")},_initAutoLinking:function(){var d,e,f,g=this,h=c.canDisableAutoLinking(),i=c.doesAutoLinkingInContentEditable();h&&this.commands.exec("autoUrlDetect",!1),this.config.autoLink&&((!i||i&&h)&&(this.parent.on("newword:composer",function(){b.getTextContent(g.element).match(b.autoLink.URL_REG_EXP)&&g.selection.executeAndRestore(function(c,d){var e,f=g.element.querySelectorAll("."+g.config.uneditableContainerClassname),h=!1;for(e=f.length;e--;)a.dom.contains(f[e],d)&&(h=!0);h||b.autoLink(d.parentNode,[g.config.uneditableContainerClassname])})}),b.observe(this.element,"blur",function(){b.autoLink(g.element,[g.config.uneditableContainerClassname])})),d=this.sandbox.getDocument().getElementsByTagName("a"),e=b.autoLink.URL_REG_EXP,f=function(c){var d=a.lang.string(b.getTextContent(c)).trim();return"www."===d.substr(0,4)&&(d="http://"+d),d},b.observe(this.element,"keydown",function(a){if(d.length){var c,h=g.selection.getSelectedNode(a.target.ownerDocument),i=b.getParentElement(h,{nodeName:"A"},4);i&&(c=f(i),setTimeout(function(){var a=f(i);a!==c&&a.match(e)&&i.setAttribute("href",a)},0))}}))},_initObjectResizing:function(){if(this.commands.exec("enableObjectResizing",!0),c.supportsEvent("resizeend")){var d=["width","height"],e=d.length,f=this.element;b.observe(f,"resizeend",function(b){var c,g=b.target||b.srcElement,h=g.style,i=0;if("IMG"===g.nodeName){for(;e>i;i++)c=d[i],h[c]&&(g.setAttribute(c,parseInt(h[c],10)),h[c]="");a.quirks.redraw(f)}})}},_initUndoManager:function(){this.undoManager=new a.UndoManager(this.parent)},_initLineBreaking:function(){function d(a){var c=b.getParentElement(a,{nodeName:["P","DIV"]},2);c&&b.contains(e.element,c)&&e.selection.executeAndRestore(function(){e.config.useLineBreaks?b.replaceWithChildNodes(c):"P"!==c.nodeName&&b.renameElement(c,"p")})}var e=this,f=["LI","P","H1","H2","H3","H4","H5","H6"],g=["UL","OL","MENU"];this.config.useLineBreaks||b.observe(this.element,["focus","keydown"],function(){if(e.isEmpty()){var a=e.doc.createElement("P");e.element.innerHTML="",e.element.appendChild(a),c.displaysCaretInEmptyContentEditableCorrectly()?e.selection.selectNode(a,!0):(a.innerHTML="<br>",e.selection.setBefore(a.firstChild))}}),b.observe(this.element,"keydown",function(c){var h,i=c.keyCode;if(!c.shiftKey&&(i===a.ENTER_KEY||i===a.BACKSPACE_KEY))return h=b.getParentElement(e.selection.getSelectedNode(),{nodeName:f},4),h?(setTimeout(function(){var c,f=e.selection.getSelectedNode();if("LI"===h.nodeName){if(!f)return;c=b.getParentElement(f,{nodeName:g},2),c||d(f)}i===a.ENTER_KEY&&h.nodeName.match(/^H[1-6]$/)&&d(f)},0),void 0):(e.config.useLineBreaks&&i===a.ENTER_KEY&&!a.browser.insertsLineBreaksOnReturn()&&(c.preventDefault(),e.commands.exec("insertLineBreak")),void 0)})}})}(wysihtml5),function(a){var b=a.dom,c=document,d=window,e=c.createElement("div"),f=["background-color","color","cursor","font-family","font-size","font-style","font-variant","font-weight","line-height","letter-spacing","text-align","text-decoration","text-indent","text-rendering","word-break","word-wrap","word-spacing"],g=["background-color","border-collapse","border-bottom-color","border-bottom-style","border-bottom-width","border-left-color","border-left-style","border-left-width","border-right-color","border-right-style","border-right-width","border-top-color","border-top-style","border-top-width","clear","display","float","margin-bottom","margin-left","margin-right","margin-top","outline-color","outline-offset","outline-width","outline-style","padding-left","padding-right","padding-top","padding-bottom","position","top","left","right","bottom","z-index","vertical-align","text-align","-webkit-box-sizing","-moz-box-sizing","-ms-box-sizing","box-sizing","-webkit-box-shadow","-moz-box-shadow","-ms-box-shadow","box-shadow","-webkit-border-top-right-radius","-moz-border-radius-topright","border-top-right-radius","-webkit-border-bottom-right-radius","-moz-border-radius-bottomright","border-bottom-right-radius","-webkit-border-bottom-left-radius","-moz-border-radius-bottomleft","border-bottom-left-radius","-webkit-border-top-left-radius","-moz-border-radius-topleft","border-top-left-radius","width","height"],h=["html { height: 100%; }","body { height: 100%; padding: 1px 0 0 0; margin: -1px 0 0 0; }","body > p:first-child { margin-top: 0; }","._wysihtml5-temp { display: none; }",a.browser.isGecko?"body.placeholder { color: graytext !important; }":"body.placeholder { color: #a9a9a9 !important; }","img:-moz-broken { -moz-force-broken-image-icon: 1; height: 24px; width: 24px; }"],i=function(a){if(a.setActive)try{a.setActive()}catch(e){}else{var f=a.style,g=c.documentElement.scrollTop||c.body.scrollTop,h=c.documentElement.scrollLeft||c.body.scrollLeft,i={position:f.position,top:f.top,left:f.left,WebkitUserSelect:f.WebkitUserSelect};b.setStyles({position:"absolute",top:"-99999px",left:"-99999px",WebkitUserSelect:"none"}).on(a),a.focus(),b.setStyles(i).on(a),d.scrollTo&&d.scrollTo(h,g)}};a.views.Composer.prototype.style=function(){var d,j,k=this,l=c.querySelector(":focus"),m=this.textarea.element,n=m.hasAttribute("placeholder"),o=n&&m.getAttribute("placeholder"),p=m.style.display,q=m.disabled;return this.focusStylesHost=e.cloneNode(!1),this.blurStylesHost=e.cloneNode(!1),this.disabledStylesHost=e.cloneNode(!1),n&&m.removeAttribute("placeholder"),m===l&&m.blur(),m.disabled=!1,m.style.display=d="none",(m.getAttribute("rows")&&"auto"===b.getStyle("height").from(m)||m.getAttribute("cols")&&"auto"===b.getStyle("width").from(m))&&(m.style.display=d=p),b.copyStyles(g).from(m).to(this.editableArea).andTo(this.blurStylesHost),b.copyStyles(f).from(m).to(this.element).andTo(this.blurStylesHost),b.insertCSS(h).into(this.element.ownerDocument),m.disabled=!0,b.copyStyles(g).from(m).to(this.disabledStylesHost),b.copyStyles(f).from(m).to(this.disabledStylesHost),m.disabled=q,m.style.display=p,i(m),m.style.display=d,b.copyStyles(g).from(m).to(this.focusStylesHost),b.copyStyles(f).from(m).to(this.focusStylesHost),m.style.display=p,b.copyStyles(["display"]).from(m).to(this.editableArea),j=a.lang.array(g).without(["display"]),l?l.focus():m.blur(),n&&m.setAttribute("placeholder",o),this.parent.on("focus:composer",function(){b.copyStyles(j).from(k.focusStylesHost).to(k.editableArea),b.copyStyles(f).from(k.focusStylesHost).to(k.element)}),this.parent.on("blur:composer",function(){b.copyStyles(j).from(k.blurStylesHost).to(k.editableArea),b.copyStyles(f).from(k.blurStylesHost).to(k.element)}),this.parent.observe("disable:composer",function(){b.copyStyles(j).from(k.disabledStylesHost).to(k.editableArea),b.copyStyles(f).from(k.disabledStylesHost).to(k.element)}),this.parent.observe("enable:composer",function(){b.copyStyles(j).from(k.blurStylesHost).to(k.editableArea),b.copyStyles(f).from(k.blurStylesHost).to(k.element)}),this}}(wysihtml5),function(a){var b=a.dom,c=a.browser,d={66:"bold",73:"italic",85:"underline"},e=function(a,b,c){var d,e=a.getPreviousNode(b,!0),f=a.getSelectedNode();if(1!==f.nodeType&&f.parentNode!==c&&(f=f.parentNode),e)if(1==f.nodeType){if(d=f.firstChild,1==e.nodeType)for(;f.firstChild;)e.appendChild(f.firstChild);else for(;f.firstChild;)b.parentNode.insertBefore(f.firstChild,b);f.parentNode&&f.parentNode.removeChild(f),a.setBefore(d)}else 1==e.nodeType?e.appendChild(f):b.parentNode.insertBefore(f,b),a.setBefore(f)},f=function(a,b,c,d){var f,g,h;b.isCollapsed()?b.caretIsInTheBeginnig("LI")?(a.preventDefault(),d.commands.exec("outdentList")):b.caretIsInTheBeginnig()?a.preventDefault():(b.caretIsFirstInSelection()&&b.getPreviousNode()&&b.getPreviousNode().nodeName&&/^H\d$/gi.test(b.getPreviousNode().nodeName)&&(f=b.getPreviousNode(),a.preventDefault(),/^\s*$/.test(f.textContent||f.innerText)?f.parentNode.removeChild(f):(g=f.ownerDocument.createRange(),g.selectNodeContents(f),g.collapse(!1),b.setSelection(g))),h=b.caretIsBeforeUneditable(),h&&(a.preventDefault(),e(b,h,c))):b.containsUneditable()&&(a.preventDefault(),b.deleteContents())},g=function(a){if(a.selection.isCollapsed()){if(a.selection.caretIsInTheBeginnig("LI")&&a.commands.exec("indentList"))return}else a.selection.deleteContents();
a.commands.exec("insertHTML"," ")};a.views.Composer.prototype.observe=function(){var e,h,i=this,j=this.getValue(!1,!1),k=this.sandbox.getIframe?this.sandbox.getIframe():this.sandbox.getContentEditable(),l=this.element,m=c.supportsEventsInIframeCorrectly()||this.sandbox.getContentEditable?l:this.sandbox.getWindow(),n=["drop","paste","beforepaste"],o=["drop","paste","mouseup","focus","keyup"];b.observe(k,"DOMNodeRemoved",function(){clearInterval(e),i.parent.fire("destroy:composer")}),c.supportsMutationEvents()||(e=setInterval(function(){b.contains(document.documentElement,k)||(clearInterval(e),i.parent.fire("destroy:composer"))},250)),b.observe(m,o,function(){setTimeout(function(){i.parent.fire("interaction").fire("interaction:composer")},0)}),this.config.handleTables&&(!this.tableClickHandle&&this.doc.execCommand&&a.browser.supportsCommand(this.doc,"enableObjectResizing")&&a.browser.supportsCommand(this.doc,"enableInlineTableEditing")&&(this.sandbox.getIframe?this.tableClickHandle=b.observe(k,["focus","mouseup","mouseover"],function(){i.doc.execCommand("enableObjectResizing",!1,"false"),i.doc.execCommand("enableInlineTableEditing",!1,"false"),i.tableClickHandle.stop()}):setTimeout(function(){i.doc.execCommand("enableObjectResizing",!1,"false"),i.doc.execCommand("enableInlineTableEditing",!1,"false")},0)),this.tableSelection=a.quirks.tableCellsSelection(l,i.parent)),b.observe(m,"focus",function(a){i.parent.fire("focus",a).fire("focus:composer",a),setTimeout(function(){j=i.getValue(!1,!1)},0)}),b.observe(m,"blur",function(a){if(j!==i.getValue(!1,!1)){var b=a;"function"==typeof Object.create&&(b=Object.create(a,{type:{value:"change"}})),i.parent.fire("change",b).fire("change:composer",b)}i.parent.fire("blur",a).fire("blur:composer",a)}),b.observe(l,"dragenter",function(){i.parent.fire("unset_placeholder")}),b.observe(l,n,function(a){i.parent.fire(a.type,a).fire(a.type+":composer",a)}),this.config.copyedFromMarking&&b.observe(l,"copy",function(a){a.clipboardData&&(a.clipboardData.setData("text/html",i.config.copyedFromMarking+i.selection.getHtml()),a.preventDefault()),i.parent.fire(a.type,a).fire(a.type+":composer",a)}),b.observe(l,"keyup",function(b){var c=b.keyCode;(c===a.SPACE_KEY||c===a.ENTER_KEY)&&i.parent.fire("newword:composer")}),this.parent.on("paste:composer",function(){setTimeout(function(){i.parent.fire("newword:composer")},0)}),c.canSelectImagesInContentEditable()||b.observe(l,"mousedown",function(b){var c=b.target,d=l.querySelectorAll("img"),e=l.querySelectorAll("."+i.config.uneditableContainerClassname+" img"),f=a.lang.array(d).without(e);"IMG"===c.nodeName&&a.lang.array(f).contains(c)&&i.selection.selectNode(c)}),c.canSelectImagesInContentEditable()||b.observe(l,"drop",function(){setTimeout(function(){i.selection.getSelection().removeAllRanges()},0)}),c.hasHistoryIssue()&&c.supportsSelectionModify()&&b.observe(l,"keydown",function(a){if(a.metaKey||a.ctrlKey){var b=a.keyCode,c=l.ownerDocument.defaultView,d=c.getSelection();(37===b||39===b)&&(37===b&&(d.modify("extend","left","lineboundary"),a.shiftKey||d.collapseToStart()),39===b&&(d.modify("extend","right","lineboundary"),a.shiftKey||d.collapseToEnd()),a.preventDefault())}}),b.observe(l,"keydown",function(a){var b=a.keyCode,c=d[b];(a.ctrlKey||a.metaKey)&&!a.altKey&&c&&(i.commands.exec(c),a.preventDefault()),8===b?f(a,i.selection,l,i):i.config.handleTabKey&&9===b&&(a.preventDefault(),g(i,l))}),b.observe(l,"keydown",function(b){var c,d=i.selection.getSelectedNode(!0),e=b.keyCode;!d||"IMG"!==d.nodeName||e!==a.BACKSPACE_KEY&&e!==a.DELETE_KEY||(c=d.parentNode,c.removeChild(d),"A"!==c.nodeName||c.firstChild||c.parentNode.removeChild(c),setTimeout(function(){a.quirks.redraw(l)},0),b.preventDefault())}),!this.config.contentEditableMode&&c.hasIframeFocusIssue()&&(b.observe(k,"focus",function(){setTimeout(function(){i.doc.querySelector(":focus")!==i.element&&i.focus()},0)}),b.observe(this.element,"blur",function(){setTimeout(function(){i.selection.getSelection().removeAllRanges()},0)})),h={IMG:"Image: ",A:"Link: "},b.observe(l,"mouseover",function(a){var b,c,d=a.target,e=d.nodeName;("A"===e||"IMG"===e)&&(c=d.hasAttribute("title"),c||(b=h[e]+(d.getAttribute("href")||d.getAttribute("src")),d.setAttribute("title",b)))})}}(wysihtml5),function(a){var b=400;a.views.Synchronizer=Base.extend({constructor:function(a,b,c){this.editor=a,this.textarea=b,this.composer=c,this._observe()},fromComposerToTextarea:function(b){this.textarea.setValue(a.lang.string(this.composer.getValue(!1,!1)).trim(),b)},fromTextareaToComposer:function(a){var b=this.textarea.getValue(!1,!1);b?this.composer.setValue(b,a):(this.composer.clear(),this.editor.fire("set_placeholder"))},sync:function(a){"textarea"===this.editor.currentView.name?this.fromTextareaToComposer(a):this.fromComposerToTextarea(a)},_observe:function(){var c,d=this,e=this.textarea.element.form,f=function(){c=setInterval(function(){d.fromComposerToTextarea()},b)},g=function(){clearInterval(c),c=null};f(),e&&(a.dom.observe(e,"submit",function(){d.sync(!0)}),a.dom.observe(e,"reset",function(){setTimeout(function(){d.fromTextareaToComposer()},0)})),this.editor.on("change_view",function(a){"composer"!==a||c?"textarea"===a&&(d.fromComposerToTextarea(!0),g()):(d.fromTextareaToComposer(!0),f())}),this.editor.on("destroy:composer",g)}})}(wysihtml5),wysihtml5.views.Textarea=wysihtml5.views.View.extend({name:"textarea",constructor:function(a,b,c){this.base(a,b,c),this._observe()},clear:function(){this.element.value=""},getValue:function(a){var b=this.isEmpty()?"":this.element.value;return a!==!1&&(b=this.parent.parse(b)),b},setValue:function(a,b){b&&(a=this.parent.parse(a)),this.element.value=a},cleanUp:function(){var a=this.parent.parse(this.element.value);this.element.value=a},hasPlaceholderSet:function(){var a=wysihtml5.browser.supportsPlaceholderAttributeOn(this.element),b=this.element.getAttribute("placeholder")||null,c=this.element.value,d=!c;return a&&d||c===b},isEmpty:function(){return!wysihtml5.lang.string(this.element.value).trim()||this.hasPlaceholderSet()},_observe:function(){var a=this.element,b=this.parent,c={focusin:"focus",focusout:"blur"},d=wysihtml5.browser.supportsEvent("focusin")?["focusin","focusout","change"]:["focus","blur","change"];b.on("beforeload",function(){wysihtml5.dom.observe(a,d,function(a){var d=c[a.type]||a.type;b.fire(d).fire(d+":textarea")}),wysihtml5.dom.observe(a,["paste","drop"],function(){setTimeout(function(){b.fire("paste").fire("paste:textarea")},0)})})}}),function(a){var b,c={name:b,style:!0,toolbar:b,showToolbarAfterInit:!0,autoLink:!0,handleTables:!0,handleTabKey:!0,parserRules:{tags:{br:{},span:{},div:{},p:{}},classes:{}},pasteParserRulesets:null,parser:a.dom.parse,composerClassName:"wysihtml5-editor",bodyClassName:"wysihtml5-supported",useLineBreaks:!0,stylesheets:[],placeholderText:b,supportTouchDevices:!0,cleanUp:!0,contentEditableMode:!1,uneditableContainerClassname:"wysihtml5-uneditable-container",copyedFromMarking:'<meta name="copied-from" content="wysihtml5">'};a.Editor=a.lang.Dispatcher.extend({constructor:function(b,d){if(this.editableElement="string"==typeof b?document.getElementById(b):b,this.config=a.lang.object({}).merge(c).merge(d).get(),this._isCompatible=a.browser.supported(),"textarea"!=this.editableElement.nodeName.toLowerCase()&&(this.config.contentEditableMode=!0,this.config.noTextarea=!0),this.config.noTextarea||(this.textarea=new a.views.Textarea(this,this.editableElement,this.config),this.currentView=this.textarea),!this._isCompatible||!this.config.supportTouchDevices&&a.browser.isTouchDevice()){var e=this;return setTimeout(function(){e.fire("beforeload").fire("load")},0),void 0}a.dom.addClass(document.body,this.config.bodyClassName),this.composer=new a.views.Composer(this,this.editableElement,this.config),this.currentView=this.composer,"function"==typeof this.config.parser&&this._initParser(),this.on("beforeload",this.handleBeforeLoad)},handleBeforeLoad:function(){this.config.noTextarea||(this.synchronizer=new a.views.Synchronizer(this,this.textarea,this.composer)),this.config.toolbar&&(this.toolbar=new a.toolbar.Toolbar(this,this.config.toolbar,this.config.showToolbarAfterInit))},isCompatible:function(){return this._isCompatible},clear:function(){return this.currentView.clear(),this},getValue:function(a,b){return this.currentView.getValue(a,b)},setValue:function(a,b){return this.fire("unset_placeholder"),a?(this.currentView.setValue(a,b),this):this.clear()},cleanUp:function(){this.currentView.cleanUp()},focus:function(a){return this.currentView.focus(a),this},disable:function(){return this.currentView.disable(),this},enable:function(){return this.currentView.enable(),this},isEmpty:function(){return this.currentView.isEmpty()},hasPlaceholderSet:function(){return this.currentView.hasPlaceholderSet()},parse:function(b,c){var d=this.config.contentEditableMode?document:this.composer?this.composer.sandbox.getDocument():null,e=this.config.parser(b,{rules:this.config.parserRules,cleanUp:this.config.cleanUp,context:d,uneditableClass:this.config.uneditableContainerClassname,clearInternals:c});return"object"==typeof b&&a.quirks.redraw(b),e},_initParser:function(){var b,c=this;a.browser.supportsModenPaste()?this.on("paste:composer",function(d){d.preventDefault(),b=a.dom.getPastedHtml(d),b&&c._cleanAndPaste(b)}):this.on("beforepaste:composer",function(b){b.preventDefault(),a.dom.getPastedHtmlWithDiv(c.composer,function(a){a&&c._cleanAndPaste(a)})})},_cleanAndPaste:function(b){var c=a.quirks.cleanPastedHTML(b,{referenceNode:this.composer.element,rules:this.config.pasteParserRulesets||[{set:this.config.parserRules}],uneditableClass:this.config.uneditableContainerClassname});this.composer.selection.deleteContents(),this.composer.selection.insertHTML(c)}})}(wysihtml5),function(a){var b=a.dom,c="wysihtml5-command-dialog-opened",d="input, select, textarea",e="[data-wysihtml5-dialog-field]",f="data-wysihtml5-dialog-field";a.toolbar.Dialog=a.lang.Dispatcher.extend({constructor:function(a,b){this.link=a,this.container=b},_observe:function(){var e,f,g,h,i,j;if(!this._observed){for(e=this,f=function(a){var b=e._serialize();b==e.elementToChange?e.fire("edit",b):e.fire("save",b),e.hide(),a.preventDefault(),a.stopPropagation()},b.observe(e.link,"click",function(){b.hasClass(e.link,c)&&setTimeout(function(){e.hide()},0)}),b.observe(this.container,"keydown",function(b){var c=b.keyCode;c===a.ENTER_KEY&&f(b),c===a.ESCAPE_KEY&&(e.fire("cancel"),e.hide())}),b.delegate(this.container,"[data-wysihtml5-dialog-action=save]","click",f),b.delegate(this.container,"[data-wysihtml5-dialog-action=cancel]","click",function(a){e.fire("cancel"),e.hide(),a.preventDefault(),a.stopPropagation()}),g=this.container.querySelectorAll(d),h=0,i=g.length,j=function(){clearInterval(e.interval)};i>h;h++)b.observe(g[h],"change",j);this._observed=!0}},_serialize:function(){for(var a=this.elementToChange||{},b=this.container.querySelectorAll(e),c=b.length,d=0;c>d;d++)a[b[d].getAttribute(f)]=b[d].value;return a},_interpolate:function(a){for(var b,c,d,g=document.querySelector(":focus"),h=this.container.querySelectorAll(e),i=h.length,j=0;i>j;j++)b=h[j],b!==g&&(a&&"hidden"===b.type||(c=b.getAttribute(f),d=this.elementToChange&&"boolean"!=typeof this.elementToChange?this.elementToChange.getAttribute(c)||"":b.defaultValue,b.value=d))},show:function(a){if(!b.hasClass(this.link,c)){var e=this,f=this.container.querySelector(d);if(this.elementToChange=a,this._observe(),this._interpolate(),a&&(this.interval=setInterval(function(){e._interpolate(!0)},500)),b.addClass(this.link,c),this.container.style.display="",this.fire("show"),f&&!a)try{f.focus()}catch(g){}}},hide:function(){clearInterval(this.interval),this.elementToChange=null,b.removeClass(this.link,c),this.container.style.display="none",this.fire("hide")}})}(wysihtml5),function(a){var b=a.dom,c={position:"relative"},d={left:0,margin:0,opacity:0,overflow:"hidden",padding:0,position:"absolute",top:0,zIndex:1},e={cursor:"inherit",fontSize:"50px",height:"50px",marginTop:"-25px",outline:0,padding:0,position:"absolute",right:"-4px",top:"50%"},f={"x-webkit-speech":"",speech:""};a.toolbar.Speech=function(g,h){var i,j,k,l=document.createElement("input");return a.browser.supportsSpeechApiOn(l)?(i=g.editor.textarea.element.getAttribute("lang"),i&&(f.lang=i),j=document.createElement("div"),a.lang.object(d).merge({width:h.offsetWidth+"px",height:h.offsetHeight+"px"}),b.insert(l).into(j),b.insert(j).into(h),b.setStyles(e).on(l),b.setAttributes(f).on(l),b.setStyles(d).on(j),b.setStyles(c).on(h),k="onwebkitspeechchange"in l?"webkitspeechchange":"speechchange",b.observe(l,k,function(){g.execCommand("insertText",l.value),l.value=""}),b.observe(l,"click",function(a){b.hasClass(h,"wysihtml5-command-disabled")&&a.preventDefault(),a.stopPropagation()}),void 0):(h.style.display="none",void 0)}}(wysihtml5),function(a){var b="wysihtml5-command-disabled",c="wysihtml5-commands-disabled",d="wysihtml5-command-active",e="wysihtml5-action-active",f=a.dom;a.toolbar.Toolbar=Base.extend({constructor:function(f,g,h){this.editor=f,this.container="string"==typeof g?document.getElementById(g):g,this.composer=f.composer,this._getLinks("command"),this._getLinks("action"),this._observe(),h&&this.show(),null!=f.config.classNameCommandDisabled&&(b=f.config.classNameCommandDisabled),null!=f.config.classNameCommandsDisabled&&(c=f.config.classNameCommandsDisabled),null!=f.config.classNameCommandActive&&(d=f.config.classNameCommandActive),null!=f.config.classNameActionActive&&(e=f.config.classNameActionActive);for(var i=this.container.querySelectorAll("[data-wysihtml5-command=insertSpeech]"),j=i.length,k=0;j>k;k++)new a.toolbar.Speech(this,i[k])},_getLinks:function(b){for(var c,d,e,f,g,h=this[b+"Links"]=a.lang.array(this.container.querySelectorAll("[data-wysihtml5-"+b+"]")).get(),i=h.length,j=0,k=this[b+"Mapping"]={};i>j;j++)c=h[j],e=c.getAttribute("data-wysihtml5-"+b),f=c.getAttribute("data-wysihtml5-"+b+"-value"),d=this.container.querySelector("[data-wysihtml5-"+b+"-group='"+e+"']"),g=this._getDialog(c,e),k[e+":"+f]={link:c,group:d,name:e,value:f,dialog:g,state:!1}},_getDialog:function(b,c){var d,e,f=this,g=this.container.querySelector("[data-wysihtml5-dialog='"+c+"']");return g&&(d=a.toolbar["Dialog_"+c]?new a.toolbar["Dialog_"+c](b,g):new a.toolbar.Dialog(b,g),d.on("show",function(){e=f.composer.selection.getBookmark(),f.editor.fire("show:dialog",{command:c,dialogContainer:g,commandLink:b})}),d.on("save",function(a){e&&f.composer.selection.setBookmark(e),f._execCommand(c,a),f.editor.fire("save:dialog",{command:c,dialogContainer:g,commandLink:b})}),d.on("cancel",function(){f.editor.focus(!1),f.editor.fire("cancel:dialog",{command:c,dialogContainer:g,commandLink:b})})),d},execCommand:function(a,b){if(!this.commandsDisabled){var c=this.commandMapping[a+":"+b];c&&c.dialog&&!c.state?c.dialog.show():this._execCommand(a,b)}},_execCommand:function(a,b){this.editor.focus(!1),this.composer.commands.exec(a,b),this._updateLinkStates()},execAction:function(a){var b=this.editor;"change_view"===a&&b.textarea&&(b.currentView===b.textarea?b.fire("change_view","composer"):b.fire("change_view","textarea")),"showSource"==a&&b.fire("showSource")},_observe:function(){for(var a=this,b=this.editor,d=this.container,e=this.commandLinks.concat(this.actionLinks),g=e.length,h=0;g>h;h++)"A"===e[h].nodeName?f.setAttributes({href:"javascript:;",unselectable:"on"}).on(e[h]):f.setAttributes({unselectable:"on"}).on(e[h]);f.delegate(d,"[data-wysihtml5-command], [data-wysihtml5-action]","mousedown",function(a){a.preventDefault()}),f.delegate(d,"[data-wysihtml5-command]","click",function(b){var c=this,d=c.getAttribute("data-wysihtml5-command"),e=c.getAttribute("data-wysihtml5-command-value");a.execCommand(d,e),b.preventDefault()}),f.delegate(d,"[data-wysihtml5-action]","click",function(b){var c=this.getAttribute("data-wysihtml5-action");a.execAction(c),b.preventDefault()}),b.on("interaction:composer",function(){a._updateLinkStates()}),b.on("focus:composer",function(){a.bookmark=null}),this.editor.config.handleTables&&(b.on("tableselect:composer",function(){a.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display=""}),b.on("tableunselect:composer",function(){a.container.querySelectorAll('[data-wysihtml5-hiddentools="table"]')[0].style.display="none"})),b.on("change_view",function(e){b.textarea&&setTimeout(function(){a.commandsDisabled="composer"!==e,a._updateLinkStates(),a.commandsDisabled?f.addClass(d,c):f.removeClass(d,c)},0)})},_updateLinkStates:function(){var c,g,h,i,j=this.commandMapping,k=this.actionMapping;for(c in j)i=j[c],this.commandsDisabled?(g=!1,f.removeClass(i.link,d),i.group&&f.removeClass(i.group,d),i.dialog&&i.dialog.hide()):(g=this.composer.commands.state(i.name,i.value),f.removeClass(i.link,b),i.group&&f.removeClass(i.group,b)),i.state!==g&&(i.state=g,g?(f.addClass(i.link,d),i.group&&f.addClass(i.group,d),i.dialog&&("object"==typeof g||a.lang.object(g).isArray()?(!i.dialog.multiselect&&a.lang.object(g).isArray()&&(g=1===g.length?g[0]:!0,i.state=g),i.dialog.show(g)):i.dialog.hide())):(f.removeClass(i.link,d),i.group&&f.removeClass(i.group,d),i.dialog&&i.dialog.hide()));for(c in k)h=k[c],"change_view"===h.name&&(h.state=this.editor.currentView===this.editor.textarea,h.state?f.addClass(h.link,e):f.removeClass(h.link,e))},show:function(){this.container.style.display=""},hide:function(){this.container.style.display="none"}})}(wysihtml5),function(a){a.toolbar.Dialog_createTable=a.toolbar.Dialog.extend({show:function(a){this.base(a)}})}(wysihtml5),function(a){var b=(a.dom,"[data-wysihtml5-dialog-field]"),c="data-wysihtml5-dialog-field";a.toolbar.Dialog_foreColorStyle=a.toolbar.Dialog.extend({multiselect:!0,_serialize:function(){for(var a={},d=this.container.querySelectorAll(b),e=d.length,f=0;e>f;f++)a[d[f].getAttribute(c)]=d[f].value;return a},_interpolate:function(d){for(var e,f=document.querySelector(":focus"),g=this.container.querySelectorAll(b),h=g.length,i=0,j=this.elementToChange?a.lang.object(this.elementToChange).isArray()?this.elementToChange[0]:this.elementToChange:null,k=j?j.getAttribute("style"):null,l=k?a.quirks.styleParser.parseColor(k,"color"):null;h>i;i++)e=g[i],e!==f&&(d&&"hidden"===e.type||"color"===e.getAttribute(c)&&(e.value=l?l[3]&&1!=l[3]?"rgba("+l[0]+","+l[1]+","+l[2]+","+l[3]+");":"rgb("+l[0]+","+l[1]+","+l[2]+");":"rgb(0,0,0);"))}})}(wysihtml5),function(a){a.dom;a.toolbar.Dialog_fontSizeStyle=a.toolbar.Dialog.extend({multiselect:!0,_serialize:function(){return{size:this.container.querySelector('[data-wysihtml5-dialog-field="size"]').value}},_interpolate:function(){var b=document.querySelector(":focus"),c=this.container.querySelector("[data-wysihtml5-dialog-field='size']"),d=this.elementToChange?a.lang.object(this.elementToChange).isArray()?this.elementToChange[0]:this.elementToChange:null,e=d?d.getAttribute("style"):null,f=e?a.quirks.styleParser.parseFontSize(e):null;c&&c!==b&&f&&!/^\s*$/.test(f)&&(c.value=f)}})}(wysihtml5),Handlebars=function(){var a=function(){"use strict";function a(a){this.string=a}var b;return a.prototype.toString=function(){return""+this.string},b=a}(),b=function(a){"use strict";function b(a){return k[a]||"&"}function c(a,b){for(var c in b)Object.prototype.hasOwnProperty.call(b,c)&&(a[c]=b[c])}function d(a){return a instanceof j?""+a:a||0===a?(a=""+a,m.test(a)?a.replace(l,b):a):""}function e(a){return a||0===a?h(a)&&0===a.length?!0:!1:!0}var f,g,h,i={},j=a,k={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},l=/[&<>"'`]/g,m=/[&<>"'`]/;return i.extend=c,f=Object.prototype.toString,i.toString=f,g=function(a){return"function"==typeof a},g(/x/)&&(g=function(a){return"function"==typeof a&&"[object Function]"===f.call(a)}),i.isFunction=g,h=Array.isArray||function(a){return a&&"object"==typeof a?"[object Array]"===f.call(a):!1},i.isArray=h,i.escapeExpression=d,i.isEmpty=e,i}(a),c=function(){"use strict";function a(a,b){var d,e,f;for(b&&b.firstLine&&(d=b.firstLine,a+=" - "+d+":"+b.firstColumn),e=Error.prototype.constructor.call(this,a),f=0;f<c.length;f++)this[c[f]]=e[c[f]];d&&(this.lineNumber=d,this.column=b.firstColumn)}var b,c=["description","fileName","lineNumber","message","name","number","stack"];return a.prototype=Error(),b=a}(),d=function(a,b){"use strict";function c(a,b){this.helpers=a||{},this.partials=b||{},d(this)}function d(a){a.registerHelper("helperMissing",function(a){if(2===arguments.length)return void 0;throw new p("Missing helper: '"+a+"'")}),a.registerHelper("blockHelperMissing",function(b,c){var d=c.inverse||function(){},e=c.fn;return i(b)&&(b=b.call(this)),b===!0?e(this):b===!1||null==b?d(this):h(b)?b.length>0?a.helpers.each(b,c):d(this):e(b)}),a.registerHelper("each",function(a,b){var c,d,e,f=b.fn,g=b.inverse,j=0,k="";if(i(a)&&(a=a.call(this)),b.data&&(c=m(b.data)),a&&"object"==typeof a)if(h(a))for(d=a.length;d>j;j++)c&&(c.index=j,c.first=0===j,c.last=j===a.length-1),k+=f(a[j],{data:c});else for(e in a)a.hasOwnProperty(e)&&(c&&(c.key=e,c.index=j,c.first=0===j),k+=f(a[e],{data:c}),j++);return 0===j&&(k=g(this)),k}),a.registerHelper("if",function(a,b){return i(a)&&(a=a.call(this)),!b.hash.includeZero&&!a||o.isEmpty(a)?b.inverse(this):b.fn(this)}),a.registerHelper("unless",function(b,c){return a.helpers["if"].call(this,b,{fn:c.inverse,inverse:c.fn,hash:c.hash})}),a.registerHelper("with",function(a,b){return i(a)&&(a=a.call(this)),o.isEmpty(a)?void 0:b.fn(a)}),a.registerHelper("log",function(b,c){var d=c.data&&null!=c.data.level?parseInt(c.data.level,10):1;a.log(d,b)})}function e(a,b){l.log(a,b)}var f,g,h,i,j,k,l,m,n={},o=a,p=b,q="1.3.0";return n.VERSION=q,f=4,n.COMPILER_REVISION=f,g={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:">= 1.0.0"},n.REVISION_CHANGES=g,h=o.isArray,i=o.isFunction,j=o.toString,k="[object Object]",n.HandlebarsEnvironment=c,c.prototype={constructor:c,logger:l,log:e,registerHelper:function(a,b,c){if(j.call(a)===k){if(c||b)throw new p("Arg not supported with multiple helpers");o.extend(this.helpers,a)}else c&&(b.not=c),this.helpers[a]=b},registerPartial:function(a,b){j.call(a)===k?o.extend(this.partials,a):this.partials[a]=b}},l={methodMap:{0:"debug",1:"info",2:"warn",3:"error"},DEBUG:0,INFO:1,WARN:2,ERROR:3,level:3,log:function(a,b){if(l.level<=a){var c=l.methodMap[a];"undefined"!=typeof console&&console[c]&&console[c].call(console,b)}}},n.logger=l,n.log=e,m=function(a){var b={};return o.extend(b,a),b},n.createFrame=m,n}(b,c),e=function(a,b,c){"use strict";function d(a){var b,c,d=a&&a[0]||1,e=m;if(d!==e){if(e>d)throw b=n[e],c=n[d],new l("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+b+") or downgrade your runtime to an older version ("+c+").");throw new l("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+a[1]+").")}}function e(a,b){if(!b)throw new l("No environment passed to template");var c=function(a,c,d,e,f,g){var h,i=b.VM.invokePartial.apply(this,arguments);if(null!=i)return i;if(b.compile)return h={helpers:e,partials:f,data:g},f[c]=b.compile(a,{data:void 0!==g},b),f[c](d,h);throw new l("The partial "+c+" could not be compiled when running in runtime-only mode")},d={escapeExpression:k.escapeExpression,invokePartial:c,programs:[],program:function(a,b,c){var d=this.programs[a];return c?d=g(a,b,c):d||(d=this.programs[a]=g(a,b)),d},merge:function(a,b){var c=a||b;return a&&b&&a!==b&&(c={},k.extend(c,b),k.extend(c,a)),c},programWithDepth:b.VM.programWithDepth,noop:b.VM.noop,compilerInfo:null};return function(c,e){var f,g,h,i;return e=e||{},h=e.partial?e:b,e.partial||(f=e.helpers,g=e.partials),i=a.call(d,h,c,f,g,e.data),e.partial||b.VM.checkRevision(d.compilerInfo),i}}function f(a,b,c){var d=Array.prototype.slice.call(arguments,3),e=function(a,e){return e=e||{},b.apply(this,[a,e.data||c].concat(d))};return e.program=a,e.depth=d.length,e}function g(a,b,c){var d=function(a,d){return d=d||{},b(a,d.data||c)};return d.program=a,d.depth=0,d}function h(a,b,c,d,e,f){var g={partial:!0,helpers:d,partials:e,data:f};if(void 0===a)throw new l("The partial "+b+" could not be found");return a instanceof Function?a(c,g):void 0}function i(){return""}var j={},k=a,l=b,m=c.COMPILER_REVISION,n=c.REVISION_CHANGES;return j.checkRevision=d,j.template=e,j.programWithDepth=f,j.program=g,j.invokePartial=h,j.noop=i,j}(b,c,d),f=function(a,b,c,d,e){"use strict";var f,g=a,h=b,i=c,j=d,k=e,l=function(){var a=new g.HandlebarsEnvironment;return j.extend(a,g),a.SafeString=h,a.Exception=i,a.Utils=j,a.VM=k,a.template=function(b){return k.template(b,a)},a},m=l();return m.create=l,f=m}(d,a,c,b,e);return f}(),this.wysihtml5=this.wysihtml5||{},this.wysihtml5.tpl=this.wysihtml5.tpl||{},this.wysihtml5.tpl.blockquote=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b)),c}function g(){return' \n <span class="fa fa-quote-left"></span>\n '}function h(){return'\n <span class="glyphicon glyphicon-quote"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li>\n <a class="btn ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="blockquote" data-wysihtml5-display-format-name="false" tabindex="-1">\n ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.fa),{hash:{},inverse:m.program(5,h,e),fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+="\n </a>\n</li>\n",j}),this.wysihtml5.tpl.color=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+j((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===i?b.apply(a):b)),c}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var g,h="",i="function",j=this.escapeExpression,k=this;return h+='<li class="dropdown">\n <a class="btn btn-default dropdown-toggle ',g=c["if"].call(b,(g=b&&b.options,g=null==g||g===!1?g:g.toolbar,null==g||g===!1?g:g.size),{hash:{},inverse:k.noop,fn:k.program(1,f,e),data:e}),(g||0===g)&&(h+=g),h+='" data-toggle="dropdown" tabindex="-1">\n <span class="current-color">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.black,typeof g===i?g.apply(b):g))+'</span>\n <b class="caret"></b>\n </a>\n <ul class="dropdown-menu">\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="black"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="black">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.black,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="silver"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="silver">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.silver,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="gray"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="gray">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.gray,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="maroon"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="maroon">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.maroon,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="red"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="red">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.red,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="purple"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="purple">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.purple,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="green"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="green">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.green,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="olive"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="olive">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.olive,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="navy"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="navy">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.navy,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="blue"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="blue">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.blue,typeof g===i?g.apply(b):g))+'</a></li>\n <li><div class="wysihtml5-colors" data-wysihtml5-command-value="orange"></div><a class="wysihtml5-colors-title" data-wysihtml5-command="foreColor" data-wysihtml5-command-value="orange">'+j((g=b&&b.locale,g=null==g||g===!1?g:g.colours,g=null==g||g===!1?g:g.orange,typeof g===i?g.apply(b):g))+"</a></li>\n </ul>\n</li>\n",h}),this.wysihtml5.tpl.emphasis=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+k((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===j?b.apply(a):b)),c}function g(a,b){var d,e="";return e+='\n <a class="btn ',d=c["if"].call(a,(d=a&&a.options,d=null==d||d===!1?d:d.toolbar,null==d||d===!1?d:d.size),{hash:{},inverse:l.noop,fn:l.program(1,f,b),data:b}),(d||0===d)&&(e+=d),e+=' btn-default" data-wysihtml5-command="small" title="CTRL+S" tabindex="-1">'+k((d=a&&a.locale,d=null==d||d===!1?d:d.emphasis,d=null==d||d===!1?d:d.small,typeof d===j?d.apply(a):d))+"</a>\n ",e}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var h,i="",j="function",k=this.escapeExpression,l=this;return i+='<li>\n <div class="btn-group">\n <a class="btn ',h=c["if"].call(b,(h=b&&b.options,h=null==h||h===!1?h:h.toolbar,null==h||h===!1?h:h.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="bold" title="CTRL+B" tabindex="-1">'+k((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.bold,typeof h===j?h.apply(b):h))+'</a>\n <a class="btn ',h=c["if"].call(b,(h=b&&b.options,h=null==h||h===!1?h:h.toolbar,null==h||h===!1?h:h.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="italic" title="CTRL+I" tabindex="-1">'+k((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.italic,typeof h===j?h.apply(b):h))+'</a>\n <a class="btn ',h=c["if"].call(b,(h=b&&b.options,h=null==h||h===!1?h:h.toolbar,null==h||h===!1?h:h.size),{hash:{},inverse:l.noop,fn:l.program(1,f,e),data:e}),(h||0===h)&&(i+=h),i+=' btn-default" data-wysihtml5-command="underline" title="CTRL+U" tabindex="-1">'+k((h=b&&b.locale,h=null==h||h===!1?h:h.emphasis,h=null==h||h===!1?h:h.underline,typeof h===j?h.apply(b):h))+"</a>\n ",h=c["if"].call(b,(h=b&&b.options,h=null==h||h===!1?h:h.toolbar,h=null==h||h===!1?h:h.emphasis,null==h||h===!1?h:h.small),{hash:{},inverse:l.noop,fn:l.program(3,g,e),data:e}),(h||0===h)&&(i+=h),i+="\n </div>\n</li>\n",i
}),this.wysihtml5.tpl["font-styles"]=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b)),c}function g(){return'\n <span class="fa fa-font"></span>\n '}function h(){return'\n <span class="glyphicon glyphicon-font"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li class="dropdown">\n <a class="btn btn-default dropdown-toggle ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+='" data-toggle="dropdown">\n ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.fa),{hash:{},inverse:m.program(5,h,e),fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+='\n <span class="current-font">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.normal,typeof i===k?i.apply(b):i))+'</span>\n <b class="caret"></b>\n </a>\n <ul class="dropdown-menu">\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="p" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.normal,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h1" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h1,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h2" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h2,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h3" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h3,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h4" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h4,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h5" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h5,typeof i===k?i.apply(b):i))+'</a></li>\n <li><a data-wysihtml5-command="formatBlock" data-wysihtml5-command-value="h6" tabindex="-1">'+l((i=b&&b.locale,i=null==i||i===!1?i:i.font_styles,i=null==i||i===!1?i:i.h6,typeof i===k?i.apply(b):i))+"</a></li>\n </ul>\n</li>\n",j}),this.wysihtml5.tpl.html=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+l((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===k?b.apply(a):b)),c}function g(){return'\n <span class="fa fa-pencil"></span>\n '}function h(){return'\n <span class="glyphicon glyphicon-pencil"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var i,j="",k="function",l=this.escapeExpression,m=this;return j+='<li>\n <div class="btn-group">\n <a class="btn ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.size),{hash:{},inverse:m.noop,fn:m.program(1,f,e),data:e}),(i||0===i)&&(j+=i),j+=' btn-default" data-wysihtml5-action="change_view" title="'+l((i=b&&b.locale,i=null==i||i===!1?i:i.html,i=null==i||i===!1?i:i.edit,typeof i===k?i.apply(b):i))+'" tabindex="-1">\n ',i=c["if"].call(b,(i=b&&b.options,i=null==i||i===!1?i:i.toolbar,null==i||i===!1?i:i.fa),{hash:{},inverse:m.program(5,h,e),fn:m.program(3,g,e),data:e}),(i||0===i)&&(j+=i),j+="\n </a>\n </div>\n</li>\n",j}),this.wysihtml5.tpl.image=Handlebars.template(function(a,b,c,d,e){function f(){return"modal-sm"}function g(a){var b,c="";return c+="btn-"+m((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===l?b.apply(a):b)),c}function h(){return'\n <span class="fa fa-file-image-o"></span>\n '}function i(){return'\n <span class="glyphicon glyphicon-picture"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var j,k="",l="function",m=this.escapeExpression,n=this;return k+='<li>\n <div class="bootstrap-wysihtml5-insert-image-modal modal fade" data-wysihtml5-dialog="insertImage">\n <div class="modal-dialog ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.smallmodals),{hash:{},inverse:n.noop,fn:n.program(1,f,e),data:e}),(j||0===j)&&(k+=j),k+='">\n <div class="modal-content">\n <div class="modal-header">\n <a class="close" data-dismiss="modal">×</a>\n <h3>'+m((j=b&&b.locale,j=null==j||j===!1?j:j.image,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'</h3>\n </div>\n <div class="modal-body">\n <div class="form-group">\n <input value="http://" class="bootstrap-wysihtml5-insert-image-url form-control" data-wysihtml5-dialog-field="src">\n </div> \n </div>\n <div class="modal-footer">\n <a class="btn btn-default" data-dismiss="modal" data-wysihtml5-dialog-action="cancel" href="#">'+m((j=b&&b.locale,j=null==j||j===!1?j:j.image,j=null==j||j===!1?j:j.cancel,typeof j===l?j.apply(b):j))+'</a>\n <a class="btn btn-primary" data-dismiss="modal" data-wysihtml5-dialog-action="save" href="#">'+m((j=b&&b.locale,j=null==j||j===!1?j:j.image,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'</a>\n </div>\n </div>\n </div>\n </div>\n <a class="btn ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.size),{hash:{},inverse:n.noop,fn:n.program(3,g,e),data:e}),(j||0===j)&&(k+=j),k+=' btn-default" data-wysihtml5-command="insertImage" title="'+m((j=b&&b.locale,j=null==j||j===!1?j:j.image,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'" tabindex="-1">\n ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.fa),{hash:{},inverse:n.program(7,i,e),fn:n.program(5,h,e),data:e}),(j||0===j)&&(k+=j),k+="\n </a>\n</li>\n",k}),this.wysihtml5.tpl.link=Handlebars.template(function(a,b,c,d,e){function f(){return"modal-sm"}function g(a){var b,c="";return c+="btn-"+m((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===l?b.apply(a):b)),c}function h(){return'\n <span class="fa fa-share-square-o"></span>\n '}function i(){return'\n <span class="glyphicon glyphicon-share"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var j,k="",l="function",m=this.escapeExpression,n=this;return k+='<li>\n <div class="bootstrap-wysihtml5-insert-link-modal modal fade" data-wysihtml5-dialog="createLink">\n <div class="modal-dialog ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.smallmodals),{hash:{},inverse:n.noop,fn:n.program(1,f,e),data:e}),(j||0===j)&&(k+=j),k+='">\n <div class="modal-content">\n <div class="modal-header">\n <a class="close" data-dismiss="modal">×</a>\n <h3>'+m((j=b&&b.locale,j=null==j||j===!1?j:j.link,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'</h3>\n </div>\n <div class="modal-body">\n <div class="form-group">\n <input value="http://" class="bootstrap-wysihtml5-insert-link-url form-control" data-wysihtml5-dialog-field="href">\n </div> \n <div class="checkbox">\n <label> \n <input type="checkbox" class="bootstrap-wysihtml5-insert-link-target" checked>'+m((j=b&&b.locale,j=null==j||j===!1?j:j.link,j=null==j||j===!1?j:j.target,typeof j===l?j.apply(b):j))+'\n </label>\n </div>\n </div>\n <div class="modal-footer">\n <a class="btn btn-default" data-dismiss="modal" data-wysihtml5-dialog-action="cancel" href="#">'+m((j=b&&b.locale,j=null==j||j===!1?j:j.link,j=null==j||j===!1?j:j.cancel,typeof j===l?j.apply(b):j))+'</a>\n <a href="#" class="btn btn-primary" data-dismiss="modal" data-wysihtml5-dialog-action="save">'+m((j=b&&b.locale,j=null==j||j===!1?j:j.link,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'</a>\n </div>\n </div>\n </div>\n </div>\n <a class="btn ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.size),{hash:{},inverse:n.noop,fn:n.program(3,g,e),data:e}),(j||0===j)&&(k+=j),k+=' btn-default" data-wysihtml5-command="createLink" title="'+m((j=b&&b.locale,j=null==j||j===!1?j:j.link,j=null==j||j===!1?j:j.insert,typeof j===l?j.apply(b):j))+'" tabindex="-1">\n ',j=c["if"].call(b,(j=b&&b.options,j=null==j||j===!1?j:j.toolbar,null==j||j===!1?j:j.fa),{hash:{},inverse:n.program(7,i,e),fn:n.program(5,h,e),data:e}),(j||0===j)&&(k+=j),k+="\n </a>\n</li>\n",k}),this.wysihtml5.tpl.lists=Handlebars.template(function(a,b,c,d,e){function f(a){var b,c="";return c+="btn-"+r((b=a&&a.options,b=null==b||b===!1?b:b.toolbar,b=null==b||b===!1?b:b.size,typeof b===q?b.apply(a):b)),c}function g(){return'\n <span class="fa fa-list-ul"></span>\n '}function h(){return'\n <span class="glyphicon glyphicon-list"></span>\n '}function i(){return'\n <span class="fa fa-list-ol"></span>\n '}function j(){return'\n <span class="glyphicon glyphicon-th-list"></span>\n '}function k(){return'\n <span class="fa fa-outdent"></span>\n '}function l(){return'\n <span class="glyphicon glyphicon-indent-right"></span>\n '}function m(){return'\n <span class="fa fa-indent"></span>\n '}function n(){return'\n <span class="glyphicon glyphicon-indent-left"></span>\n '}this.compilerInfo=[4,">= 1.0.0"],c=this.merge(c,a.helpers),e=e||{};var o,p="",q="function",r=this.escapeExpression,s=this;return p+='<li>\n <div class="btn-group">\n <a class="btn ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.size),{hash:{},inverse:s.noop,fn:s.program(1,f,e),data:e}),(o||0===o)&&(p+=o),p+=' btn-default" data-wysihtml5-command="insertUnorderedList" title="'+r((o=b&&b.locale,o=null==o||o===!1?o:o.lists,o=null==o||o===!1?o:o.unordered,typeof o===q?o.apply(b):o))+'" tabindex="-1">\n ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.fa),{hash:{},inverse:s.program(5,h,e),fn:s.program(3,g,e),data:e}),(o||0===o)&&(p+=o),p+='\n </a>\n <a class="btn ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.size),{hash:{},inverse:s.noop,fn:s.program(1,f,e),data:e}),(o||0===o)&&(p+=o),p+=' btn-default" data-wysihtml5-command="insertOrderedList" title="'+r((o=b&&b.locale,o=null==o||o===!1?o:o.lists,o=null==o||o===!1?o:o.ordered,typeof o===q?o.apply(b):o))+'" tabindex="-1">\n ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.fa),{hash:{},inverse:s.program(9,j,e),fn:s.program(7,i,e),data:e}),(o||0===o)&&(p+=o),p+='\n </a>\n <a class="btn ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.size),{hash:{},inverse:s.noop,fn:s.program(1,f,e),data:e}),(o||0===o)&&(p+=o),p+=' btn-default" data-wysihtml5-command="Outdent" title="'+r((o=b&&b.locale,o=null==o||o===!1?o:o.lists,o=null==o||o===!1?o:o.outdent,typeof o===q?o.apply(b):o))+'" tabindex="-1">\n ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.fa),{hash:{},inverse:s.program(13,l,e),fn:s.program(11,k,e),data:e}),(o||0===o)&&(p+=o),p+='\n </a>\n <a class="btn ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.size),{hash:{},inverse:s.noop,fn:s.program(1,f,e),data:e}),(o||0===o)&&(p+=o),p+=' btn-default" data-wysihtml5-command="Indent" title="'+r((o=b&&b.locale,o=null==o||o===!1?o:o.lists,o=null==o||o===!1?o:o.indent,typeof o===q?o.apply(b):o))+'" tabindex="-1">\n ',o=c["if"].call(b,(o=b&&b.options,o=null==o||o===!1?o:o.toolbar,null==o||o===!1?o:o.fa),{hash:{},inverse:s.program(17,n,e),fn:s.program(15,m,e),data:e}),(o||0===o)&&(p+=o),p+="\n </a>\n </div>\n</li>\n",p}),function(a){"use strict";"function"==typeof define&&define.amd?define("bootstrap.wysihtml5",["jquery","wysihtml5","bootstrap","bootstrap.wysihtml5.templates","bootstrap.wysihtml5.commands"],a):a(jQuery,wysihtml5)}(function(a,b){"use strict";var c=function(a,b){var c,d,e,f=function(a,c,d){return b.tpl[a]?b.tpl[a]({locale:c,options:d}):void 0},g=function(c,e){var f,g;this.el=c,f=a.extend(!0,{},d,e);for(g in f.customTemplates)f.customTemplates.hasOwnProperty(g)&&(b.tpl[g]=f.customTemplates[g]);this.toolbar=this.createToolbar(c,f),this.editor=this.createEditor(f)};g.prototype={constructor:g,createEditor:function(b){b=b||{},b=a.extend(!0,{},b),b.toolbar=this.toolbar[0],this.initializeEditor(this.el[0],b)},initializeEditor:function(a,c){var d,e=new b.Editor(this.el[0],c);if(e.on("beforeload",this.syncBootstrapDialogEvents),e.on("beforeload",this.loadParserRules),e.composer.editableArea.contentDocument?this.addMoreShortcuts(e,e.composer.editableArea.contentDocument.body||e.composer.editableArea.contentDocument,c.shortcuts):this.addMoreShortcuts(e,e.composer.editableArea,c.shortcuts),c&&c.events)for(d in c.events)c.events.hasOwnProperty(d)&&e.on(d,c.events[d]);return e},loadParserRules:function(){"string"===a.type(this.config.parserRules)&&a.ajax({dataType:"json",url:this.config.parserRules,context:this,error:function(a,b,c){void 0},success:function(a){this.config.parserRules=a,void 0}}),this.config.pasteParserRulesets&&"string"===a.type(this.config.pasteParserRulesets)&&a.ajax({dataType:"json",url:this.config.pasteParserRulesets,context:this,error:function(a,b,c){void 0},success:function(a){this.config.pasteParserRulesets=a}})},syncBootstrapDialogEvents:function(){var b=this;a.map(this.toolbar.commandMapping,function(a){return[a]}).filter(function(a){return a.dialog}).map(function(a){return a.dialog}).forEach(function(c){c.on("show",function(){a(this.container).modal("show")}),c.on("hide",function(){a(this.container).modal("hide"),setTimeout(b.composer.focus,0)}),a(c.container).on("shown.bs.modal",function(){a(this).find("input, select, textarea").first().focus()})}),this.on("change_view",function(){a(this.toolbar.container.children).find("a.btn").not('[data-wysihtml5-action="change_view"]').toggleClass("disabled")})},createToolbar:function(b,c){var g,h,i=this,j=a("<ul/>",{"class":"wysihtml5-toolbar",style:"display:none"}),k=c.locale||d.locale||"en";e.hasOwnProperty(k)||(void 0,k="en"),g=a.extend(!0,{},e.en,e[k]);for(h in c.toolbar)c.toolbar[h]&&j.append(f(h,g,c));return j.find('a[data-wysihtml5-command="formatBlock"]').click(function(b){var c=b.delegateTarget||b.target||b.srcElement,d=a(c),e=d.data("wysihtml5-display-format-name"),f=d.data("wysihtml5-format-name")||d.html();(void 0===e||"true"===e)&&i.toolbar.find(".current-font").text(f)}),j.find('a[data-wysihtml5-command="foreColor"]').click(function(b){var c=b.target||b.srcElement,d=a(c);i.toolbar.find(".current-color").text(d.html())}),this.el.before(j),j},addMoreShortcuts:function(a,c,d){b.dom.observe(c,"keydown",function(c){var e,f=c.keyCode,g=d[f];(c.ctrlKey||c.metaKey||c.altKey)&&g&&b.commands[g]&&(e=a.toolbar.commandMapping[g+":null"],e&&e.dialog&&!e.state?e.dialog.show():b.commands[g].exec(a.composer,g),c.preventDefault())})}},c={resetDefaults:function(){a.fn.wysihtml5.defaultOptions=a.extend(!0,{},a.fn.wysihtml5.defaultOptionsCache)},bypassDefaults:function(b){return this.each(function(){var c=a(this);c.data("wysihtml5",new g(c,b))})},shallowExtend:function(b){var d=a.extend({},a.fn.wysihtml5.defaultOptions,b||{},a(this).data()),e=this;return c.bypassDefaults.apply(e,[d])},deepExtend:function(b){var d=a.extend(!0,{},a.fn.wysihtml5.defaultOptions,b||{}),e=this;return c.bypassDefaults.apply(e,[d])},init:function(a){var b=this;return c.shallowExtend.apply(b,[a])}},a.fn.wysihtml5=function(b){return c[b]?c[b].apply(this,Array.prototype.slice.call(arguments,1)):"object"!=typeof b&&b?(a.error("Method "+b+" does not exist on jQuery.wysihtml5"),void 0):c.init.apply(this,arguments)},a.fn.wysihtml5.Constructor=g,d=a.fn.wysihtml5.defaultOptions={toolbar:{"font-styles":!0,color:!1,emphasis:{small:!0},blockquote:!0,lists:!0,html:!1,link:!0,image:!0,smallmodals:!1},useLineBreaks:!1,parserRules:{classes:{"wysiwyg-color-silver":1,"wysiwyg-color-gray":1,"wysiwyg-color-white":1,"wysiwyg-color-maroon":1,"wysiwyg-color-red":1,"wysiwyg-color-purple":1,"wysiwyg-color-fuchsia":1,"wysiwyg-color-green":1,"wysiwyg-color-lime":1,"wysiwyg-color-olive":1,"wysiwyg-color-yellow":1,"wysiwyg-color-navy":1,"wysiwyg-color-blue":1,"wysiwyg-color-teal":1,"wysiwyg-color-aqua":1,"wysiwyg-color-orange":1},tags:{b:{},i:{},strong:{},em:{},p:{},br:{},ol:{},ul:{},li:{},h1:{},h2:{},h3:{},h4:{},h5:{},h6:{},blockquote:{},u:1,img:{check_attributes:{width:"numbers",alt:"alt",src:"url",height:"numbers"}},a:{check_attributes:{href:"url"},set_attributes:{target:"_blank",rel:"nofollow"}},span:1,div:1,small:1,code:1,pre:1}},locale:"en",shortcuts:{83:"small",75:"createLink"}},void 0===a.fn.wysihtml5.defaultOptionsCache&&(a.fn.wysihtml5.defaultOptionsCache=a.extend(!0,{},a.fn.wysihtml5.defaultOptions)),e=a.fn.wysihtml5.locale={}};c(a,b)}),function(a){a.commands.small={exec:function(b,c){return a.commands.formatInline.exec(b,c,"small")},state:function(b,c){return a.commands.formatInline.state(b,c,"small")}}}(wysihtml5),function(a){"function"==typeof define&&define.amd?define("bootstrap.wysihtml5.en-US",["jquery","bootstrap.wysihtml5"],a):a(jQuery)}(function(a){a.fn.wysihtml5.locale.en=a.fn.wysihtml5.locale["en-US"]={font_styles:{normal:"Normal text",h1:"Heading 1",h2:"Heading 2",h3:"Heading 3",h4:"Heading 4",h5:"Heading 5",h6:"Heading 6"},emphasis:{bold:"Bold",italic:"Italic",underline:"Underline",small:"Small"},lists:{unordered:"Unordered list",ordered:"Ordered list",outdent:"Outdent",indent:"Indent"},link:{insert:"Insert link",cancel:"Cancel",target:"Open link in new window"},image:{insert:"Insert image",cancel:"Cancel"},html:{edit:"Edit HTML"},colours:{black:"Black",silver:"Silver",gray:"Grey",maroon:"Maroon",red:"Red",purple:"Purple",green:"Green",olive:"Olive",navy:"Navy",blue:"Blue",orange:"Orange"}}});
|
export default {
// define the role name as object key
admin: [
// user model permissions
'user:findAll',
'user:count',
'user:create',
'user:update',
'user:delete',
'user:findOne',
'user:findById',
'user:roles:find',
'user:roles:count',
'user:roles:set',
'user:roles:add',
'user:roles:addMultiple',
// sesion model permissions
'session:findAll',
'session:count',
'session:create',
'session:delete',
'session:findOne',
'session:findById',
'session:user:find',
],
};
|
const Dispatcher = require('../../../core/http/server/dispatcher')
/**
* @memberof Api
* @extends {superhero/core/http/server/dispatcher}
*/
class CreateCalculationEndpoint extends Dispatcher
{
dispatch()
{
const
calculator = this.locator.locate('domain/aggregate/calculator'),
calculationId = calculator.createCalculation()
this.view.body.id = calculationId
}
}
module.exports = CreateCalculationEndpoint
|
import {remote} from 'electron';
import {connect as reduxConnect} from 'react-redux';
// patching Module._load
// so plugins can `require` them wihtout needing their own version
// https://github.com/zeit/hyper/issues/619
import React from 'react';
import ReactDOM from 'react-dom';
import Component from '../component';
import Notification from '../components/notification';
import notify from './notify';
const Module = require('module'); // eslint-disable-line import/newline-after-import
const originalLoad = Module._load;
Module._load = function (path) {
switch (path) {
case 'react':
return React;
case 'react-dom':
return ReactDOM;
case 'hyper/component':
return Component;
case 'hyper/notify':
return notify;
case 'hyper/Notification':
return Notification;
case 'hyper/decorate':
return decorate;
default:
return originalLoad.apply(this, arguments);
}
};
// remote interface to `../plugins`
const plugins = remote.require('./plugins');
// `require`d modules
let modules;
// cache of decorated components
let decorated = {};
// various caches extracted of the plugin methods
let connectors;
let middlewares;
let uiReducers;
let sessionsReducers;
let termGroupsReducers;
let tabPropsDecorators;
let tabsPropsDecorators;
let termPropsDecorators;
let termGroupPropsDecorators;
let propsDecorators;
let reducersDecorators;
// the fs locations where user plugins are stored
const {path, localPath} = plugins.getBasePaths();
const clearModulesCache = () => {
// trigger unload hooks
modules.forEach(mod => {
if (mod.onRendererUnload) {
mod.onRendererUnload(window);
}
});
// clear require cache
for (const entry in window.require.cache) {
if (entry.indexOf(path) === 0 || entry.indexOf(localPath) === 0) {
// `require` is webpacks', `window.require` is electron's
delete window.require.cache[entry];
}
}
};
const getPluginName = path => window.require('path').basename(path);
const loadModules = () => {
console.log('(re)loading renderer plugins');
const paths = plugins.getPaths();
// initialize cache that we populate with extension methods
connectors = {
Terms: {state: [], dispatch: []},
Header: {state: [], dispatch: []},
Hyper: {state: [], dispatch: []},
Notifications: {state: [], dispatch: []}
};
uiReducers = [];
middlewares = [];
sessionsReducers = [];
termGroupsReducers = [];
tabPropsDecorators = [];
tabsPropsDecorators = [];
termPropsDecorators = [];
termGroupPropsDecorators = [];
propsDecorators = {
getTermProps: termPropsDecorators,
getTabProps: tabPropsDecorators,
getTabsProps: tabsPropsDecorators,
getTermGroupProps: termGroupPropsDecorators
};
reducersDecorators = {
reduceUI: uiReducers,
reduceSessions: sessionsReducers,
reduceTermGroups: termGroupsReducers
};
modules = paths.plugins.concat(paths.localPlugins)
.map(path => {
let mod;
const pluginName = getPluginName(path);
// window.require allows us to ensure this doesn't get
// in the way of our build
try {
mod = window.require(path);
} catch (err) {
console.error(err.stack);
notify('Plugin load error', `"${pluginName}" failed to load in the renderer process. Check Developer Tools for details.`);
return undefined;
}
for (const i in mod) {
if ({}.hasOwnProperty.call(mod, i)) {
mod[i]._pluginName = pluginName;
}
}
// mapHyperTermState mapping for backwards compatibility with hyperterm
if (mod.mapHyperTermState) {
mod.mapHyperState = mod.mapHyperTermState;
console.error('mapHyperTermState is deprecated. Use mapHyperState instead.');
}
// mapHyperTermDispatch mapping for backwards compatibility with hyperterm
if (mod.mapHyperTermDispatch) {
mod.mapHyperDispatch = mod.mapHyperTermDispatch;
console.error('mapHyperTermDispatch is deprecated. Use mapHyperDispatch instead.');
}
if (mod.middleware) {
middlewares.push(mod.middleware);
}
if (mod.reduceUI) {
uiReducers.push(mod.reduceUI);
}
if (mod.reduceSessions) {
sessionsReducers.push(mod.reduceSessions);
}
if (mod.reduceTermGroups) {
termGroupsReducers.push(mod.reduceTermGroups);
}
if (mod.mapTermsState) {
connectors.Terms.state.push(mod.mapTermsState);
}
if (mod.mapTermsDispatch) {
connectors.Terms.dispatch.push(mod.mapTermsDispatch);
}
if (mod.mapHeaderState) {
connectors.Header.state.push(mod.mapHeaderState);
}
if (mod.mapHeaderDispatch) {
connectors.Header.dispatch.push(mod.mapHeaderDispatch);
}
if (mod.mapHyperState) {
connectors.Hyper.state.push(mod.mapHyperState);
}
if (mod.mapHyperDispatch) {
connectors.Hyper.dispatch.push(mod.mapHyperDispatch);
}
if (mod.mapNotificationsState) {
connectors.Notifications.state.push(mod.mapNotificationsState);
}
if (mod.mapNotificationsDispatch) {
connectors.Notifications.dispatch.push(mod.mapNotificationsDispatch);
}
if (mod.getTermGroupProps) {
termGroupPropsDecorators.push(mod.getTermGroupProps);
}
if (mod.getTermProps) {
termPropsDecorators.push(mod.getTermProps);
}
if (mod.getTabProps) {
tabPropsDecorators.push(mod.getTabProps);
}
if (mod.getTabsProps) {
tabsPropsDecorators.push(mod.getTabsProps);
}
if (mod.onRendererWindow) {
mod.onRendererWindow(window);
}
return mod;
})
.filter(mod => Boolean(mod));
};
// load modules for initial decoration
loadModules();
export function reload() {
clearModulesCache();
loadModules();
// trigger re-decoration when components
// get re-rendered
decorated = {};
}
function getProps(name, props, ...fnArgs) {
const decorators = propsDecorators[name];
let props_;
decorators.forEach(fn => {
let ret_;
if (!props_) {
props_ = Object.assign({}, props);
}
try {
ret_ = fn(...fnArgs, props_);
} catch (err) {
console.error(err.stack);
notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`);
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\` (object expected).`);
return;
}
props_ = ret_;
});
return props_ || props;
}
export function getTermGroupProps(uid, parentProps, props) {
return getProps('getTermGroupProps', props, uid, parentProps);
}
export function getTermProps(uid, parentProps, props) {
return getProps('getTermProps', props, uid, parentProps);
}
export function getTabsProps(parentProps, props) {
return getProps('getTabsProps', props, parentProps);
}
export function getTabProps(tab, parentProps, props) {
return getProps('getTabProps', props, tab, parentProps);
}
// connects + decorates a class
// plugins can override mapToState, dispatchToProps
// and the class gets decorated (proxied)
export function connect(stateFn, dispatchFn, c, d = {}) {
return (Class, name) => {
return reduxConnect(
state => {
let ret = stateFn(state);
connectors[name].state.forEach(fn => {
let ret_;
try {
ret_ = fn(state, ret);
} catch (err) {
console.error(err.stack);
notify('Plugin error', `${fn._pluginName}: Error occurred in \`map${name}State\`. Check Developer Tools for details.`);
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}State\` (object expected).`);
return;
}
ret = ret_;
});
return ret;
},
dispatch => {
let ret = dispatchFn(dispatch);
connectors[name].dispatch.forEach(fn => {
let ret_;
try {
ret_ = fn(dispatch, ret);
} catch (err) {
console.error(err.stack);
notify('Plugin error', `${fn._pluginName}: Error occurred in \`map${name}Dispatch\`. Check Developer Tools for details.`);
return;
}
if (!ret_ || typeof ret_ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`map${name}Dispatch\` (object expected).`);
return;
}
ret = ret_;
});
return ret;
},
c,
d
)(decorate(Class, name));
};
}
function decorateReducer(name, fn) {
const reducers = reducersDecorators[name];
return (state, action) => {
let state_ = fn(state, action);
reducers.forEach(pluginReducer => {
let state__;
try {
state__ = pluginReducer(state_, action);
} catch (err) {
console.error(err.stack);
notify('Plugin error', `${fn._pluginName}: Error occurred in \`${name}\`. Check Developer Tools for details.`);
return;
}
if (!state__ || typeof state__ !== 'object') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${name}\`.`);
return;
}
state_ = state__;
});
return state_;
};
}
export function decorateTermGroupsReducer(fn) {
return decorateReducer('reduceTermGroups', fn);
}
export function decorateUIReducer(fn) {
return decorateReducer('reduceUI', fn);
}
export function decorateSessionsReducer(fn) {
return decorateReducer('reduceSessions', fn);
}
// redux middleware generator
export const middleware = store => next => action => {
const nextMiddleware = remaining => action => remaining.length ?
remaining[0](store)(nextMiddleware(remaining.slice(1)))(action) :
next(action);
nextMiddleware(middlewares)(action);
};
// expose decorated component instance to the higher-order components
function exposeDecorated(Component) {
return class extends React.Component {
constructor(props, context) {
super(props, context);
this.onRef = this.onRef.bind(this);
}
onRef(decorated) {
if (this.props.onDecorated) {
this.props.onDecorated(decorated);
}
}
render() {
return React.createElement(Component, Object.assign({}, this.props, {ref: this.onRef}));
}
};
}
function getDecorated(parent, name) {
if (!decorated[name]) {
let class_ = exposeDecorated(parent);
class_.displayName = `_exposeDecorated(${name})`;
modules.forEach(mod => {
const method = 'decorate' + name;
const fn = mod[method];
if (fn) {
let class__;
try {
class__ = fn(class_, {React, Component, Notification, notify});
class__.displayName = `${fn._pluginName}(${name})`;
} catch (err) {
console.error(err.stack);
notify('Plugin error', `${fn._pluginName}: Error occurred in \`${method}\`. Check Developer Tools for details`);
return;
}
if (!class__ || typeof class__.prototype.render !== 'function') {
notify('Plugin error', `${fn._pluginName}: Invalid return value of \`${method}\`. No \`render\` method found. Please return a \`React.Component\`.`);
return;
}
class_ = class__;
}
});
decorated[name] = class_;
}
return decorated[name];
}
// for each component, we return a higher-order component
// that wraps with the higher-order components
// exposed by plugins
export function decorate(Component, name) {
return class extends React.Component {
render() {
const Sub = getDecorated(Component, name);
return React.createElement(Sub, this.props);
}
};
}
|
require('dotenv').config();
module.exports = (Discord, client, message) => {
const prefix = process.env.BOT_PREFIX;
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
if(command) command.execute(client, cmd, message, args, Discord);
}
|
var searchData=
[
['graph',['Graph',['../classlitegraph_1_1Graph.html#a12cc129bd0eb148e5703d810a825318b',1,'litegraph::Graph']]]
];
|
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var path_1 = __importDefault(require("path"));
var dotenv = __importStar(require("dotenv"));
var dotenv_expand_1 = __importDefault(require("dotenv-expand"));
/**
* @param {string} dir The directory containing the .env files to load.
*/
function processEnv(dir) {
// replicate Next.js handling/behavior, but without a default NODE_ENV
// https://github.com/vercel/next.js/blob/v10.0.5/packages/next-env/index.ts#L80-L90
var mode = process.env.NODE_ENV;
var dotenvFiles = [
mode && ".env." + mode + ".local",
// Don't include `.env.local` for `test` environment
// since normally you expect tests to produce the same
// results for everyone
mode !== 'test' && '.env.local',
mode && ".env." + mode,
'.env',
].filter(Boolean);
// inspired by https://github.com/entropitor/dotenv-cli/blob/v4.0.0/cli.js#L53-L55
dotenvFiles.forEach(function (env) {
dotenv_expand_1.default(dotenv.config({ path: path_1.default.resolve(dir, env) }));
});
}
exports.default = processEnv;
|
!(function(e, i, n, t) {
'use strict';
(i = void 0 !== i && i.Math == Math ? i : 'undefined' != typeof self && self.Math == Math ? self : Function('return this')()),
(e.fn.sidebar = function(t) {
var o,
r = e(this),
s = e(i),
a = e(n),
l = e('html'),
c = e('head'),
d = r.selector || '',
u = new Date().getTime(),
f = [],
b = arguments[0],
h = 'string' == typeof b,
m = [].slice.call(arguments, 1),
v =
i.requestAnimationFrame ||
i.mozRequestAnimationFrame ||
i.webkitRequestAnimationFrame ||
i.msRequestAnimationFrame ||
function(e) {
setTimeout(e, 0);
};
return (
r.each(function() {
var r,
g,
p,
y,
C,
k,
w = e.isPlainObject(t) ? e.extend(!0, {}, e.fn.sidebar.settings, t) : e.extend({}, e.fn.sidebar.settings),
T = w.selector,
x = w.className,
S = w.namespace,
A = w.regExp,
F = w.error,
O = '.' + S,
P = 'module-' + S,
E = e(this),
H = e(w.context),
M = E.children(T.sidebar),
D = H.children(T.fixed),
j = H.children(T.pusher),
R = this,
z = E.data(P);
(k = {
initialize: function() {
k.debug('Initializing sidebar', t),
k.create.id(),
(C = k.get.transitionEvent()),
w.delaySetup ? v(k.setup.layout) : k.setup.layout(),
v(function() {
k.setup.cache();
}),
k.instantiate();
},
instantiate: function() {
k.verbose('Storing instance of module', k), (z = k), E.data(P, k);
},
create: {
id: function() {
(p = (Math.random().toString(16) + '000000000').substr(2, 8)), (g = '.' + p), k.verbose('Creating unique id for element', p);
}
},
destroy: function() {
k.verbose('Destroying previous module for', E), E.off(O).removeData(P), k.is.ios() && k.remove.ios(), H.off(g), s.off(g), a.off(g);
},
event: {
clickaway: function(e) {
var i = j.find(e.target).length > 0 || j.is(e.target),
n = H.is(e.target);
i && (k.verbose('User clicked on dimmed page'), k.hide()), n && (k.verbose('User clicked on dimmable context (scaled out page)'), k.hide());
},
touch: function(e) {},
containScroll: function(e) {
R.scrollTop <= 0 && (R.scrollTop = 1), R.scrollTop + R.offsetHeight >= R.scrollHeight && (R.scrollTop = R.scrollHeight - R.offsetHeight - 1);
},
scroll: function(i) {
0 === e(i.target).closest(T.sidebar).length && i.preventDefault();
}
},
bind: {
clickaway: function() {
k.verbose('Adding clickaway events to context', H), w.closable && H.on('click' + g, k.event.clickaway).on('touchend' + g, k.event.clickaway);
},
scrollLock: function() {
w.scrollLock && (k.debug('Disabling page scroll'), s.on('DOMMouseScroll' + g, k.event.scroll)),
k.verbose('Adding events to contain sidebar scroll'),
a.on('touchmove' + g, k.event.touch),
E.on('scroll' + O, k.event.containScroll);
}
},
unbind: {
clickaway: function() {
k.verbose('Removing clickaway events from context', H), H.off(g);
},
scrollLock: function() {
k.verbose('Removing scroll lock from page'), a.off(g), s.off(g), E.off('scroll' + O);
}
},
add: {
inlineCSS: function() {
var i,
n = k.cache.width || E.outerWidth(),
t = k.cache.height || E.outerHeight(),
o = k.is.rtl(),
s = k.get.direction(),
a = { left: n, right: -n, top: t, bottom: -t };
o && (k.verbose('RTL detected, flipping widths'), (a.left = -n), (a.right = n)),
(i = '<style>'),
'left' === s || 'right' === s
? (k.debug('Adding CSS rules for animation distance', n),
(i +=
' .ui.visible.' +
s +
'.sidebar ~ .fixed, .ui.visible.' +
s +
'.sidebar ~ .pusher { -webkit-transform: translate3d(' +
a[s] +
'px, 0, 0); transform: translate3d(' +
a[s] +
'px, 0, 0); }'))
: ('top' !== s && 'bottom' != s) ||
(i +=
' .ui.visible.' +
s +
'.sidebar ~ .fixed, .ui.visible.' +
s +
'.sidebar ~ .pusher { -webkit-transform: translate3d(0, ' +
a[s] +
'px, 0); transform: translate3d(0, ' +
a[s] +
'px, 0); }'),
k.is.ie() &&
('left' === s || 'right' === s
? (k.debug('Adding CSS rules for animation distance', n),
(i +=
' body.pushable > .ui.visible.' +
s +
'.sidebar ~ .pusher:after { -webkit-transform: translate3d(' +
a[s] +
'px, 0, 0); transform: translate3d(' +
a[s] +
'px, 0, 0); }'))
: ('top' !== s && 'bottom' != s) ||
(i +=
' body.pushable > .ui.visible.' +
s +
'.sidebar ~ .pusher:after { -webkit-transform: translate3d(0, ' +
a[s] +
'px, 0); transform: translate3d(0, ' +
a[s] +
'px, 0); }'),
(i +=
' body.pushable > .ui.visible.left.sidebar ~ .ui.visible.right.sidebar ~ .pusher:after, body.pushable > .ui.visible.right.sidebar ~ .ui.visible.left.sidebar ~ .pusher:after { -webkit-transform: translate3d(0px, 0, 0); transform: translate3d(0px, 0, 0); }')),
(i += '</style>'),
(r = e(i).appendTo(c)),
k.debug('Adding sizing css to head', r);
}
},
refresh: function() {
k.verbose('Refreshing selector cache'),
(H = e(w.context)),
(M = H.children(T.sidebar)),
(j = H.children(T.pusher)),
(D = H.children(T.fixed)),
k.clear.cache();
},
refreshSidebars: function() {
k.verbose('Refreshing other sidebars'), (M = H.children(T.sidebar));
},
repaint: function() {
k.verbose('Forcing repaint event'), (R.style.display = 'none');
R.offsetHeight;
(R.scrollTop = R.scrollTop), (R.style.display = '');
},
setup: {
cache: function() {
k.cache = { width: E.outerWidth(), height: E.outerHeight(), rtl: 'rtl' == E.css('direction') };
},
layout: function() {
0 === H.children(T.pusher).length &&
(k.debug('Adding wrapper element for sidebar'),
k.error(F.pusher),
(j = e('<div class="pusher" />')),
H.children()
.not(T.omitted)
.not(M)
.wrapAll(j),
k.refresh()),
(0 !== E.nextAll(T.pusher).length && E.nextAll(T.pusher)[0] === j[0]) ||
(k.debug('Moved sidebar to correct parent element'), k.error(F.movedSidebar, R), E.detach().prependTo(H), k.refresh()),
k.clear.cache(),
k.set.pushable(),
k.set.direction();
}
},
attachEvents: function(i, n) {
var t = e(i);
(n = e.isFunction(k[n]) ? k[n] : k.toggle),
t.length > 0 ? (k.debug('Attaching sidebar events to element', i, n), t.on('click' + O, n)) : k.error(F.notFound, i);
},
show: function(i) {
if (((i = e.isFunction(i) ? i : function() {}), k.is.hidden())) {
if ((k.refreshSidebars(), w.overlay && (k.error(F.overlay), (w.transition = 'overlay')), k.refresh(), k.othersActive()))
if ((k.debug('Other sidebars currently visible'), w.exclusive)) {
if ('overlay' != w.transition) return void k.hideOthers(k.show);
k.hideOthers();
} else w.transition = 'overlay';
k.pushPage(function() {
i.call(R), w.onShow.call(R);
}),
w.onChange.call(R),
w.onVisible.call(R);
} else k.debug('Sidebar is already visible');
},
hide: function(i) {
(i = e.isFunction(i) ? i : function() {}),
(k.is.visible() || k.is.animating()) &&
(k.debug('Hiding sidebar', i),
k.refreshSidebars(),
k.pullPage(function() {
i.call(R), w.onHidden.call(R);
}),
w.onChange.call(R),
w.onHide.call(R));
},
othersAnimating: function() {
return M.not(E).filter('.' + x.animating).length > 0;
},
othersVisible: function() {
return M.not(E).filter('.' + x.visible).length > 0;
},
othersActive: function() {
return k.othersVisible() || k.othersAnimating();
},
hideOthers: function(e) {
var i = M.not(E).filter('.' + x.visible),
n = i.length,
t = 0;
(e = e || function() {}),
i.sidebar('hide', function() {
++t == n && e();
});
},
toggle: function() {
k.verbose('Determining toggled direction'), k.is.hidden() ? k.show() : k.hide();
},
pushPage: function(i) {
var n,
t,
o,
r = k.get.transition(),
s = 'overlay' === r || k.othersActive() ? E : j;
(i = e.isFunction(i) ? i : function() {}),
'scale down' == w.transition && k.scrollToTop(),
k.set.transition(r),
k.repaint(),
(n = function() {
k.bind.clickaway(), k.add.inlineCSS(), k.set.animating(), k.set.visible();
}),
(t = function() {
k.set.dimmed();
}),
(o = function(e) {
e.target == s[0] && (s.off(C + g, o), k.remove.animating(), k.bind.scrollLock(), i.call(R));
}),
s.off(C + g),
s.on(C + g, o),
v(n),
w.dimPage && !k.othersVisible() && v(t);
},
pullPage: function(i) {
var n,
t,
o = k.get.transition(),
r = 'overlay' == o || k.othersActive() ? E : j;
(i = e.isFunction(i) ? i : function() {}),
k.verbose('Removing context push state', k.get.direction()),
k.unbind.clickaway(),
k.unbind.scrollLock(),
(n = function() {
k.set.transition(o), k.set.animating(), k.remove.visible(), w.dimPage && !k.othersVisible() && j.removeClass(x.dimmed);
}),
(t = function(e) {
e.target == r[0] &&
(r.off(C + g, t),
k.remove.animating(),
k.remove.transition(),
k.remove.inlineCSS(),
('scale down' == o || (w.returnScroll && k.is.mobile())) && k.scrollBack(),
i.call(R));
}),
r.off(C + g),
r.on(C + g, t),
v(n);
},
scrollToTop: function() {
k.verbose('Scrolling to top of page to avoid animation issues'), (y = e(i).scrollTop()), E.scrollTop(0), i.scrollTo(0, 0);
},
scrollBack: function() {
k.verbose('Scrolling back to original page position'), i.scrollTo(0, y);
},
clear: {
cache: function() {
k.verbose('Clearing cached dimensions'), (k.cache = {});
}
},
set: {
ios: function() {
l.addClass(x.ios);
},
pushed: function() {
H.addClass(x.pushed);
},
pushable: function() {
H.addClass(x.pushable);
},
dimmed: function() {
j.addClass(x.dimmed);
},
active: function() {
E.addClass(x.active);
},
animating: function() {
E.addClass(x.animating);
},
transition: function(e) {
(e = e || k.get.transition()), E.addClass(e);
},
direction: function(e) {
(e = e || k.get.direction()), E.addClass(x[e]);
},
visible: function() {
E.addClass(x.visible);
},
overlay: function() {
E.addClass(x.overlay);
}
},
remove: {
inlineCSS: function() {
k.debug('Removing inline css styles', r), r && r.length > 0 && r.remove();
},
ios: function() {
l.removeClass(x.ios);
},
pushed: function() {
H.removeClass(x.pushed);
},
pushable: function() {
H.removeClass(x.pushable);
},
active: function() {
E.removeClass(x.active);
},
animating: function() {
E.removeClass(x.animating);
},
transition: function(e) {
(e = e || k.get.transition()), E.removeClass(e);
},
direction: function(e) {
(e = e || k.get.direction()), E.removeClass(x[e]);
},
visible: function() {
E.removeClass(x.visible);
},
overlay: function() {
E.removeClass(x.overlay);
}
},
get: {
direction: function() {
return E.hasClass(x.top) ? x.top : E.hasClass(x.right) ? x.right : E.hasClass(x.bottom) ? x.bottom : x.left;
},
transition: function() {
var e,
i = k.get.direction();
return (
(e = k.is.mobile()
? 'auto' == w.mobileTransition
? w.defaultTransition.mobile[i]
: w.mobileTransition
: 'auto' == w.transition
? w.defaultTransition.computer[i]
: w.transition),
k.verbose('Determined transition', e),
e
);
},
transitionEvent: function() {
var e,
i = n.createElement('element'),
t = { transition: 'transitionend', OTransition: 'oTransitionEnd', MozTransition: 'transitionend', WebkitTransition: 'webkitTransitionEnd' };
for (e in t) if (void 0 !== i.style[e]) return t[e];
}
},
is: {
ie: function() {
var e = !i.ActiveXObject && 'ActiveXObject' in i,
n = 'ActiveXObject' in i;
return e || n;
},
ios: function() {
var e = navigator.userAgent,
i = e.match(A.ios),
n = e.match(A.mobileChrome);
return !(!i || n) && (k.verbose('Browser was found to be iOS', e), !0);
},
mobile: function() {
var e = navigator.userAgent;
return e.match(A.mobile)
? (k.verbose('Browser was found to be mobile', e), !0)
: (k.verbose('Browser is not mobile, using regular transition', e), !1);
},
hidden: function() {
return !k.is.visible();
},
visible: function() {
return E.hasClass(x.visible);
},
open: function() {
return k.is.visible();
},
closed: function() {
return k.is.hidden();
},
vertical: function() {
return E.hasClass(x.top);
},
animating: function() {
return H.hasClass(x.animating);
},
rtl: function() {
return void 0 === k.cache.rtl && (k.cache.rtl = 'rtl' == E.css('direction')), k.cache.rtl;
}
},
setting: function(i, n) {
if ((k.debug('Changing setting', i, n), e.isPlainObject(i))) e.extend(!0, w, i);
else {
if (void 0 === n) return w[i];
e.isPlainObject(w[i]) ? e.extend(!0, w[i], n) : (w[i] = n);
}
},
internal: function(i, n) {
if (e.isPlainObject(i)) e.extend(!0, k, i);
else {
if (void 0 === n) return k[i];
k[i] = n;
}
},
debug: function() {
!w.silent &&
w.debug &&
(w.performance
? k.performance.log(arguments)
: ((k.debug = Function.prototype.bind.call(console.info, console, w.name + ':')), k.debug.apply(console, arguments)));
},
verbose: function() {
!w.silent &&
w.verbose &&
w.debug &&
(w.performance
? k.performance.log(arguments)
: ((k.verbose = Function.prototype.bind.call(console.info, console, w.name + ':')), k.verbose.apply(console, arguments)));
},
error: function() {
w.silent || ((k.error = Function.prototype.bind.call(console.error, console, w.name + ':')), k.error.apply(console, arguments));
},
performance: {
log: function(e) {
var i, n, t;
w.performance &&
((i = new Date().getTime()),
(t = u || i),
(n = i - t),
(u = i),
f.push({ Name: e[0], Arguments: [].slice.call(e, 1) || '', Element: R, 'Execution Time': n })),
clearTimeout(k.performance.timer),
(k.performance.timer = setTimeout(k.performance.display, 500));
},
display: function() {
var i = w.name + ':',
n = 0;
(u = !1),
clearTimeout(k.performance.timer),
e.each(f, function(e, i) {
n += i['Execution Time'];
}),
(i += ' ' + n + 'ms'),
d && (i += " '" + d + "'"),
(void 0 !== console.group || void 0 !== console.table) &&
f.length > 0 &&
(console.groupCollapsed(i),
console.table
? console.table(f)
: e.each(f, function(e, i) {
console.log(i.Name + ': ' + i['Execution Time'] + 'ms');
}),
console.groupEnd()),
(f = []);
}
},
invoke: function(i, n, t) {
var r,
s,
a,
l = z;
return (
(n = n || m),
(t = R || t),
'string' == typeof i &&
void 0 !== l &&
((i = i.split(/[\. ]/)),
(r = i.length - 1),
e.each(i, function(n, t) {
var o = n != r ? t + i[n + 1].charAt(0).toUpperCase() + i[n + 1].slice(1) : i;
if (e.isPlainObject(l[o]) && n != r) l = l[o];
else {
if (void 0 !== l[o]) return (s = l[o]), !1;
if (!e.isPlainObject(l[t]) || n == r) return void 0 !== l[t] ? ((s = l[t]), !1) : (k.error(F.method, i), !1);
l = l[t];
}
})),
e.isFunction(s) ? (a = s.apply(t, n)) : void 0 !== s && (a = s),
e.isArray(o) ? o.push(a) : void 0 !== o ? (o = [o, a]) : void 0 !== a && (o = a),
s
);
}
}),
h ? (void 0 === z && k.initialize(), k.invoke(b)) : (void 0 !== z && k.invoke('destroy'), k.initialize());
}),
void 0 !== o ? o : this
);
}),
(e.fn.sidebar.settings = {
name: 'Sidebar',
namespace: 'sidebar',
silent: !1,
debug: !1,
verbose: !1,
performance: !0,
transition: 'auto',
mobileTransition: 'auto',
defaultTransition: {
computer: { left: 'uncover', right: 'uncover', top: 'overlay', bottom: 'overlay' },
mobile: { left: 'uncover', right: 'uncover', top: 'overlay', bottom: 'overlay' }
},
context: 'body',
exclusive: !1,
closable: !0,
dimPage: !0,
scrollLock: !1,
returnScroll: !1,
delaySetup: !1,
duration: 500,
onChange: function() {},
onShow: function() {},
onHide: function() {},
onHidden: function() {},
onVisible: function() {},
className: {
active: 'active',
animating: 'animating',
dimmed: 'dimmed',
ios: 'ios',
pushable: 'pushable',
pushed: 'pushed',
right: 'right',
top: 'top',
left: 'left',
bottom: 'bottom',
visible: 'visible'
},
selector: { fixed: '.fixed', omitted: 'script, link, style, .ui.modal, .ui.dimmer, .ui.nag, .ui.fixed', pusher: '.pusher', sidebar: '.ui.sidebar' },
regExp: {
ios: /(iPad|iPhone|iPod)/g,
mobileChrome: /(CriOS)/g,
mobile: /Mobile|iP(hone|od|ad)|Android|BlackBerry|IEMobile|Kindle|NetFront|Silk-Accelerated|(hpw|web)OS|Fennec|Minimo|Opera M(obi|ini)|Blazer|Dolfin|Dolphin|Skyfire|Zune/g
},
error: {
method: 'The method you called is not defined.',
pusher: 'Had to add pusher element. For optimal performance make sure body content is inside a pusher element',
movedSidebar: 'Had to move sidebar. For optimal performance make sure sidebar and pusher are direct children of your body tag',
overlay: 'The overlay setting is no longer supported, use animation: overlay',
notFound: 'There were no elements that matched the specified selector'
}
});
})(jQuery, window, document);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const insert_select_1 = require("../../insert-select");
const table_1 = require("../../../table");
const column_ref_1 = require("../../../column-ref");
function insertSelect(query, modifier, table, delegate) {
if (!table.insertAllowed) {
throw new Error(`Cannot SELECT ... INSERT into table ${table.alias}`);
}
const ref = column_ref_1.ColumnRefUtil.fromSelectItemArray(query._selects);
const row = delegate(column_ref_1.ColumnRefUtil.toConvenient(ref));
for (let columnName of table_1.TableUtil.requiredColumnNames(table)) {
if (!(columnName in row)) {
throw new Error(`A value for ${table.alias}.${columnName} is required`);
}
}
return new insert_select_1.InsertSelect({
_query: query,
_table: table,
_row: row,
_modifier: modifier,
});
}
exports.insertSelect = insertSelect;
//# sourceMappingURL=insert-select.js.map
|
import PropTypes from 'prop-types'
import cn from 'classnames'
import scrollbarSize from 'dom-helpers/util/scrollbarSize'
import React from 'react'
import dates from './utils/dates'
import { elementType, accessor, dateFormat } from './utils/propTypes'
import localizer from './localizer'
import DateContentRow from './DateContentRow'
import Header from './Header'
import { notify } from './utils/helpers'
import { accessor as get } from './utils/accessors'
class TimeGridHeader extends React.Component {
static propTypes = {
range: PropTypes.array.isRequired,
events: PropTypes.array.isRequired,
resources: PropTypes.array,
getNow: PropTypes.func.isRequired,
isOverflowing: PropTypes.bool,
dayFormat: dateFormat,
eventPropGetter: PropTypes.func,
dayPropGetter: PropTypes.func,
culture: PropTypes.string,
rtl: PropTypes.bool,
width: PropTypes.number,
titleAccessor: accessor.isRequired,
tooltipAccessor: accessor.isRequired,
allDayAccessor: accessor.isRequired,
startAccessor: accessor.isRequired,
endAccessor: accessor.isRequired,
resourceAccessor: accessor.isRequired,
resourceIdAccessor: accessor.isRequired,
resourceTitleAccessor: accessor.isRequired,
selected: PropTypes.object,
selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
longPressThreshold: PropTypes.number,
headerComponent: elementType,
eventComponent: elementType,
eventWrapperComponent: elementType.isRequired,
dateCellWrapperComponent: elementType,
timeGutterHeaderComponent: elementType,
onSelectSlot: PropTypes.func,
onSelectEvent: PropTypes.func,
onDoubleClickEvent: PropTypes.func,
onDrillDown: PropTypes.func,
getDrilldownView: PropTypes.func.isRequired,
}
static defaultProps = {
headerComponent: Header,
}
handleHeaderClick = (date, view, e) => {
e.preventDefault()
notify(this.props.onDrillDown, [date, view])
}
renderHeaderResources(range, resources) {
const { resourceTitleAccessor, getNow } = this.props
const today = getNow()
return range.map((date, i) => {
return resources.map((resource, j) => {
return (
<div
key={`${i}-${j}`}
className={cn(
'rbc-header',
dates.eq(date, today, 'day') && 'rbc-today'
)}
>
{get(resource, resourceTitleAccessor)}
</div>
)
})
})
}
renderHeaderCells(range) {
let {
dayFormat,
culture,
dayPropGetter,
getDrilldownView,
getNow,
headerComponent: Header,
} = this.props
const today = getNow()
return range.map((date, i) => {
let drilldownView = getDrilldownView(date)
let label = localizer.format(date, dayFormat, culture)
const { className, style } = (dayPropGetter && dayPropGetter(date)) || {}
let header = (
<Header
date={date}
label={label}
localizer={localizer}
format={dayFormat}
culture={culture}
/>
)
return (
<div
key={i}
style={style}
className={cn(
'rbc-header',
className,
dates.eq(date, today, 'day') && 'rbc-today'
)}
>
{drilldownView ? (
<a
href="#"
onClick={e => this.handleHeaderClick(date, drilldownView, e)}
>
{header}
</a>
) : (
<span>{header}</span>
)}
</div>
)
})
}
render() {
let {
width,
events,
rtl,
selectable,
resources,
getNow,
range,
isOverflowing,
eventComponent,
dateCellWrapperComponent,
eventWrapperComponent,
timeGutterHeaderComponent: TimeGutterHeader,
} = this.props
let style = {}
if (isOverflowing) {
style[rtl ? 'marginLeft' : 'marginRight'] = `${scrollbarSize()}px`
}
return (
<div
ref="headerCell"
style={style}
className={cn('rbc-time-header', isOverflowing && 'rbc-overflowing')}
>
<div className="rbc-label rbc-time-header-gutter" style={{ width }}>
{TimeGutterHeader && <TimeGutterHeader />}
</div>
<div className="rbc-time-header-content">
<div className="rbc-row rbc-time-header-cell">
{this.renderHeaderCells(range)}
</div>
{resources && (
<div className="rbc-row rbc-row-resource">
{this.renderHeaderResources(range, resources)}
</div>
)}
<DateContentRow
isAllDay
rtl={rtl}
getNow={getNow}
minRows={2}
range={range}
events={events}
className="rbc-allday-cell"
selectable={selectable}
selected={this.props.selected}
eventComponent={eventComponent}
eventWrapperComponent={eventWrapperComponent}
dateCellWrapperComponent={dateCellWrapperComponent}
dayPropGetter={this.props.dayPropGetter}
titleAccessor={this.props.titleAccessor}
tooltipAccessor={this.props.tooltipAccessor}
startAccessor={this.props.startAccessor}
endAccessor={this.props.endAccessor}
allDayAccessor={this.props.allDayAccessor}
eventPropGetter={this.props.eventPropGetter}
onSelect={this.props.onSelectEvent}
onDoubleClick={this.props.onDoubleClickEvent}
onSelectSlot={this.props.onSelectSlot}
longPressThreshold={this.props.longPressThreshold}
/>
</div>
</div>
)
}
}
export default TimeGridHeader
|
/*global defineSuite*/
defineSuite([
'Core/definedNotNull'
], function(
definedNotNull) {
"use strict";
it('works', function() {
expect(definedNotNull(0)).toEqual(true);
expect(definedNotNull(undefined)).toEqual(false);
expect(definedNotNull(null)).toEqual(false);
});
});
|
import React from "react";
import Navbar from "./Navbar";
import Footer from "./Footer";
import OportunidadesBody from "./OportunidadesBody";
import Oportunidade from "./Header_oportunidades";
import Barra_footer_oportunidades from "./Barra_footer_oportunidades";
const Oportunidades = () => {
return (
<>
<Navbar/>
<Oportunidade/>
<OportunidadesBody/>
<Barra_footer_oportunidades/>
<Footer/>
</>
);
}
export default Oportunidades;
|
import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Checkbox from '@material-ui/core/Checkbox';
import axios from 'axios';
import Modal from '../Modal/Modal';
import { ROOT_URL } from '../../config';
import CR_Title from '../../media/images/cr_title.png';
import { Icons } from '../../media/icons';
class Landing extends Component {
constructor(props) {
super(props);
this.modal = props.modal.bind(this);
this.state = {
email: '',
username: '',
password: '',
vpassword: '',
match: true,
agree: false,
signin: true
};
}
componentDidMount() {
if (this.props.location.pathname.includes('verify')) {
const key = this.props.match.params.key;
axios
.post(`${ROOT_URL.API}/auth/verify`, { key })
.then(() => {
this.modal(<p>Successfully validated email. You can now login</p>);
this.setState({ validated: true });
})
.catch((err) => {
if (err.response) {
if (err.response.data.code === 'EXPTOKEN') {
this.modal(<p>Token is expired. Please request a new one.</p>);
}
} else {
this.modal(<p>Failed to validate email. Please try again!</p>, () => {
this.modal(
// Create a small input form to grab email from user
<React.Fragment>
<p>Please input your email address to resend the verification email.</p>
<TextField
className="landing-input"
label="Email"
margin="normal"
onChange={this.handleChange('email')}
type="text"
/>
</React.Fragment>,
this.resendEmail
);
});
}
this.setState({ validated: false });
});
}
}
resendEmail = () => {
const { email } = this.state;
axios
.post(`${ROOT_URL.API}/auth/sendverifyemail`, { email })
.then(() => {
this.modal(<p>Successfully resent verification. Please check your email</p>);
})
.catch((err) => {
this.modal(<p>Failure resending verification. Please try again.</p>);
});
};
handleChange = (name) => (event) => {
// Calibrate for input field and check box variation
const prop = name === 'agree' ? 'checked' : 'value';
this.setState({ [name]: event.target[prop] }, () => {
// Wait until first state is resolved to ensure accurate match represantation
this.setState({
match: this.state.password === this.state.vpassword
});
});
};
toggleSignin = () => {
this.setState({ signin: !this.state.signin });
};
signIn = () => {
const { email, password } = this.state;
axios
.post(`${ROOT_URL.API}/auth/login`, { email, password })
.then((res) => {
this.signInSuccess(res.data);
window.location = `${ROOT_URL.WEB}/upload`;
})
.catch((err) => {
if (err.response.data.err) {
if (err.response.data.err.message === 'Sorry, you must validate email first') {
this.modal(<p>You must validate your account. Please check your email.</p>);
}
} else {
this.modal(<p>Failed to sign in. Please try again!</p>);
}
localStorage.removeItem('authToken');
});
};
signUp = () => {
// Checks for errors from top to bottom
if (this.state.password.length === 0) {
this.modal(<p>You must input a valid password.</p>);
return;
} else if (!this.state.match) {
this.modal(<p>Passwords do not match. Please try again.</p>);
return;
} else if (!this.state.agree) {
this.modal(<p>Please indicate that you agree to the Terms and Conditions.</p>);
return;
}
const { username, password, email } = this.state;
axios
.post(`${ROOT_URL.API}/auth/signup`, { username, password, email })
.then((res) => {
localStorage.setItem('authToken', `Bearer ${res.data.token}`);
this.modal(<p>Successfully signed up. Please check your email to validate your account</p>);
})
.catch((err) => {
this.modal(<p>Failed to sign up. Please try again!</p>);
});
this.setState({ username: '', email: '', password: '', vpassword: '', agree: false });
};
signInSuccess = (data) => {
localStorage.setItem('authToken', `Bearer ${data.token}`);
};
render() {
return (
<div className="landing-container">
<div className="landing-main">
<img alt="closet roulette title" className="landing-title" src={CR_Title} />
<div className="landing-form">
{/* Only show email when not signing in */}
{this.state.signin ? null : (
<TextField
className="landing-input"
label="Username"
margin="normal"
onChange={this.handleChange('username')}
type="text"
value={this.state.username}
/>
)}
<TextField
className="landing-input"
label="Email"
margin="normal"
onChange={this.handleChange('email')}
type="text"
value={this.state.email}
/>
<TextField
className="landing-input"
label="Password"
margin="normal"
onChange={this.handleChange('password')}
type="password"
value={this.state.password}
/>
{/* Only show verify password field and checkbox when not signing in */}
{this.state.signin ? null : (
<React.Fragment>
<TextField
error={!this.state.match}
className="landing-input"
label="Verify Password"
margin="normal"
onChange={this.handleChange('vpassword')}
type="password"
value={this.state.vpassword}
/>
<div className="landing-agree">
<Checkbox
checked={this.state.agree}
className="landing-agree-check"
color="default"
onChange={this.handleChange('agree')}
value="agree"
/>
<span className="landing-agree-text">
I agree that I will only upload images that I own.
</span>
</div>
</React.Fragment>
)}
{/* Modify button content and action based on sign in status */}
<Button
className="mui-button landing-button-main"
variant="outlined"
onClick={this.state.signin ? this.signIn : this.signUp}
>
{this.state.signin ? 'Login' : 'Signup'}
</Button>
<Button className="mui-button landing-button-sub" onClick={this.toggleSignin}>
{this.state.signin ? 'Signup' : 'Login'}
</Button>
<div className="landing-oauth">
<a href={`${ROOT_URL.API}/auth/google`}>
<img alt="google icon" className="landing-oauth-icon" src={Icons.google} />
</a>
<a href={`${ROOT_URL.API}/auth/facebook`}>
<img alt="facebook icon" className="landing-oauth-icon" src={Icons.facebook} />
</a>
<a href={`${ROOT_URL.API}/auth/github`}>
<img alt="github icon" className="landing-oauth-icon" src={Icons.github} />
</a>
</div>
</div>
</div>
<div className="landing-info" />
{this.state.modal ? <Modal content={this.state.content} action={this.state.action} /> : null}
</div>
);
}
}
export default Landing;
|
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
const Asset = require('../CCAsset');
const Texture = require('../CCTexture2D');
const PixelFormat = Texture.PixelFormat;
const EffectAsset = require('./CCEffectAsset');
const textureUtil = require('../../utils/texture-util');
const gfx = cc.gfx;
/**
* !#en Material builtin name
* !#zh 内置材质名字
* @enum Material.BUILTIN_NAME
*/
const BUILTIN_NAME = cc.Enum({
/**
* @property SPRITE
* @readonly
* @type {String}
*/
SPRITE: '2d-sprite',
/**
* @property GRAY_SPRITE
* @readonly
* @type {String}
*/
GRAY_SPRITE: '2d-gray-sprite',
/**
* @property UNLIT
* @readonly
* @type {String}
*/
UNLIT: 'unlit',
});
/**
* !#en Material Asset.
* !#zh 材质资源类。
* @class Material
* @extends Asset
*/
let Material = cc.Class({
name: 'cc.Material',
extends: Asset,
ctor () {
this.loaded = false;
this._manualHash = false;
this._dirty = true;
this._effect = null;
},
properties: {
// deprecated
_defines: {
default: undefined,
type: Object
},
// deprecated
_props: {
default: undefined,
type: Object
},
_effectAsset: {
type: EffectAsset,
default: null,
},
_techniqueIndex: 0,
_techniqueData: Object,
effectName: CC_EDITOR ? {
get () {
return this._effectAsset && this._effectAsset.name;
},
set (val) {
let effectAsset = cc.assetManager.builtins.getBuiltin('effect', val);
if (!effectAsset) {
Editor.warn(`no effect named '${val}' found`);
return;
}
this.effectAsset = effectAsset;
}
} : undefined,
effectAsset: {
get () {
return this._effectAsset;
},
set (asset) {
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
return;
}
this._effectAsset = asset;
if (!asset) {
cc.error('Can not set an empty effect asset.');
return;
}
this._effect = this._effectAsset.getInstantiatedEffect();
}
},
effect: {
get () {
return this._effect;
}
},
techniqueIndex: {
get () {
return this._techniqueIndex;
},
set (v) {
this._techniqueIndex = v;
this._effect.switchTechnique(v);
}
}
},
statics: {
/**
* !#en Get built-in materials
* !#zh 获取内置材质
* @static
* @method getBuiltinMaterial
* @param {string} name
* @return {Material}
*/
getBuiltinMaterial (name) {
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
return new cc.Material();
}
return cc.assetManager.builtins.getBuiltin('material', 'builtin-' + name);
},
BUILTIN_NAME,
/**
* !#en Creates a Material with builtin Effect.
* !#zh 使用内建 Effect 创建一个材质。
* @static
* @method createWithBuiltin
* @param {string} effectName
* @param {number} [techniqueIndex]
* @return {Material}
*/
createWithBuiltin (effectName, techniqueIndex = 0) {
let effectAsset = cc.assetManager.builtins.getBuiltin('effect', 'builtin-' + effectName);
return Material.create(effectAsset, techniqueIndex);
},
/**
* !#en Creates a Material.
* !#zh 创建一个材质。
* @static
* @method create
* @param {EffectAsset} effectAsset
* @param {number} [techniqueIndex]
* @return {Material}
*/
create (effectAsset, techniqueIndex = 0) {
if (!effectAsset) return null;
let material = new Material();
material.effectAsset = effectAsset;
material.techniqueIndex = techniqueIndex;
return material;
}
},
/**
* !#en Sets the Material property
* !#zh 设置材质的属性
* @method setProperty
* @param {string} name
* @param {Object} val
* @param {number} [passIdx]
* @param {boolean} [directly]
*/
setProperty (name, val, passIdx, directly) {
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return;
if (typeof passIdx === 'string') {
passIdx = parseInt(passIdx);
}
if (val instanceof Texture) {
let isAlphaAtlas = val.isAlphaAtlas();
let key = 'CC_USE_ALPHA_ATLAS_' + name;
let def = this.getDefine(key, passIdx);
if (isAlphaAtlas || def) {
this.define(key, isAlphaAtlas);
}
if (!val.loaded) {
cc.assetManager.postLoadNative(val);
}
}
this._effect.setProperty(name, val, passIdx, directly);
},
/**
* !#en Sets the Material property as fast as possible, but maybe not safe.
* !#zh 快速设置材质的属性, 需要用户在自己的代码中去确保该操作的正确性.
* @method setPropertyFast
* @param {string} name
* @param {Object} val
* @param {number} [passIdx]
* @param {boolean} [directly]
*/
setPropertyFast (name, val, passIdx, directly) {
const effect = this._effect;
effect._setPassProperty(name, val, effect._passes[passIdx || 0], directly);
},
/**
* !#en Gets the Material property.
* !#zh 获取材质的属性。
* @method getProperty
* @param {string} name
* @param {number} passIdx
* @return {Object}
*/
getProperty (name, passIdx) {
if (typeof passIdx === 'string') {
passIdx = parseInt(passIdx);
}
return this._effect.getProperty(name, passIdx);
},
/**
* !#en Sets the Material define.
* !#zh 设置材质的宏定义。
* @method define
* @param {string} name
* @param {boolean|number} val
* @param {number} [passIdx]
* @param {boolean} [force]
*/
define (name, val, passIdx, force) {
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) return;
if (typeof passIdx === 'string') {
passIdx = parseInt(passIdx);
}
this._effect.define(name, val, passIdx, force);
},
/**
* !#en Gets the Material define.
* !#zh 获取材质的宏定义。
* @method getDefine
* @param {string} name
* @param {number} [passIdx]
* @return {boolean|number}
*/
getDefine (name, passIdx) {
if (typeof passIdx === 'string') {
passIdx = parseInt(passIdx);
}
return this._effect.getDefine(name, passIdx);
},
/**
* !#en Sets the Material cull mode.
* !#zh 设置材质的裁减模式。
* @method setCullMode
* @param {number} cullMode
* @param {number} passIdx
*/
setCullMode (cullMode = gfx.CULL_BACK, passIdx) {
this._effect.setCullMode(cullMode, passIdx);
},
/**
* !#en Sets the Material depth states.
* !#zh 设置材质的深度渲染状态。
* @method setDepth
* @param {boolean} depthTest
* @param {boolean} depthWrite
* @param {number} depthFunc
* @param {number} passIdx
*/
setDepth (
depthTest = false,
depthWrite = false,
depthFunc = gfx.DS_FUNC_LESS,
passIdx
) {
this._effect.setDepth(depthTest, depthWrite, depthFunc, passIdx);
},
/**
* !#en Sets the Material blend states.
* !#zh 设置材质的混合渲染状态。
* @method setBlend
* @param {boolean} enabled
* @param {number} blendEq
* @param {number} blendSrc
* @param {number} blendDst
* @param {number} blendAlphaEq
* @param {number} blendSrcAlpha
* @param {number} blendDstAlpha
* @param {number} blendColor
* @param {number} passIdx
*/
setBlend (
enabled = false,
blendEq = gfx.BLEND_FUNC_ADD,
blendSrc = gfx.BLEND_SRC_ALPHA,
blendDst = gfx.BLEND_ONE_MINUS_SRC_ALPHA,
blendAlphaEq = gfx.BLEND_FUNC_ADD,
blendSrcAlpha = gfx.BLEND_SRC_ALPHA,
blendDstAlpha = gfx.BLEND_ONE_MINUS_SRC_ALPHA,
blendColor = 0xffffffff,
passIdx
) {
this._effect.setBlend(enabled, blendEq, blendSrc, blendDst, blendAlphaEq, blendSrcAlpha, blendDstAlpha, blendColor, passIdx);
},
/**
* !#en Sets whether enable the stencil test.
* !#zh 设置是否开启模板测试。
* @method setStencilEnabled
* @param {number} stencilTest
* @param {number} passIdx
*/
setStencilEnabled (stencilTest = gfx.STENCIL_INHERIT, passIdx) {
this._effect.setStencilEnabled(stencilTest, passIdx);
},
/**
* !#en Sets the Material stencil render states.
* !#zh 设置材质的模板测试渲染参数。
* @method setStencil
* @param {number} stencilTest
* @param {number} stencilFunc
* @param {number} stencilRef
* @param {number} stencilMask
* @param {number} stencilFailOp
* @param {number} stencilZFailOp
* @param {number} stencilZPassOp
* @param {number} stencilWriteMask
* @param {number} passIdx
*/
setStencil (
stencilTest = gfx.STENCIL_INHERIT,
stencilFunc = gfx.DS_FUNC_ALWAYS,
stencilRef = 0,
stencilMask = 0xff,
stencilFailOp = gfx.STENCIL_OP_KEEP,
stencilZFailOp = gfx.STENCIL_OP_KEEP,
stencilZPassOp = gfx.STENCIL_OP_KEEP,
stencilWriteMask = 0xff,
passIdx
) {
this._effect.setStencil(stencilTest, stencilFunc, stencilRef, stencilMask, stencilFailOp, stencilZFailOp, stencilZPassOp, stencilWriteMask, passIdx);
},
updateHash (hash) {
this._manualHash = hash;
this._effect && this._effect.updateHash(hash);
},
getHash () {
return this._manualHash || (this._effect && this._effect.getHash());
},
onLoad () {
this.effectAsset = this._effectAsset;
if (!this._effect) return;
if (this._techniqueIndex) {
this._effect.switchTechnique(this._techniqueIndex);
}
this._techniqueData = this._techniqueData || {};
let passDatas = this._techniqueData;
for (let index in passDatas) {
index = parseInt(index);
let passData = passDatas[index];
if (!passData) continue;
for (let def in passData.defines) {
this.define(def, passData.defines[def], index);
}
for (let prop in passData.props) {
this.setProperty(prop, passData.props[prop], index);
}
}
},
});
export default Material;
cc.Material = Material;
|
import * as components from './components';
const forEach = Array.prototype.forEach;
const createAndReleaseComponentsUponDOMMutation = (
records,
componentClasses,
componentClassesForWatchInit,
options
) => {
records.forEach(record => {
forEach.call(record.addedNodes, node => {
if (node.nodeType === Node.ELEMENT_NODE) {
componentClassesForWatchInit.forEach(Clz => {
Clz.init(node, options);
});
}
});
forEach.call(record.removedNodes, node => {
if (node.nodeType === Node.ELEMENT_NODE) {
componentClasses.forEach(Clz => {
if (node.matches(Clz.options.selectorInit)) {
const instance = Clz.components.get(node);
if (instance) {
instance.release();
}
} else {
forEach.call(
node.querySelectorAll(Clz.options.selectorInit),
element => {
const instance = Clz.components.get(element);
if (instance) {
instance.release();
}
}
);
}
});
}
});
});
};
/**
* Automatically instantiates/destroys components in the given element, by watching for DOM additions/removals.
* @param {Node} target The DOM node to instantiate components in. Should be a document or an element.
* @param {Object} [options] The component options.
* @returns {Handle} The handle to stop watching.
*/
export default function(target = document, options = {}) {
if (
target.nodeType !== Node.ELEMENT_NODE &&
target.nodeType !== Node.DOCUMENT_NODE
) {
throw new TypeError(
'DOM document or DOM element should be given to watch for DOM node to create/release components.'
);
}
const componentClasses = Object.keys(components)
.map(key => components[key])
.filter(component => typeof component.init === 'function');
const handles = componentClasses
.map(Clz => Clz.init(target, options))
.filter(Boolean);
const componentClassesForWatchInit = componentClasses.filter(
Clz => !Clz.forLazyInit
);
let observer = new MutationObserver(records => {
createAndReleaseComponentsUponDOMMutation(
records,
componentClasses,
componentClassesForWatchInit,
options
);
});
observer.observe(target, {
childList: true,
subtree: true,
});
return {
release() {
for (let handle = handles.pop(); handle; handle = handles.pop()) {
handle.release();
}
if (observer) {
observer.disconnect();
observer = null;
}
},
};
}
|
"use strict";
var tools = require("../../tools");
module.exports = function(ecs, game) { // eslint-disable-line no-unused-vars
ecs.addEach(function(entity, context) { // eslint-disable-line no-unused-vars
var textBox = game.entities.get(entity, "textBox");
if (textBox.message.length > 0) {
//viewport
var viewPort = 1;
var viewPortPosition = game.entities.get(viewPort, "position");
var viewPortSize = game.entities.get(viewPort, "size");
var size = game.entities.get(entity, "size");
var position = game.entities.get(entity, "position");
position.x = viewPortPosition.x;
position.y = (viewPortPosition.y + viewPortSize.height) - size.height;
context.fillStyle = textBox.fontColor;
context.font = textBox.fontSize + "px " + textBox.font;
tools.wrapText(
context,
textBox.message,
Math.floor(position.x + size.padding),
Math.floor(position.y + size.padding),
size.width - size.padding,
textBox.fontSize
);
}
}, "textBox");
};
|
!(function(){var ace = window.___ace___;
ace.define("ace/snippets/swig",["require","exports","module"], function(require, exports, module) {
"use strict";
exports.snippetText =undefined;
exports.scope = "swig";
});
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.