text
stringlengths
2
1.05M
/** * Created by Ali on 8/13/2016. */ module.exports = { pnEndPointPath: "private_networks", listPrivateNetworks: function (callback) { req.is_get([this.pnEndPointPath], callback) }, listPrivateNetworksWithOptions: function (options, callback) { var path = this.pnEndPointPath; if (options) { path += "?"; if (options.page) { path += "&page=" + options.page; } if (options.perPage) { path += "&per_page=" + options.perPage; } if (options.sort) { path += "&sort=" + options.sort; } if (options.query) { path += "&q=" + options.query; } if (options.fields) { path += "&fields=" + options.fields; } } req.is_get([path], callback) }, createPrivateNetwork: function (json, callback) { req.is_post([this.pnEndPointPath], json, callback) }, getPrivateNetwork: function (pn_id, callback) { req.is_get([this.pnEndPointPath, pn_id], callback) }, updatePrivateNetwork: function (pn_id, json, callback) { req.is_put([this.pnEndPointPath, pn_id], json, callback) }, deletePrivateNetwork: function (pn_id, callback) { req.is_del([this.pnEndPointPath, pn_id], callback) }, listPrivateNetworkServers: function (pn_id, callback) { req.is_get([this.pnEndPointPath, pn_id, "servers"], callback) }, attachServerToPrivateNetwork: function (pn_id, json, callback) { req.is_post([this.pnEndPointPath, pn_id, "servers"], json, callback) }, getPrivateNetworkServer: function (pn_id, srv_id, callback) { req.is_get([this.pnEndPointPath, pn_id, "servers", srv_id], callback) }, detachServerFromPrivateNetwork: function (pn_id, srv_id, json, callback) { req.is_del([this.pnEndPointPath, pn_id, "servers", srv_id], json, callback) }, }
var searchData= [ ['mybase',['MyBase',['../structpvr_1_1async_1_1_texture_load_future__.html#ab87cc198bd4f73a6ffe95a5409a98c9c',1,'pvr::async::TextureLoadFuture_']]] ];
// Require Data const { queue } = require("../muzateki.js"); // Run's Stop Command exports.run = async(client, msg, args) => { var serverQueue = queue.get(msg.guild.id); if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!'); if (!serverQueue) return msg.channel.send('There is nothing playing that I could stop for you.'); serverQueue.songs = []; serverQueue.connection.dispatcher.end('Stop command has been used!'); return msg.channel.send("Song has been stopped!"); return undefined; } exports.conf = { aliases: ['st'] } exports.help = { name: "stop" }
const {promisify} = require('util'); const fs = require('fs'); const path = require('path'); const test = require('ava'); const getStream = require('get-stream'); const isPng = require('is-png'); const imageminPngquant = require('.'); const readFile = promisify(fs.readFile); test('optimize a PNG', async t => { const buffer = await readFile(path.join(__dirname, 'fixture.png')); const data = await imageminPngquant()(buffer); t.true(data.length < buffer.length); t.true(isPng(data)); }); test('support pngquant options', async t => { const buffer = await readFile(path.join(__dirname, 'fixture.png')); const data = await imageminPngquant({ speed: 10, quality: [0.8, 1] })(buffer); t.true(data.length > 30000); t.true(isPng(data)); }); test('support streams', async t => { const buffer = await readFile(path.join(__dirname, 'fixture.png')); const stream = fs.createReadStream(path.join(__dirname, 'fixture.png')); const data = await getStream.buffer(imageminPngquant()(stream)); t.true(data.length < buffer.length); t.true(isPng(data)); }); test('skip optimizing a non-PNG file', async t => { const buffer = await readFile(__filename); const data = await imageminPngquant()(buffer); t.is(data.length, buffer.length); });
import React from 'react' import Layout from '../components/layout'; import styled from 'styled-components'; const FeaturedImage = styled.img` max-width: 300px; margin: 16px 0; ` export default ({pageContext}) => ( <Layout> {console.log(pageContext)} <h1> {pageContext.title} </h1> <strong> Website url: </strong> <a href={pageContext.acf.portfolio_url} target="_blank"> {pageContext.acf.portfolio_url} </a> <FeaturedImage src={pageContext.featured_media.source_url} /> <div dangerouslySetInnerHTML={{__html: pageContext.content}} /> {pageContext.acf.flexible_content_portfolio.map((section, index) => ( <div id={index}>{section.content}</div>))} </Layout> );
import React, { Component } from 'react'; class Footer extends Component { render() { if (this.props.data) { var networks = this.props.data.social.map(function (network) { return <li key={network.name}><a href={network.url}><i className={network.className}></i></a></li> }) } return ( <footer> <div className="row"> <div className="twelve columns"> <ul className="social-links"> {networks} </ul> <ul> <li>Modified with love by the Clever Programmer team ♥️</li> </ul> <ul className="copyright"> <li>&copy; All credit goes to Tim Baker - Copyright 2017 Tim Baker</li> <li>Design by <a title="Styleshout" href="http://www.styleshout.com/">Styleshout</a></li> </ul> </div> <div id="go-top"><a className="smoothscroll" title="Back to Top" href="#home"><i className="icon-up-open"></i></a></div> </div> {/* <div class="shuffel-bg" style={{ opacity: 0 }} /> */} </footer> ); } } export default Footer;
import React from 'react' import { Row, Col } from 'react-awesome-styled-grid' import { Tabs, useTabState, usePanelState } from './Tabs' import { motion } from 'framer-motion' import MarkdownContent from './MarkdownContent' import * as styled from './styled/Accordion' const variants = { hidden: { height: 0 }, visible: { height: 'auto' } } const Tab = ({ children }) => { const { isActive, onClick } = useTabState() return ( <styled.AccordionItem onClick={onClick}> {children} <styled.AccordionState isActive={isActive} /> </styled.AccordionItem> ) } const Panel = ({ children }) => { const isActive = usePanelState() return ( <motion.div animate={isActive ? 'visible' : 'hidden'} initial='hidden' variants={variants} style={{ overflow: 'hidden' }} > {children} </motion.div> ) } const Accordions = ({ cols = 2, accordions }) => ( <Tabs> <Row> {[...Array(cols).keys()] .map(c => accordions .filter((_, i) => i % cols === c) ).map((column, cIndex) => ( <Col key={cIndex} xs={4} sm={8} md={12 / cols}> <Row style={{ alignContent: 'flex-start' }}> {column.map(({ heading, body }, index) => ( <Col key={index} xs={4}> <Tab> <styled.AccordionHeader> <styled.AccordionIndicator>{`${index * cols + cIndex + 1}`.padStart(2, 0)}</styled.AccordionIndicator> {heading} </styled.AccordionHeader> </Tab> <Panel> <styled.AccordionBody> <MarkdownContent content={body} /> </styled.AccordionBody> </Panel> </Col> ))} </Row> </Col> ))} </Row> </Tabs> ) export default Accordions
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = NativeInput; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _dates = require("../shared/dates"); var _propTypes2 = require("../shared/propTypes"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function NativeInput(_ref) { var ariaLabel = _ref.ariaLabel, disabled = _ref.disabled, maxDate = _ref.maxDate, minDate = _ref.minDate, name = _ref.name, onChange = _ref.onChange, required = _ref.required, value = _ref.value, valueType = _ref.valueType; var nativeInputType = function () { switch (valueType) { case 'decade': case 'year': return 'number'; case 'month': return 'month'; case 'day': return 'date'; default: throw new Error('Invalid valueType.'); } }(); var nativeValueParser = function () { switch (valueType) { case 'century': case 'decade': case 'year': return _dates.getYear; case 'month': return _dates.getISOLocalMonth; case 'day': return _dates.getISOLocalDate; default: throw new Error('Invalid valueType.'); } }(); function stopPropagation(event) { event.stopPropagation(); } return _react["default"].createElement("input", { "aria-label": ariaLabel, disabled: disabled, max: maxDate ? nativeValueParser(maxDate) : null, min: minDate ? nativeValueParser(minDate) : null, name: name, onChange: onChange, onFocus: stopPropagation, required: required, style: { visibility: 'hidden', position: 'absolute', top: '-9999px', left: '-9999px' }, type: nativeInputType, value: value ? nativeValueParser(value) : '' }); } NativeInput.propTypes = { ariaLabel: _propTypes["default"].string, disabled: _propTypes["default"].bool, maxDate: _propTypes2.isMaxDate, minDate: _propTypes2.isMinDate, name: _propTypes["default"].string, onChange: _propTypes["default"].func, required: _propTypes["default"].bool, value: _propTypes["default"].oneOfType([_propTypes["default"].string, _propTypes["default"].instanceOf(Date)]), valueType: _propTypes2.isValueType };
/** * Copyright (c) 2017- Kibae Shin (nonunnet@gmail.com) * All rights reserved. * * This source code is licensed under the MIT license found in the * README.md file in the root directory of this source tree. */ var EventEmitter = require('events').EventEmitter; var util = require('util'); var pg = require('pg'); function standbyStatusUpdate(client, upperWAL, lowerWAL, msg = 'nothing') { // Timestamp as microseconds since midnight 2000-01-01 var now = (Date.now() - 946080000000); var upperTimestamp = Math.floor(now / 4294967.296); var lowerTimestamp = Math.floor((now - upperTimestamp * 4294967.296)); if (lowerWAL === 4294967295) { // [0xff, 0xff, 0xff, 0xff] upperWAL = upperWAL + 1; lowerWAL = 0; } else { lowerWAL = lowerWAL + 1; } var response = Buffer.alloc(34); response.fill(0x72); // 'r' // Last WAL Byte + 1 received and written to disk locally response.writeUInt32BE(upperWAL, 1); response.writeUInt32BE(lowerWAL, 5); // Last WAL Byte + 1 flushed to disk in the standby response.writeUInt32BE(upperWAL, 9); response.writeUInt32BE(lowerWAL, 13); // Last WAL Byte + 1 applied in the standby response.writeUInt32BE(upperWAL, 17); response.writeUInt32BE(lowerWAL, 21); // Timestamp as microseconds since midnight 2000-01-01 response.writeUInt32BE(upperTimestamp, 25); response.writeUInt32BE(lowerTimestamp, 29); // If 1, requests server to respond immediately - can be used to verify connectivity response.writeInt8(0, 33); client.connection.sendCopyFromChunk(response); } var LogicalReplication = function(config) { EventEmitter.call(this); var self = this; config = config || {}; config.replication = 'database'; var client; var stoped = false; var lastLsn; var lastStatus = 0; var feedbackCheckInterval; var standbyMessageTimeout; this.getChanges = function(slotName, uptoLsn, option, cb /*(start_err)*/) { if (client) { client.removeAllListeners(); client.end(); client = null; } option = option || {}; standbyMessageTimeout = (typeof option.standbyMessageTimeout === 'undefined') ? 10 : option.standbyMessageTimeout; /* * includeXids : include xid on BEGIN and COMMIT, default false * includeTimestamp : include timestamp on COMMIT, default false */ stoped = false; client = new pg.Client(config); client.on('error', function(err) { self.emit('error', err); }); client.connect(function(err) { //error handling if (err) { self.emit('error', err); return; } var sql = 'START_REPLICATION SLOT ' + slotName + ' LOGICAL ' + (uptoLsn ? uptoLsn : '0/00000000'); var opts = [ '"include-xids" \'' + (option.includeXids === true ? 'on' : 'off') + '\'', '"include-timestamp" \'' + (option.includeTimestamp === true ? 'on' : 'off') + '\'', ]; if (option.queryOptions) { Object.keys(option.queryOptions).forEach(key => { var value = option.queryOptions[key]; if (typeof value === 'boolean') { value = value === true ? 'on' : 'off'; } opts.push( `"${key}" '${value}'` ) }) } sql += ' (' + (opts.join(' , ')) + ')'; client.query(sql, function(err) { if (err) { if (!stoped && cb) { cb(err); cb = null; } } cb = null; }); self.removeListener('acknowledge', onAcknowledge); client.connection.once('replicationStart', function() { //start self.emit('start', self); client.connection.on('copyData', function(msg) { if (msg.chunk[0] == 0x77) { // XLogData var lsn = (msg.chunk.readUInt32BE(1).toString(16).toUpperCase()) + '/' + (msg.chunk.readUInt32BE(5).toString(16).toUpperCase()); self.emit('data', { lsn, log: msg.chunk.slice(25), }); self.emit('acknowledge', { lsn }); lastLsn = lsn; } else if (msg.chunk[0] == 0x6b) { // Primary keepalive message var lsn = (msg.chunk.readUInt32BE(1).toString(16).toUpperCase()) + '/' + (msg.chunk.readUInt32BE(5).toString(16).toUpperCase()); var timestamp = Math.floor(msg.chunk.readUInt32BE(9) * 4294967.296 + msg.chunk.readUInt32BE(13) / 1000 + 946080000000); var shouldRespond = msg.chunk.readInt8(17); self.emit('heartbeat', { lsn, timestamp, shouldRespond }); lastLsn = lsn; } else { console.log('Unknown message', msg.chunk[0]); } }); self.on('acknowledge', onAcknowledge); startStandbyTimeoutCheck(); }); }); return self; }; function onAcknowledge(msg) { var lsn = msg.lsn.split('/'); standbyStatusUpdate(client, parseInt(lsn[0], 16), parseInt(lsn[1], 16), 'acknowledge'); updateLastStatus(); } function startStandbyTimeoutCheck() { if (standbyMessageTimeout <= 0) { return; } feedbackCheckInterval = setInterval(function () { if ((Date.now() - lastStatus) > standbyMessageTimeout * 1000) { sendFeedback(); } }, 1000); } function stopStandbyTimeoutCheck() { clearInterval(feedbackCheckInterval); } function updateLastStatus() { lastStatus = Date.now(); } function sendFeedback() { if (!lastLsn) { return; } var lsn = lastLsn.split('/'); if (!stoped && client) { standbyStatusUpdate(client, parseInt(lsn[0], 16), parseInt(lsn[1], 16), 'feedback'); updateLastStatus(); } } this.stop = function() { stoped = true; stopStandbyTimeoutCheck(); if (client) { client.removeAllListeners(); client.end(); client = null; } }; }; util.inherits(LogicalReplication, EventEmitter); LogicalReplication.LoadPlugin = function(module) { return require('./plugins/' + module); }; module.exports = LogicalReplication;
load("201224b0d1c296b45befd2285e95dd42.js"); var x = {get prop() { return 2; }, set prop(v) {}}; var y = {__proto__: x, prop: 1}; assertEq(y.__lookupGetter__("prop"), undefined); assertEq(y.__lookupSetter__("prop"), undefined);
module.exports = { automock: false, moduleNameMapper: { '\\.(css|less|sass|scss)$': 'identity-obj-proxy', }, preset: 'ts-jest/presets/js-with-babel', moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], testPathIgnorePatterns: ['/lib/', '/node_modules/'], testRegex: '/__tests__/.*.spec.ts[x]?$', transformIgnorePatterns: ['/node_modules/(?!(@jupyter(lab|-widgets)/.*)/)'], globals: { 'ts-jest': { tsconfig: '<rootDir>/tsconfig.json', }, }, };
(function(){ "use strict"; //VIEWPORT DETECTION: $(document).ready(function() { /*----------------------------------------------------- Shuffle Grid -------------------------------------------------------*/ /* initialize shuffle plugin */ var $grid = $('#grid'); $grid.shuffle({ itemSelector: '.port-tile-main' // the selector for the items in the grid }); /* reshuffle when user clicks a filter item */ $('.filter li a').click(function (e) { e.preventDefault(); // set active class $('.filter li a').removeClass('active'); $(this).addClass('active'); // get group name from clicked item var groupName = $(this).attr('data-group'); // reshuffle grid $grid.shuffle('shuffle', groupName ); }); /*----------------------------------------------------- Portfolio Triggers -------------------------------------------------------*/ //$(".video-frame").fitVids(); $('.ajax_area_trigger').slideUp(); $(".proj_ajax").click(function(){ $('.ajax_area_trigger').slideDown(1000); $.ajax({ url: $(this).attr("href"), success: function(response) { $('.ajax_area_trigger').addClass('ajax_area'); //Dropping Content var html = $('#ajax-era', response).html(); $(".ajax_drop").html(html); //$(response).filter(".video-frame").fitVids(); $(".pro_owl").owlCarousel({ autoPlay:15000, //Set AutoPlay to 5 seconds autoHeight : true, slideSpeed:400, singleItem:true, navigation: false, pagination: true, navigationText: ["",""] }); /*--------------*/ $("html, body").animate({ scrollTop: $('.ajax_area_trigger').offset().top-24 +"px" },{ duration: 500, easing: "swing" }); //Triggering Slider $(".portslider").owlCarousel({ autoPlay:12000, //Set AutoPlay to 5 seconds autoHeight : true, slideSpeed:400, singleItem:true, navigation: false, pagination: true, }); } }); return false; }); /*Closing the Ajax Grid*/ $(".ajax_close").click(function(){ $('.ajax_area_trigger').slideUp(); $('.ajax_area_trigger').removeClass('ajax_area'); return false; }); }); })();
import React from 'react'; import PropTypes from 'prop-types'; export default class AddressInput extends React.Component { constructor(props) { super(props); this.state = { value: this.props.value.type ? this.props.value.value : this.props.value, }; this.handleChangeField = this.handleChangeField.bind(this); this.handleSelectState = this.handleSelectState.bind(this); } handleSelectState(e) { const index = e.nativeEvent.target.selectedIndex; const { line1, line2, city, postcode, } = this.state.value; const theState = this.props.states.find(ss => ss.value === e.nativeEvent.target[index].value); const state = { value: { line1, line2, city, state: theState, postcode, }, }; this.setState(state, this.props.onChange.bind(null, { type: 'address', value: state.value })); } handleChangeField(field, e) { const { line1, line2, city, postcode, } = this.state.value; let theState = this.props.states.find(ss => ss.value === this.state.value.state.value); if (!theState) { theState = this.props.states[0]; } const ns = { value: { line1, line2, city, state: theState, postcode, }, }; ns.value[field] = e.target.value; this.setState(ns, this.props.onChange.bind(null, { type: 'address', value: ns.value })); } renderSelect() { const options = this.props.states.map(opt => (<option key={opt.value} value={opt.value}>{opt.text}</option>)); return ( <select name={`${this.props.name}-state`} id={`${this.props.id}-state`} className={this.props.classes.select} value={this.state.value.state ? this.state.value.state.value : ''} required={this.props.required ? 'required' : undefined} onChange={e => this.handleSelectState(e)} onFocus={() => this.props.onFocus(this.props.id)} > {options} </select> ); } render() { const { onFocus, placeholders } = this.props; const sel = this.renderSelect(); const address = ( <div> <div> <input type="text" name={`${this.props.name}-line1`} id={`${this.props.id}-line1`} aria-labelledby={`${this.props.labelId}-line1`} className={this.props.classes.input} placeholder={placeholders.line1} value={this.state.value.line1} required={this.props.required ? 'required' : undefined} onChange={e => this.handleChangeField('line1', e)} onFocus={() => onFocus(this.props.id)} /> </div> <div> <input type="text" name={`${this.props.name}-line2`} id={`${this.props.id}-line2`} aria-labelledby={`${this.props.labelId}-line2`} className={this.props.classes.input} placeholder={placeholders.line2} value={this.state.value.line2} required={this.props.required ? 'required' : undefined} onChange={e => this.handleChangeField('line2', e)} onFocus={() => onFocus(this.props.id)} /> </div> <div className="city-line"> <div className="beginning"> <input type="text" name={`${this.props.name}-city`} id={`${this.props.id}-city`} aria-labelledby={`${this.props.labelId}-city`} className={this.props.classes.input} placeholder={placeholders.city} value={this.state.value.city} required={this.props.required ? 'required' : undefined} onChange={e => this.handleChangeField('city', e)} onFocus={() => onFocus(this.props.id)} /> </div> <div className="middle"> {sel} </div> <div className="ending"> <input type="text" name={`${this.props.name}-postcode`} id={`${this.props.id}-postcode`} aria-labelledby={`${this.props.labelId}-postcode`} className={this.props.classes.input} placeholder={placeholders.postcode} value={this.state.value.postcode} required={this.props.required ? 'required' : undefined} onChange={e => this.handleChangeField('postcode', e)} onFocus={() => onFocus(this.props.id)} /> </div> </div> </div>); return address; } } AddressInput.propTypes = { value: PropTypes.object, states: PropTypes.array, onChange: PropTypes.func, name: PropTypes.string, id: PropTypes.string, classes: PropTypes.string, required: PropTypes.string, onFocus: PropTypes.func, placeholders: PropTypes.object, labelId: PropTypes.string.isRequired, }; AddressInput.defaultProps = { classes: {}, name: '', id: '', required: undefined, value: { line1: '', line2: '', city: '', state: { text: 'New South Wales', value: 'NSW', }, postcode: '', }, placeholders: { line1: 'e.g 100 Pitt St', line2: 'e.g Sydney CBD', city: 'e.g Sydney', postcode: 'e.g 2000', }, states: [{ text: 'Select state', value: '', }, { text: 'New South Wales', value: 'NSW', }, { text: 'Australian Capital Territory', value: 'ACT', }, { text: 'Northern Territory', value: 'NT', }, { text: 'Queensland', value: 'QLD', }, { text: 'South Australia', value: 'SA', }, { text: 'Tasmania', value: 'TAS', }, { text: 'Victoria', value: 'VIC', }, { text: 'Western Australia', value: 'WA', }], onChange: () => { }, onFocus: () => { }, };
const plainHighlighter = require("./src/syntaxHighlightPlain"); const prismjsHighlighter = require("./src/syntaxHighlightPrism"); module.exports = function(eleventyConfig) { // compatibility with existing {% highlight js %} and others eleventyConfig.addLiquidTag("highlight", prismjsHighlighter); eleventyConfig.addLiquidTag("highlight-plain", plainHighlighter); };
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/license */ CKEDITOR.lang['id']={"editor":"Rich Text Editor","editorPanel":"Panel Rich Text Editor","common":{"editorHelp":"Tekan ALT 0 untuk bantuan.","browseServer":"Jelajah Server","url":"URL","protocol":"Protokol","upload":"Unggah","uploadSubmit":"Kirim ke Server","image":"Gambar","flash":"Flash","form":"Formulir","checkbox":"Kotak Cek","radio":"Tombol Radio","textField":"Kolom Teks","textarea":"Area Teks","hiddenField":"Kolom Tersembunyi","button":"Tombol","select":"Kolom Seleksi","imageButton":"Tombol Gambar","notSet":"<tidak diatur>","id":"Id","name":"Nama","langDir":"Arah Bahasa","langDirLtr":"Kiri ke Kanan (LTR)","langDirRtl":"Kanan ke Kiri","langCode":"Kode Bahasa","longDescr":"Deskripsi URL Panjang","cssClass":"Kelas Stylesheet","advisoryTitle":"Penasehat Judul","cssStyle":"Gaya","ok":"OK","cancel":"Batal","close":"Tutup","preview":"Pratinjau","resize":"Ubah ukuran","generalTab":"Umum","advancedTab":"Lebih Lanjut","validateNumberFailed":"Nilai ini tidak sebuah angka","confirmNewPage":"Semua perubahan yang tidak disimpan di konten ini akan hilang. Apakah anda yakin ingin memuat halaman baru?","confirmCancel":"Beberapa opsi telah berubah. Apakah anda yakin ingin menutup dialog?","options":"Opsi","target":"Sasaran","targetNew":"Jendela Baru (_blank)","targetTop":"Laman Atas (_top)","targetSelf":"Jendela yang Sama (_self)","targetParent":"Jendela Induk (_parent)","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","styles":"Gaya","cssClasses":"Kelas Stylesheet","width":"Lebar","height":"Tinggi","align":"Penjajaran","left":"Kiri","right":"Kanan","center":"Tengah","justify":"Rata kiri-kanan","alignLeft":"Align Left","alignRight":"Align Right","alignCenter":"Align Center","alignTop":"Atas","alignMiddle":"Tengah","alignBottom":"Bawah","alignNone":"Tidak ada","invalidValue":"Nilai tidak sah.","invalidHeight":"Tinggi harus sebuah angka.","invalidWidth":"Lebar harus sebuah angka.","invalidLength":"Value specified for the \"%1\" field must be a positive number with or without a valid measurement unit (%2).","invalidCssLength":"Nilai untuk \"%1\" harus sebuah angkat positif dengan atau tanpa pengukuran unit CSS yang sah (px, %, in, cm, mm, em, ex, pt, or pc).","invalidHtmlLength":"Nilai yang dispesifikasian untuk kolom \"%1\" harus sebuah angka positif dengan atau tanpa sebuah unit pengukuran HTML (px atau %) yang valid.","invalidInlineStyle":"Nilai pada inline style merupakan pasangan nama dan nilai dengan format \"nama : nilai\", yang dipisahkan dengan titik dua.","cssLengthTooltip":"Masukkan sebuah angka untuk sebuah nilai dalam pixel atau sebuah angka dengan unit CSS yang sah (px, %, in, cm, mm, em, ex, pt, or pc).","unavailable":"%1<span class=\"cke_accessibility\">, tidak tersedia</span>","keyboard":{"8":"Backspace","13":"Enter","16":"Shift","17":"Ctrl","18":"Alt","32":"Spasi","35":"End","36":"Home","46":"Hapus","112":"F1","113":"F2","114":"F3","115":"F4","116":"F5","117":"F6","118":"F7","119":"F8","120":"F9","121":"F10","122":"F11","123":"F12","124":"F13","125":"F14","126":"F15","127":"F16","128":"F17","129":"F18","130":"F19","131":"F20","132":"F21","133":"F22","134":"F23","135":"F24","224":"Command"},"keyboardShortcut":"Pintasan Keyboard","optionDefault":"Default"},"about":{"copy":"Hak cipta &copy; $1. All rights reserved.","dlgTitle":"Tentang CKEditor 4","moreInfo":"Untuk informasi lisensi silahkan kunjungi web site kami:"},"basicstyles":{"bold":"Huruf Tebal","italic":"Huruf Miring","strike":"Strikethrough","subscript":"Subscript","superscript":"Superscript","underline":"Garis Bawah"},"bidi":{"ltr":"Arah penulisan dari kiri ke kanan.","rtl":"Arah penulisan dari kanan ke kiri."},"blockquote":{"toolbar":"Kutipan Blok"},"notification":{"closed":"Pemberitahuan ditutup"},"toolbar":{"toolbarCollapse":"Ciutkan Toolbar","toolbarExpand":"Bentangkan Toolbar","toolbarGroups":{"document":"Dokumen","clipboard":"Papan klip / Kembalikan perlakuan","editing":"Sunting","forms":"Formulir","basicstyles":"Gaya Dasar","paragraph":"Paragraf","links":"Tautan","insert":"Sisip","styles":"Gaya","colors":"Warna","tools":"Alat"},"toolbars":"Toolbar Penyunting"},"clipboard":{"copy":"Salin","copyError":"Pengaturan keamanan peramban anda tidak mengizinkan editor untuk mengeksekusi operasi menyalin secara otomatis. Mohon gunakan papan tuts (Ctrl/Cmd+C)","cut":"Potong","cutError":"Your browser security settings don't permit the editor to automatically execute cutting operations. Please use the keyboard for that (Ctrl/Cmd+X).","paste":"Tempel","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","pasteArea":"Area Tempel","pasteMsg":"Paste your content inside the area below and press OK."},"colorbutton":{"auto":"Automatic","bgColorTitle":"Warna Latar Belakang","colors":{"000":"Hitam","800000":"Merah Tua","8B4513":"Saddle Brown","2F4F4F":"Dark Slate Gray","008080":"Teal","000080":"Navy","4B0082":"Indigo","696969":"Abu-abu Gelap","B22222":"Merah Bata","A52A2A":"Coklat","DAA520":"Golden Rod","006400":"Hijau Gelap","40E0D0":"Turquoise","0000CD":"Biru Sedang","800080":"Ungu","808080":"Abu-abu","F00":"Merah","FF8C00":"Jingga Gelap","FFD700":"Emas","008000":"Hijau","0FF":"Cyan","00F":"Biru","EE82EE":"Violet","A9A9A9":"Abu-abu Redup","FFA07A":"Salmon Cerah","FFA500":"Jingga","FFFF00":"Kuning","00FF00":"Jeruk Lemon","AFEEEE":"Biru Hijau Pucat","ADD8E6":"Biru Cerah","DDA0DD":"Plum","D3D3D3":"Abu-abu Cerah","FFF0F5":"Lavender Blush","FAEBD7":"Antique White","FFFFE0":"Kuning Cerah","F0FFF0":"Honeydew","F0FFFF":"Azure","F0F8FF":"Alice Blue","E6E6FA":"Lavender","FFF":"Putih","1ABC9C":"Strong Cyan","2ECC71":"Emerald","3498DB":"Bright Blue","9B59B6":"Amethyst","4E5F70":"Grayish Blue","F1C40F":"Vivid Yellow","16A085":"Dark Cyan","27AE60":"Dark Emerald","2980B9":"Strong Blue","8E44AD":"Dark Violet","2C3E50":"Desaturated Blue","F39C12":"Orange","E67E22":"Carrot","E74C3C":"Pale Red","ECF0F1":"Bright Silver","95A5A6":"Light Grayish Cyan","DDD":"Light Gray","D35400":"Pumpkin","C0392B":"Strong Red","BDC3C7":"Silver","7F8C8D":"Grayish Cyan","999":"Dark Gray"},"more":"Warna lainnya...","panelTitle":"Warna","textColorTitle":"Warna Teks"},"colordialog":{"clear":"Hapus","highlight":"Sorot","options":"Pilihan Warna","selected":"Warna Dipilih","title":"Pilih Warna"},"templates":{"button":"Contoh","emptyListMsg":"(Tidak ada contoh didefinisikan)","insertOption":"Ganti konten sebenarnya","options":"Opsi Contoh","selectPromptMsg":"Mohon pilih contoh untuk dibuka di editor","title":"Contoh Konten"},"contextmenu":{"options":"Opsi Konteks Pilihan"},"copyformatting":{"label":"Copy Formatting","notification":{"copied":"Formatting copied","applied":"Formatting applied","canceled":"Formatting canceled","failed":"Formatting failed. You cannot apply styles without copying them first."}},"div":{"IdInputLabel":"Id","advisoryTitleInputLabel":"Penasehat Judul","cssClassInputLabel":"Kelas Stylesheet","edit":"Sunting Div","inlineStyleInputLabel":"Inline Style","langDirLTRLabel":"Kiri ke Kanan (LTR)","langDirLabel":"Arah Bahasa","langDirRTLLabel":"Kanan ke Kiri (RTL)","languageCodeInputLabel":"Kode Bahasa","remove":"Hapus Div","styleSelectLabel":"Gaya","title":"Ciptakan Wadah Div","toolbar":"Cipatakan Wadah Div"},"elementspath":{"eleLabel":"Elements path","eleTitle":"%1 element"},"filetools":{"loadError":"Error terjadi ketika berkas dibaca","networkError":"Jaringan error terjadi ketika mengunggah berkas","httpError404":"HTTP error terjadi ketika mengunggah berkas (404: Berkas tidak ditemukan)","httpError403":"HTTP error terjadi ketika mengunggah berkas (403: Gangguan)","httpError":"HTTP error terjadi ketika mengunggah berkas (status error: %1)","noUrlError":"Unggahan URL tidak terdefinisi","responseError":"Respon server tidak sesuai"},"find":{"find":"Temukan","findOptions":"Opsi menemukan","findWhat":"Temukan apa:","matchCase":"Match case","matchCyclic":"Match cyclic","matchWord":"Match whole word","notFoundMsg":"Teks yang dipilih tidak ditemukan","replace":"Ganti","replaceAll":"Ganti Semua","replaceSuccessMsg":"%1 occurrence(s) replaced.","replaceWith":"Ganti dengan:","title":"Temukan dan Ganti"},"fakeobjects":{"anchor":"Anchor","flash":"Animasi Flash","hiddenfield":"Kolom Tersembunyi","iframe":"IFrame","unknown":"Obyek Tak Dikenal"},"flash":{"access":"Script Access","accessAlways":"Selalu","accessNever":"Tidak Pernah","accessSameDomain":"Domain yang sama","alignAbsBottom":"Abs Bottom","alignAbsMiddle":"Abs Middle","alignBaseline":"Dasar","alignTextTop":"Text Top","bgcolor":"Warna Latar Belakang","chkFull":"Izinkan Layar Penuh","chkLoop":"Loop","chkMenu":"Enable Flash Menu","chkPlay":"Mainkan Otomatis","flashvars":"Variables for Flash","hSpace":"HSpace","properties":"Flash Properties","propertiesTab":"Properti","quality":"Kualitas","qualityAutoHigh":"Tinggi Otomatis","qualityAutoLow":"Rendah Otomatis","qualityBest":"Terbaik","qualityHigh":"Tinggi","qualityLow":"Rendah","qualityMedium":"Sedang","scale":"Scale","scaleAll":"Perlihatkan semua","scaleFit":"Exact Fit","scaleNoBorder":"Tanpa Batas","title":"Flash Properties","vSpace":"VSpace","validateHSpace":"HSpace harus sebuah angka","validateSrc":"URL tidak boleh kosong","validateVSpace":"VSpace harus sebuah angka","windowMode":"Window mode","windowModeOpaque":"Opaque","windowModeTransparent":"Transparan","windowModeWindow":"Jendela"},"font":{"fontSize":{"label":"Ukuran","voiceLabel":"Ukuran Huruf","panelTitle":"Ukuran Huruf"},"label":"Huruf","panelTitle":"Font Name","voiceLabel":"Huruf"},"forms":{"button":{"title":"Properti Tombol","text":"Teks (Nilai)","type":"Tipe","typeBtn":"Tombol","typeSbm":"Menyerahkan","typeRst":"Atur Ulang"},"checkboxAndRadio":{"checkboxTitle":"Checkbox Properties","radioTitle":"Radio Button Properties","value":"Nilai","selected":"Terpilih","required":"Wajib"},"form":{"title":"Form Properties","menu":"Form Properties","action":"Aksi","method":"Metode","encoding":"Encoding"},"hidden":{"title":"Hidden Field Properties","name":"Nama","value":"Nilai"},"select":{"title":"Selection Field Properties","selectInfo":"Select Info","opAvail":"Available Options","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","cols":"Kolom","rows":"Baris"},"textfield":{"title":"Text Field Properties","name":"Name","value":"Nilai","charWidth":"Character Width","maxChars":"Maximum Characters","required":"Wajib","type":"Tipe","typeText":"Teks","typePass":"Kata kunci","typeEmail":"Surel","typeSearch":"Cari","typeTel":"Nomor Telepon","typeUrl":"URL"}},"format":{"label":"Bentuk","panelTitle":"Bentuk Paragraf","tag_address":"Alamat","tag_div":"Normal (DIV)","tag_h1":"Heading 1","tag_h2":"Heading 2","tag_h3":"Heading 3","tag_h4":"Heading 4","tag_h5":"Heading 5","tag_h6":"Heading 6","tag_p":"Normal","tag_pre":"Membentuk"},"horizontalrule":{"toolbar":"Sisip Garis Horisontal"},"iframe":{"border":"Tampilkan Batas Bingkai","noUrl":"Please type the iframe URL","scrolling":"Aktifkan Scrollbar","title":"IFrame Properties","toolbar":"IFrame"},"image":{"alt":"Teks alternatif","border":"Batas","btnUpload":"Kirim ke Server","button2Img":"Do you want to transform the selected image button on a simple image?","hSpace":"HSpace","img2Button":"Apakah anda ingin mengubah gambar yang dipilih pada tombol gambar?","infoTab":"Info Gambar","linkTab":"Tautan","lockRatio":"Lock Ratio","menu":"Image Properties","resetSize":"Atur Ulang Ukuran","title":"Image Properties","titleButton":"Image Button Properties","upload":"Unggah","urlMissing":"Image source URL is missing.","vSpace":"VSpace","validateBorder":"Border harus berupa angka","validateHSpace":"HSpace harus berupa angka","validateVSpace":"VSpace must be a whole number."},"indent":{"indent":"Tingkatkan Lekuk","outdent":"Kurangi Lekuk"},"smiley":{"options":"Opsi Smiley","title":"Sisip sebuah Smiley","toolbar":"Smiley"},"language":{"button":"Atur Bahasa","remove":"Hapus Bahasa"},"link":{"acccessKey":"Access Key","advanced":"Advanced","advisoryContentType":"Advisory Content Type","advisoryTitle":"Penasehat Judul","anchor":{"toolbar":"Anchor","menu":"Edit Anchor","title":"Anchor Properties","name":"Anchor Name","errorName":"Please type the anchor name","remove":"Remove Anchor"},"anchorId":"By Element Id","anchorName":"By Anchor Name","charset":"Linked Resource Charset","cssClasses":"Kelas Stylesheet","download":"Force Download","displayText":"Display Text","emailAddress":"Alamat E-mail","emailBody":"Message Body","emailSubject":"Judul Pesan","id":"Id","info":"Link Info","langCode":"Kode Bahasa","langDir":"Arah Bahasa","langDirLTR":"Kiri ke Kanan (LTR)","langDirRTL":"Kanan ke Kiri (RTL)","menu":"Sunting Tautan","name":"Nama","noAnchors":"(No anchors available in the document)","noEmail":"Silahkan ketikkan alamat e-mail","noUrl":"Silahkan ketik URL tautan","noTel":"Please type the phone number","other":"<lainnya>","phoneNumber":"Phone number","popupDependent":"Dependent (Netscape)","popupFeatures":"Popup Window Features","popupFullScreen":"Full Screen (IE)","popupLeft":"Left Position","popupLocationBar":"Location Bar","popupMenuBar":"Menu Bar","popupResizable":"Resizable","popupScrollBars":"Scroll Bars","popupStatusBar":"Status Bar","popupToolbar":"Toolbar","popupTop":"Top Position","rel":"Hubungan","selectAnchor":"Select an Anchor","styles":"Gaya","tabIndex":"Tab Index","target":"Sasaran","targetFrame":"<frame>","targetFrameName":"Target Frame Name","targetPopup":"<popup window>","targetPopupName":"Popup Window Name","title":"Tautan","toAnchor":"Link to anchor in the text","toEmail":"E-mail","toUrl":"URL","toPhone":"Phone","toolbar":"Tautan","type":"Link Type","unlink":"Unlink","upload":"Unggah"},"list":{"bulletedlist":"Sisip/Hapus Daftar Bullet","numberedlist":"Sisip/Hapus Daftar Bernomor"},"liststyle":{"bulletedTitle":"Bulleted List Properties","circle":"Lingkaran","decimal":"Desimal (1, 2, 3, dst.)","disc":"Cakram","lowerAlpha":"Huruf Kecil (a, b, c, d, e, dst.)","lowerRoman":"Angka Romawi (i, ii, iii, iv, v, dst.)","none":"Tidak ada","notset":"<tidak diatur>","numberedTitle":"Numbered List Properties","square":"Persegi","start":"Mulai","type":"Tipe","upperAlpha":"Huruf Besar (A, B, C, D, E, dst.)","upperRoman":"Upper Roman (I, II, III, IV, V, etc.)","validateStartNumber":"List start number must be a whole number."},"magicline":{"title":"Masukkan paragraf disini"},"maximize":{"maximize":"Memperbesar","minimize":"Memperkecil"},"newpage":{"toolbar":"Halaman Baru"},"pagebreak":{"alt":"Halaman Istirahat","toolbar":"Sisip Halaman Istirahat untuk Pencetakan "},"pastetext":{"button":"Tempel sebagai teks polos","pasteNotification":"Press %1 to paste. Your browser doesn‘t support pasting with the toolbar button or context menu option.","title":"Tempel sebagai Teks Polos"},"pastefromword":{"confirmCleanup":"Teks yang ingin anda tempel sepertinya di salin dari Word. Apakah anda mau membersihkannya sebelum menempel?","error":"Tidak mungkin membersihkan data yang ditempel dikerenakan kesalahan internal","title":"Tempel dari Word","toolbar":"Tempel dari Word"},"preview":{"preview":"Pratinjau"},"print":{"toolbar":"Cetak"},"removeformat":{"toolbar":"Hapus Format"},"save":{"toolbar":"Simpan"},"selectall":{"toolbar":"Pilih Semua"},"showblocks":{"toolbar":"Perlihatkan Blok"},"sourcearea":{"toolbar":"Sumber"},"specialchar":{"options":"Opsi spesial karakter","title":"Pilih spesial karakter","toolbar":"Sisipkan spesial karakter"},"scayt":{"btn_about":"About SCAYT","btn_dictionaries":"Dictionaries","btn_disable":"Disable SCAYT","btn_enable":"Enable SCAYT","btn_langs":"Languages","btn_options":"Options","text_title":"Spell Check As You Type"},"stylescombo":{"label":"Gaya","panelTitle":"Formatting Styles","panelTitle1":"Block Styles","panelTitle2":"Inline Styles","panelTitle3":"Object Styles"},"table":{"border":"Ukuran batas","caption":"Judul halaman","cell":{"menu":"Sel","insertBefore":"Sisip Sel Sebelum","insertAfter":"Sisip Sel Setelah","deleteCell":"Hapus Sel","merge":"Gabungkan Sel","mergeRight":"Gabungkan ke Kanan","mergeDown":"Gabungkan ke Bawah","splitHorizontal":"Pisahkan Sel Secara Horisontal","splitVertical":"Pisahkan Sel Secara Vertikal","title":"Properti Sel","cellType":"Tipe Sel","rowSpan":"Rentang antar baris","colSpan":"Rentang antar kolom","wordWrap":"Word Wrap","hAlign":"Jajaran Horisontal","vAlign":"Jajaran Vertikal","alignBaseline":"Dasar","bgColor":"Warna Latar Belakang","borderColor":"Warna Batasan","data":"Data","header":"Header","yes":"Ya","no":"Tidak","invalidWidth":"Lebar sel harus sebuah angka.","invalidHeight":"Tinggi sel harus sebuah angka","invalidRowSpan":"Rentang antar baris harus angka seluruhnya.","invalidColSpan":"Rentang antar kolom harus angka seluruhnya","chooseColor":"Pilih"},"cellPad":"Sel spasi dalam","cellSpace":"Spasi antar sel","column":{"menu":"Kolom","insertBefore":"Sisip Kolom Sebelum","insertAfter":"Sisip Kolom Sesudah","deleteColumn":"Hapus Kolom"},"columns":"Kolom","deleteTable":"Hapus Tabel","headers":"Headers","headersBoth":"Keduanya","headersColumn":"Kolom pertama","headersNone":"Tidak ada","headersRow":"Baris Pertama","invalidBorder":"Ukuran batasan harus sebuah angka","invalidCellPadding":"'Spasi dalam' sel harus angka positif.","invalidCellSpacing":"Spasi antar sel harus angka positif.","invalidCols":"Jumlah kolom harus sebuah angka lebih besar dari 0","invalidHeight":"Tinggi tabel harus sebuah angka.","invalidRows":"Jumlah barus harus sebuah angka dan lebih besar dari 0.","invalidWidth":"Lebar tabel harus sebuah angka.","menu":"Properti Tabel","row":{"menu":"Baris","insertBefore":"Sisip Baris Sebelum","insertAfter":"Sisip Baris Sesudah","deleteRow":"Hapus Baris"},"rows":"Baris","summary":"Intisari","title":"Properti Tabel","toolbar":"Tabe","widthPc":"persen","widthPx":"piksel","widthUnit":"lebar satuan"},"undo":{"redo":"Kembali lakukan","undo":"Batalkan perlakuan"},"widget":{"move":"Tekan dan geser untuk memindahkan","label":"%1 widget"},"uploadwidget":{"abort":"Pengunggahan dibatalkan oleh pengguna","doneOne":"Berkas telah berhasil diunggah","doneMany":"Pengunggahan berkas %1 berhasil","uploadOne":"Mengunggah berkas ({percentage}%)...","uploadMany":"Pengunggahan berkas {current} dari {max} berhasil ({percentage}%)..."},"wsc":{"btnIgnore":"Ignore","btnIgnoreAll":"Ignore All","btnReplace":"Replace","btnReplaceAll":"Replace All","btnUndo":"Undo","changeTo":"Change to","errorLoading":"Error loading application service host: %s.","ieSpellDownload":"Spell checker not installed. Do you want to download it now?","manyChanges":"Spell check complete: %1 words changed","noChanges":"Spell check complete: No words changed","noMispell":"Spell check complete: No misspellings found","noSuggestions":"- No suggestions -","notAvailable":"Sorry, but service is unavailable now.","notInDic":"Not in dictionary","oneChange":"Spell check complete: One word changed","progress":"Spell check in progress...","title":"Spell Checker","toolbar":"Check Spelling"},"codesnippet":{"button":"Masukkan potongan kode","codeContents":"Konten kode","emptySnippetError":"Potongan kode tidak boleh kosong","language":"Bahasa","title":"Potongan kode","pathName":"potongan kode"},"youtube":{"button":"Embed YouTube Video","title":"Embed YouTube Video","txtEmbed":"Paste Embed Code Here","txtUrl":"Paste YouTube Video URL","txtWidth":"Width","txtHeight":"Height","chkRelated":"Show suggested videos at the video's end","txtStartAt":"Start at (ss or mm:ss or hh:mm:ss)","chkPrivacy":"Enable privacy-enhanced mode","chkOlderCode":"Use old embed code","chkAutoplay":"Autoplay","chkControls":"Show player controls","noCode":"You must input an embed code or URL","invalidEmbed":"The embed code you've entered doesn't appear to be valid","invalidUrl":"The URL you've entered doesn't appear to be valid","or":"or","noWidth":"You must inform the width","invalidWidth":"Inform a valid width","noHeight":"You must inform the height","invalidHeight":"Inform a valid height","invalidTime":"Inform a valid start time","txtResponsive":"Make Responsive (ignore width and height, fit to width)","txtNoEmbed":"Video image and link only"},"pbckcode":{"title":"PBCKCODE","addCode":"Add code","editCode":"Edit code","editor":"Editor","settings":"Settings","mode":"Mode","tabSize":"Tab size","theme":"Theme","softTab":"Enable soft tabs","emmet":"Enable Emmet"}};
/** * Assumes settings from default Ember blueprints are included. * @see https://github.com/ember-cli/ember-new-output/blob/master/.eslintrc.js */ module.exports = { plugins: ['ember', 'hbs'], extends: [ // https://github.com/platinumazure/eslint-plugin-qunit 'plugin:qunit/recommended', ], rules: { /** * Disallow usage of empty attributes in Ember Data models. * @see https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/no-empty-attrs.md */ 'ember/no-empty-attrs': 'error', /** * Enforce proper order of properties. * @see https://github.com/ember-cli/eslint-plugin-ember#stylistic-issues */ 'ember/order-in-components': 'error', 'ember/order-in-controllers': 'error', 'ember/order-in-models': 'error', 'ember/order-in-routes': 'error', /** * Enforce usage of `Ember.get` and `Ember.set`. * @see https://github.com/ember-cli/eslint-plugin-ember/blob/master/docs/rules/use-ember-get-and-set.md */ 'ember/use-ember-get-and-set': 'error', /** * Run ember-template-lint on inline Handlebars templates. * @see https://github.com/ember-template-lint/eslint-plugin-hbs/blob/master/docs/rules/check-hbs-template-literals.md */ 'hbs/check-hbs-template-literals': ['error', 2], }, };
/** * created July 2019 as an MIT License modification * of Peter Dematté's 2015 Scientific Calculator * * I've converted the ES5 to ES6 and changed * functions to reflect more modern Javascript. * * @summary Javascript Scientific Calculator * @author Derek Reidy <mail@derekreidy.com> * Created at : 2019-07-24 17:45:25 * Last modified : 2019-07-26 15:00:47 */ (window => { const calcSS3 = document.querySelector('.calc-main'); const display = calcSS3.querySelector('.calc-display span'); const radDeg = calcSS3.querySelector('.calc-rad'); const smallerButton = calcSS3.querySelector('.calc-smaller'); const hold = calcSS3.querySelector('.calc-hold'); const lnButton = calcSS3.querySelector('.calc-ln'); const helpButton = calcSS3.querySelector('.calc-info'); const secondKeySet = [].slice.call(calcSS3.querySelector('.calc-left').children, 12, 20); const hiddenCopy = calcSS3.querySelector('textarea'); let pressedKey; let frozenKey; // active calculation keys let secondActive = false; // 2nd key active? let bracketKey; let brackets = 0; // count of current open brackets const calculator = []; // instances of Calculator let deg = false; // Deg mode or Rad let memory = 0; let resBuffer = '0'; let bigger = false; // app size let ln = 0; let buffStr = []; const sav = ['secondActive', 'deg', 'memory', 'buffStr', 'resBuffer']; const keyBoard = {}; const secondLayer = [ ['sin', 'cos', 'tan', 'ln', 'sinh', 'cosh', 'tanh', 'e<sup>x</sup>'], [ 'sin<sup>-1</sup>', 'cos<sup>-1</sup>', 'tan<sup>-1</sup>', 'log<sub>2</sub>', 'sinh<sup>-1</sup>', 'cosh<sup>-1</sup>', 'tanh<sup>-1</sup>', '2<sup>x</sup>' ] ]; class Calculator { constructor() { // for every '(' a new instance this.stack = [], this.num = 0, this.res = 0, this.buff = [false, false]; this.curr = true; this.rank = { '=': 0, '+': 1, '-': 1, '/': 2, '*': 2, 'yx': 3, 'x√y': 3, 'EE': 3 }; } calc(key, val) { const rank = this.rank; if (key === '%') { this.curr = 'funk'; return `${this.stack[0] ? this.stack[this.num - 1][0] / 100 * val : val / 100}`; } key = key.replace('×', '*').replace('÷', '/').replace('–', '-'); if (key !== '=') { this.buff[1] = key; } else if (this.buff[0] === false) { this.buff[0] = val; // feed buffer for repeating '=' } if (key === '=' && !this.stack[0] && this.curr && this.buff[1]) { // repeating '=' return `${this.buff[1] === 'yx' ? val ** this.buff[0] : this.buff[1] === 'x√y' ? val ** (1 / this.buff[0]) : [1] === 'EE' ? val * (10 ** this.buff[0]) : eval(`(${val})${this.buff[1]}(${this.buff[0]})`)}`; } if (!this.stack[0] && key !== '=') { // first filling this.buff[0] = false; this.stack[this.num++] = [val, key]; this.curr = true; return `${val}`; } if (this.stack[0] && this.curr && this.curr !== 'funk' && key !== '=') { // retyping / correcting operant this.stack[this.num - 1] = [val, key]; return `${val}`; } if (!this.stack[0]) { return `${val}`; } if (rank[key] <= rank[this.stack[this.num - 1][1]]) { this.stack[this.num - 1] = [ this.stack[this.num - 1][1] === 'yx' ? this.stack[this.num - 1][0] ** val : this.stack[this.num - 1][1] === 'x√y' ? this.stack[this.num - 1][0] ** (1 / val) : this.stack[this.num - 1][1] === 'EE' ? this.stack[this.num - 1][0] * (10 ** val) : eval(`(${this.stack[this.num - 1][0]})${this.stack[this.num - 1][1]}(${val})`), key ]; } if (rank[key] > rank[this.stack[this.num - 1][1]]) { this.stack[this.num++] = [val, key]; } else if (this.stack[this.num - 2] && rank[key] <= rank[this.stack[this.num - 2][1]]) { this.calc(key, this.stack[--this.num][0]); } this.res = `${this.stack[this.num - 1] ? this.stack[this.num - 1][0] : this.res}`; if (key === '=') { this.init('AX'); } this.curr = true; return this.res; } init(key) { if (key.match(/A/)) { this.stack = []; this.num = 0; }; if (key === 'AC') { this.buff = [false, false]; } return '0'; } } // ---------- INIT ---------- // // hiddenCopy.focus(); // for Chrome extension only // Collect all keys for (let k = 2; k--; ) { for (let l = calcSS3.children[k + 1], m = l.children, n = m.length; n--; ) { keyBoard[l.children[n].textContent.replace(/\s*/g, '')] = l.children[n]; } } keyBoard['C'] = keyBoard['AC']; keyBoard['Rad'] = keyBoard['Deg']; for (let m = secondLayer[0], n = m.length; n--; ) { keyBoard[secondLayer[1][n].replace(/<\/*\w+>/g, '')] = keyBoard[m[n]]; } keyBoard['2x'] = keyBoard['ex']; calculator[0] = new Calculator(); // recover after reload or crash... (localStorage => { if (!localStorage || !localStorage['resBuffer']) { return; // for the very first run or after fatal crash } bigger = localStorage['bigger'] ? eval(localStorage['bigger']) : true; toggleCalc(); if (+localStorage['ln']) { ln = localStorage['ln']; switchGrouping(); } try { if (localStorage['secondActive'].match(/false|null/) ? false : true) { keyDown(false, keyBoard['2nd']); doKey('2nd', true); } if (eval(localStorage['deg'])) doKey('Deg', true); if (localStorage['memory']) { render(localStorage['memory']); doKey('m+', true); } render(localStorage['resBuffer']); const buffStrX = localStorage['buffStr'].split(','); for (let n = 0, m = buffStrX.length; n < m; n++) { if (buffStrX[n]) doKey(buffStrX[n], true); } render(localStorage['resBuffer']); resBuffer = localStorage['resBuffer']; } catch (e) { for (let n = sav.length; n--;) { localStorage.removeItem(sav[n]); } } })(window.localStorage); // ---------------- Event Listener Keys ---------------- // document.addEventListener('keypress', ({which}) => { let key = which; const holdKey = hold.textContent; const keyMatch = (',|.|-|–|/|÷|*|×|#|+/–|x|x!|E|EE|e|ex| |2nd|r|x√y|R|√|p|π|^|yx|\'|yx|"|yx|m|mr|v|mc|b|m+|n|m-|' + 's|sin|c|cos|t|tan|S|sin-1|C|cos-1|T|tan-1|d|Deg|°|Deg|l|ln|L|log|\\|1/x|X|2x').split('|'); const keyMatchHold = ('sin|sinh|cos|cosh|tan|tanh|m-|Rand|Deg|Rand|sin-1|sinh-1|cos-1|cosh-1|tan-1|tanh-1|' + '1|1/x|2|x2|3|x3|x√y|√|ln|log2|ex|2x').split('|'); if (key === 13) key = 61; key = String.fromCharCode(key); for (let n = 0, m = keyMatch.length; n < m; n = n + 2) if (key === keyMatch[n]) { key = key.replace(key, keyMatch[n + 1]); break } if (holdKey) { for (let n = 0, m = keyMatchHold.length; n < m; n = n + 2) if (key == keyMatchHold[n]) { key = key.replace(key, keyMatchHold[n + 1]); break } hold.textContent = ''; } if ((key === 'h' || key === 'H') && !holdKey) hold.textContent = 'hold'; if (key === 'G' && holdKey) switchGrouping(true); if (!keyBoard[key]) return false; if ((key.match(/-1$|log2$|2x$/) && !secondActive) || (key.match(/h$|n$|cos$|ex$/) && secondActive)) { keyDown(false, keyBoard['2nd']); doKey('2nd', true); } keyDown(false, keyBoard[key]); doKey(key, true); }, false); document.addEventListener('keydown', e => { const str = resBuffer.replace(/\s/g, ''); const strLen = str.split('').length - 1; toggleOptions(); if (e.which === 8 && calculator[brackets].curr !== true && calculator[brackets].curr !== 'funk' && str !== '0') { e.preventDefault(); while (buffStr.length && !keyBoard[buffStr[buffStr.length - 1]]) { // bull shit key(s) buffStr.pop(); } if (buffStr[buffStr.length - 1] === '+/–') { doKey('+/–', true); buffStr.pop(); } else if (resBuffer.match(/\-\d$/) || resBuffer.match(/^\d$/)) { buffStr.pop(); doKey('C', true); render('0'); } else { render(str.substring(0, strLen), true); } buffStr.pop(); if (buffStr[buffStr.length - 1] === '.') { render(str.substring(0, strLen - 1)); buffStr.pop() } } if (e.which === 220) { keyDown(false, keyBoard['xy']); } if (e.which === 46) { keyDown(false, keyBoard['AC']); doKey(keyBoard['AC'].textContent, true); } if (e.which === 9) { toggleCalc(true); e.preventDefault(); } }, false); document.addEventListener('keyup', () => { keyUp(); saveState(); }, false); document.body.addEventListener('paste', e => { render(`${parseFloat(`${e.clipboardData.getData("Text")}`)}`); calculator[brackets].curr = true; keyBoard['AC'].children[0].firstChild.data = 'C'; if (frozenKey) freezeKey(frozenKey, true); e.preventDefault(); }, false); document.body.addEventListener('copy', e => { hiddenCopy.textContent = resBuffer.replace(/\s/g, ''); hiddenCopy.focus(); hiddenCopy.select(); }, false); // ---------------- Event Listener For Mouse --------------- // calcSS3.onmousedown = e => { keyDown(e); if (!pressedKey) return false; document.addEventListener('mouseout', keyUp, false); document.addEventListener('mouseover', keyDown, false); return false; } document.addEventListener('mouseup', e => { const event = e || window.event; const target = getTargetKey(event.target); const keyText = target.textContent.replace(/\s*/g, ''); const key = keyBoard[keyText]; if (event.target === helpButton) { window.location = 'http://dematte.at/calculator#usage'; } if (event.target === smallerButton) { toggleCalc(true); } if (event.target === lnButton) { switchGrouping(true); } if (event.target !== lnButton) { toggleOptions(); } document.removeEventListener('mouseout', keyUp, false); document.removeEventListener('mouseover', keyDown, false); if (!pressedKey) { return false; } if (key) { doKey(keyText); saveState(); } }, false); display.parentElement.addEventListener('dblclick', () => { if (!helpButton.active) { toggleCalc(true); } }, false); helpButton.addEventListener('mouseover', () => { toggleOptions(true); }, false); // ------------------- Event Related Functions ------------------ // function keyDown (e, obj) { // works for mouse and key const event = e || window.event; const target = obj || getTargetKey(event.target); const keyText = target.textContent.replace(/\s*/g, ''); const key = keyBoard[keyText]; if (key) { keyUp(); // recover key in case of a javaScript Error pressedKey = key; key.className = `${key.className} calc-press`; } return false; } function getTargetKey(elm) { while (elm !== calcSS3 && elm.parentNode && elm.parentNode.style && !/calc-(?:left|right)/.test(elm.parentNode.className)) { elm = elm.parentNode; } return elm; } function keyUp() { if (pressedKey && pressedKey !== secondActive) { pressedKey.className = pressedKey.className.replace(' calc-press', ''); pressedKey = null; } } function freezeKey(key, del) { const obj = (!del || del !== 2) ? frozenKey : key; if (obj) obj.className = obj.className.replace(' calc-active', ''); if (!del) { key.className = `${key.className} calc-active`; frozenKey = key; } return obj; } function saveState() { for (let n = sav.length; n--;) { localStorage[sav[n]] = eval(sav[n]); } } function toggleOptions(doIt) { helpButton.active = !!doIt; } function toggleCalc(doIt) { const cName = calcSS3.className; if (doIt) { bigger = !bigger; } localStorage['bigger'] = bigger; calcSS3.className = bigger ? cName.replace(' calc-small', '') : `${cName} calc-small`; smallerButton.firstChild.data = bigger ? '>' : '<'; render(resBuffer); } function switchGrouping(doIt) { if (doIt) { ln = ++ln > 3 ? 0 : ln; } lnButton.firstChild.data = !ln ? '.' : ln === 1 ? ',' : ln === 2 ? ',.' : '.,'; render(resBuffer); localStorage['ln'] = ln; } function render(val, inp) { const regx = /(\d+)(\d{3})/; const hasComma = val.match(/\./); let tmp; const valAbs = Math.abs(+val); let fontSize = 45; const displayStyle = display.style; const displayParentStyle = display.parentNode.style; if (val.match(/NaN|Inf|Error/)) { tmp = 'Error'; } else { resBuffer = val; if (valAbs >= 1e+16) { val = `${(+val).toExponential(13)}`; } if (!bigger && ((!inp || inp === '+/–') && valAbs !== 0)) { val = (+val).toPrecision(9); } tmp = (`${val}`).split('.'); if (tmp[1]) { tmp[2] = tmp[1].split('e'); if (tmp[2][1]) { tmp[1] = tmp[2][0]; } if (!inp || inp === '+/–') { tmp[1] = (`${(+(`1.${tmp[1]}`)).toPrecision(bigger ? 16 : tmp[2][1] ? 7 : 9)}`); if (tmp[1] >= 2) { tmp[0] = `${+tmp[0] + 1}`; } tmp[1] = tmp[1].substr(2).replace(/0+$/, ''); } } while (regx.test(tmp[0])) { tmp[0] = tmp[0].replace(regx, '$1' + ' ' + '$2'); } tmp = tmp[0] + ((tmp[1] || hasComma) ? `.${tmp[1]}` : ''). replace('.undefined', ''). replace(inp ? '' : /\.$/, '') + (tmp[2] && tmp[2][1] ? `e${tmp[2][1]}` : ''); } if (ln) { tmp = tmp.replace(/\./g, '#'). replace(/\s/g, ln === 1 ? ' ' : ln === 2 ? ',' : '.'). replace(/#/g, ln === 2 ? '.' : ','); } display.firstChild.data = tmp; // For common use: Get the values of pixels dynamically to stay free from design (...but outside this function) displayStyle.fontSize = '45px'; displayParentStyle.lineHeight = '61px'; while (display.offsetWidth > display.parentNode.offsetWidth - (bigger ? 40 : 30)) { displayStyle.fontSize = `${fontSize--}px`; displayParentStyle.lineHeight = `${fontSize + 18}px` } } function doKey(text, alt) { const key = keyBoard[text]; // text = key.textContent.replace(/\s*/g, ''); if (text === '2nd') { secondActive = secondActive ? null : true; key.className = secondActive ? 'calc-press calc-second' : ''; // !!! for (let n = secondKeySet.length; n--; ) { secondKeySet[n].children[0].innerHTML = secondLayer[secondActive ? 1 : 0][n]; } } else if (text.match(/^[+|–|÷|×|yx|x√y|E]+$/) && text !== '√') { freezeKey(key); } else if (text.match(/^[\d|\.|π]$/)) { freezeKey(key, true); keyBoard['AC'].children[0].firstChild.data = 'C'; } else if (text === 'C') { key.children[0].firstChild.data = 'AC'; if (frozenKey) freezeKey(frozenKey); } else if (text.match(/AC|=/)) { if (bracketKey) freezeKey(bracketKey, 2); freezeKey(key, true); frozenKey = null } else if (text.match(/Deg|Rad/)) { radDeg.firstChild.data = deg ? 'Rad' : 'Deg'; key.children[0].firstChild.data = deg ? 'Deg' : 'Rad'; deg = !deg } else if (text === '(') { bracketKey = key; freezeKey(bracketKey, 2).className += ' calc-active'; } else if (text === ')' && brackets === 1 && bracketKey) { freezeKey(bracketKey, 2); } else if (text.match(/^mr$/) && memory) { keyBoard['AC'].children[0].firstChild.data = 'C'; } evalKey(text); if (!alt) { keyUp(); } if (text.match(/^m[c|+|-]/)) { freezeKey(keyBoard['mr'], 2).className += (memory ? ' calc-active' : ''); } } function evalKey(key) { let dispVal = `${resBuffer.replace(/\s/g, '').replace(/Error|∞|-∞/, '0')}`; const _PI = Math.PI; let lastKey; if (!key.match(/2nd|Deg|Rad|m/)) { // +/- issue buffStr.push(key); if ((buffStr[buffStr.length - 2] === '=' && key !== '=' && calculator[brackets].curr) || key === 'AC') { buffStr = [key]; } } lastKey = buffStr[buffStr.length - 2]; if (key.match(/^[\d|\.]$/) || key === '+/–') { if (calculator[brackets].curr && key !== '+/–' || (key === '+/–' && lastKey && lastKey.match(/^[+|–|÷|×|yx|x√y|E|^C]+$/))) { dispVal = '0'; calculator[brackets].curr = false; } if ((Math.abs(+(dispVal + key)) > (bigger ? 1e15 : 1e9) || dispVal.replace(/^-/, '').length > 15 || (dispVal.replace('-', '').replace(/\./g, '').length > (bigger ? 14 : 8)) || (dispVal.match(/\.|\e\+/) && key === '.')) && key !== '+/–') { buffStr.pop(); return; } else if (key === '+/–') { render(!(dispVal.replace(/e[\+|\-]/, '')).match('-') ? `-${dispVal}` : dispVal.replace(/^-/, ''), '+/–'); } else { render((dispVal + key).replace(/^(-)*?0(\d)$/, '$1' + '$2'), true); } } else if (key.match(/^C|AC/)) { render(calculator[brackets].init(key)); hold.textContent = ''; } else if (key.match(/^[+|–|÷|×|-|\/|*|yx|x√y|%|E]+$/) && key !== '√') { render(calculator[brackets].calc(key, dispVal)); } else { if (brackets > -1) { calculator[brackets].curr = 'funk'; } switch (key) { case '=': while (brackets > -1) { render(dispVal = calculator[brackets--].calc('=', dispVal)); } brackets = 0; calculator[brackets].curr = true; break; case '(': calculator[++brackets] = new Calculator(); calculator[brackets].curr = true; break; case ')': if (brackets) { render(calculator[brackets--].calc('=', dispVal)); } if (brackets > -1) { calculator[brackets].curr = false; } break; case 'mc': memory = 0; break; case 'm+': memory += +dispVal; break; case 'm-': memory -= +dispVal; break; case 'mr': render(`${memory}`); break; case '1/x': render(`${1 / dispVal}`); break; case 'x2': render(`${dispVal ** 2}`); break; case 'x3': render(`${dispVal ** 3}`); break; case 'x!': render(`${(function fak(n) { return n < 0 || n > 170 ? NaN : n <= 1 ? 1 : n * fak(n - 1)})(Math.round(+dispVal))}`); break; case '√': render(`${Math.sqrt(dispVal)}`); break; case 'log': render(`${Math.log(dispVal) / Math.log(10)}`); break; case 'sin': render(!deg && Math.abs(dispVal) === _PI ? '0' : `${Math.sin(dispVal * (deg ? _PI / 180 : 1))}`); break; case 'sin-1': render(`${Math.asin(dispVal) * (deg ? 180 / _PI : 1)}`); break; case 'cos': render(`${Math.cos(dispVal * (deg ? _PI / 180 : 1))}`); break; case 'cos-1': render(`${Math.acos(dispVal) * (deg ? 180 / _PI : 1)}`); break; case 'tan': render(!deg && Math.abs(dispVal) === _PI ? '0' : `${Math.tan(dispVal * (deg ? _PI / 180 : 1))}`); break; case 'tan-1': render(`${Math.atan(dispVal) * (deg ? 180 / _PI : 1)}`); break; case 'ln': render(`${Math.log(dispVal)}`); break; case 'log2': render(`${Math.log(dispVal) / Math.log(2)}`); break; case 'sinh': render(`${(Math.E ** dispVal - Math.E ** -dispVal) / 2}`); break; case 'sinh-1': render(`${Math.log(+dispVal + Math.sqrt(1 + dispVal ** 2))}`); break; case 'cosh': render(`${(Math.E ** dispVal + Math.E ** -dispVal) / 2}`); break; case 'cosh-1': render(`${2 * Math.log(Math.sqrt((+dispVal + 1) / 2) + Math.sqrt((+dispVal - 1) / 2))}`); break; case 'tanh': ((e1, e2) => { render(`${(e1 - e2) / (e1 + e2)}`); })(Math.E ** dispVal, Math.E ** -dispVal); break; case 'tanh-1': render(`${(Math.log(+dispVal + 1) - Math.log(1 - dispVal)) / 2}`); break; case 'ex': render(`${Math.exp(dispVal)}`); break; case '2x': render(`${2 ** dispVal}`); break; case 'π': render(`${_PI}`); break; case 'Rand': render(`${Math.random()}`); break; default: // buffStr.pop(); break; } } } })(window);
let utils = require('./utils'); let config = require('./config'); // 节点在旧节点树中的索引(位置) let keyIndex = -1; // diff 方法获取的,记录差异的对象 var allPatches; /** * 开始打补丁,从根节点开始,按照差异描述对象,按索引处理 * @param {DOM Element} root 根节点 * @param {Object} patches 差异描述对象 */ function patch(root, patches) { allPatches = patches; walk(root); } /** * 处理的顺序 * @param {DOM Element} node */ function walk(node) { // 索引绝对递增 ++keyIndex; let patch = allPatches[keyIndex]; // 差异上到下获取,补丁从下到上打,所以这里采用的是`后序遍历打补丁` // 先遍历处理子节点 (node.childNodes || []).forEach(child => walk(child)); // 最后处理当前节点 if (patch) { doPatch(node, patch); } } /** * 处理具体的节点 * @param {DOM Element} node * @param {Object} patch */ function doPatch(node, patch) { // 根据约定的 type 进行处理 switch (patch.type) { case config.REMOVE: // 节点删除 node.parentNode.removeChild(node); case config.TEXT: // 文本修改 node.textContent = patch.content; break; case config.ATTRS: // 属性修改 for (let attr in patch.attrs) { let value = patch.attrs[attr]; if (value) { utils.setAttr(node, attr, value); } else { node.removeAttribute(attr); } } break; case config.REPLACE: // 节点替换 let newNode = (patch.node instanceof Element) ? patch.node.render() : document.createTextNode(patch.node); node.parentNode.replaceChild(newNode, node); break; } } module.exports = patch;
const { Schema } = require('./config') const ObjectId = Schema.Types.ObjectId const CommentSchema = new Schema({ //头像 用户名 文章 内容 content:String, //关联用户表 from: { type: ObjectId, ref: 'users' }, //关联到article 表 article: { type: ObjectId, ref: 'articles' } },{ versionKey: false, timestamps: { createdAt: 'created' } }) //versionKey 显示版本号 //timestamps 显示创建时间 和 更新时间 // 设置comment 的 remove钩子 // 前置钩子 // CommentSchema.pre('remove', (next) => { // // this 指向当前文档 // }) // 后置钩子 在所有钩子最后 同样处于事件之前 CommentSchema.post('remove', (doc) => { //当前这个回调函数 一定会在remove之前触发 const Article = require('../Models/article.js') const User = require('../Models/user.js') const { from, article } = doc // 对应 文章评论数 -1 Article.updateOne({_id: article}, {$inc: {commentNum: -1}}).exec() // 当前被删除的评论作者 commentNum -1 User.updateOne({_id: from}, {$inc: {commentNum: -1}}).exec() }) module.exports = CommentSchema
/** * Route for uploading video files */ 'use strict' const router = require('express').Router() const sanitize = require('mongo-sanitize') const VideoInfo = require('../../models/VideoInfo') const VideoAmount = require('../../models/VideoAmount') const fsDAO = require('../../models/fsDAO') const path = require('path') const Lib = require('../../lib/Lib') const fileType = require('file-type') router.route('/upload') // for rendering upload form .get((req, res) => { if (!req.session.username) { res.status(403) res.render('error/403') } else { res.render('video/upload') } }) // for video storage .post(async (req, res) => { if (!req.session.username) { res.status(403) res.render('error/403') } else { const cleanBody = sanitize(req.body) const fileContent = req.files.video const buffer = fileContent.data const fType = fileType(buffer) // validates the file format if (!path.extname(fileContent.name) || !Lib.validate.mimeType(fType.mime)) { req.session.flash = { type: 'error', text: 'Unsupported file format' } res.status(400) res.redirect('/upload') } else if (cleanBody.title.length > 50 || cleanBody.description.length > 500) { req.session.flash = { type: 'error', text: ` Title cannot be longer than 50 characters, and description cannot be longer than 500 characters. ` } res.status(400) res.redirect('/upload') } else { const fileName = Lib.make.randomString() + path.extname(fileContent.name) const filePath = `./public/uploads/videos/${fileName}` // saves file to fs await fsDAO.putFile(filePath, buffer) const thumbnailDir = './public/uploads/thumbnails/' // Generates and saves thumbnail const thumbnailName = await Lib.make.thumbnail(filePath, thumbnailDir) // saves video info in separate mongoose model const videoInfo = new VideoInfo({ fileName: fileName, thumbnailName: thumbnailName, contentType: fType.mime, title: cleanBody.title, description: cleanBody.description, createdBy: req.session.username, creatorId: req.session.userid }) await videoInfo.save() // to update video amount const videoAmount = await VideoAmount.findOne({ name: 'VideoAmount' }) if (videoAmount) { videoAmount.amount += 1 await videoAmount.save() } else { const newVideoAmount = new VideoAmount() newVideoAmount.amount += 1 await newVideoAmount.save() } req.session.flash = { type: 'success', text: 'The Video has been succesfully uploaded!' } res.status(201) res.redirect(`/play/${fileName}`) } } }) module.exports = router
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ module.exports=[ "Cheer", "PogChamp", "cheerwhal", "Corgo", "uni", "ShowLove", "Party", "SeemsGood", "Pride", "Kappa", "FrankerZ", "HeyGuys", "DansGame", "EleGiggle", "TriHard", "Kreygasm", "4Head", "SwiftRage", "NotLikeThis", "FailFish", "VoHiYo", "PJSalt", "MrDestructoid", "bday", "RIPCheer", "Anon" ] },{}],2:[function(require,module,exports){ /* 기본 설정 */ configDefault = { numChatMax : 20, // html에 한꺼번에 표시될 수 있는 메세지의 최대 갯수 personalColor : false, /* 이름 색깔을 트위치 이름색과 일치시킬지 theme에서 제한 가능 */ badgeVisible : false, /* 구독, 비트 등 뱃지를 표시할지 theme에서 제한 가능 */ badgeChannelId : 0, // 구독 뱃지를 불러올 채널ID themeURI : "", /* 불러올 테마 Uri. 로컬 테마를 이용할 경우 공백으로 둔다. */ theme : "default", // 사용할 테마. theme\테마\*의 파일을 사용 themeName : "", /* 테마의 이름 theme로부터 import */ msgExistDuration : 0, // 메세지가 애니메이션을 빼면 얼마나 오래 표시될 지 msgAniDuration : 0, /* 메세지 표시 애니메이션의 소요시간 theme로부터 import */ debugLevel : 2, // 0:미표시, 1:console.log, 2:addChatMessage useDisplayName : true, // 한글 닉네임으로 이름을 표시할지 loadCheerImgs : true, // 비트 후원채팅을 이미지로 표시할지 loadTwitchCons : true, // 트위치 이모티콘과 구독콘을 불러올지 loadTwitchv2 : true, // 움직이는 트위치 이모티콘을 불러올지 loadDcCons : true, // 디씨콘을 불러올지 dcConsURI : "", /* 불러올 디씨콘 Uri. 로컬 디씨콘을 이용할 경우 공백으로 둔다. */ subMonthsMsg : "☆ {!0:{months} 개월 }구독{0: 시작}! ☆", // 구독 메세지를 받았을 때 추가로 출력할 텍스트 cheersMsg : "☆ {!0:{bits} 비트 }후원 ! ☆", // 비트 후원을 받았을 때 추가로 출력할 텍스트 clipReplaceMsg : "[클립]", // 클립 링크의 대체 텍스트 linkReplaceMsg : "[링크]", // (일반) 링크의 대체 텍스트 webSocket : "wss://irc-ws.chat.twitch.tv:443", /* 접속할 웹소켓 const value */ nick : "justinfan00000", // 트위치 IRC에서 이용할 gust nickname pass : "foobar", // 트위치 IRC에서 이용할 guest password channel : "#mr_watert", /* 접속할 채널 "#id1,#id2,.."으로 여러 채널에 접속 가능 */ retryInterval : 3, // 접속에 끊겼을 때 재접속 시도 간격(초) allMessageHandle : false, /* IRC로부터 받은 처리되지 않은 메세지를 html에 표시 "처리되지 않은 메세지를 수신했습니다" */ muteUser : ["Nightbot"], /* html에 표시하지 않을 유저 nickname display-name과 트위치 id를 모두 사용 가능 */ deleteBanMsg : true, // ban된 유저의 메세지를 지우기 commands : [ {exe:"clear", msg:"!!clear"}, {exe:"theme", msg:"!!theme"}, {exe:"load", msg:"!!load"}, {exe:"scale", msg:"!!scale"} ], // 활성화시킬 명령어 replaceMsgs : [] /* 봇 메세지 등을 대체 { orig: 원문(문자열 또는 정규표현식), to: 대체할 문자열("{no_display}"로 미표시) } */ }; /* 메세지 출력 함수 정의 */ var numChat = 0; var replaceMsgFormat = function(message, amount) { if (typeof amount != "number") { amount = 0; } var retMessage = message.replace("{months}", amount).replace("{bits}", amount); if (amount == 0) { retMessage = retMessage.replace(/\{0:([^\}]*)}/g, "$1").replace(/\{!0:([^\}]*)}/g, ""); } else { retMessage = retMessage.replace(/\{!0:([^\}]*)}/g, "$1").replace(/\{0:([^\}]*)}/g, ""); } return retMessage; } var getRemoveTimeout = function(box) { return function() { if ((box||{}).parentElement != null) { box.remove(); --numChat; } }; } var timeToMs = function(time) { var num = time.split(/[a-z]/i)[0]; try { num = Number(num); } catch(e) { return 0; } var isMs = /ms/.test(time); return num * (isMs? 1: 1000); } var applyMessageRemove = function(box) { // 기존 타이머를 정리 if (box.timeout) { clearTimeout(box.timeout); } if (!box.nodeType) { return; } // CSS 애니메이션 적용 if (configData.msgAniDuration) { var computedStyle = getComputedStyle(box); var origName = computedStyle.animationName; var origDuration = computedStyle.animationDuration; var origAnimation = computedStyle.animation; var origDirection = computedStyle.animationDirection; box.classList.add("remove"); var newName = computedStyle.animationName; var newDuration = computedStyle.animationDuration; var condOrig = (origName != "none"); var condNew = (newName != "none"); var condSame = (origName == newName); if (!condNew && !condOrig) { // 애니메이션이 하나도 없을 경우 그냥 삭제 (getRemoveTimeout(box))(); return; } if (condOrig && (condNew == condSame)) { // 메세지 삭제 애니메이션만 없을 경우 생성 애니메이션을 반전 box.style.animation = origAnimation; box.style.animationDirection = { "normal": "reverse", "alternate": "alternate-reverse", "reverse": "normal", "alternate-reverse": "alternate" }[origDirection] || "reverse"; } if (configData.msgAniDuration > 0) { // 애니메이션 시간을 적용 newDuration = configData.msgAniDuration + "s"; box.style.animationDuration = newDuration; } box.timeout = setTimeout( getRemoveTimeout(box), timeToMs(newDuration) || timeToMs(origDuration) ); } else { // 메세지 삭제 애니메이션 무시 (getRemoveTimeout(box))(); return; } } addChatMessage = function(nick, message, data) { // DOM Element 생성 var chatNicknameBox = document.createElement("div"); chatNicknameBox.classList.add("chat_nickname_box"); var chatBadgeBox = document.createElement("div"); chatBadgeBox.classList.add("chat_badge_box"); var chatUpperBox = document.createElement("div"); chatUpperBox.classList.add("chat_upper_box"); var chatMessageBox = document.createElement("div"); chatMessageBox.classList.add("chat_msg_box"); var chatLowerBox = document.createElement("div"); chatLowerBox.classList.add("chat_lower_box"); var chatOuterBox = document.createElement("div"); chatOuterBox.classList.add("chat_outer_box"); if (data.nick) { chatOuterBox.classList.add("user_"+data.nick); } // Element에 내용 추가 chatNicknameBox.innerHTML = nick; message = message.replace(/\\\"/g, '"').replace(/\\\\/g, "\\"); if (typeof applyMessage != "undefined") { chatMessageBox.innerHTML = applyMessage(message, data); if (data.noDisplay) { return null; } } else { chatMessageBox.innerHTML = message; } if (data) { if (data.color && configData.personalColor) { chatNicknameBox.style.color = data.color; } if (data.badges && configData.badgeVisible) { // 뱃지 채워넣고 data.badges.toString().split(",").forEach( function(badge) { var badgeName = badge.split("/")[0]; var badgeTier = badge.split("/")[1]; var targets = Object.keys(badgeList||{}) .filter( function(name) { return (name.indexOf(badgeName + "/") == 0); } ) .filter( function(name) { if (!isNaN(badgeTier)) { return Number(name.split("/")[1]) <= badgeTier; } return (name.indexOf(badgeTier) == badgeName.length+1); } ) .sort( function(right, left) { return Number(left.split("/")[1]) - Number(right.split("/")[1]); } ); if (targets.length > 0) { var chatBadge = document.createElement("img"); chatBadge.src = badgeList[targets[0]]; chatBadge.classList.add("badge_" + badgeName); chatBadge.classList.add("badge_" + badge); chatBadgeBox.appendChild(chatBadge); } } ); } if (chatBadgeBox.children.length == 0) { chatBadgeBox.classList.add("empty"); } if (data.clip) { // 클립 추가하고 chatLowerBox.innerHTML = data.clip + chatLowerBox.innerHTML; } if (data.subMonths != undefined) { // 후원메세지 그 위에 추가하고 chatLowerBox.innerHTML = '<div class="chat_subscribe_box">' + replaceMsgFormat(configData.subMonthsMsg, data.subMonths) + "</div>" + chatLowerBox.innerHTML; } if (data.cheers != undefined) { // 비트 메세지도 그 위에 추가하고 chatLowerBox.innerHTML = '<div class="chat_cheer_box">' + replaceMsgFormat(configData.cheersMsg, data.cheers) + "</div>" + chatLowerBox.innerHTML; } } if ( chatMessageBox.innerHTML.replace(/(<[^>]*>)|\s/g,"").length == 0) { chatMessageBox.classList.add("image_only"); } // 페이지에 Element 연결 chatUpperBox.appendChild(chatNicknameBox); chatUpperBox.appendChild(chatBadgeBox); chatOuterBox.appendChild(chatUpperBox); chatOuterBox.upper = chatUpperBox; chatOuterBox.appendChild(chatLowerBox); chatOuterBox.lower = chatLowerBox; chatLowerBox.appendChild(chatMessageBox); chatLowerBox.msg = chatMessageBox; document.getElementById("chat_wrapper").appendChild(chatOuterBox); // 메세지 타임아웃 설정 if (configData.msgExistDuration > 0) { setTimeout( function() { applyMessageRemove(chatOuterBox); }, configData.msgExistDuration*1000 ); } // 넘치는 메세지를 삭제 if((++numChat > configData.numChatMax)) { var first = document.getElementsByClassName("chat_outer_box")[0]; document.getElementById("chat_wrapper").removeChild(first); --numChat; } return chatOuterBox; } var concatChatMessage = function(nick, message, data) { var lChild = document.getElementById("chat_wrapper").lastChild; if (lChild && lChild.getElementsByClassName("chat_nickname_box")[0].innerHTML == nick) { if (typeof applyMessage != "undefined") { message = applyMessage(message, data); } with (lChild.lower.msg) { innerHTML += "\n" + message; style.maxHeight = "none"; style.whiteSpace = "pre-line"; style.lineHeight = "1.5"; } } else { addChatMessage.apply(this, arguments); } } var banChatMessage = function(nick) { var children = document.getElementsByClassName("user_"+nick); if (children && children.length > 0) { for (var index in children) { if (isNaN(Number(index))) { continue; } children[index].lower.msg.innerHTML = "&lt;message deleted&gt;"; } } } var applyReplace = function(message, data){ return message; }; var applyCheerIcon = function(message, data){ return message; }; var applyTwitchCon = function(message, data){ return message; }; var applyDcCon = function(message, data){ return message; }; var applyMessage = function(message, data) { // 색채팅 제거 if ( (message.indexOf("ACTION")==6) && (message.indexOf("\\u0001")!=-1) ) { message = message.replace(/\\u0001/g, "").replace(/^ACTION /, ""); } // HTML 이스케이핑 if ((data.escape == undefined) || (data.escape == true)) { message = message.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"); } message = applyReplace(message, data); message = applyTwitchCon(message, data); message = applyCheerIcon(message, data); message = applyDcCon(message, data); var twipApply = require("./twip_apply.js"); if (twipApply) { message = twipApply.apply(message, data); } return message; } /* URL에서 설정값을 가져와 덮어쓰기 */ if (window.location.href.indexOf("?") != -1) { var queries = window.location.search; if (queries||"".length > 0) { queries.slice(1).split("&").forEach( function(queryData) { var value = queryData.split("="); var key = value.shift(); value = value[0]; if (value == undefined) { return; } if (key == "scale") { if (!isNaN(value)) { window.localStorage.setItem("scale", value); } } else if (configDefault.hasOwnProperty(key)) { switch (key) { case "channel": configData.channel = value.split(",").map( function(channel) { return "#" + channel; } ).join(","); return; case "muteUser": configData.muteUser = (value==="")? []: value.split(","); return; case "webSocket": case "nick": case "pass": return; default: break; } switch (typeof(configDefault[key])) { case "object": return; case "boolean": configData[key] = (value === "true"); return; case "number": var numberValue = Number(value); if (!isNaN(numberValue)) { configData[key] = numberValue; } return; case "string": default: break; } configData[key] = value; } } ); } } /* 배율 설정 적용 */ var setScale = function() { var scale = window.localStorage.getItem("scale"); if (!scale) { return; } with (document.body.style) { width = (10000 / scale) + "%"; transformOrigin = "left bottom"; transform = "scale(" + scale/100 + ")"; } } setScale(); /* 설정 파일 확인 및 디버그 내용 출력 함수 정의 */ var completeCount = 0; var checkComplete = function() { /* CSS, 디씨콘, 뱃지, 이모티콘+구독콘, 후원아이콘, 설정, 그리고 접속채널들 */ var num = 6 + configData.channel.match(/#/g).length; if (++completeCount == num) { var width = Number(getComputedStyle(document.body).width.slice(0,-2)); width = Math.max(12, parseInt(width/20))+"px"; var chat = addChatMessage("", '<center style="line-height:1em; box-sizing:border-box;">' + '<div style="display:inline-block; font-size:' + width + ";" + 'padding:0.45em; background:black">' + '<div style="padding:0.45em; border:0.1em solid white; ' + "display:inline-block !important; white-space:pre !important;" + "font-size:" + width + "; line-height:1em; color:white !important;" + "font-family:'굴림체' !important; font-weight:normal; " + 'text-shadow:.05em .05em dodgerblue;">' + " B r i d g e \n ■■□□ □□■■ \n" + " ■ □ □ □ ■ \n ■■□□ □ ■ \n" + " ■ □ □ □ ■ \n ■■□□□ □□■■。" + "</div></div></center>", { badges:[], escape:false } ) if (chat != null) { chat.upper.style.display = "none"; chat.lower.msg.style.maxHeight = "none"; } checkComplete = function(){}; } } if (typeof configData == "undefined") { configData = {}; } debugLog = function(dat) {}; { var configLoadMessage = ""; var configDataLength = Object.keys(configData).length; if (configDataLength == 0) { configLoadMessage = "설정 파일(lib/config.js)을 로드하는 데 문제가 생겨 기본 설정을 사용합니다.<br />"; Object.assign(configData, configDefault); } else { var unloadedConfigs = Object.keys(configDefault).reduce( function(acc, cur) { if (configData[cur] === undefined) { configData[cur] = JSON.parse(JSON.stringify(configDefault[cur])); return (++acc); } return acc; }, 0 ); if (unloadedConfigs > 0) { configLoadMessage = "일부 설정값을 찾을 수 없어 기본값을 사용합니다.<br />"; } } if (configData.debugLevel != 0) { if (configData.debugLevel == 1) { debugLog = function(dat) { console.log(dat); }; } else { debugLog = function(dat, unConcat) { if (unConcat) { addChatMessage("DEBUG", dat, { badges:["moderator/1"], color:"red", escape:false }); } else { concatChatMessage("DEBUG", dat, { badges:["moderator/1"], color:"red", escape:false }); } }; } } debugLog(configLoadMessage + "설정을 불러왔습니다."); checkComplete(); } /* 지정 메세지 대체 */ if ((configData.replaceMsgs) && (configData.replaceMsgs.length>0)) { applyReplace = function(message, data) { for(var index in configData.replaceMsgs) { var msg = configData.replaceMsgs[index]; if ( (!msg.nick) || (msg.nick == data.nick) ) { if ((msg.to=="{no_display}") && (message.match(msg.orig)!=null)) { data.noDisplay = true; return message; } message = message.replace(msg.orig, msg.to); } } return message; }; } /* CSS 로드 */ var loadCss = function(isRetrying) { // 재 로드를 위해 기존 css를 제거 var existings = document.getElementsByClassName("chat_theme"); for(var index=0; index<existings.length; ++index) { existings[index].remove(); } document.head.appendChild( function() { if (configData.themeURI == "") { configData.themeURI = "./theme/"; } else if (configData.themeURI[configData.themeURI.length-1] != "/") { configData.themeURI += "/"; } var ret = document.createElement("link"); ret.onload = function() { debugLog(configData.themeName + " 테마를 적용했습니다."); checkComplete(); }; ret.onerror = function() { debugLog("테마 적용에 실패했습니다."); if (isRetrying != true) { debugLog("기본 설정으로 테마 설정을 재시도합니다."); configData.theme = configDefault.theme; loadCss(true); } }; ret.rel = "stylesheet"; ret.href = configData.themeURI + configData.theme + "/theme.css"; ret.classList.add("chat_theme"); return ret; }() ); }; loadCss(); /* 뱃지 정보 로드 */ var badgeList = {}; if (configData.badgeVisible) { var globalBadgeRequest = new window.XMLHttpRequest(); globalBadgeRequest.open( "GET", "https://badges.twitch.tv/v1/badges/global/display", true ); var handler = function(response) { var data = JSON.parse(response)["badge_sets"]; Object.keys(data).forEach( function(name) { var tiers = data[name].versions||{}; Object.keys(tiers).forEach( function(tier) { badgeList[name + "/" + tier] = tiers[tier]["image_url_1x"]; } ); } ); }; globalBadgeRequest.onreadystatechange = function(evt) { if (globalBadgeRequest.readyState == 4) { if (globalBadgeRequest.status == 200) { handler(globalBadgeRequest.responseText); if (configData.badgeChannelId && Number(configData.badgeChannelId)>0) { var channelBadgeUrl = "https://badges.twitch.tv/v1/badges/channels/"; channelBadgeUrl += configData.badgeChannelId + "/display"; var channelBadgeRequest = new window.XMLHttpRequest(); channelBadgeRequest.open("GET", channelBadgeUrl, true); channelBadgeRequest.onreadystatechange = function(evt) { if (channelBadgeRequest.readyState == 4) { if (channelBadgeRequest.status == 200) { handler(channelBadgeRequest.responseText); debugLog("뱃지 정보를 모두 불러왔습니다."); } else { debugLog( "스트리머 고유 뱃지를 불러오는 데 실패했습니다." + "\n에러 코드 " + channelBadgeRequest.status); } checkComplete(); } } channelBadgeRequest.send(null); } else { debugLog("뱃지 정보를 불러왔습니다."); checkComplete(); } } else { debugLog( "뱃지 정보를 불러오는 데 실패했습니다." + "\n에러 코드 " + globalBadgeRequest.status); } } }; globalBadgeRequest.send(null); } /* 비트 후원 메시지 아이콘으로 변경*/ var cheerList = require("./cheer_list.json"); var cheerRegExp = new RegExp("(\\s|^)(" + cheerList.join("|") + ")(\\d+)(\\s|$)", "i"); if (configData.loadCheerImgs) { applyCheerIcon = function(message, data) { if ((!data.cheers) && (data.cheers=="")) { return message; } var matches = message; var newMessage = ""; while ((matches) && (matches.match(cheerRegExp) != null)) { var match = matches.match(cheerRegExp); var remain = matches.split(match[0]); newMessage += remain.shift(); matches = match[4] + remain.join(match[0]); var value = match[3]>=100? ( match[3]>=1000? ( match[3]>=5000? ( match[3]>=10000? ( match[3]==100000? 100000: 10000): 5000 ): 1000 ): 100 ): 1; newMessage += match[1] + '<div class="chat_cheer_text"><img class="cheer_icon" src="./images/cheer/' + match[2] + value + '.gif"/>' + match[3] + "</div> "; } return newMessage + (matches? matches: ""); }; debugLog("후원 아이콘을 불러왔습니다."); checkComplete(); } else { debugLog("설정에 의해 후원 아이콘을 불러오지 않았습니다."); checkComplete(); } /* 디씨콘 및 구독콘 로드 및 적용 */ if (configData.loadTwitchCons) { var twitchConsUrlTemplate = "https://static-cdn.jtvnw.net/emoticons/v2/"; applyTwitchCon = function(message, data) { if ( !(data && data.emotes) || (data.emotes.length==0) ) { return message; } // 받은 emotes 데이터를 가공 var emotes = {}; data.emotes.split("/").forEach( function(emote) { var emoteDataArray = emote.split(/[:,-]/g); var emoteId = emoteDataArray[0]; var from = Number(emoteDataArray[1]); var to = Number(emoteDataArray[2]); emotes[data.message.slice(from, to+1)] = emoteId; } ); // 가공된 데이터를 이용해 메세지를 변조 Object.keys(emotes) .sort( function(a,b) { return b.length - a.length; } ) .forEach( function(emote) { var emoteRegExp = new RegExp( "( |^)(" + emote .replace(/</g,"&lt;").replace(/>/g,"&gt;") .replace(/\(/g, "\\(").replace(/\)/g, "\\)") + ")(\\s|$)" ); var emoteElement = '<img class="twitch_emote" src="' + twitchConsUrlTemplate + emotes[emote] + (configData.loadTwitchv2? "/default": "/static") + '/dark/3.0" />'; while (message.match(emoteRegExp)) { message = message.replace(emoteRegExp, "$1" + emoteElement + "$3"); } } ); return message; }; debugLog("트위치 이모티콘과 구독콘을 적용했습니다."); checkComplete(); } else { debugLog("설정에 따라 트위치 이모티콘과 구독콘을 불러오지 않았습니다."); checkComplete(); } dcConsData = []; var loadDcCon = function() {}; if (configData.loadDcCons) { loadDcCon = function() { var dcConsSubURI = "images/"; var dcConsMainURI = ""; if (configData.dcConsURI == "" || configData.dcConsURI == "./") { configData.dcConsURI = "./"; dcConsSubURI = "images/dccon/"; dcConsMainURI = "lib/"; } else if (configData.dcConsURI[configData.dcConsURI.length-1] != "/") { configData.dcConsURI += "/"; } var dcConScript = document.createElement("script"); dcConScript.type = "text/javascript"; dcConScript.charset = "utf-8"; dcConScript.src = configData.dcConsURI + dcConsMainURI + "dccon_list.js?ts=" + new Date().getTime(); document.body.appendChild(dcConScript); dcConScript.onload = function() { if (dcConsData.length == 0) { debugLog("디씨콘을 불러오는 데 실패했습니다."); } else { var keywords = []; for (var index in dcConsData) { for (var index2 in dcConsData[index].keywords) { keywords.push(dcConsData[index].keywords[index2]); } } keywords.sort(function(a,b) { return b.length - a.length; } ); applyDcCon = function(message, data) { for (var index in keywords) { var keyword = keywords[index]; if (message.indexOf("~" + keyword) != -1) { message = message.split("~" + keyword).join( '<img class="dccon" src="' + configData.dcConsURI + dcConsSubURI + dcConsData.find( function(element) { return element.keywords.indexOf(keyword) != -1; } ).name + '" />'); } } return message; }; debugLog("디씨콘을 적용했습니다."); checkComplete(); } }; }; loadDcCon(); } else { debugLog("설정에 따라 디씨콘을 적용하지 않았습니다."); checkComplete(); } /* 명령어 정의 */ var commandExecute = function(exe, arg) { switch (exe) { case "clear" : manageMessage("@ : CLEARCHAT #\n"); return true; case "theme" : arg = arg.match(/[a-zA-Z0-9_-]+/)[0]; if (arg != null) { configData.theme = arg.toLowerCase(); loadCss(); return true; } else { debugLog("잘못된 테마가 입력되었습니다."); return false; } case "load" : if (arg == "" || arg == "디씨콘" || arg == "디시콘" || arg == "dccon") { loadDcCon(); return true; } break; case "scale": if (arg == "") { debugLog("현재 배율 : " + (window.localStorage.getItem("scale")||100) + "%"); return true; } if (!isNaN(arg)) { window.localStorage.setItem("scale", Number(arg)); setScale(); return true; } break; default: break; } debugLog("잘못된 명령어입니다."); return false; } /* IRC 클라이언트 설정 */ var joinCount = 0; defaultColors = [ "#FF0000", "#0000FF", "#00FF00", "#B22222", "#FF7F50", "#9ACD32", "#FF4500", "#2E8B57", "#DAA520", "#D2691E", "#5F9EA0", "#1E90FF", "#FF69B4", "#8A2BE2", "#00FF7F"]; debugLog("트위치에 접속을 시도합니다."); manageMessage = function() {}; // 받은 명령어 처리 함수 var client = function() { ws = new WebSocket(configData.webSocket); ws.onopen = function() { ws.send("PASS " + configData.pass + "\r\n"); ws.send("NICK " + configData.nick + "\r\n"); ws.send('CAP REQ :twitch.tv/tags twitch.tv/commands twitch.tv/membership' + "\r\n"); ws.send("JOIN " + configData.channel + "\r\n"); } var onmessageEventHandler = function(evt) { var lines = evt.data.toString().split(/\r\n|\r|\n/); lines.pop(); lines.forEach( function(element) { var line = JSON.stringify(element).slice(1,-1); var args = line.replace(/^(:|@)/m, "").split(" "); if (line[0] == ":") { // IRC 명령어 처리 switch (args[1]) { case "421": // 잘못된 명령어를 보냈을 때 case "001": // 웰컴 메세지 case "002": // 호스트 알림 case "003": // 서버 상태태 case "004": // 접속초기메세지 끝 case "375": // MOTD(공지사항) 시작 case "372": // MOTD case "376": // MOTD 끝 case "CAP": // 트위치 명령어 수신 확인 메세지 case "353": // 접속자 목록(로드가 안된상태라 justinfan뿐이지만) case "366": // 이름 목록 끝 case "MODE": // 관리자 권한 감지 case "PART": // 서버에서 유저 접속 해제 case "HOSTTARGET": // 호스팅에 변화가 생겼을 때 break; case "JOIN": // 서버에 유저가 접속 if(args[0].search("justinfan") != -1) { debugLog( args[2].substring(1) + "에 접속했습니다."); } if(++joinCount <= configData.channel.match(/#/g).length) { checkComplete(); } break; default: // 미처리 메세지 if (configData.allMessageHandle) { debugLog("처리되지 않은 메세지를 수신했습니다.<br />" + line); } break; } } else if (line[0] == "@") { // 트위치 명령어 처리 var data = {}; var twitchArgs = {}; args.shift().split(";").forEach( function(element) { var keyval = element.split("="); twitchArgs[keyval[0]] = keyval[1]; } ); switch(args[1]) { case "ROOMSTATE": // 방 정보 break; case "USERNOTICE": switch(twitchArgs["msg-id"]) { case "sub": case "resub": // 구독 메세지 수신 data.subMonths = Number(twitchArgs["msg-param-cumulative-months"]); break; case "subgift": case "anonsubgift": case "submysterygift": case "rewardgift": case "anongiftpaidupgrade": case "raid": case "unraid": case "ritual": case "bitsbadgetier": default: if (configData.allMessageHandle) { debugLog("처리되지 않은 메세지를 수신했습니다.<br />" + line); } break; } break; case "PRIVMSG": // 채팅 수신 // 이름 지정 var nick = args[0].split(/[!@]/g)[1]; nick = (nick==undefined? twitchArgs.login: nick); var displayNick = twitchArgs["display-name"]; var realNick = ""; if ( (configData.useDisplayName) && (displayNick.replace(/\s/g, "")!="") ) { realNick = displayNick; } else { realNick = nick; } var message = args.slice(3).join(" ").substring(1); data.message = message; data.badges = twitchArgs.badges; data.color = twitchArgs.color; data.emotes = twitchArgs.emotes; data.nick = nick; // muteUser 적용 if (configData.muteUser) { var match = configData.muteUser.find( function(element) { return (element == displayNick) || (element == nick); } ); if (match != undefined) break; } // 명령어 파싱 if (configData.commands.length > 0) { if (data.badges.toString().search("broadcaster") != -1) { var isBreak = false; for(var index in configData.commands) { var cmd = configData.commands[index]; if (message.search(cmd.msg) == 0) { var cmdText = cmd.exe; var cmdArgument = message.split(cmd.msg + " "); cmdArgument.shift(); cmdArgument = cmdArgument.join(cmd.msg + " "); isBreak = isBreak || commandExecute(cmdText, cmdArgument); } } if (isBreak) break; } } // 링크 파싱 var linkRegExp = /^(https?:\/\/)?([A-Za-z0-9#%\-_=+]+\.)+[a-z]{2,}(\/[0-9A-Za-z#%&()+/\-\.:=?@_~]*)?/; message.split(/\s/).forEach( function(phrase) { if (phrase.match(linkRegExp)) { if ( ((configData.clipReplaceMsg||"").length>0) && (phrase.indexOf("twitch")>=0) && (phrase.indexOf("clip")>=0) ) { message = message.replace(phrase, configData.clipReplaceMsg); } else if ((configData.linkReplaceMsg||"").length>0) { message = message.replace(phrase, configData.linkReplaceMsg); } } } ); // 유저 이름색 지정 if (!data.color || data.color=="") { var n = realNick.charCodeAt(0) + realNick.charCodeAt(1)*new Date().getDate(); data.color = defaultColors[n % defaultColors.length]; } // 비트 메세지 파싱 if (twitchArgs.bits) { data.cheers = Number(twitchArgs.bits); } // 메세지 출력 addChatMessage(realNick, message, data); break; case "NOTICE": // 공지 메세지 switch(twitchArgs["msg-id"]) { case "host_off": // 호스팅을 끊었을 때 case "host_target_went_offline": // 호스팅이 끊겼을 때 debugLog("호스팅이 종료되었습니다."); break; case "host_on": // 호스팅되었을 때 debugLog( args[5].slice(0,-1) + " 호스팅 중.\n" + "호스팅중인 채팅의 전송은 지원하지 않습니다."); break; } break; case "CLEARCHAT": // 매니저가 /clear 했을 때 if(args.length == 4) { banChatMessage(args[3].substring(1)); } else { document.getElementById("chat_wrapper").innerHTML = ""; numChat = 0; } break; default: // 미처리 메세지 if (configData.allMessageHandle) { debugLog("처리되지 않은 메세지를 수신했습니다.<br />" + line); } break; } } else { // 서버 연결상태 확인용 ping-pong if (args[0] == "PING") { ws.send("PONG :tmi.witch.tv\r\n"); } else if (configData.allMessageHandle) { debugLog("처리되지 않은 메세지를 수신했습니다.<br />" + line); } } } ); } ws.onmessage = onmessageEventHandler; manageMessage = function(string) { var evt = {}; evt.data = string; onmessageEventHandler(evt); }; ws.onclose = function() { debugLog( "채팅 서버와의 연결이 종료되었습니다.<br />" + configData.retryInterval + "초 후 재접속을 시도합니다."); setTimeout( function() { client(); }, configData.retryInterval * 1000 ); } }; client(); },{"./cheer_list.json":1,"./twip_apply.js":3}],3:[function(require,module,exports){ var twipMsg = configData&&configData.twipCheersMsg? configData.twipCheersMsg: configData.cheersMsg; exports.apply = function(message, data) { if (data.nick == "twipkr") { if ( (data.message.indexOf("ACTION")!=-1) && (data.message.indexOf("\\u0001")!=-1) ) { var amount = message.match(/ (\d+,)*\d{3}/g); var twipMessage = ""; if (amount == null) { twipMessage = twipMsg.replace("{bits}", ""). replace(/\{0:([^\}]*)}/g, "$1").replace(/\{!0:([^\}]*)}/g, ""); } else { amount = amount[0].split(" ")[1].replace(/[^\d]/g, ""); twipMessage = twipMsg.replace("{bits}", amount).replace(/((\d)\s+)?비트/, "$2원"). replace(/\{!0:([^\}]*)}/g, "$1").replace(/\{0:([^\}]*)}/g, ""); } message = '<div class="chat_cheer_box">' + twipMessage + "</div>" + message; } } return message; }; },{}]},{},[2]);
import React from 'react'; import { StyleSheet } from 'react-native'; import { View, Item, Input, Label, Text } from 'native-base'; import { colors } from '../../theme'; const styles = StyleSheet.create({ errorText: { color: colors.tertiary, fontSize: 12, paddingLeft: 10, paddingRight: 10, marginTop: 8, marginBottom: 8, }, }); export const FormInputItem = ({ input: { ...input }, errorStyle = {}, label, stackedLabel, floatingLabel, itemStyle, name, meta: { touched, error, warning }, ...props }) => ( <View> <Item stackedLabel={stackedLabel} floatingLabel={floatingLabel} style={itemStyle} error={touched && typeof error !== 'undefined'} last > <Label style={props.style}>{label}</Label> <Input {...props} onChangeText={input.onChange} {...input} /> </Item> {touched && error && <Text style={[styles.errorText, errorStyle]}>{error}</Text>} {touched && warning && <Text style={[styles.errorText, errorStyle]}>{warning}</Text>} </View> ); export const required = value => (value ? undefined : 'Required'); export const maxLength = max => value => (value && value.length > max ? `Must be ${max} characters or less` : undefined); export const maxLength15 = maxLength(15); export const isNumber = value => (value && isNaN(Number(value)) ? 'Must be a number' : undefined);
/* eslint-disable no-undef */ module.exports = (client, member) => { const ordinal = require('ordinal'); const { MessageEmbed } = require('discord.js'); const Colour = require('../../data/colours.json'); const moment = require('moment'); const Server = client.guilds.cache.get(process.env.GUILD); const MemberCount = Server.memberCount; const WelcomeMessages = [ `Welcome to Saikou, please make sure to read our <#397797150840324115>. You are the ${ordinal(MemberCount)} user to join!`, 'has just entered the server! Great to see you!', 'Welcome to Saikou, please be sure to read our <#397797150840324115> carefully before chatting. Enjoy your stay with us!', 'Welcome to the Saikou Discord! We hope you have a great time here.', 'Welcome to Saikou Development! We have been waiting for you.', 'Welcome to the Saikou Discord, we are happy to have you here!', 'Welcome to our server, thanks for stopping by!', ]; const result = Math.floor((Math.random() * WelcomeMessages.length)); const WelcomeEmbed = new MessageEmbed() .setTitle('👋 Welcome to the Server!') .setDescription(`**${member.user.username}** ${WelcomeMessages[result]}`) .setColor(Colour.green) .setFooter('User joined') .setTimestamp(); joinleaves.send(WelcomeEmbed); // -- Log join embed const logjoinembed = new MessageEmbed() .setColor(Colour.blurple) .setTitle(':information_source: Member Joined') .setDescription(`<@!${member.user.id}> has joined the server.`) .addField('Username', member.user.username, true) .addField('Created', moment(member.user.createdAt).format('MMMM Do YYYY'), true) .setFooter(`ID: ${member.user.id}`) .setTimestamp(); modLogs.send(logjoinembed); };
const logger = require('@blackbaud/skyux-logger'); const mock = require('mock-require'); describe('plugin', () => { const specPattern = 'src/app/**/*.pact-spec.ts'; const testPath = '@skyux-sdk/builder/config/karma/test.karma.conf'; const watchPath = '@skyux-sdk/builder/config/karma/watch.karma.conf'; let getSkyPagesConfigSpy; let httpProxySpy; let httpSpy; let portfinderSpy; let karmaUtilsSpy; let tsLinterSpy; let pactServers; beforeEach(() => { pactServers = mock.reRequire('./utils/pact-servers'); spyOn(logger, 'info'); spyOn(logger, 'error'); spyOn(process, 'exit'); mock(testPath, () => {}); mock(watchPath, () => {}); mock('./config/karma/pact.karma.conf', () => {}); getSkyPagesConfigSpy = jasmine.createSpy('getSkyPagesConfig'); getSkyPagesConfigSpy.and.returnValue({ skyux: { pacts: [ { provider: 'test-provider1', consumer: 'test-consumer1', spec: 1 } ] } }); mock('@skyux-sdk/builder/config/sky-pages/sky-pages.config', { outPath: (path) => path, getSkyPagesConfig: getSkyPagesConfigSpy }); tsLinterSpy = jasmine.createSpyObj('tslinter', ['lintSync']); tsLinterSpy.lintSync.and.returnValue({ exitCode: 0 }); mock('@skyux-sdk/builder/cli/utils/ts-linter', tsLinterSpy); portfinderSpy = jasmine.createSpyObj('portfinder', ['getPorts']); portfinderSpy.getPorts.and.callFake((count, options, cb) => { cb(undefined, [0]); }); mock('portfinder', portfinderSpy); karmaUtilsSpy = jasmine.createSpyObj('karmaUtils', ['run']); karmaUtilsSpy.run.and.returnValue(Promise.resolve()); mock('./utils/karma-utils', karmaUtilsSpy); httpProxySpy = jasmine.createSpyObj('http-proxy', ['createProxyServer']); httpProxySpy.createProxyServer.and.returnValue({ on: () => {}, web: () => {} }); mock('http-proxy', httpProxySpy); httpSpy = jasmine.createSpyObj('http', ['createServer']); httpSpy.createServer.and.returnValue({ on: () => {}, listen: () => {} }); mock('http', httpSpy); }); afterEach(() => { mock.stopAll(); }); it('should log an error if no pacts in config', async () => { getSkyPagesConfigSpy.and.returnValue({ skyux: {} }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); expect(logger.error).toHaveBeenCalledWith( 'skyux pact failed! pacts does not exist on configuration file.' ); }); it('exit if portfinder returns error', async (done) => { const error = 'custom-portfinder-error'; portfinderSpy.getPorts.and.callFake((count, options, cb) => { cb(error); expect(logger.error).toHaveBeenCalledWith(error); expect(process.exit).toHaveBeenCalled(); done(); }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); }); it('should support a custom host and custom port', async (done) => { const pacts = [ { provider: 'test-provider1', consumer: 'test-consumer1', host: 'custom-host', spec: 1 }, { provider: 'test-provider2', consumer: 'test-consumer2', port: 'custom-port', spec: 2 } ]; getSkyPagesConfigSpy.and.returnValue({ skyux: { pacts } }); spyOn(pactServers, 'savePactServer'); portfinderSpy.getPorts.and.callFake((count, options, cb) => { const ports = pacts.map((pact, index) => 8000 + index ); cb(undefined, ports); expect(count).toBe(pacts.length + 1); expect(pactServers.savePactServer).toHaveBeenCalledWith( pacts[0].provider, 'custom-host', ports[0] ); expect(pactServers.savePactServer).toHaveBeenCalledWith( pacts[1].provider, 'localhost', pacts[1].port ); done(); }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); }); async function testOriginHeader(expectedOrigin, done) { const ports = [8000, 8001]; const origin = 'custom-origin'; const httpProxyOn = {}; const httpOn = {}; const headers = {}; const setHeaderSpy = jasmine.createSpy('setHeader'); httpProxySpy.createProxyServer.and.returnValue({ on: (evt, cb) => httpProxyOn[evt] = cb }); httpSpy.createServer.and.returnValue({ on: (evt, cb) => httpOn[evt] = cb, listen: (port) => { httpProxyOn['proxyReq']({ setHeader: setHeaderSpy }); httpProxyOn['proxyRes']( { headers }, { headers: { origin } } ); expect(port).toBe(ports[1]); expect(headers['Access-Control-Allow-Origin']).toBe(origin); expect(setHeaderSpy).toHaveBeenCalledWith('Origin', expectedOrigin); done(); } }); portfinderSpy.getPorts.and.callFake((count, options, cb) => { cb(undefined, ports); }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); } it('sets headers upon request and response on proxy server', async (done) => { await testOriginHeader('https://host.nxt.blackbaud.com', done); }); it('sets custom headers upon request and response on proxy server', async (done) => { const url = 'custom-url'; getSkyPagesConfigSpy.and.returnValue({ skyux: { pacts: [ { provider: 'test-provider1', consumer: 'test-consumer1', spec: 1 } ], host: { url } } }); await testOriginHeader(url, done); }); it('gets correct pact server before call to proxy server', async (done) => { const providerFullUrl = 'full-url'; const req = { url: 'base/provider-that-does-exist/endpoint' }; const res = { custom: true }; spyOn(pactServers, 'getAllPactServers').and.returnValue({ 'provider-that-does-exist': true }); spyOn(pactServers, 'getPactServer').and.returnValue({ fullUrl: providerFullUrl }); httpProxySpy.createProxyServer.and.returnValue({ on: () => {}, web: (webReq, webRes, options) => { expect(webReq).toEqual(req); expect(webRes).toEqual(res); expect(options).toEqual({ target: providerFullUrl }); done(); } }); httpSpy.createServer.and.callFake(cb => { cb(req, res); return { on: () => {}, listen: () => {} }; }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); }); it('logs error when malformed proxy url is requested', async (done) => { spyOn(pactServers, 'getAllPactServers').and.returnValue({ 'provider-that-does-not-exist': false }); httpSpy.createServer.and.callFake(cb => { const req = { url: 'bad-url' }; cb(req, {}); return { on: () => {}, listen: () => { expect(logger.error).toHaveBeenCalledWith( 'Pact proxy path is invalid. Expected format is base/provider-name/api-path.' ); done(); } }; }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); }); it('logs when proxy server is successfully started', async () => { const ports = [8000]; const httpOn = {}; httpSpy.createServer.and.returnValue({ on: (evt, cb) => httpOn[evt] = cb, listen: () => {} }); portfinderSpy.getPorts.and.callFake((count, options, cb) => { cb(undefined, ports); }); const plugin = mock.reRequire('./plugin'); await plugin.pact('', {}); httpOn['connect'](); expect(logger.info).toHaveBeenCalledWith( `Pact proxy server successfully started on http://localhost:${ports[ports.length - 1]}` ); }); it('should pass command, argv, and specPattern to karmaUtils.run', async (done) => { const argv = { custom: true }; const command = 'custom-command1'; const tsLinterExitCode = 3; tsLinterSpy.lintSync.and.returnValue({ exitCode: tsLinterExitCode }); process.exit.and.callFake(exitCode => { expect(exitCode).toBe(0 || tsLinterExitCode); expect(karmaUtilsSpy.run.calls.argsFor(0)[1].command).toBe(command); expect(karmaUtilsSpy.run).toHaveBeenCalledWith( command, argv, specPattern ); done(); }); const plugin = mock.reRequire('./plugin'); await plugin.pact(command, argv); }); it('should use process.argv if no arguments passed in', async () => { const argvClean = process.argv; const argv = { process: true }; const command = 'custom-command2'; process.argv = argv; const plugin = mock.reRequire('./plugin'); await plugin.pact(command); expect(karmaUtilsSpy.run).toHaveBeenCalledWith( command, argv, specPattern ); process.argv = argvClean; }); });
/** * @license * Copyright 2020 Google LLC * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview The namespace used to keep track of keyboard shortcuts and the * key codes used to execute those shortcuts. * @author aschmiedt@google.com (Abby Schmiedt) */ 'use strict'; goog.provide('Blockly.ShortcutRegistry'); goog.require('Blockly.navigation'); goog.require('Blockly.ShortcutItems'); goog.require('Blockly.utils.object'); /** * Class for the registry of keyboard shortcuts. This is intended to be a * singleton. You should not create a new instance, and only access this class * from Blockly.ShortcutRegistry.registry. * @constructor */ Blockly.ShortcutRegistry = function() { // Singleton instance should be registered once. Blockly.ShortcutRegistry.registry = this; /** * Registry of all keyboard shortcuts, keyed by name of shortcut. * @type {!Object<string, !Blockly.ShortcutRegistry.KeyboardShortcut>} * @private */ this.registry_ = Object.create(null); /** * Map of key codes to an array of shortcut names. * @type {!Object<string, !Array<string>>} * @private */ this.keyMap_ = Object.create(null); Blockly.ShortcutItems.registerDefaultShortcuts(); Blockly.navigation.registerNavigationShortcuts(); }; /** * Enum of valid modifiers. * @enum {!Blockly.utils.KeyCodes<number>} */ Blockly.ShortcutRegistry.modifierKeys = { Shift: Blockly.utils.KeyCodes.SHIFT, Control: Blockly.utils.KeyCodes.CTRL, Alt: Blockly.utils.KeyCodes.ALT, Meta: Blockly.utils.KeyCodes.META }; /** * A keyboard shortcut. * @typedef {{ * callback: ((function(!Blockly.Workspace, Event, * !Blockly.ShortcutRegistry.KeyboardShortcut):boolean)|undefined), * name: string, * preconditionFn: ((function(!Blockly.Workspace):boolean)|undefined), * metadata: (Object|undefined) * }} */ Blockly.ShortcutRegistry.KeyboardShortcut; /** * Registers a keyboard shortcut. * @param {!Blockly.ShortcutRegistry.KeyboardShortcut} shortcut The * shortcut for this key code. * @param {boolean=} opt_allowOverrides True to prevent a warning when * overriding an already registered item. * @throws {Error} if a shortcut with the same name already exists. * @public */ Blockly.ShortcutRegistry.prototype.register = function( shortcut, opt_allowOverrides) { var registeredShortcut = this.registry_[shortcut.name]; if (registeredShortcut && !opt_allowOverrides) { throw new Error( 'Shortcut with name "' + shortcut.name + '" already exists.'); } this.registry_[shortcut.name] = shortcut; }; /** * Unregisters a keyboard shortcut registered with the given key code. This will * also remove any key mappings that reference this shortcut. * @param {string} shortcutName The name of the shortcut to unregister. * @return {boolean} True if an item was unregistered, false otherwise. * @public */ Blockly.ShortcutRegistry.prototype.unregister = function(shortcutName) { var shortcut = this.registry_[shortcutName]; if (!shortcut) { console.warn( 'Keyboard shortcut with name "' + shortcutName + '" not found.'); return false; } this.removeAllKeyMappings(shortcutName); delete this.registry_[shortcutName]; return true; }; /** * Adds a mapping between a keycode and a keyboard shortcut. * @param {string} keyCode The key code for the keyboard shortcut. If * registering a key code with a modifier (ex: ctrl+c) use * Blockly.ShortcutRegistry.registry.createSerializedKey; * @param {string} shortcutName The name of the shortcut to execute when the * given keycode is pressed. * @param {boolean=} opt_allowCollision True to prevent an error when adding a * shortcut to a key that is already mapped to a shortcut. * @throws {Error} if the given key code is already mapped to a shortcut. * @public */ Blockly.ShortcutRegistry.prototype.addKeyMapping = function( keyCode, shortcutName, opt_allowCollision) { var shortcutNames = this.keyMap_[keyCode]; if (shortcutNames && !opt_allowCollision) { throw new Error( 'Shortcut with name "' + shortcutName + '" collides with shortcuts ' + shortcutNames.toString()); } else if (shortcutNames && opt_allowCollision) { shortcutNames.unshift(shortcutName); } else { this.keyMap_[keyCode] = [shortcutName]; } }; /** * Removes a mapping between a keycode and a keyboard shortcut. * @param {string} keyCode The key code for the keyboard shortcut. If * registering a key code with a modifier (ex: ctrl+c) use * Blockly.ShortcutRegistry.registry.createSerializedKey; * @param {string} shortcutName The name of the shortcut to execute when the * given keycode is pressed. * @param {boolean=} opt_quiet True to not console warn when there is no * shortcut to remove. * @return {boolean} True if a key mapping was removed, false otherwise. * @public */ Blockly.ShortcutRegistry.prototype.removeKeyMapping = function( keyCode, shortcutName, opt_quiet) { var shortcutNames = this.keyMap_[keyCode]; if (!shortcutNames && !opt_quiet) { console.warn( 'No keyboard shortcut with name "' + shortcutName + '" registered with key code "' + keyCode + '"'); return false; } var shortcutIdx = shortcutNames.indexOf(shortcutName); if (shortcutIdx > -1) { shortcutNames.splice(shortcutIdx, 1); if (shortcutNames.length == 0) { delete this.keyMap_[keyCode]; } return true; } else if (!opt_quiet) { console.warn( 'No keyboard shortcut with name "' + shortcutName + '" registered with key code "' + keyCode + '"'); return false; } return false; }; /** * Removes all the key mappings for a shortcut with the given name. * Useful when changing the default key mappings and the key codes registered to the shortcut are * unknown. * @param {string} shortcutName The name of the shortcut to remove from the key map. * @public */ Blockly.ShortcutRegistry.prototype.removeAllKeyMappings = function(shortcutName) { for (var keyCode in this.keyMap_) { this.removeKeyMapping(keyCode, shortcutName, true); } }; /** * Sets the key map. Setting the key map will override any default key mappings. * @param {!Object<string, !Array<string>>} keyMap The object with key code to * shortcut names. * @public */ Blockly.ShortcutRegistry.prototype.setKeyMap = function(keyMap) { this.keyMap_ = keyMap; }; /** * Gets the current key map. * @return {!Object<string,!Array<!Blockly.ShortcutRegistry.KeyboardShortcut>>} * The object holding key codes to Blockly.ShortcutRegistry.KeyboardShortcut. * @public */ Blockly.ShortcutRegistry.prototype.getKeyMap = function() { return Blockly.utils.object.deepMerge(Object.create(null), this.keyMap_); }; /** * Gets the registry of keyboard shortcuts. * @return {!Object<string, !Blockly.ShortcutRegistry.KeyboardShortcut>} * The registry of keyboard shortcuts. * @public */ Blockly.ShortcutRegistry.prototype.getRegistry = function() { return Blockly.utils.object.deepMerge(Object.create(null), this.registry_); }; /** * Handles key down events. * @param {!Blockly.Workspace} workspace The main workspace where the event was * captured. * @param {!Event} e The key down event. * @return {boolean} True if the event was handled, false otherwise. * @public */ Blockly.ShortcutRegistry.prototype.onKeyDown = function(workspace, e) { var key = this.serializeKeyEvent_(e); var shortcutNames = this.getShortcutNamesByKeyCode(key); if (!shortcutNames) { return false; } for (var i = 0, shortcutName; (shortcutName = shortcutNames[i]); i++) { var shortcut = this.registry_[shortcutName]; if (!shortcut.preconditionFn || shortcut.preconditionFn(workspace)) { // If the key has been handled, stop processing shortcuts. if (shortcut.callback && shortcut.callback(workspace, e, shortcut)) { return true; } } } return false; }; /** * Gets the shortcuts registered to the given key code. * @param {string} keyCode The serialized key code. * @return {!Array<string>|undefined} The list of shortcuts to call when the * given keyCode is used. Undefined if no shortcuts exist. * @public */ Blockly.ShortcutRegistry.prototype.getShortcutNamesByKeyCode = function( keyCode) { return this.keyMap_[keyCode] || []; }; /** * Gets the serialized key codes that the shortcut with the given name is * registered under. * @param {string} shortcutName The name of the shortcut. * @return {!Array<string>} An array with all the key codes the shortcut is * registered under. * @public */ Blockly.ShortcutRegistry.prototype.getKeyCodesByShortcutName = function( shortcutName) { var keys = []; for (var keyCode in this.keyMap_) { var shortcuts = this.keyMap_[keyCode]; var shortcutIdx = shortcuts.indexOf(shortcutName); if (shortcutIdx > -1) { keys.push(keyCode); } } return keys; }; /** * Serializes a key event. * @param {!Event} e A key down event. * @return {string} The serialized key code for the given event. * @private */ Blockly.ShortcutRegistry.prototype.serializeKeyEvent_ = function(e) { var serializedKey = ''; if (e.getModifierState && typeof(e.getModifierState) == "function") { for (var modifier in Blockly.ShortcutRegistry.modifierKeys) { if (e.getModifierState(modifier)) { if (serializedKey != '') { serializedKey += '+'; } serializedKey += modifier; } } } else { // What else should I do, when I dont have support for 'getModifierState'... if (e.shiftKey) { ("" != serializedKey && (serializedKey += "+"), serializedKey += "Shift"); } if (e.ctrlKey) { ("" != serializedKey && (serializedKey += "+"), serializedKey += "Control"); } if (e.altKey) { ("" != serializedKey && (serializedKey += "+"), serializedKey += "Alt"); } if (e.metaKey) { ("" != serializedKey && (serializedKey += "+"), serializedKey += "Meta"); } } if (serializedKey != '' && e.keyCode) { serializedKey = serializedKey + '+' + e.keyCode; } else if (e.keyCode) { serializedKey = e.keyCode.toString(); } return serializedKey; }; /** * Checks whether any of the given modifiers are not valid. * @param {!Array<string>} modifiers List of modifiers to be used with the key. * @throws {Error} if the modifier is not in the valid modifiers list. * @private */ Blockly.ShortcutRegistry.prototype.checkModifiers_ = function( modifiers) { var validModifiers = Blockly.utils.object.values( Blockly.ShortcutRegistry.modifierKeys); for (var i = 0, modifier; (modifier = modifiers[i]); i++) { if (validModifiers.indexOf(modifier) < 0) { throw new Error(modifier + ' is not a valid modifier key.'); } } }; /** * Creates the serialized key code that will be used in the key map. * @param {number} keyCode Number code representing the key. * @param {?Array.<string>} modifiers List of modifier key codes to be used with * the key. All valid modifiers can be found in the * Blockly.ShortcutRegistry.modifierKeys. * @return {string} The serialized key code for the given modifiers and key. * @public */ Blockly.ShortcutRegistry.prototype.createSerializedKey = function( keyCode, modifiers) { var serializedKey = ''; if (modifiers) { this.checkModifiers_(modifiers); for (var modifier in Blockly.ShortcutRegistry.modifierKeys) { var modifierKeyCode = Blockly.ShortcutRegistry.modifierKeys[modifier]; if (modifiers.indexOf(modifierKeyCode) > -1) { if (serializedKey != '') { serializedKey += '+'; } serializedKey += modifier; } } } if (serializedKey != '' && keyCode) { serializedKey = serializedKey + '+' + keyCode; } else if (keyCode) { serializedKey = keyCode.toString(); } return serializedKey; }; // Creates and assigns the singleton instance. new Blockly.ShortcutRegistry();
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import registerServiceWorker from './registerServiceWorker'; import './index.css'; import App from './pages/app/App'; import store from './common/stores'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); registerServiceWorker();
/** * dat-gui JavaScript Controller Library * http://code.google.com/p/dat-gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 */ /** @namespace */ var dat = dat || {}; /** @namespace */ dat.gui = dat.gui || {}; /** @namespace */ dat.utils = dat.utils || {}; /** @namespace */ dat.controllers = dat.controllers || {}; /** @namespace */ dat.dom = dat.dom || {}; /** @namespace */ dat.color = dat.color || {}; dat.utils.css = (function () { return { load: function (url, doc) { doc = doc || document; var link = doc.createElement('link'); link.type = 'text/css'; link.rel = 'stylesheet'; link.href = url; doc.getElementsByTagName('head')[0].appendChild(link); }, inject: function(css, doc) { doc = doc || document; var injected = document.createElement('style'); injected.type = 'text/css'; injected.innerHTML = css; doc.getElementsByTagName('head')[0].appendChild(injected); } } })(); dat.utils.common = (function () { var ARR_EACH = Array.prototype.forEach; var ARR_SLICE = Array.prototype.slice; /** * Band-aid methods for things that should be a lot easier in JavaScript. * Implementation and structure inspired by underscore.js * http://documentcloud.github.com/underscore/ */ return { BREAK: {}, extend: function(target) { this.each(ARR_SLICE.call(arguments, 1), function(obj) { for (var key in obj) if (!this.isUndefined(obj[key])) target[key] = obj[key]; }, this); return target; }, defaults: function(target) { this.each(ARR_SLICE.call(arguments, 1), function(obj) { for (var key in obj) if (this.isUndefined(target[key])) target[key] = obj[key]; }, this); return target; }, compose: function() { var toCall = ARR_SLICE.call(arguments); return function() { var args = ARR_SLICE.call(arguments); for (var i = toCall.length -1; i >= 0; i--) { args = [toCall[i].apply(this, args)]; } return args[0]; } }, each: function(obj, itr, scope) { if (!obj) return; if (ARR_EACH && obj.forEach && obj.forEach === ARR_EACH) { obj.forEach(itr, scope); } else if (obj.length === obj.length + 0) { // Is number but not NaN for (var key = 0, l = obj.length; key < l; key++) if (key in obj && itr.call(scope, obj[key], key) === this.BREAK) return; } else { for (var key in obj) if (itr.call(scope, obj[key], key) === this.BREAK) return; } }, defer: function(fnc) { setTimeout(fnc, 0); }, toArray: function(obj) { if (obj.toArray) return obj.toArray(); return ARR_SLICE.call(obj); }, isUndefined: function(obj) { return obj === undefined; }, isNull: function(obj) { return obj === null; }, isNaN: function(obj) { return obj !== obj; }, isArray: Array.isArray || function(obj) { return obj.constructor === Array; }, isObject: function(obj) { return obj === Object(obj); }, isNumber: function(obj) { return obj === obj+0; }, isString: function(obj) { return obj === obj+''; }, isBoolean: function(obj) { return obj === false || obj === true; }, isFunction: function(obj) { return Object.prototype.toString.call(obj) === '[object Function]'; } }; })(); dat.controllers.Controller = (function (common) { /** * @class An "abstract" class that represents a given property of an object. * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * * @member dat.controllers */ var Controller = function(object, property) { this.initialValue = object[property]; /** * Those who extend this class will put their DOM elements in here. * @type {DOMElement} */ this.domElement = document.createElement('div'); /** * The object to manipulate * @type {Object} */ this.object = object; /** * The name of the property to manipulate * @type {String} */ this.property = property; /** * The function to be called on change. * @type {Function} * @ignore */ this.__onChange = undefined; /** * The function to be called on finishing change. * @type {Function} * @ignore */ this.__onFinishChange = undefined; }; common.extend( Controller.prototype, /** @lends dat.controllers.Controller.prototype */ { /** * Specify that a function fire every time someone changes the value with * this Controller. * * @param {Function} fnc This function will be called whenever the value * is modified via this Controller. * @returns {dat.controllers.Controller} this */ onChange: function(fnc) { this.__onChange = fnc; return this; }, /** * Specify that a function fire every time someone "finishes" changing * the value wih this Controller. Useful for values that change * incrementally like numbers or strings. * * @param {Function} fnc This function will be called whenever * someone "finishes" changing the value via this Controller. * @returns {dat.controllers.Controller} this */ onFinishChange: function(fnc) { this.__onFinishChange = fnc; return this; }, /** * Change the value of <code>object[property]</code> * * @param {Object} newValue The new value of <code>object[property]</code> */ setValue: function(newValue) { this.object[this.property] = newValue; if (this.__onChange) { this.__onChange.call(this, newValue); } this.updateDisplay(); return this; }, /** * Gets the value of <code>object[property]</code> * * @returns {Object} The current value of <code>object[property]</code> */ getValue: function() { return this.object[this.property]; }, /** * Refreshes the visual display of a Controller in order to keep sync * with the object's current value. * @returns {dat.controllers.Controller} this */ updateDisplay: function() { return this; }, /** * @returns {Boolean} true if the value has deviated from initialValue */ isModified: function() { return this.initialValue !== this.getValue() } } ); return Controller; })(dat.utils.common); dat.dom.dom = (function (common) { var EVENT_MAP = { 'HTMLEvents': ['change'], 'MouseEvents': ['click','mousemove','mousedown','mouseup', 'mouseover'], 'KeyboardEvents': ['keydown'] }; var EVENT_MAP_INV = {}; common.each(EVENT_MAP, function(v, k) { common.each(v, function(e) { EVENT_MAP_INV[e] = k; }); }); var CSS_VALUE_PIXELS = /(\d+(\.\d+)?)px/; function cssValueToPixels(val) { if (val === '0' || common.isUndefined(val)) return 0; var match = val.match(CSS_VALUE_PIXELS); if (!common.isNull(match)) { return parseFloat(match[1]); } // TODO ...ems? %? return 0; } /** * @namespace * @member dat.dom */ var dom = { /** * * @param elem * @param selectable */ makeSelectable: function(elem, selectable) { if (elem === undefined || elem.style === undefined) return; elem.onselectstart = selectable ? function() { return false; } : function() { }; elem.style.MozUserSelect = selectable ? 'auto' : 'none'; elem.style.KhtmlUserSelect = selectable ? 'auto' : 'none'; elem.unselectable = selectable ? 'on' : 'off'; }, /** * * @param elem * @param horizontal * @param vertical */ makeFullscreen: function(elem, horizontal, vertical) { if (common.isUndefined(horizontal)) horizontal = true; if (common.isUndefined(vertical)) vertical = true; elem.style.position = 'absolute'; if (horizontal) { elem.style.left = 0; elem.style.right = 0; } if (vertical) { elem.style.top = 0; elem.style.bottom = 0; } }, /** * * @param elem * @param eventType * @param params */ fakeEvent: function(elem, eventType, params, aux) { params = params || {}; var className = EVENT_MAP_INV[eventType]; if (!className) { throw new Error('Event type ' + eventType + ' not supported.'); } var evt = document.createEvent(className); switch (className) { case 'MouseEvents': var clientX = params.x || params.clientX || 0; var clientY = params.y || params.clientY || 0; evt.initMouseEvent(eventType, params.bubbles || false, params.cancelable || true, window, params.clickCount || 1, 0, //screen X 0, //screen Y clientX, //client X clientY, //client Y false, false, false, false, 0, null); break; case 'KeyboardEvents': var init = evt.initKeyboardEvent || evt.initKeyEvent; // webkit || moz common.defaults(params, { cancelable: true, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, keyCode: undefined, charCode: undefined }); init(eventType, params.bubbles || false, params.cancelable, window, params.ctrlKey, params.altKey, params.shiftKey, params.metaKey, params.keyCode, params.charCode); break; default: evt.initEvent(eventType, params.bubbles || false, params.cancelable || true); break; } common.defaults(evt, aux); elem.dispatchEvent(evt); }, /** * * @param elem * @param event * @param func * @param bool */ bind: function(elem, event, func, bool) { bool = bool || false; if (elem.addEventListener) elem.addEventListener(event, func, bool); else if (elem.attachEvent) elem.attachEvent('on' + event, func); return dom; }, /** * * @param elem * @param event * @param func * @param bool */ unbind: function(elem, event, func, bool) { bool = bool || false; if (elem.removeEventListener) elem.removeEventListener(event, func, bool); else if (elem.detachEvent) elem.detachEvent('on' + event, func); return dom; }, /** * * @param elem * @param className */ addClass: function(elem, className) { if (elem.className === undefined) { elem.className = className; } else if (elem.className !== className) { var classes = elem.className.split(/ +/); if (classes.indexOf(className) == -1) { classes.push(className); elem.className = classes.join(' ').replace(/^\s+/, '').replace(/\s+$/, ''); } } return dom; }, /** * * @param elem * @param className */ removeClass: function(elem, className) { if (className) { if (elem.className === undefined) { // elem.className = className; } else if (elem.className === className) { elem.removeAttribute('class'); } else { var classes = elem.className.split(/ +/); var index = classes.indexOf(className); if (index != -1) { classes.splice(index, 1); elem.className = classes.join(' '); } } } else { elem.className = undefined; } return dom; }, hasClass: function(elem, className) { return new RegExp('(?:^|\\s+)' + className + '(?:\\s+|$)').test(elem.className) || false; }, /** * * @param elem */ getWidth: function(elem) { var style = getComputedStyle(elem); return cssValueToPixels(style['border-left-width']) + cssValueToPixels(style['border-right-width']) + cssValueToPixels(style['padding-left']) + cssValueToPixels(style['padding-right']) + cssValueToPixels(style['width']); }, /** * * @param elem */ getHeight: function(elem) { var style = getComputedStyle(elem); return cssValueToPixels(style['border-top-width']) + cssValueToPixels(style['border-bottom-width']) + cssValueToPixels(style['padding-top']) + cssValueToPixels(style['padding-bottom']) + cssValueToPixels(style['height']); }, /** * * @param elem */ getOffset: function(elem) { var offset = {left: 0, top:0}; if (elem.offsetParent) { do { offset.left += elem.offsetLeft; offset.top += elem.offsetTop; } while (elem = elem.offsetParent); } return offset; }, // http://stackoverflow.com/posts/2684561/revisions /** * * @param elem */ isActive: function(elem) { return elem === document.activeElement && ( elem.type || elem.href ); } }; return dom; })(dat.utils.common); dat.controllers.OptionController = (function (Controller, dom, common) { /** * @class Provides a select input to alter the property of an object, using a * list of accepted values. * * @extends dat.controllers.Controller * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * @param {Object|string[]} options A map of labels to acceptable values, or * a list of acceptable string values. * * @member dat.controllers */ var OptionController = function(object, property, options) { OptionController.superclass.call(this, object, property); var _this = this; /** * The drop down menu * @ignore */ this.__select = document.createElement('select'); if (common.isArray(options)) { var map = {}; common.each(options, function(element) { map[element] = element; }); options = map; } common.each(options, function(value, key) { var opt = document.createElement('option'); opt.innerHTML = key; opt.setAttribute('value', value); _this.__select.appendChild(opt); }); // Acknowledge original value this.updateDisplay(); dom.bind(this.__select, 'change', function() { var desiredValue = this.options[this.selectedIndex].value; _this.setValue(desiredValue); }); this.domElement.appendChild(this.__select); }; OptionController.superclass = Controller; common.extend( OptionController.prototype, Controller.prototype, { setValue: function(v) { var toReturn = OptionController.superclass.prototype.setValue.call(this, v); if (this.__onFinishChange) { this.__onFinishChange.call(this, this.getValue()); } return toReturn; }, updateDisplay: function() { this.__select.value = this.getValue(); return OptionController.superclass.prototype.updateDisplay.call(this); } } ); return OptionController; })(dat.controllers.Controller, dat.dom.dom, dat.utils.common); dat.controllers.NumberController = (function (Controller, common) { /** * @class Represents a given property of an object that is a number. * * @extends dat.controllers.Controller * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * @param {Object} [params] Optional parameters * @param {Number} [params.min] Minimum allowed value * @param {Number} [params.max] Maximum allowed value * @param {Number} [params.step] Increment by which to change value * * @member dat.controllers */ var NumberController = function(object, property, params) { NumberController.superclass.call(this, object, property); params = params || {}; this.__min = params.min; this.__max = params.max; this.__step = params.step; if (common.isUndefined(this.__step)) { if (this.initialValue == 0) { this.__impliedStep = 1; // What are we, psychics? } else { // Hey Doug, check this out. this.__impliedStep = Math.pow(10, Math.floor(Math.log(this.initialValue)/Math.LN10))/10; } } else { this.__impliedStep = this.__step; } this.__precision = numDecimals(this.__impliedStep); }; NumberController.superclass = Controller; common.extend( NumberController.prototype, Controller.prototype, /** @lends dat.controllers.NumberController.prototype */ { setValue: function(v) { if (this.__min !== undefined && v < this.__min) { v = this.__min; } else if (this.__max !== undefined && v > this.__max) { v = this.__max; } if (this.__step !== undefined && v % this.__step != 0) { v = Math.round(v / this.__step) * this.__step; } return NumberController.superclass.prototype.setValue.call(this, v); }, /** * Specify a minimum value for <code>object[property]</code>. * * @param {Number} minValue The minimum value for * <code>object[property]</code> * @returns {dat.controllers.NumberController} this */ min: function(v) { this.__min = v; return this; }, /** * Specify a maximum value for <code>object[property]</code>. * * @param {Number} maxValue The maximum value for * <code>object[property]</code> * @returns {dat.controllers.NumberController} this */ max: function(v) { this.__max = v; return this; }, /** * Specify a step value that dat.controllers.NumberController * increments by. * * @param {Number} stepValue The step value for * dat.controllers.NumberController * @default if minimum and maximum specified increment is 1% of the * difference otherwise stepValue is 1 * @returns {dat.controllers.NumberController} this */ step: function(v) { this.__step = v; this.__impliedStep = v; this.__precision = numDecimals(v); return this; } } ); function numDecimals(x) { x = x.toString(); if (x.indexOf('.') > -1) { return x.length - x.indexOf('.') - 1; } else { return 0; } } return NumberController; })(dat.controllers.Controller, dat.utils.common); dat.controllers.NumberControllerBox = (function (NumberController, dom, common) { /** * @class Represents a given property of an object that is a number and * provides an input element with which to manipulate it. * * @extends dat.controllers.Controller * @extends dat.controllers.NumberController * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * @param {Object} [params] Optional parameters * @param {Number} [params.min] Minimum allowed value * @param {Number} [params.max] Maximum allowed value * @param {Number} [params.step] Increment by which to change value * * @member dat.controllers */ var NumberControllerBox = function(object, property, params) { this.__truncationSuspended = false; NumberControllerBox.superclass.call(this, object, property, params); var _this = this; /** * {Number} Previous mouse y position * @ignore */ var prev_y; this.__input = document.createElement('input'); this.__input.setAttribute('type', 'text'); // Makes it so manually specified values are not truncated. dom.bind(this.__input, 'change', onChange); dom.bind(this.__input, 'blur', onBlur); dom.bind(this.__input, 'mousedown', onMouseDown); dom.bind(this.__input, 'keydown', function(e) { // When pressing entire, you can be as precise as you want. if (e.keyCode === 13) { _this.__truncationSuspended = true; this.blur(); _this.__truncationSuspended = false; } }); function onChange() { var attempted = parseFloat(_this.__input.value); if (!common.isNaN(attempted)) _this.setValue(attempted); } function onBlur() { onChange(); if (_this.__onFinishChange) { _this.__onFinishChange.call(_this, _this.getValue()); } } function onMouseDown(e) { dom.bind(window, 'mousemove', onMouseDrag); dom.bind(window, 'mouseup', onMouseUp); prev_y = e.clientY; } function onMouseDrag(e) { var diff = prev_y - e.clientY; _this.setValue(_this.getValue() + diff * _this.__impliedStep); prev_y = e.clientY; } function onMouseUp() { dom.unbind(window, 'mousemove', onMouseDrag); dom.unbind(window, 'mouseup', onMouseUp); } this.updateDisplay(); this.domElement.appendChild(this.__input); }; NumberControllerBox.superclass = NumberController; common.extend( NumberControllerBox.prototype, NumberController.prototype, { updateDisplay: function() { this.__input.value = this.__truncationSuspended ? this.getValue() : roundToDecimal(this.getValue(), this.__precision); return NumberControllerBox.superclass.prototype.updateDisplay.call(this); } } ); function roundToDecimal(value, decimals) { var tenTo = Math.pow(10, decimals); return Math.round(value * tenTo) / tenTo; } return NumberControllerBox; })(dat.controllers.NumberController, dat.dom.dom, dat.utils.common); dat.controllers.NumberControllerSlider = (function (NumberController, dom, css, common, styleSheet) { /** * @class Represents a given property of an object that is a number, contains * a minimum and maximum, and provides a slider element with which to * manipulate it. It should be noted that the slider element is made up of * <code>&lt;div&gt;</code> tags, <strong>not</strong> the html5 * <code>&lt;slider&gt;</code> element. * * @extends dat.controllers.Controller * @extends dat.controllers.NumberController * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * @param {Number} minValue Minimum allowed value * @param {Number} maxValue Maximum allowed value * @param {Number} stepValue Increment by which to change value * * @member dat.controllers */ var NumberControllerSlider = function(object, property, min, max, step) { NumberControllerSlider.superclass.call(this, object, property, { min: min, max: max, step: step }); var _this = this; this.__background = document.createElement('div'); this.__foreground = document.createElement('div'); dom.bind(this.__background, 'mousedown', onMouseDown); dom.addClass(this.__background, 'slider'); dom.addClass(this.__foreground, 'slider-fg'); function onMouseDown(e) { dom.bind(window, 'mousemove', onMouseDrag); dom.bind(window, 'mouseup', onMouseUp); onMouseDrag(e); } function onMouseDrag(e) { e.preventDefault(); var offset = dom.getOffset(_this.__background); var width = dom.getWidth(_this.__background); _this.setValue( map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max) ); return false; } function onMouseUp() { dom.unbind(window, 'mousemove', onMouseDrag); dom.unbind(window, 'mouseup', onMouseUp); if (_this.__onFinishChange) { _this.__onFinishChange.call(_this, _this.getValue()); } } this.updateDisplay(); this.__background.appendChild(this.__foreground); this.domElement.appendChild(this.__background); }; NumberControllerSlider.superclass = NumberController; /** * Injects default stylesheet for slider elements. */ NumberControllerSlider.useDefaultStyles = function() { css.inject(styleSheet); }; common.extend( NumberControllerSlider.prototype, NumberController.prototype, { updateDisplay: function() { var pct = (this.getValue() - this.__min)/(this.__max - this.__min); this.__foreground.style.width = pct*100+'%'; return NumberControllerSlider.superclass.prototype.updateDisplay.call(this); } } ); function map(v, i1, i2, o1, o2) { return o1 + (o2 - o1) * ((v - i1) / (i2 - i1)); } return NumberControllerSlider; })(dat.controllers.NumberController, dat.dom.dom, dat.utils.css, dat.utils.common, "/**\n * dat-gui JavaScript Controller Library\n * http://code.google.com/p/dat-gui\n *\n * Copyright 2011 Data Arts Team, Google Creative Lab\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n */\n\n.slider {\n box-shadow: inset 0 2px 4px rgba(0,0,0,0.15);\n height: 1em;\n border-radius: 1em;\n background-color: #eee;\n padding: 0 0.5em;\n overflow: hidden;\n}\n\n.slider-fg {\n padding: 1px 0 2px 0;\n background-color: #aaa;\n height: 1em;\n margin-left: -0.5em;\n padding-right: 0.5em;\n border-radius: 1em 0 0 1em;\n}\n\n.slider-fg:after {\n display: inline-block;\n border-radius: 1em;\n background-color: #fff;\n border: 1px solid #aaa;\n content: '';\n float: right;\n margin-right: -1em;\n margin-top: -1px;\n height: 0.9em;\n width: 0.9em;\n}"); dat.controllers.FunctionController = (function (Controller, dom, common) { /** * @class Provides a GUI interface to fire a specified method, a property of an object. * * @extends dat.controllers.Controller * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * * @member dat.controllers */ var FunctionController = function(object, property, text) { FunctionController.superclass.call(this, object, property); var _this = this; this.__button = document.createElement('div'); this.__button.innerHTML = text === undefined ? 'Fire' : text; dom.bind(this.__button, 'click', function(e) { e.preventDefault(); _this.fire(); return false; }); dom.addClass(this.__button, 'button'); this.domElement.appendChild(this.__button); }; FunctionController.superclass = Controller; common.extend( FunctionController.prototype, Controller.prototype, { fire: function() { if (this.__onChange) { this.__onChange.call(this); } this.getValue().call(this.object); if (this.__onFinishChange) { this.__onFinishChange.call(this, this.getValue()); } } } ); return FunctionController; })(dat.controllers.Controller, dat.dom.dom, dat.utils.common); dat.controllers.BooleanController = (function (Controller, dom, common) { /** * @class Provides a checkbox input to alter the boolean property of an object. * @extends dat.controllers.Controller * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * * @member dat.controllers */ var BooleanController = function(object, property) { BooleanController.superclass.call(this, object, property); var _this = this; this.__prev = this.getValue(); this.__checkbox = document.createElement('input'); this.__checkbox.setAttribute('type', 'checkbox'); dom.bind(this.__checkbox, 'change', onChange, false); this.domElement.appendChild(this.__checkbox); // Match original value this.updateDisplay(); function onChange() { _this.setValue(!_this.__prev); } }; BooleanController.superclass = Controller; common.extend( BooleanController.prototype, Controller.prototype, { setValue: function(v) { var toReturn = BooleanController.superclass.prototype.setValue.call(this, v); if (this.__onFinishChange) { this.__onFinishChange.call(this, this.getValue()); } this.__prev = this.getValue(); return toReturn; }, updateDisplay: function() { if (this.getValue() === true) { this.__checkbox.setAttribute('checked', 'checked'); this.__checkbox.checked = true; } else { this.__checkbox.checked = false; } return BooleanController.superclass.prototype.updateDisplay.call(this); } } ); return BooleanController; })(dat.controllers.Controller, dat.dom.dom, dat.utils.common); dat.color.toString = (function (common) { return function(color) { if (color.a == 1 || common.isUndefined(color.a)) { var s = color.hex.toString(16); while (s.length < 6) { s = '0' + s; } return '#' + s; } else { return 'rgba(' + Math.round(color.r) + ',' + Math.round(color.g) + ',' + Math.round(color.b) + ',' + color.a + ')'; } } })(dat.utils.common); dat.color.interpret = (function (toString, common) { var result, toReturn; var interpret = function() { toReturn = false; var original = arguments.length > 1 ? common.toArray(arguments) : arguments[0]; common.each(INTERPRETATIONS, function(family) { if (family.litmus(original)) { common.each(family.conversions, function(conversion, conversionName) { result = conversion.read(original); if (toReturn === false && result !== false) { toReturn = result; result.conversionName = conversionName; result.conversion = conversion; return common.BREAK; } }); return common.BREAK; } }); return toReturn; }; var INTERPRETATIONS = [ // Strings { litmus: common.isString, conversions: { THREE_CHAR_HEX: { read: function(original) { var test = original.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i); if (test === null) return false; return { space: 'HEX', hex: parseInt( '0x' + test[1].toString() + test[1].toString() + test[2].toString() + test[2].toString() + test[3].toString() + test[3].toString()) }; }, write: toString }, SIX_CHAR_HEX: { read: function(original) { var test = original.match(/^#([A-F0-9]{6})$/i); if (test === null) return false; return { space: 'HEX', hex: parseInt('0x' + test[1].toString()) }; }, write: toString }, CSS_RGB: { read: function(original) { var test = original.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/); if (test === null) return false; return { space: 'RGB', r: parseFloat(test[1]), g: parseFloat(test[2]), b: parseFloat(test[3]) }; }, write: toString }, CSS_RGBA: { read: function(original) { var test = original.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\,\s*(.+)\s*\)/); if (test === null) return false; return { space: 'RGB', r: parseFloat(test[1]), g: parseFloat(test[2]), b: parseFloat(test[3]), a: parseFloat(test[4]) }; }, write: toString } } }, // Numbers { litmus: common.isNumber, conversions: { HEX: { read: function(original) { return { space: 'HEX', hex: original, conversionName: 'HEX' } }, write: function(color) { return color.hex; } } } }, // Arrays { litmus: common.isArray, conversions: { RGB_ARRAY: { read: function(original) { if (original.length != 3) return false; return { space: 'RGB', r: original[0], g: original[1], b: original[2] }; }, write: function(color) { return [color.r, color.g, color.b]; } }, RGBA_ARRAY: { read: function(original) { if (original.length != 4) return false; return { space: 'RGB', r: original[0], g: original[1], b: original[2], a: original[3] }; }, write: function(color) { return [color.r, color.g, color.b, color.a]; } } } }, // Objects { litmus: common.isObject, conversions: { RGBA_OBJ: { read: function(original) { if (common.isNumber(original.r) && common.isNumber(original.g) && common.isNumber(original.b) && common.isNumber(original.a)) { return { space: 'RGB', r: original.r, g: original.g, b: original.b, a: original.a } } return false; }, write: function(color) { return { r: color.r, g: color.g, b: color.b, a: color.a } } }, RGB_OBJ: { read: function(original) { if (common.isNumber(original.r) && common.isNumber(original.g) && common.isNumber(original.b)) { return { space: 'RGB', r: original.r, g: original.g, b: original.b } } return false; }, write: function(color) { return { r: color.r, g: color.g, b: color.b } } }, HSVA_OBJ: { read: function(original) { if (common.isNumber(original.h) && common.isNumber(original.s) && common.isNumber(original.v) && common.isNumber(original.a)) { return { space: 'HSV', h: original.h, s: original.s, v: original.v, a: original.a } } return false; }, write: function(color) { return { h: color.h, s: color.s, v: color.v, a: color.a } } }, HSV_OBJ: { read: function(original) { if (common.isNumber(original.h) && common.isNumber(original.s) && common.isNumber(original.v)) { return { space: 'HSV', h: original.h, s: original.s, v: original.v } } return false; }, write: function(color) { return { h: color.h, s: color.s, v: color.v } } } } } ]; return interpret; })(dat.color.toString, dat.utils.common); dat.GUI = dat.gui.GUI = (function (css, saveDialogueContents, styleSheet, controllerFactory, Controller, BooleanController, FunctionController, NumberControllerBox, NumberControllerSlider, OptionController, ColorController, requestAnimationFrame, CenteredDiv, dom, common) { css.inject(styleSheet); /** Outer-most className for GUI's */ var CSS_NAMESPACE = 'dg'; var HIDE_KEY_CODE = 72; /** The only value shared between the JS and SCSS. Use caution. */ var CLOSE_BUTTON_HEIGHT = 20; var DEFAULT_DEFAULT_PRESET_NAME = 'Default'; var SUPPORTS_LOCAL_STORAGE = (function() { try { return 'localStorage' in window && window['localStorage'] !== null; } catch (e) { return false; } })(); var SAVE_DIALOGUE; /** Have we yet to create an autoPlace GUI? */ var auto_place_virgin = true; /** Fixed position div that auto place GUI's go inside */ var auto_place_container; /** Are we hiding the GUI's ? */ var hide = false; /** GUI's which should be hidden */ var hideable_guis = []; /** * A lightweight controller library for JavaScript. It allows you to easily * manipulate variables and fire functions on the fly. * @class * * @member dat.gui * * @param {Object} [params] * @param {String} [params.name] The name of this GUI. * @param {Object} [params.load] JSON object representing the saved state of * this GUI. * @param {Boolean} [params.auto=true] * @param {dat.gui.GUI} [params.parent] The GUI I'm nested in. * @param {Boolean} [params.closed] If true, starts closed */ var GUI = function(params) { var _this = this; /** * Outermost DOM Element * @type DOMElement */ this.domElement = document.createElement('div'); this.__ul = document.createElement('ul'); this.domElement.appendChild(this.__ul); dom.addClass(this.domElement, CSS_NAMESPACE); /** * Nested GUI's by name * @ignore */ this.__folders = {}; this.__controllers = []; /** * List of objects I'm remembering for save, only used in top level GUI * @ignore */ this.__rememberedObjects = []; /** * Maps the index of remembered objects to a map of controllers, only used * in top level GUI. * * @private * @ignore * * @example * [ * { * propertyName: Controller, * anotherPropertyName: Controller * }, * { * propertyName: Controller * } * ] */ this.__rememberedObjectIndecesToControllers = []; this.__listening = []; params = params || {}; // Default parameters params = common.defaults(params, { autoPlace: true, width: GUI.DEFAULT_WIDTH }); params = common.defaults(params, { resizable: params.autoPlace, hideable: params.autoPlace }); if (!common.isUndefined(params.load)) { // Explicit preset if (params.preset) params.load.preset = params.preset; } else { params.load = { preset: DEFAULT_DEFAULT_PRESET_NAME }; } if (common.isUndefined(params.parent) && params.hideable) { hideable_guis.push(this); } // Only root level GUI's are resizable. params.resizable = common.isUndefined(params.parent) && params.resizable; if (params.autoPlace && common.isUndefined(params.scrollable)) { params.scrollable = true; } // params.scrollable = common.isUndefined(params.parent) && params.scrollable === true; // Not part of params because I don't want people passing this in via // constructor. Should be a 'remembered' value. var use_local_storage = SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(this, 'isLocal')) === 'true'; var saveToLocalStorage; Object.defineProperties(this, /** @lends dat.gui.GUI.prototype */ { /** * The parent <code>GUI</code> * @type dat.gui.GUI */ parent: { get: function() { return params.parent; } }, scrollable: { get: function() { return params.scrollable; } }, /** * Handles <code>GUI</code>'s element placement for you * @type Boolean */ autoPlace: { get: function() { return params.autoPlace; } }, /** * The identifier for a set of saved values * @type String */ preset: { get: function() { if (_this.parent) { return _this.getRoot().preset; } else { return params.load.preset; } }, set: function(v) { if (_this.parent) { _this.getRoot().preset = v; } else { params.load.preset = v; } setPresetSelectIndex(this); _this.revert(); } }, /** * The width of <code>GUI</code> element * @type Number */ width: { get: function() { return params.width; }, set: function(v) { params.width = v; setWidth(_this, v); } }, /** * The name of <code>GUI</code>. Used for folders. i.e * a folder's name * @type String */ name: { get: function() { return params.name; }, set: function(v) { // TODO Check for collisions among sibling folders params.name = v; if (title_row_name) { title_row_name.innerHTML = params.name; } } }, /** * Whether the <code>GUI</code> is collapsed or not * @type Boolean */ closed: { get: function() { return params.closed; }, set: function(v) { params.closed = v; if (params.closed) { dom.addClass(_this.__ul, GUI.CLASS_CLOSED); } else { dom.removeClass(_this.__ul, GUI.CLASS_CLOSED); } // For browsers that aren't going to respect the CSS transition, // Lets just check our height against the window height right off // the bat. this.onResize(); if (_this.__closeButton) { _this.__closeButton.innerHTML = v ? GUI.TEXT_OPEN : GUI.TEXT_CLOSED; } } }, /** * Contains all presets * @type Object */ load: { get: function() { return params.load; } }, /** * Determines whether or not to use <a href="https://developer.mozilla.org/en/DOM/Storage#localStorage">localStorage</a> as the means for * <code>remember</code>ing * @type Boolean */ useLocalStorage: { get: function() { return use_local_storage; }, set: function(bool) { if (SUPPORTS_LOCAL_STORAGE) { use_local_storage = bool; if (bool) { dom.bind(window, 'unload', saveToLocalStorage); } else { dom.unbind(window, 'unload', saveToLocalStorage); } localStorage.setItem(getLocalStorageHash(_this, 'isLocal'), bool); } } } }); // Are we a root level GUI? if (common.isUndefined(params.parent)) { params.closed = false; dom.addClass(this.domElement, GUI.CLASS_MAIN); dom.makeSelectable(this.domElement, false); // Are we supposed to be loading locally? if (SUPPORTS_LOCAL_STORAGE) { if (use_local_storage) { _this.useLocalStorage = true; var saved_gui = localStorage.getItem(getLocalStorageHash(this, 'gui')); if (saved_gui) { params.load = JSON.parse(saved_gui); } } } this.__closeButton = document.createElement('div'); this.__closeButton.innerHTML = GUI.TEXT_CLOSED; dom.addClass(this.__closeButton, GUI.CLASS_CLOSE_BUTTON); this.domElement.appendChild(this.__closeButton); dom.bind(this.__closeButton, 'click', function() { _this.closed = !_this.closed; }); // Oh, you're a nested GUI! } else { if (params.closed === undefined) { params.closed = true; } var title_row_name = document.createTextNode(params.name); dom.addClass(title_row_name, 'controller-name'); var title_row = addRow(_this, title_row_name); var on_click_title = function(e) { e.preventDefault(); _this.closed = !_this.closed; return false; }; dom.addClass(this.__ul, GUI.CLASS_CLOSED); dom.addClass(title_row, 'title'); dom.bind(title_row, 'click', on_click_title); if (!params.closed) { this.closed = false; } } if (params.autoPlace) { if (common.isUndefined(params.parent)) { if (auto_place_virgin) { auto_place_container = document.createElement('div'); dom.addClass(auto_place_container, CSS_NAMESPACE); dom.addClass(auto_place_container, GUI.CLASS_AUTO_PLACE_CONTAINER); document.body.appendChild(auto_place_container); auto_place_virgin = false; } // Put it in the dom for you. auto_place_container.appendChild(this.domElement); // Apply the auto styles dom.addClass(this.domElement, GUI.CLASS_AUTO_PLACE); } // Make it not elastic. if (!this.parent) setWidth(_this, params.width); } dom.bind(window, 'resize', function() { _this.onResize() }); dom.bind(this.__ul, 'webkitTransitionEnd', function() { _this.onResize(); }); dom.bind(this.__ul, 'transitionend', function() { _this.onResize() }); dom.bind(this.__ul, 'oTransitionEnd', function() { _this.onResize() }); this.onResize(); if (params.resizable) { addResizeHandle(this); } saveToLocalStorage = function () { if (SUPPORTS_LOCAL_STORAGE && localStorage.getItem(getLocalStorageHash(_this, 'isLocal')) === 'true') { localStorage.setItem(getLocalStorageHash(_this, 'gui'), JSON.stringify(_this.getSaveObject())); } }; // expose this method publicly this.saveToLocalStorageIfPossible = saveToLocalStorage; var root = _this.getRoot(); function resetWidth() { var root = _this.getRoot(); root.width += 1; common.defer(function() { root.width -= 1; }); } if (!params.parent) { resetWidth(); } }; GUI.toggleHide = function() { hide = !hide; common.each(hideable_guis, function(gui) { gui.domElement.style.zIndex = hide ? -999 : 999; gui.domElement.style.opacity = hide ? 0 : 1; }); }; GUI.CLASS_AUTO_PLACE = 'a'; GUI.CLASS_AUTO_PLACE_CONTAINER = 'ac'; GUI.CLASS_MAIN = 'main'; GUI.CLASS_CONTROLLER_ROW = 'cr'; GUI.CLASS_TOO_TALL = 'taller-than-window'; GUI.CLASS_CLOSED = 'closed'; GUI.CLASS_CLOSE_BUTTON = 'close-button'; GUI.CLASS_DRAG = 'drag'; GUI.DEFAULT_WIDTH = 245; GUI.TEXT_CLOSED = 'Close Controls'; GUI.TEXT_OPEN = 'Open Controls'; dom.bind(window, 'keydown', function(e) { if (document.activeElement.type !== 'text' && (e.which === HIDE_KEY_CODE || e.keyCode == HIDE_KEY_CODE)) { GUI.toggleHide(); } }, false); common.extend( GUI.prototype, /** @lends dat.gui.GUI */ { /** * @param object * @param property * @returns {dat.controllers.Controller} The new controller that was added. * @instance */ add: function(object, property) { return add( this, object, property, { factoryArgs: Array.prototype.slice.call(arguments, 2) } ); }, /** * @param object * @param property * @returns {dat.controllers.ColorController} The new controller that was added. * @instance */ addColor: function(object, property) { return add( this, object, property, { color: true } ); }, /** * @param controller * @instance */ remove: function(controller) { // TODO listening? this.__ul.removeChild(controller.__li); this.__controllers.splice(this.__controllers.indexOf(controller), 1); var _this = this; common.defer(function() { _this.onResize(); }); }, destroy: function() { if (this.autoPlace) { auto_place_container.removeChild(this.domElement); } }, /** * @param name * @returns {dat.gui.GUI} The new folder. * @throws {Error} if this GUI already has a folder by the specified * name * @instance */ addFolder: function(name) { // We have to prevent collisions on names in order to have a key // by which to remember saved values if (this.__folders[name] !== undefined) { throw new Error('You already have a folder in this GUI by the' + ' name "' + name + '"'); } var new_gui_params = { name: name, parent: this }; // We need to pass down the autoPlace trait so that we can // attach event listeners to open/close folder actions to // ensure that a scrollbar appears if the window is too short. new_gui_params.autoPlace = this.autoPlace; // Do we have saved appearance data for this folder? if (this.load && // Anything loaded? this.load.folders && // Was my parent a dead-end? this.load.folders[name]) { // Did daddy remember me? // Start me closed if I was closed new_gui_params.closed = this.load.folders[name].closed; // Pass down the loaded data new_gui_params.load = this.load.folders[name]; } var gui = new GUI(new_gui_params); this.__folders[name] = gui; var li = addRow(this, gui.domElement); dom.addClass(li, 'folder'); return gui; }, open: function() { this.closed = false; }, close: function() { this.closed = true; }, onResize: function() { var root = this.getRoot(); if (root.scrollable) { var top = dom.getOffset(root.__ul).top; var h = 0; common.each(root.__ul.childNodes, function(node) { if (! (root.autoPlace && node === root.__save_row)) h += dom.getHeight(node); }); if (window.innerHeight - top - CLOSE_BUTTON_HEIGHT < h) { dom.addClass(root.domElement, GUI.CLASS_TOO_TALL); root.__ul.style.height = window.innerHeight - top - CLOSE_BUTTON_HEIGHT + 'px'; } else { dom.removeClass(root.domElement, GUI.CLASS_TOO_TALL); root.__ul.style.height = 'auto'; } } if (root.__resize_handle) { common.defer(function() { root.__resize_handle.style.height = root.__ul.offsetHeight + 'px'; }); } if (root.__closeButton) { root.__closeButton.style.width = root.width + 'px'; } }, /** * Mark objects for saving. The order of these objects cannot change as * the GUI grows. When remembering new objects, append them to the end * of the list. * * @param {Object...} objects * @throws {Error} if not called on a top level GUI. * @instance */ remember: function() { if (common.isUndefined(SAVE_DIALOGUE)) { SAVE_DIALOGUE = new CenteredDiv(); SAVE_DIALOGUE.domElement.innerHTML = saveDialogueContents; } if (this.parent) { throw new Error("You can only call remember on a top level GUI."); } var _this = this; common.each(Array.prototype.slice.call(arguments), function(object) { if (_this.__rememberedObjects.length == 0) { addSaveMenu(_this); } if (_this.__rememberedObjects.indexOf(object) == -1) { _this.__rememberedObjects.push(object); } }); if (this.autoPlace) { // Set save row width setWidth(this, this.width); } }, /** * @returns {dat.gui.GUI} the topmost parent GUI of a nested GUI. * @instance */ getRoot: function() { var gui = this; while (gui.parent) { gui = gui.parent; } return gui; }, /** * @returns {Object} a JSON object representing the current state of * this GUI as well as its remembered properties. * @instance */ getSaveObject: function() { var toReturn = this.load; toReturn.closed = this.closed; // Am I remembering any values? if (this.__rememberedObjects.length > 0) { toReturn.preset = this.preset; if (!toReturn.remembered) { toReturn.remembered = {}; } toReturn.remembered[this.preset] = getCurrentPreset(this); } toReturn.folders = {}; common.each(this.__folders, function(element, key) { toReturn.folders[key] = element.getSaveObject(); }); return toReturn; }, save: function() { if (!this.load.remembered) { this.load.remembered = {}; } this.load.remembered[this.preset] = getCurrentPreset(this); markPresetModified(this, false); this.saveToLocalStorageIfPossible(); }, saveAs: function(presetName) { if (!this.load.remembered) { // Retain default values upon first save this.load.remembered = {}; this.load.remembered[DEFAULT_DEFAULT_PRESET_NAME] = getCurrentPreset(this, true); } this.load.remembered[presetName] = getCurrentPreset(this); this.preset = presetName; addPresetOption(this, presetName, true); this.saveToLocalStorageIfPossible(); }, revert: function(gui) { common.each(this.__controllers, function(controller) { // Make revert work on Default. if (!this.getRoot().load.remembered) { controller.setValue(controller.initialValue); } else { recallSavedValue(gui || this.getRoot(), controller); } }, this); common.each(this.__folders, function(folder) { folder.revert(folder); }); if (!gui) { markPresetModified(this.getRoot(), false); } }, listen: function(controller) { var init = this.__listening.length == 0; this.__listening.push(controller); if (init) updateDisplays(this.__listening); } } ); function add(gui, object, property, params) { if (object[property] === undefined) { throw new Error("Object " + object + " has no property \"" + property + "\""); } var controller; if (params.color) { controller = new ColorController(object, property); } else { var factoryArgs = [object,property].concat(params.factoryArgs); controller = controllerFactory.apply(gui, factoryArgs); } if (params.before instanceof Controller) { params.before = params.before.__li; } recallSavedValue(gui, controller); dom.addClass(controller.domElement, 'c'); var name = document.createElement('span'); dom.addClass(name, 'property-name'); name.innerHTML = controller.property; var container = document.createElement('div'); container.appendChild(name); container.appendChild(controller.domElement); var li = addRow(gui, container, params.before); dom.addClass(li, GUI.CLASS_CONTROLLER_ROW); dom.addClass(li, typeof controller.getValue()); augmentController(gui, li, controller); gui.__controllers.push(controller); return controller; } /** * Add a row to the end of the GUI or before another row. * * @param gui * @param [dom] If specified, inserts the dom content in the new row * @param [liBefore] If specified, places the new row before another row */ function addRow(gui, dom, liBefore) { var li = document.createElement('li'); if (dom) li.appendChild(dom); if (liBefore) { gui.__ul.insertBefore(li, params.before); } else { gui.__ul.appendChild(li); } gui.onResize(); return li; } function augmentController(gui, li, controller) { controller.__li = li; controller.__gui = gui; common.extend(controller, { options: function(options) { if (arguments.length > 1) { controller.remove(); return add( gui, controller.object, controller.property, { before: controller.__li.nextElementSibling, factoryArgs: [common.toArray(arguments)] } ); } if (common.isArray(options) || common.isObject(options)) { controller.remove(); return add( gui, controller.object, controller.property, { before: controller.__li.nextElementSibling, factoryArgs: [options] } ); } }, name: function(v) { controller.__li.firstElementChild.firstElementChild.innerHTML = v; return controller; }, listen: function() { controller.__gui.listen(controller); return controller; }, remove: function() { controller.__gui.remove(controller); return controller; } }); // All sliders should be accompanied by a box. if (controller instanceof NumberControllerSlider) { var box = new NumberControllerBox(controller.object, controller.property, { min: controller.__min, max: controller.__max, step: controller.__step }); common.each(['updateDisplay', 'onChange', 'onFinishChange'], function(method) { var pc = controller[method]; var pb = box[method]; controller[method] = box[method] = function() { var args = Array.prototype.slice.call(arguments); pc.apply(controller, args); return pb.apply(box, args); } }); dom.addClass(li, 'has-slider'); controller.domElement.insertBefore(box.domElement, controller.domElement.firstElementChild); } else if (controller instanceof NumberControllerBox) { var r = function(returned) { // Have we defined both boundaries? if (common.isNumber(controller.__min) && common.isNumber(controller.__max)) { // Well, then lets just replace this with a slider. controller.remove(); return add( gui, controller.object, controller.property, { before: controller.__li.nextElementSibling, factoryArgs: [controller.__min, controller.__max, controller.__step] }); } return returned; }; controller.min = common.compose(r, controller.min); controller.max = common.compose(r, controller.max); } else if (controller instanceof BooleanController) { dom.bind(li, 'click', function() { dom.fakeEvent(controller.__checkbox, 'click'); }); dom.bind(controller.__checkbox, 'click', function(e) { e.stopPropagation(); // Prevents double-toggle }) } else if (controller instanceof FunctionController) { dom.bind(li, 'click', function() { dom.fakeEvent(controller.__button, 'click'); }); dom.bind(li, 'mouseover', function() { dom.addClass(controller.__button, 'hover'); }); dom.bind(li, 'mouseout', function() { dom.removeClass(controller.__button, 'hover'); }); } else if (controller instanceof ColorController) { dom.addClass(li, 'color'); controller.updateDisplay = common.compose(function(r) { li.style.borderLeftColor = controller.__color.toString(); return r; }, controller.updateDisplay); controller.updateDisplay(); } controller.setValue = common.compose(function(r) { if (gui.getRoot().__preset_select && controller.isModified()) { markPresetModified(gui.getRoot(), true); } return r; }, controller.setValue); } function recallSavedValue(gui, controller) { // Find the topmost GUI, that's where remembered objects live. var root = gui.getRoot(); // Does the object we're controlling match anything we've been told to // remember? var matched_index = root.__rememberedObjects.indexOf(controller.object); // Why yes, it does! if (matched_index != -1) { // Let me fetch a map of controllers for thcommon.isObject. var controller_map = root.__rememberedObjectIndecesToControllers[matched_index]; // Ohp, I believe this is the first controller we've created for this // object. Lets make the map fresh. if (controller_map === undefined) { controller_map = {}; root.__rememberedObjectIndecesToControllers[matched_index] = controller_map; } // Keep track of this controller controller_map[controller.property] = controller; // Okay, now have we saved any values for this controller? if (root.load && root.load.remembered) { var preset_map = root.load.remembered; // Which preset are we trying to load? var preset; if (preset_map[gui.preset]) { preset = preset_map[gui.preset]; } else if (preset_map[DEFAULT_DEFAULT_PRESET_NAME]) { // Uhh, you can have the default instead? preset = preset_map[DEFAULT_DEFAULT_PRESET_NAME]; } else { // Nada. return; } // Did the loaded object remember thcommon.isObject? if (preset[matched_index] && // Did we remember this particular property? preset[matched_index][controller.property] !== undefined) { // We did remember something for this guy ... var value = preset[matched_index][controller.property]; // And that's what it is. controller.initialValue = value; controller.setValue(value); } } } } function getLocalStorageHash(gui, key) { // TODO how does this deal with multiple GUI's? return document.location.href + '.' + key; } function addSaveMenu(gui) { var div = gui.__save_row = document.createElement('li'); dom.addClass(gui.domElement, 'has-save'); gui.__ul.insertBefore(div, gui.__ul.firstChild); dom.addClass(div, 'save-row'); var gears = document.createElement('span'); gears.innerHTML = '&nbsp;'; dom.addClass(gears, 'button gears'); // TODO replace with FunctionController var button = document.createElement('span'); button.innerHTML = 'Save'; dom.addClass(button, 'button'); dom.addClass(button, 'save'); var button2 = document.createElement('span'); button2.innerHTML = 'New'; dom.addClass(button2, 'button'); dom.addClass(button2, 'save-as'); var button3 = document.createElement('span'); button3.innerHTML = 'Revert'; dom.addClass(button3, 'button'); dom.addClass(button3, 'revert'); var select = gui.__preset_select = document.createElement('select'); if (gui.load && gui.load.remembered) { common.each(gui.load.remembered, function(value, key) { addPresetOption(gui, key, key == gui.preset); }); } else { addPresetOption(gui, DEFAULT_DEFAULT_PRESET_NAME, false); } dom.bind(select, 'change', function() { for (var index = 0; index < gui.__preset_select.length; index++) { gui.__preset_select[index].innerHTML = gui.__preset_select[index].value; } gui.preset = this.value; }); div.appendChild(select); div.appendChild(gears); div.appendChild(button); div.appendChild(button2); div.appendChild(button3); if (SUPPORTS_LOCAL_STORAGE) { var saveLocally = document.getElementById('dg-save-locally'); var explain = document.getElementById('dg-local-explain'); saveLocally.style.display = 'block'; var localStorageCheckBox = document.getElementById('dg-local-storage'); if (localStorage.getItem(getLocalStorageHash(gui, 'isLocal')) === 'true') { localStorageCheckBox.setAttribute('checked', 'checked'); } function showHideExplain() { explain.style.display = gui.useLocalStorage ? 'block' : 'none'; } showHideExplain(); // TODO: Use a boolean controller, fool! dom.bind(localStorageCheckBox, 'change', function() { gui.useLocalStorage = !gui.useLocalStorage; showHideExplain(); }); } var newConstructorTextArea = document.getElementById('dg-new-constructor'); dom.bind(newConstructorTextArea, 'keydown', function(e) { if (e.metaKey && (e.which === 67 || e.keyCode == 67)) { SAVE_DIALOGUE.hide(); } }); dom.bind(gears, 'click', function() { newConstructorTextArea.innerHTML = JSON.stringify(gui.getSaveObject(), undefined, 2); SAVE_DIALOGUE.show(); newConstructorTextArea.focus(); newConstructorTextArea.select(); }); dom.bind(button, 'click', function() { gui.save(); }); dom.bind(button2, 'click', function() { var presetName = prompt('Enter a new preset name.'); if (presetName) gui.saveAs(presetName); }); dom.bind(button3, 'click', function() { gui.revert(); }); // div.appendChild(button2); } function addResizeHandle(gui) { gui.__resize_handle = document.createElement('div'); common.extend(gui.__resize_handle.style, { width: '6px', marginLeft: '-3px', height: '200px', cursor: 'ew-resize', position: 'absolute' // border: '1px solid blue' }); var pmouseX; dom.bind(gui.__resize_handle, 'mousedown', dragStart); dom.bind(gui.__closeButton, 'mousedown', dragStart); gui.domElement.insertBefore(gui.__resize_handle, gui.domElement.firstElementChild); function dragStart(e) { e.preventDefault(); pmouseX = e.clientX; dom.addClass(gui.__closeButton, GUI.CLASS_DRAG); dom.bind(window, 'mousemove', drag); dom.bind(window, 'mouseup', dragStop); return false; } function drag(e) { e.preventDefault(); gui.width += pmouseX - e.clientX; gui.onResize(); pmouseX = e.clientX; return false; } function dragStop() { dom.removeClass(gui.__closeButton, GUI.CLASS_DRAG); dom.unbind(window, 'mousemove', drag); dom.unbind(window, 'mouseup', dragStop); } } function setWidth(gui, w) { gui.domElement.style.width = w + 'px'; // Auto placed save-rows are position fixed, so we have to // set the width manually if we want it to bleed to the edge if (gui.__save_row && gui.autoPlace) { gui.__save_row.style.width = w + 'px'; }if (gui.__closeButton) { gui.__closeButton.style.width = w + 'px'; } } function getCurrentPreset(gui, useInitialValues) { var toReturn = {}; // For each object I'm remembering common.each(gui.__rememberedObjects, function(val, index) { var saved_values = {}; // The controllers I've made for thcommon.isObject by property var controller_map = gui.__rememberedObjectIndecesToControllers[index]; // Remember each value for each property common.each(controller_map, function(controller, property) { saved_values[property] = useInitialValues ? controller.initialValue : controller.getValue(); }); // Save the values for thcommon.isObject toReturn[index] = saved_values; }); return toReturn; } function addPresetOption(gui, name, setSelected) { var opt = document.createElement('option'); opt.innerHTML = name; opt.value = name; gui.__preset_select.appendChild(opt); if (setSelected) { gui.__preset_select.selectedIndex = gui.__preset_select.length - 1; } } function setPresetSelectIndex(gui) { for (var index = 0; index < gui.__preset_select.length; index++) { if (gui.__preset_select[index].value == gui.preset) { gui.__preset_select.selectedIndex = index; } } } function markPresetModified(gui, modified) { var opt = gui.__preset_select[gui.__preset_select.selectedIndex]; // console.log('mark', modified, opt); if (modified) { opt.innerHTML = opt.value + "*"; } else { opt.innerHTML = opt.value; } } function updateDisplays(controllerArray) { if (controllerArray.length != 0) { requestAnimationFrame(function() { updateDisplays(controllerArray); }); } common.each(controllerArray, function(c) { c.updateDisplay(); }); } return GUI; })(dat.utils.css, "<div id=\"dg-save\" class=\"dg dialogue\">\n\n Here's the new load parameter for your <code>GUI</code>'s constructor:\n\n <textarea id=\"dg-new-constructor\"></textarea>\n\n <div id=\"dg-save-locally\">\n\n <input id=\"dg-local-storage\" type=\"checkbox\"/> Automatically save\n values to <code>localStorage</code> on exit.\n\n <div id=\"dg-local-explain\">The values saved to <code>localStorage</code> will\n override those passed to <code>dat.GUI</code>'s constructor. This makes it\n easier to work incrementally, but <code>localStorage</code> is fragile,\n and your friends may not see the same values you do.\n \n </div>\n \n </div>\n\n</div>", ".dg {\n /** Clear list styles */\n /* Auto-place container */\n /* Auto-placed GUI's */\n /* Line items that don't contain folders. */\n /** Folder names */\n /** Hides closed items */\n /** Controller row */\n /** Name-half (left) */\n /** Controller-half (right) */\n /** Controller placement */\n /** Shorter number boxes when slider is present. */\n /** Ensure the entire boolean and function row shows a hand */ }\n .dg ul {\n list-style: none;\n margin: 0;\n padding: 0;\n width: 100%;\n clear: both; }\n .dg.ac {\n position: fixed;\n top: 0;\n left: 0;\n right: 0;\n height: 0;\n z-index: 0; }\n .dg:not(.ac) .main {\n /** Exclude mains in ac so that we don't hide close button */\n overflow: hidden; }\n .dg.main {\n -webkit-transition: opacity 0.1s linear;\n -o-transition: opacity 0.1s linear;\n -moz-transition: opacity 0.1s linear;\n transition: opacity 0.1s linear; }\n .dg.main.taller-than-window {\n overflow-y: auto; }\n .dg.main.taller-than-window .close-button {\n opacity: 1;\n /* TODO, these are style notes */\n margin-top: -1px;\n border-top: 1px solid #2c2c2c; }\n .dg.main ul.closed .close-button {\n opacity: 1 !important; }\n .dg.main:hover .close-button,\n .dg.main .close-button.drag {\n opacity: 1; }\n .dg.main .close-button {\n /*opacity: 0;*/\n -webkit-transition: opacity 0.1s linear;\n -o-transition: opacity 0.1s linear;\n -moz-transition: opacity 0.1s linear;\n transition: opacity 0.1s linear;\n border: 0;\n position: absolute;\n line-height: 19px;\n height: 20px;\n /* TODO, these are style notes */\n cursor: pointer;\n text-align: center;\n background-color: #000; }\n .dg.main .close-button:hover {\n background-color: #111; }\n .dg.a {\n float: right;\n margin-right: 15px;\n overflow-x: hidden; }\n .dg.a.has-save > ul {\n margin-top: 27px; }\n .dg.a.has-save > ul.closed {\n margin-top: 0; }\n .dg.a .save-row {\n position: fixed;\n top: 0;\n z-index: 1002; }\n .dg li {\n -webkit-transition: height 0.1s ease-out;\n -o-transition: height 0.1s ease-out;\n -moz-transition: height 0.1s ease-out;\n transition: height 0.1s ease-out; }\n .dg li:not(.folder) {\n cursor: auto;\n height: 27px;\n line-height: 27px;\n overflow: hidden;\n padding: 0 4px 0 5px; }\n .dg li.folder {\n padding: 0;\n border-left: 4px solid rgba(0, 0, 0, 0); }\n .dg li.title {\n cursor: pointer;\n margin-left: -4px; }\n .dg .closed li:not(.title),\n .dg .closed ul li,\n .dg .closed ul li > * {\n height: 0;\n overflow: hidden;\n border: 0; }\n .dg .cr {\n clear: both;\n padding-left: 3px;\n height: 27px; }\n .dg .property-name {\n cursor: default;\n float: left;\n clear: left;\n width: 40%;\n overflow: hidden;\n text-overflow: ellipsis; }\n .dg .c {\n float: left;\n width: 60%; }\n .dg .c input[type=text] {\n border: 0;\n margin-top: 4px;\n padding: 3px;\n width: 100%;\n float: right; }\n .dg .has-slider input[type=text] {\n width: 30%;\n /*display: none;*/\n margin-left: 0; }\n .dg .slider {\n float: left;\n width: 66%;\n margin-left: -5px;\n margin-right: 0;\n height: 19px;\n margin-top: 4px; }\n .dg .slider-fg {\n height: 100%; }\n .dg .c input[type=checkbox] {\n margin-top: 9px; }\n .dg .c select {\n margin-top: 5px; }\n .dg .cr.function,\n .dg .cr.function .property-name,\n .dg .cr.function *,\n .dg .cr.boolean,\n .dg .cr.boolean * {\n cursor: pointer; }\n .dg .selector {\n display: none;\n position: absolute;\n margin-left: -9px;\n margin-top: 23px;\n z-index: 10; }\n .dg .c:hover .selector,\n .dg .selector.drag {\n display: block; }\n .dg li.save-row {\n padding: 0; }\n .dg li.save-row .button {\n display: inline-block;\n padding: 0px 6px; }\n .dg.dialogue {\n background-color: #222;\n width: 460px;\n padding: 15px;\n font-size: 13px;\n line-height: 15px; }\n\n/* TODO Separate style and structure */\n#dg-new-constructor {\n padding: 10px;\n color: #222;\n font-family: Monaco, monospace;\n font-size: 10px;\n border: 0;\n resize: none;\n box-shadow: inset 1px 1px 1px #888;\n word-wrap: break-word;\n margin: 12px 0;\n display: block;\n width: 440px;\n overflow-y: scroll;\n height: 100px;\n position: relative; }\n\n#dg-local-explain {\n display: none;\n font-size: 11px;\n line-height: 17px;\n border-radius: 3px;\n background-color: #333;\n padding: 8px;\n margin-top: 10px; }\n #dg-local-explain code {\n font-size: 10px; }\n\n#dat-gui-save-locally {\n display: none; }\n\n/** Main type */\n.dg {\n color: #eee;\n font: 11px 'Lucida Grande', sans-serif;\n text-shadow: 0 -1px 0 #111;\n /** Auto place */\n /* Controller row, <li> */\n /** Controllers */ }\n .dg.main {\n /** Scrollbar */ }\n .dg.main::-webkit-scrollbar {\n width: 5px;\n background: #1a1a1a; }\n .dg.main::-webkit-scrollbar-corner {\n height: 0;\n display: none; }\n .dg.main::-webkit-scrollbar-thumb {\n border-radius: 5px;\n background: #676767; }\n .dg li:not(.folder) {\n background: #1a1a1a;\n border-bottom: 1px solid #2c2c2c; }\n .dg li.save-row {\n line-height: 25px;\n background: #dad5cb;\n border: 0; }\n .dg li.save-row select {\n margin-left: 5px;\n width: 108px; }\n .dg li.save-row .button {\n margin-left: 5px;\n margin-top: 1px;\n border-radius: 2px;\n font-size: 9px;\n line-height: 7px;\n padding: 4px 4px 5px 4px;\n background: #c5bdad;\n color: #fff;\n text-shadow: 0 1px 0 #b0a58f;\n box-shadow: 0 -1px 0 #b0a58f;\n cursor: pointer; }\n .dg li.save-row .button.gears {\n background: #c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;\n height: 7px;\n width: 8px; }\n .dg li.save-row .button:hover {\n background-color: #bab19e;\n box-shadow: 0 -1px 0 #b0a58f; }\n .dg li.folder {\n border-bottom: 0; }\n .dg li.title {\n padding-left: 16px;\n background: black url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;\n cursor: pointer;\n border-bottom: 1px solid rgba(255, 255, 255, 0.2); }\n .dg .closed li.title {\n background-image: url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==); }\n .dg .cr.boolean {\n border-left: 3px solid #806787; }\n .dg .cr.function {\n border-left: 3px solid #e61d5f; }\n .dg .cr.number {\n border-left: 3px solid #2fa1d6; }\n .dg .cr.number input[type=text] {\n color: #2fa1d6; }\n .dg .cr.string {\n border-left: 3px solid #1ed36f; }\n .dg .cr.string input[type=text] {\n color: #1ed36f; }\n .dg .cr.function:hover, .dg .cr.boolean:hover {\n background: #111; }\n .dg .c input[type=text] {\n background: #303030;\n outline: none; }\n .dg .c input[type=text]:hover {\n background: #3c3c3c; }\n .dg .c input[type=text]:focus {\n background: #494949;\n color: #fff; }\n .dg .c .slider {\n background: #303030;\n cursor: ew-resize; }\n .dg .c .slider-fg {\n background: #2fa1d6; }\n .dg .c .slider:hover {\n background: #3c3c3c; }\n .dg .c .slider:hover .slider-fg {\n background: #44abda; }\n", dat.controllers.factory = (function (OptionController, NumberControllerBox, NumberControllerSlider, StringController, FunctionController, BooleanController, common) { return function(object, property) { var initialValue = object[property]; // Providing options? if (common.isArray(arguments[2]) || common.isObject(arguments[2])) { return new OptionController(object, property, arguments[2]); } // Providing a map? if (common.isNumber(initialValue)) { if (common.isNumber(arguments[2]) && common.isNumber(arguments[3])) { // Has min and max. return new NumberControllerSlider(object, property, arguments[2], arguments[3]); } else { return new NumberControllerBox(object, property, { min: arguments[2], max: arguments[3] }); } } if (common.isString(initialValue)) { return new StringController(object, property); } if (common.isFunction(initialValue)) { return new FunctionController(object, property, ''); } if (common.isBoolean(initialValue)) { return new BooleanController(object, property); } } })(dat.controllers.OptionController, dat.controllers.NumberControllerBox, dat.controllers.NumberControllerSlider, dat.controllers.StringController = (function (Controller, dom, common) { /** * @class Provides a text input to alter the string property of an object. * * @extends dat.controllers.Controller * * @param {Object} object The object to be manipulated * @param {string} property The name of the property to be manipulated * * @member dat.controllers */ var StringController = function(object, property) { StringController.superclass.call(this, object, property); var _this = this; this.__input = document.createElement('input'); this.__input.setAttribute('type', 'text'); dom.bind(this.__input, 'keyup', onChange); dom.bind(this.__input, 'change', onChange); dom.bind(this.__input, 'blur', onBlur); dom.bind(this.__input, 'keydown', function(e) { if (e.keyCode === 13) { this.blur(); } }); function onChange() { _this.setValue(_this.__input.value); } function onBlur() { if (_this.__onFinishChange) { _this.__onFinishChange.call(_this, _this.getValue()); } } this.updateDisplay(); this.domElement.appendChild(this.__input); }; StringController.superclass = Controller; common.extend( StringController.prototype, Controller.prototype, { updateDisplay: function() { // Stops the caret from moving on account of: // keyup -> setValue -> updateDisplay if (!dom.isActive(this.__input)) { this.__input.value = this.getValue(); } return StringController.superclass.prototype.updateDisplay.call(this); } } ); return StringController; })(dat.controllers.Controller, dat.dom.dom, dat.utils.common), dat.controllers.FunctionController, dat.controllers.BooleanController, dat.utils.common), dat.controllers.Controller, dat.controllers.BooleanController, dat.controllers.FunctionController, dat.controllers.NumberControllerBox, dat.controllers.NumberControllerSlider, dat.controllers.OptionController, dat.controllers.ColorController = (function (Controller, dom, Color, interpret, common) { var ColorController = function(object, property) { ColorController.superclass.call(this, object, property); this.__color = new Color(this.getValue()); this.__temp = new Color(0); var _this = this; this.domElement = document.createElement('div'); dom.makeSelectable(this.domElement, false); this.__selector = document.createElement('div'); this.__selector.className = 'selector'; this.__saturation_field = document.createElement('div'); this.__saturation_field.className = 'saturation-field'; this.__field_knob = document.createElement('div'); this.__field_knob.className = 'field-knob'; this.__field_knob_border = '2px solid '; this.__hue_knob = document.createElement('div'); this.__hue_knob.className = 'hue-knob'; this.__hue_field = document.createElement('div'); this.__hue_field.className = 'hue-field'; this.__input = document.createElement('input'); this.__input.type = 'text'; this.__input_textShadow = '0 1px 1px '; dom.bind(this.__input, 'keydown', function(e) { if (e.keyCode === 13) { // on enter onBlur.call(this); } }); dom.bind(this.__input, 'blur', onBlur); dom.bind(this.__selector, 'mousedown', function(e) { dom .addClass(this, 'drag') .bind(window, 'mouseup', function(e) { dom.removeClass(_this.__selector, 'drag'); }); }); var value_field = document.createElement('div'); common.extend(this.__selector.style, { width: '122px', height: '102px', padding: '3px', backgroundColor: '#222', boxShadow: '0px 1px 3px rgba(0,0,0,0.3)' }); common.extend(this.__field_knob.style, { position: 'absolute', width: '12px', height: '12px', border: this.__field_knob_border + (this.__color.v < .5 ? '#fff' : '#000'), boxShadow: '0px 1px 3px rgba(0,0,0,0.5)', borderRadius: '12px', zIndex: 1 }); common.extend(this.__hue_knob.style, { position: 'absolute', width: '15px', height: '2px', borderRight: '4px solid #fff', zIndex: 1 }); common.extend(this.__saturation_field.style, { width: '100px', height: '100px', border: '1px solid #555', marginRight: '3px', display: 'inline-block', cursor: 'pointer' }); common.extend(value_field.style, { width: '100%', height: '100%', background: 'none' }); linearGradient(value_field, 'top', 'rgba(0,0,0,0)', '#000'); common.extend(this.__hue_field.style, { width: '15px', height: '100px', display: 'inline-block', border: '1px solid #555', cursor: 'ns-resize' }); hueGradient(this.__hue_field); common.extend(this.__input.style, { outline: 'none', // width: '120px', textAlign: 'center', // padding: '4px', // marginBottom: '6px', color: '#fff', border: 0, fontWeight: 'bold', textShadow: this.__input_textShadow + 'rgba(0,0,0,0.7)' }); dom.bind(this.__saturation_field, 'mousedown', fieldDown); dom.bind(this.__field_knob, 'mousedown', fieldDown); dom.bind(this.__hue_field, 'mousedown', function(e) { setH(e); dom.bind(window, 'mousemove', setH); dom.bind(window, 'mouseup', unbindH); }); function fieldDown(e) { setSV(e); // document.body.style.cursor = 'none'; dom.bind(window, 'mousemove', setSV); dom.bind(window, 'mouseup', unbindSV); } function unbindSV() { dom.unbind(window, 'mousemove', setSV); dom.unbind(window, 'mouseup', unbindSV); // document.body.style.cursor = 'default'; } function onBlur() { var i = interpret(this.value); if (i !== false) { _this.__color.__state = i; _this.setValue(_this.__color.toOriginal()); } else { this.value = _this.__color.toString(); } } function unbindH() { dom.unbind(window, 'mousemove', setH); dom.unbind(window, 'mouseup', unbindH); } this.__saturation_field.appendChild(value_field); this.__selector.appendChild(this.__field_knob); this.__selector.appendChild(this.__saturation_field); this.__selector.appendChild(this.__hue_field); this.__hue_field.appendChild(this.__hue_knob); this.domElement.appendChild(this.__input); this.domElement.appendChild(this.__selector); this.updateDisplay(); function setSV(e) { e.preventDefault(); var w = dom.getWidth(_this.__saturation_field); var o = dom.getOffset(_this.__saturation_field); var s = (e.clientX - o.left + document.body.scrollLeft) / w; var v = 1 - (e.clientY - o.top + document.body.scrollTop) / w; if (v > 1) v = 1; else if (v < 0) v = 0; if (s > 1) s = 1; else if (s < 0) s = 0; _this.__color.v = v; _this.__color.s = s; _this.setValue(_this.__color.toOriginal()); return false; } function setH(e) { e.preventDefault(); var s = dom.getHeight(_this.__hue_field); var o = dom.getOffset(_this.__hue_field); var h = 1 - (e.clientY - o.top + document.body.scrollTop) / s; if (h > 1) h = 1; else if (h < 0) h = 0; _this.__color.h = h * 360; _this.setValue(_this.__color.toOriginal()); return false; } }; ColorController.superclass = Controller; common.extend( ColorController.prototype, Controller.prototype, { updateDisplay: function() { var i = interpret(this.getValue()); if (i !== false) { var mismatch = false; // Check for mismatch on the interpreted value. common.each(Color.COMPONENTS, function(component) { if (!common.isUndefined(i[component]) && !common.isUndefined(this.__color.__state[component]) && i[component] !== this.__color.__state[component]) { mismatch = true; return {}; // break } }, this); // If nothing diverges, we keep our previous values // for statefulness, otherwise we recalculate fresh if (mismatch) { common.extend(this.__color.__state, i); } } common.extend(this.__temp.__state, this.__color.__state); this.__temp.a = 1; var flip = (this.__color.v < .5 || this.__color.s > .5) ? 255 : 0; var _flip = 255 - flip; common.extend(this.__field_knob.style, { marginLeft: 100 * this.__color.s - 7 + 'px', marginTop: 100 * (1 - this.__color.v) - 7 + 'px', backgroundColor: this.__temp.toString(), border: this.__field_knob_border + 'rgb(' + flip + ',' + flip + ',' + flip +')' }); this.__hue_knob.style.marginTop = (1 - this.__color.h / 360) * 100 + 'px'; this.__temp.s = 1; this.__temp.v = 1; linearGradient(this.__saturation_field, 'left', '#fff', this.__temp.toString()); common.extend(this.__input.style, { backgroundColor: this.__input.value = this.__color.toString(), color: 'rgb(' + flip + ',' + flip + ',' + flip +')', textShadow: this.__input_textShadow + 'rgba(' + _flip + ',' + _flip + ',' + _flip +',.7)' }); } } ); var vendors = ['-moz-','-o-','-webkit-','-ms-','']; function linearGradient(elem, x, a, b) { elem.style.background = ''; common.each(vendors, function(vendor) { elem.style.cssText += 'background: ' + vendor + 'linear-gradient('+x+', '+a+' 0%, ' + b + ' 100%); '; }); } function hueGradient(elem) { elem.style.background = ''; elem.style.cssText += 'background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);'; elem.style.cssText += 'background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; elem.style.cssText += 'background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; elem.style.cssText += 'background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);'; elem.style.cssText += 'background: linear-gradient(top, #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);' } return ColorController; })(dat.controllers.Controller, dat.dom.dom, dat.color.Color = (function (interpret, math, toString, common) { var Color = function() { this.__state = interpret.apply(this, arguments); if (this.__state === false) { throw 'Failed to interpret color arguments'; } this.__state.a = this.__state.a || 1; }; Color.COMPONENTS = ['r','g','b','h','s','v','hex','a']; common.extend(Color.prototype, { toString: function() { return toString(this); }, toOriginal: function() { return this.__state.conversion.write(this); } }); defineRGBComponent(Color.prototype, 'r', 2); defineRGBComponent(Color.prototype, 'g', 1); defineRGBComponent(Color.prototype, 'b', 0); defineHSVComponent(Color.prototype, 'h'); defineHSVComponent(Color.prototype, 's'); defineHSVComponent(Color.prototype, 'v'); Object.defineProperty(Color.prototype, 'a', { get: function() { return this.__state.a; }, set: function(v) { this.__state.a = v; } }); Object.defineProperty(Color.prototype, 'hex', { get: function() { if (!this.__state.space !== 'HEX') { this.__state.hex = math.rgb_to_hex(this.r, this.g, this.b); } return this.__state.hex; }, set: function(v) { this.__state.space = 'HEX'; this.__state.hex = v; } }); function defineRGBComponent(target, component, componentHexIndex) { Object.defineProperty(target, component, { get: function() { if (this.__state.space === 'RGB') { return this.__state[component]; } recalculateRGB(this, component, componentHexIndex); return this.__state[component]; }, set: function(v) { if (this.__state.space !== 'RGB') { recalculateRGB(this, component, componentHexIndex); this.__state.space = 'RGB'; } this.__state[component] = v; } }); } function defineHSVComponent(target, component) { Object.defineProperty(target, component, { get: function() { if (this.__state.space === 'HSV') return this.__state[component]; recalculateHSV(this); return this.__state[component]; }, set: function(v) { if (this.__state.space !== 'HSV') { recalculateHSV(this); this.__state.space = 'HSV'; } this.__state[component] = v; } }); } function recalculateRGB(color, component, componentHexIndex) { if (color.__state.space === 'HEX') { color.__state[component] = math.component_from_hex(color.__state.hex, componentHexIndex); } else if (color.__state.space === 'HSV') { common.extend(color.__state, math.hsv_to_rgb(color.__state.h, color.__state.s, color.__state.v)); } else { throw 'Corrupted color state'; } } function recalculateHSV(color) { var result = math.rgb_to_hsv(color.r, color.g, color.b); common.extend(color.__state, { s: result.s, v: result.v } ); if (!common.isNaN(result.h)) { color.__state.h = result.h; } else if (common.isUndefined(color.__state.h)) { color.__state.h = 0; } } return Color; })(dat.color.interpret, dat.color.math = (function () { var tmpComponent; return { hsv_to_rgb: function(h, s, v) { var hi = Math.floor(h / 60) % 6; var f = h / 60 - Math.floor(h / 60); var p = v * (1.0 - s); var q = v * (1.0 - (f * s)); var t = v * (1.0 - ((1.0 - f) * s)); var c = [ [v, t, p], [q, v, p], [p, v, t], [p, q, v], [t, p, v], [v, p, q] ][hi]; return { r: c[0] * 255, g: c[1] * 255, b: c[2] * 255 }; }, rgb_to_hsv: function(r, g, b) { var min = Math.min(r, g, b), max = Math.max(r, g, b), delta = max - min, h, s; if (max != 0) { s = delta / max; } else { return { h: NaN, s: 0, v: 0 }; } if (r == max) { h = (g - b) / delta; } else if (g == max) { h = 2 + (b - r) / delta; } else { h = 4 + (r - g) / delta; } h /= 6; if (h < 0) { h += 1; } return { h: h * 360, s: s, v: max / 255 }; }, rgb_to_hex: function(r, g, b) { var hex = this.hex_with_component(0, 2, r); hex = this.hex_with_component(hex, 1, g); hex = this.hex_with_component(hex, 0, b); return hex; }, component_from_hex: function(hex, componentIndex) { return (hex >> (componentIndex * 8)) & 0xFF; }, hex_with_component: function(hex, componentIndex, value) { return value << (tmpComponent = componentIndex * 8) | (hex & ~ (0xFF << tmpComponent)); } } })(), dat.color.toString, dat.utils.common), dat.color.interpret, dat.utils.common), dat.utils.requestAnimationFrame = (function () { /** * requirejs version of Paul Irish's RequestAnimationFrame * http://paulirish.com/2011/requestanimationframe-for-smart-animating/ */ return window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(callback, element) { window.setTimeout(callback, 1000 / 60); }; })(), dat.dom.CenteredDiv = (function (dom, common) { var CenteredDiv = function() { this.backgroundElement = document.createElement('div'); common.extend(this.backgroundElement.style, { backgroundColor: 'rgba(0,0,0,0.8)', top: 0, left: 0, display: 'none', zIndex: '1000', opacity: 0, WebkitTransition: 'opacity 0.2s linear', transition: 'opacity 0.2s linear' }); dom.makeFullscreen(this.backgroundElement); this.backgroundElement.style.position = 'fixed'; this.domElement = document.createElement('div'); common.extend(this.domElement.style, { position: 'fixed', display: 'none', zIndex: '1001', opacity: 0, WebkitTransition: '-webkit-transform 0.2s ease-out, opacity 0.2s linear', transition: 'transform 0.2s ease-out, opacity 0.2s linear' }); document.body.appendChild(this.backgroundElement); document.body.appendChild(this.domElement); var _this = this; dom.bind(this.backgroundElement, 'click', function() { _this.hide(); }); }; CenteredDiv.prototype.show = function() { var _this = this; this.backgroundElement.style.display = 'block'; this.domElement.style.display = 'block'; this.domElement.style.opacity = 0; // this.domElement.style.top = '52%'; this.domElement.style.webkitTransform = 'scale(1.1)'; this.layout(); common.defer(function() { _this.backgroundElement.style.opacity = 1; _this.domElement.style.opacity = 1; _this.domElement.style.webkitTransform = 'scale(1)'; }); }; CenteredDiv.prototype.hide = function() { var _this = this; var hide = function() { _this.domElement.style.display = 'none'; _this.backgroundElement.style.display = 'none'; dom.unbind(_this.domElement, 'webkitTransitionEnd', hide); dom.unbind(_this.domElement, 'transitionend', hide); dom.unbind(_this.domElement, 'oTransitionEnd', hide); }; dom.bind(this.domElement, 'webkitTransitionEnd', hide); dom.bind(this.domElement, 'transitionend', hide); dom.bind(this.domElement, 'oTransitionEnd', hide); this.backgroundElement.style.opacity = 0; // this.domElement.style.top = '48%'; this.domElement.style.opacity = 0; this.domElement.style.webkitTransform = 'scale(1.1)'; }; CenteredDiv.prototype.layout = function() { this.domElement.style.left = window.innerWidth/2 - dom.getWidth(this.domElement) / 2 + 'px'; this.domElement.style.top = window.innerHeight/2 - dom.getHeight(this.domElement) / 2 + 'px'; }; function lockScroll(e) { console.log(e); } return CenteredDiv; })(dat.dom.dom, dat.utils.common), dat.dom.dom, dat.utils.common);
/*! wow.export (https://github.com/Kruithne/wow.export) Authors: Kruithne <kruithne@gmail.com> License: MIT */ const Texture = require('../Texture'); const Skin = require('../Skin'); const MAGIC_MD21 = 0x3132444D; const MAGIC_MD20 = 0x3032444D; const CHUNK_SFID = 0x44494653; const CHUNK_TXID = 0x44495854; class M2Track { /** * Construct a new M2Track instance. * @param {number} globalSeq * @param {number} interpolation * @param {Array} timestamps * @param {Array} values */ constructor(globalSeq, interpolation, timestamps, values) { this.globalSeq = globalSeq; this.interpolation = interpolation; this.timestamps = timestamps; this.values = values; } } class M2Loader { /** * Construct a new M2Loader instance. * @param {BufferWrapper} data */ constructor(data) { this.data = data; this.isLoaded = false; } /** * Load the M2 model. */ async load() { // Prevent multiple loading of the same M2. if (this.isLoaded === true) return; while (this.data.remainingBytes > 0) { const chunkID = this.data.readUInt32LE(); const chunkSize = this.data.readUInt32LE(); const nextChunkPos = this.data.offset + chunkSize; switch (chunkID) { case MAGIC_MD21: await this.parseChunk_MD21(); break; case CHUNK_SFID: this.parseChunk_SFID(); break; case CHUNK_TXID: this.parseChunk_TXID(); break; } // Ensure that we start at the next chunk exactly. this.data.seek(nextChunkPos); } this.isLoaded = true; } /** * Get a skin at a given index from this.skins. * @param {number} index */ async getSkin(index) { const skin = this.skins[index]; if (!skin.isLoaded) await skin.load(); return skin; } /** * Returns the internal array of Skin objects. * Note: Unlike getSkin(), this does not load any of the skins. * @returns {Skin[]} */ getSkinList() { return this.skins; } /** * Parse SFID chunk for skin file data IDs. */ parseChunk_SFID() { if (this.viewCount === undefined) throw new Error('Cannot parse SFID chunk in M2 before MD21 chunk!'); this.skins = new Array(this.viewCount); for (let i = 0; i < this.viewCount; i++) this.skins[i] = new Skin(this.data.readUInt32LE()); } /** * Parse TXID chunk for texture file data IDs. */ parseChunk_TXID() { if (this.textures === undefined) throw new Error('Cannot parse TXID chunk in M2 before MD21 chunk!'); for (let i = 0, n = this.textures.length; i < n; i++) this.textures[i].fileDataID = this.data.readUInt32LE(); } /** * Parse MD21 chunk. */ async parseChunk_MD21() { const ofs = this.data.offset; const magic = this.data.readUInt32LE(); if (magic !== MAGIC_MD20) throw new Error('Invalid M2 magic: ' + magic); this.version = this.data.readUInt32LE(); this.parseChunk_MD21_modelName(ofs); this.data.move(4 + 8 + 8 + 8); // flags, loops, seq this.parseChunk_MD21_bones(ofs); this.data.move(8); this.parseChunk_MD21_vertices(ofs); this.viewCount = this.data.readUInt32LE(); this.data.move(8); // coloursCount, coloursOfs this.parseChunk_MD21_textures(ofs); this.data.move(4 * 4); // texture_weights, texture_transforms this.parseChunk_MD21_replaceableTextureLookup(ofs); this.parseChunk_MD21_materials(ofs); this.data.move(2 * 4); // boneCombos this.parseChunk_MD21_textureCombos(ofs); this.data.move(6 * 4); // textureTransformBoneMap, textureWeightCombos, textureTransformCombos this.data.move((4 + (4 * 6)) * 2); // boundingBox, boundingRadius, collisionBox, collisionRadius this.parseChunk_MD21_collision(ofs); } /** * Read an M2Array. * @param {function} read * @returns {Array} */ readM2Array(read) { const data = this.data; const arrCount = data.readUInt32LE(); const arrOfs = data.readUInt32LE(); const base = data.offset; data.seek(this.md21Ofs + arrOfs); const arr = Array(arrCount); for (let i = 0; i < arrCount; i++) arr[i] = read(); data.seek(base); return arr; } /** * Read an M2 track. * @param {function} read * @returns {M2Track} */ readM2Track(read) { const data = this.data; const interpolation = data.readUInt16LE(); const globalSeq = data.readUInt16LE(); const timestamps = this.readM2Array(() => this.readM2Array(() => data.readUInt32LE())); const values = this.readM2Array(() => this.readM2Array(read)); return new M2Track(globalSeq, interpolation, timestamps, values); } parseChunk_MD21_bones(ofs) { const data = this.data; const boneCount = data.readUInt32LE(); const boneOfs = data.readUInt32LE(); const base = data.offset; data.seek(boneOfs + ofs); this.md21Ofs = ofs; const bones = this.bones = Array(boneCount); for (let i = 0; i < boneCount; i++) { bones[i] = { boneID: data.readInt32LE(), flags: data.readUInt32LE(), parentBone: data.readInt16LE(), subMeshID: data.readUInt16LE(), boneNameCRC: data.readUInt32LE(), translation: this.readM2Track(() => data.readFloatLE(3)), rotation: this.readM2Track(() => data.readUInt16LE(4).map(e => (e / 65565) - 1)), scale: this.readM2Track(() => data.readFloatLE(3)), pivot: data.readFloatLE(3) }; } data.seek(base); } /** * Parse collision data from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_collision(ofs) { const indicesCount = this.data.readUInt32LE(); const indicesOfs = this.data.readUInt32LE(); const positionsCount = this.data.readUInt32LE(); const positionsOfs = this.data.readUInt32LE(); const normalsCount = this.data.readUInt32LE(); const normalsOfs = this.data.readUInt32LE(); const base = this.data.offset; // indices this.data.seek(indicesOfs + ofs); this.collisionIndices = this.data.readUInt16LE(indicesCount); // Positions this.data.seek(positionsOfs + ofs); const positions = this.collisionPositions = new Array(positionsCount * 3); for (let i = 0; i < positionsCount; i++) { const index = i * 3; positions[index] = this.data.readFloatLE(); positions[index + 2] = this.data.readFloatLE() * -1; positions[index + 1] = this.data.readFloatLE(); } // Normals this.data.seek(normalsOfs + ofs); const normals = this.collisionNormals = new Array(normalsCount * 3); for (let i = 0; i < normalsCount; i++) { const index = i * 3; normals[index] = this.data.readFloatLE(); normals[index + 2] = this.data.readFloatLE() * -1; normals[index + 1] = this.data.readFloatLE(); } this.data.seek(base); } /** * Parse replaceable texture lookups from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_replaceableTextureLookup(ofs) { const lookupCount = this.data.readUInt32LE(); const lookupOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(lookupOfs + ofs); this.replaceableTextureLookup = this.data.readInt16LE(lookupCount); this.data.seek(base); } /** * Parse material meta-data from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_materials(ofs) { const materialCount = this.data.readUInt32LE(); const materialOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(materialOfs + ofs); this.materials = new Array(materialCount); for (let i = 0; i < materialCount; i++) this.materials[i] = { flags: this.data.readUInt16LE(), blendingMode: this.data.readUInt16LE() }; this.data.seek(base); } /** * Parse the model name from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_modelName(ofs) { const modelNameLength = this.data.readUInt32LE(); const modelNameOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(modelNameOfs + ofs); // Always followed by single 0x0 character, -1 to trim). this.data.seek(modelNameOfs + ofs); this.name = this.data.readString(modelNameLength - 1); this.data.seek(base); } /** * Parse vertices from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_vertices(ofs) { const verticesCount = this.data.readUInt32LE(); const verticesOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(verticesOfs + ofs); // Read vertices. const vertices = this.vertices = new Array(verticesCount * 3); const normals = this.normals = new Array(verticesCount * 3); const uv = this.uv = new Array(verticesCount * 2); const boneWeights = this.boneWeights = Array(verticesCount * 4); const boneIndices = this.boneIndices = Array(verticesCount * 4); for (let i = 0; i < verticesCount; i++) { const index = i * 3; vertices[index] = this.data.readFloatLE(); vertices[index + 2] = this.data.readFloatLE() * -1; vertices[index + 1] = this.data.readFloatLE(); for (let x = 0; x < 4; x++) boneWeights[index + x] = this.data.readUInt8(); for (let x = 0; x < 4; x++) boneIndices[index + x] = this.data.readUInt8(); normals[index] = this.data.readFloatLE(); normals[index + 2] = this.data.readFloatLE() * -1; normals[index + 1] = this.data.readFloatLE(); const uvIndex = i * 2; uv[uvIndex] = this.data.readFloatLE(); uv[uvIndex + 1] = (this.data.readFloatLE() - 1) * -1; this.data.move(8); // texCoordX2, texCoordY2? } this.data.seek(base); } /** * Parse textures from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_textures(ofs) { const texturesCount = this.data.readUInt32LE(); const texturesOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(texturesOfs + ofs); // Read textures. const textures = this.textures = new Array(texturesCount); for (let i = 0; i < texturesCount; i++) { const textureType = this.data.readUInt32LE(); const texture = new Texture(this.data.readUInt32LE()); // Check if texture has a filename (legacy). if (textureType === 0) { const nameLength = this.data.readUInt32LE(); const nameOfs = this.data.readUInt32LE(); if (nameOfs >= 10) { const pos = this.data.offset; this.data.seek(nameOfs); const fileName = this.data.readString(nameLength); fileName.replace('\0', ''); // Remove NULL characters. if (fileName.length > 0) texture.setFileName(fileName); this.data.seek(pos); } } textures[i] = texture; } this.data.seek(base); } /** * Parse texture combos from an MD21 chunk. * @param {number} ofs */ parseChunk_MD21_textureCombos(ofs) { const textureComboCount = this.data.readUInt32LE(); const textureComboOfs = this.data.readUInt32LE(); const base = this.data.offset; this.data.seek(textureComboOfs + ofs); this.textureCombos = this.data.readUInt16LE(textureComboCount); this.data.seek(base); } } module.exports = M2Loader;
"use strict"; module.exports = { isNotUndefined: function (a) { return typeof a !== "undefined"; }, randomString: function (len, charSet) { charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var randomString = ''; for (var i = 0; i < len; i++) { var randomPoz = Math.floor(Math.random() * charSet.length); randomString += charSet.substring(randomPoz, randomPoz + 1); } return randomString; } };
var TaskService = (function () { function TaskService() { ; } TaskService.getInstance = function () { if (TaskService.taskService != null) { return TaskService.taskService; } else { TaskService.taskService = new TaskService(); TaskService.taskService.observerList = new Array(); TaskService.taskService.taskList = new Array(); return TaskService.taskService; } ; }; TaskService.prototype.finish = function (id) { console.log("finish" + id); for (var i = 0; i < this.taskList.length; i++) { if (this.taskList[i].getID().match(id)) { this.taskList[i].setStatus(Task.CAN_SUBMIT); this.notify(this.taskList[i]); break; } } }; TaskService.prototype.over = function (id) { var next = "null"; for (var i = 0; i < this.taskList.length; i++) { if (this.taskList[i].getID().match(id)) { this.taskList[i].setStatus(Task.SUBMITTED); next = this.taskList[i].getNextTask(); this.notify(this.taskList[i]); break; } } for (var i = 0; i < this.taskList.length; i++) { if (this.taskList[i].getID().match(next) && this.taskList[i].getStatus() == Task.UNACCEPTALBE) { this.taskList[i].setStatus(Task.ACCEPTABLE); this.notify(this.taskList[i]); } } }; TaskService.prototype.accept = function (id) { for (var i = 0; i < this.taskList.length; i++) { if (this.taskList[i].getID().match(id)) { this.taskList[i].setStatus(Task.DURING); this.notify(this.taskList[i]); break; } } }; TaskService.prototype.getTaskByCustomRole = function (rule) { return rule(this.taskList); }; TaskService.prototype.notify = function (task) { for (var i = 0; i < this.observerList.length; i++) { this.observerList[i].onChange(task); } }; TaskService.prototype.addObserver = function (x) { this.observerList.push(x); }; TaskService.prototype.addTask = function (x) { this.taskList.push(x); this.notify(x); }; return TaskService; }());
const _ = require('lodash'), mergeAllOf = require('json-schema-merge-allof'), { typesMap } = require('./common/schemaUtilsCommon'), PARAMETER_SOURCE = { REQUEST: 'REQUEST', RESPONSE: 'RESPONSE' }, SCHEMA_TYPES = { array: 'array', boolean: 'boolean', integer: 'integer', number: 'number', object: 'object', string: 'string' }, // All formats supported by both ajv and json-schema-faker SUPPORTED_FORMATS = [ 'date', 'time', 'date-time', 'uri', 'uri-reference', 'uri-template', 'email', 'hostname', 'ipv4', 'ipv6', 'regex', 'uuid', 'json-pointer', 'int64', 'float', 'double' ], DEFAULT_SCHEMA_UTILS = require('./30XUtils/schemaUtils30X'); module.exports = { /** * @param {*} rootObject - the object from which you're trying to read a property * @param {*} pathArray - each element in this array a property of the previous object * @param {*} defValue - what to return if the required path is not found * @returns {*} - required property value * @description - this is similar to _.get(rootObject, pathArray.join('.')), but also works for cases where * there's a . in the property name */ _getEscaped: function (rootObject, pathArray, defValue) { if (!(pathArray instanceof Array)) { return null; } if (!rootObject) { return defValue; } if (_.isEmpty(pathArray)) { return rootObject; } return this._getEscaped(rootObject[pathArray.shift()], pathArray, defValue); }, /** * Creates a schema that's a union of all input schemas (only type: object is supported) * * @param {array} schemaArr - array of schemas, all of which must be valid in the returned object * @param {string} parameterSourceOption tells that the schema object is of request or response * @param {*} components components in openapi spec. * @param {object} schemaResolutionCache stores already resolved references * @param {*} resolveFor - resolve refs for validation/conversion (value to be one of VALIDATION/CONVERSION) * @param {string} resolveTo The desired JSON-generation mechanism (schema: prefer using the JSONschema to generate a fake object, example: use specified examples as-is). Default: schema * @param {*} stack counter which keeps a tab on nested schemas * @param {*} seenRef References that are repeated. Used to identify circular references. * @param {*} stackLimit Depth to which the schema should be resolved. * @returns {*} schema - schema that adheres to all individual schemas in schemaArr */ resolveAllOf: function (schemaArr, parameterSourceOption, components, schemaResolutionCache, resolveFor = 'CONVERSION', resolveTo = 'schema', stack = 0, seenRef, stackLimit) { if (!(schemaArr instanceof Array)) { return null; } if (schemaArr.length === 1) { // for just one entry in allOf, don't need to enforce type: object restriction return this.resolveRefs(schemaArr[0], parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, seenRef, stackLimit); } try { return mergeAllOf({ allOf: schemaArr.map((schema) => { return this.resolveRefs(schema, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, seenRef, stackLimit); }) }, { resolvers: { // for keywords in OpenAPI schema that are not standard defined JSON schema keywords, use default resolver defaultResolver: (compacted) => { return compacted[0]; } } }); } catch (e) { console.warn('Error while resolving allOf schema: ', e); return { value: '<Error: Could not resolve allOf schema' }; } }, /** * Resolves references to components for a given schema. * @param {*} schema (openapi) to resolve references. * @param {string} parameterSourceOption tells that the schema object is of request or response * @param {*} components components in openapi spec. * @param {object} schemaResolutionCache stores already resolved references - more structure detail below * {'schema reference key': { * maxStack {Integer} : Defined as how deep of nesting level we reached while resolving schema that's being cached * resLevel {Integer} : Defined as nesting level at which schema that's being cached was resolved * schema {Object} : resolved schema that will be cached * }} * @param {*} resolveFor - resolve refs for validation/conversion (value to be one of VALIDATION/CONVERSION) * @param {string} resolveTo The desired JSON-generation mechanism (schema: prefer using the JSONschema to generate a fake object, example: use specified examples as-is). Default: schema * @param {*} stack counter which keeps a tab on nested schemas * @param {*} seenRef - References that are repeated. Used to identify circular references. * @param {*} stackLimit Depth to which the schema should be resolved. * @returns {*} schema satisfying JSON-schema-faker. */ resolveRefs: function (schema, parameterSourceOption, components, schemaResolutionCache, resolveFor = 'CONVERSION', resolveTo = 'schema', stack = 0, seenRef = {}, stackLimit = 10) { var resolvedSchema, prop, splitRef, ERR_TOO_MANY_LEVELS = '<Error: Too many levels of nesting to fake this schema>'; let concreteUtils = components && components.hasOwnProperty('concreteUtils') ? components.concreteUtils : DEFAULT_SCHEMA_UTILS; stack++; schemaResolutionCache = schemaResolutionCache || {}; if (stack > stackLimit) { return { value: ERR_TOO_MANY_LEVELS }; } if (!schema) { return { value: '<Error: Schema not found>' }; } if (schema.anyOf) { if (resolveFor === 'CONVERSION') { return this.resolveRefs(schema.anyOf[0], parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); } return { anyOf: _.map(schema.anyOf, (schemaElement) => { return this.resolveRefs(schemaElement, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); }) }; } if (schema.oneOf) { if (resolveFor === 'CONVERSION') { return this.resolveRefs(schema.oneOf[0], parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); } return { oneOf: _.map(schema.oneOf, (schemaElement) => { return this.resolveRefs(schemaElement, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); }) }; } if (schema.allOf) { return this.resolveAllOf(schema.allOf, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); } if (schema.$ref && _.isFunction(schema.$ref.split)) { let refKey = schema.$ref, outerProperties = concreteUtils.getOuterPropsIfIsSupported(schema); // if this reference is seen before, ignore and move on. if (seenRef[refKey]) { return { value: '<Circular reference to ' + refKey + ' detected>' }; } // add to seen array if not encountered before. seenRef[refKey] = stack; // points to an existing location // .split will return [#, components, schemas, schemaName] splitRef = refKey.split('/'); if (splitRef.length < 4) { // not throwing an error. We didn't find the reference - generate a dummy value return { value: 'reference ' + schema.$ref + ' not found in the OpenAPI spec' }; } // something like #/components/schemas/PaginationEnvelope/properties/page // will be resolved - we don't care about anything after the components part // splitRef.slice(1) will return ['components', 'schemas', 'PaginationEnvelope', 'properties', 'page'] // not using _.get here because that fails if there's a . in the property name (Pagination.Envelope, for example) splitRef = splitRef.slice(1).map((elem) => { // https://swagger.io/docs/specification/using-ref#escape // since / is the default delimiter, slashes are escaped with ~1 return decodeURIComponent( elem .replace(/~1/g, '/') .replace(/~0/g, '~') ); }); resolvedSchema = this._getEscaped(components, splitRef); if (outerProperties) { resolvedSchema = concreteUtils.addOuterPropsToRefSchemaIfIsSupported(resolvedSchema, outerProperties); } if (resolvedSchema) { let refResolvedSchema = this.resolveRefs(resolvedSchema, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); return refResolvedSchema; } return { value: 'reference ' + schema.$ref + ' not found in the OpenAPI spec' }; } if (concreteUtils.compareTypes(schema.type, SCHEMA_TYPES.object) || schema.hasOwnProperty('properties') || schema.hasOwnProperty('additionalProperties')) { // go through all props schema.type = SCHEMA_TYPES.object; if (_.has(schema, 'properties') || _.has(schema, 'additionalProperties')) { // shallow cloning schema object except properties object let tempSchema = _.omit(schema, ['properties', 'additionalProperties']); if (_.has(schema, 'additionalProperties')) { // don't resolve boolean values if (_.isBoolean(schema.additionalProperties)) { tempSchema.additionalProperties = schema.additionalProperties; } else { tempSchema.additionalProperties = this.resolveRefs(schema.additionalProperties, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); } } !_.isEmpty(schema.properties) && (tempSchema.properties = {}); for (prop in schema.properties) { if (schema.properties.hasOwnProperty(prop)) { /* eslint-disable max-depth */ // handling OAS readOnly and writeOnly properties in schema // Related Doc - https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#schemaObject let property = schema.properties[prop]; if (!property) { continue; } if (property.readOnly && parameterSourceOption === PARAMETER_SOURCE.REQUEST) { // remove property from required as it'll not be present in resolved schema if (_.includes(tempSchema.required, prop)) { _.remove(tempSchema.required, _.matches(prop)); } continue; } else if (property.writeOnly && parameterSourceOption === PARAMETER_SOURCE.RESPONSE) { // remove property from required as it'll not be present in resolved schema if (_.includes(tempSchema.required, prop)) { _.remove(tempSchema.required, _.matches(prop)); } continue; } /* eslint-enable */ tempSchema.properties[prop] = this.resolveRefs(property, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); } } return tempSchema; } // Override deefault value to appropriate type representation for parameter resolution to schema if (resolveFor === 'CONVERSION' && resolveTo === 'schema') { schema.default = typesMap.object; } } else if (concreteUtils.compareTypes(schema.type, SCHEMA_TYPES.array) && schema.items) { /* For VALIDATION - keep minItems and maxItems properties defined by user in schema as is FOR CONVERSION - Json schema faker fakes exactly maxItems # of elements in array Hence keeping maxItems as minimum and valid as possible for schema faking (to lessen faked items) We have enforced limit to maxItems as 100, set by Json schema faker option */ if (resolveFor === 'CONVERSION') { // Override minItems to default (2) if no minItems present if (!_.has(schema, 'minItems') && _.has(schema, 'maxItems') && schema.maxItems >= 2) { schema.minItems = 2; } // Override maxItems to minItems if minItems is available if (_.has(schema, 'minItems') && schema.minItems > 0) { schema.maxItems = schema.minItems; } // If no maxItems is defined than override with default (2) !_.has(schema, 'maxItems') && (schema.maxItems = 2); } // have to create a shallow clone of schema object, // so that the original schema.items object will not change // without this, schemas with circular references aren't faked correctly let tempSchema = _.omit(schema, 'items'); tempSchema.items = this.resolveRefs(schema.items, parameterSourceOption, components, schemaResolutionCache, resolveFor, resolveTo, stack, _.cloneDeep(seenRef), stackLimit); return tempSchema; } else if (!schema.hasOwnProperty('default')) { if (schema.hasOwnProperty('type')) { // Override default value to schema for CONVERSION only for parmeter resolution set to schema if (resolveFor === 'CONVERSION' && resolveTo === 'schema') { if (!schema.hasOwnProperty('format')) { schema.default = '<' + schema.type + '>'; } else if (typesMap.hasOwnProperty(schema.type)) { schema.default = typesMap[schema.type][schema.format]; // in case the format is a custom format (email, hostname etc.) // https://swagger.io/docs/specification/data-models/data-types/#string if (!schema.default && schema.format) { schema.default = '<' + schema.format + '>'; } } else { schema.default = '<' + schema.type + (schema.format ? ('-' + schema.format) : '') + '>'; } } } else if (schema.enum && schema.enum.length > 0) { return { type: (typeof (schema.enum[0])), value: schema.enum[0] }; } else { return { type: SCHEMA_TYPES.object }; } if (!schema.type) { schema.type = SCHEMA_TYPES.string; } // Discard format if not supported by both json-schema-faker and ajv or pattern is also defined if (!_.includes(SUPPORTED_FORMATS, schema.format) || (schema.pattern && schema.format)) { return _.omit(schema, 'format'); } } return schema; } };
import React from "react"; import Navbar from "../Components/Basic-Component/Navbar"; import Mens_product from "../Components/Basic-Component/Mens_product"; import Footer from "../Components/Basic-Component/Footer"; const Men = () => { return ( <> <Navbar /> <Mens_product /> <Footer /> </> ); }; export default Men;
// 我先来,模拟图片加载过程 run in browser console function loadImg(url) { return new Promise((resolve, reject) => { const img = new Image(100, 200); img.onload = function () { console.log(url, '加载完成'); resolve(img); }; img.onerror = function () { reject(new Error('Error at:' + url)); }; img.src = url; }); } function multiRequest(urls, maxNum) { const firstMaxNum = urls.splice(0, maxNum); let promises = firstMaxNum.map((url, index) => { return loadImg(url).then(() => { return index; }); }); return urls .reduce((res, cur) => { return res .then(() => { return Promise.race(promises); }) .then(idx => { promises[idx] = loadImg(cur).then(() => { return idx; }); }); }, Promise.resolve()) .then(() => { return Promise.all(promises); }); } const urls = [ 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0515%2Fb678fb7bp00qt4hsk00wod200m80158g00it00yv.png&thumbnail=650x2147483647&quality=80&type=jpg', 'https://yt-adp.ws.126.net/channel4/300250_aetc_20210326.jpg', 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0515%2Fa9723a8dj00qt4hsl0047d200u000u0g00g200g2.jpg&thumbnail=650x2147483647&quality=80&type=jpg', 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0515%2F3e7c1420j00qt4hsm000pd200m800hgg00it00er.jpg&thumbnail=650x2147483647&quality=80&type=jpg', 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2021%2F0515%2Feba0cc15p00qt4hsm005yd200u000apg00it006p.png&thumbnail=650x2147483647&quality=80&type=jpg', ]; multiRequest(urls, 4).then(() => { console.log('finish'); });
import React from 'react'; import createReactClass from 'create-react-class'; import Fluxxor from 'fluxxor'; import Multiselect from 'react-widgets/lib/Multiselect'; const FluxMixin = Fluxxor.FluxMixin(React), StoreWatchMixin = Fluxxor.StoreWatchMixin("DataStore"); export const TermFilter = createReactClass({ mixins: [FluxMixin, StoreWatchMixin], getInitialState(){ return {}; }, onFilterChange(filters){ this.getFlux().actions.DASHBOARD.changeTermsFilter(filters); }, getStateFromFlux() { return this.getFlux().store("DataStore").getState(); }, FilterEnabledTerms(){ let filteredTerms = []; for (var [term, value] of this.state.associatedKeywords.entries()) { if(value.enabled){ filteredTerms.push(term); } } return filteredTerms; }, render(){ return ( <div> { this.props.data && this.props.data.length > 0 ? <Multiselect {...this.props} value={this.FilterEnabledTerms()} onChange={this.onFilterChange}/> : undefined } </div> ); } });
import { publishPagination } from 'meteor/kurounin:pagination'; publishPagination(MyCollection, { filters: {is_enabled: true}, transform_options: function (filters, options) { options.fields = _.extend(options.fields, {score: { $meta: "textScore" }}); return options; } });
const { Client, Intents, MessageEmbed } = require('discord.js'); const { name, homepage } = require('../../package.json') const voiceDiscord = require(`@discordjs/voice`) const client = new Client({ intents: [ Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_VOICE_STATES, ] }); module.exports = { ARAB: function ({ channelID, guildID, logID, TOKEN, Presence: { status, type, name } }) { client.login(TOKEN) client.on("ready", () => { console.log(`Logged in as ${client.user.tag}`); client.user.setPresence({ status: status || 'dnd', activities: [{ type: type || 'LISTENING', name: name || 'ARAB STATION', }] }); let SERVER = client.guilds.cache.get(guildID) const connection = voiceDiscord.joinVoiceChannel({ channelId: channelID, guildId: guildID, adapterCreator: SERVER.voiceAdapterCreator, selfDeaf: true, }); const player = voiceDiscord.createAudioPlayer(); const resource = voiceDiscord.createAudioResource('http://stream.laut.fm/balkan-orient-deluxe'); player.play(resource); connection.subscribe(player); player.on(voiceDiscord.AudioPlayerStatus.Idle, () => { const EMBED = new MessageEmbed() .setTitle('There is currently no resource for the player to be playing (Trying to replay the resource)') .setThumbnail(client.user.displayAvatarURL({ format: 'png', size: 2048 })) .setDescription(`Powered By : [${name}](${homepage})`) .setTimestamp() player.play(resource); connection.subscribe(player); client.channels.cache.get(logID).send({ embeds: [EMBED] }); }); }) } }
export const FETCHED_EVENTS = 'FETCHED_EVENTS'; export const SELECTED_CURRENT_EVENT = 'SELECTED_CURRENT_EVENT'; export const ADD_EVENT_TO_LIST = 'ADD_EVENT_TO_LIST';
import React from 'react' export default () => <marquee>Hello world!!</marquee>
function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /* THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. */ import * as React from 'react'; var SvgConferenceOnboard = React.forwardRef(function (props, svgRef) { return React.createElement("svg", _extends({ width: "1em", height: "1em", viewBox: "0 0 32 32", ref: svgRef }, props), React.createElement("path", { fill: "inherit", d: "M17.01 13.776l.2 3.147a.45.45 0 0 1-.25.4l-.45.2h-.05l-.6 4.296c-.05.1-.1.15-.2.15h-.205l-.137.001c-.03 0-.064-.006-.079-.018s-.031-.033-.048-.063l-.126-.223-.126.223c-.017.03-.033.051-.048.063s-.038.018-.068.018l-.192-.001h-.168c-.1 0-.2-.05-.2-.15l-.599-4.296-.496-2.963-2.39-.685c-.38-.099-.599-.256-.605-.583l-.003-.078a.595.595 0 0 1 .583-.605l4.909-.08a1.349 1.349 0 0 1 1.349 1.249zm-2.048-1.748a1.3 1.3 0 1 1 .001-2.6 1.3 1.3 0 0 1-.001 2.6zm-2.058-.322l-.81.015v-1.052H.809v6.806h11.285v-2.347l.81.232v2.925H6.947l2.626 3.643h-.998l-1.717-2.382v2.382h-.81V19.47L4.16 21.928H3.139l2.799-3.643H.001V9.86h6.022V9h.86v.86h6.022v1.846z" }), React.createElement("path", { fill: "currentColor", d: "M19.749 15.18c0-.222.182-.404.404-.404h.435c.222 0 .404.182.404.404v.809a.405.405 0 0 1-.404.404h-.435a.405.405 0 0 1-.404-.404v-.809zm3.169 0v.809c0 .222.182.404.404.404h.435a.405.405 0 0 0 .404-.404v-.809a.405.405 0 0 0-.404-.404h-.435a.405.405 0 0 0-.404.404zm-5.74 2.719l14.692-.013-2.008 3.514h-.301c-3.092 0-4.159 1.212-7.292 1.212-2.001 0-3.73-.953-5.572-1.273l.48-3.441zm.596-4.158a1.812 1.812 0 0 0-.945-1.454l1.609-2.872h1.995l1.137 4.358h6.069l.594 1.003h-2.618s-.211.008-.211.17.014.303.04.477c.026.174.111.356.441.435.281.067 2.701.574 3.417.723l.325.548H17.949a.866.866 0 0 0 .026-.205v-.016l-.201-3.163v-.005z" })); }); export default SvgConferenceOnboard;
class Movie { constructor(movieName, ticketPrice) { this.movieName = movieName; this.ticketPrice = Number(ticketPrice); this.screenings = []; this._soldTickets = 0; this._totalPriceTickets = 0; } newScreening(date, hall, description) { if (this.screenings.some(x => x.date == date && x.hall === hall)) { throw Error(`Sorry, ${hall} hall is not available on ${date}`); }; let screening = { date, hall, description }; this.screenings.push(screening); return `New screening of ${this.movieName} is added.`; } endScreening(date, hall, soldTickets) { let index = -1; for (let i = 0; i < this.screenings.length; i++) { if (this.screenings[i].date == date && this.screenings[i].hall == hall) { index = i; } } if (index == -1) { throw Error(`Sorry, there is no such screening for ${this.movieName} movie.`); } this._soldTickets += soldTickets; let screeningProfit = soldTickets * this.ticketPrice; this._totalPriceTickets += screeningProfit; this.screenings.splice(index, 1); return `${this.movieName} movie screening on ${date} in ${hall} hall has ended. Screening profit: ${screeningProfit}`; } toString() { let result = []; result.push(`${this.movieName} full information:`); result.push(`Total profit: ${this._totalPriceTickets.toFixed(0)}$`); result.push(`Sold Tickets: ${this._soldTickets}`); if (this.screenings.length == 0) { result.push(`No more screenings!`); } else { result.push(`Remaining film screenings:`); this.screenings.sort((a, b) => a.hall.localeCompare(b.hall)); this.screenings.forEach(x => result.push(`${x.hall} - ${x.date} - ${x.description}`)); } return result.join('\n'); } } let m = new Movie('Wonder Woman 1984', '10.00'); console.log(m.newScreening('October 2, 2020', 'IMAX 3D', `3D`)); console.log(m.newScreening('October 3, 2020', 'Main', `regular`)); //console.log(m.newScreening('October 4, 2020', 'IMAX 3D', `3D`)); console.log(m.endScreening('October 2, 2020', 'IMAX 3D', 150)); console.log(m.endScreening('October 3, 2020', 'Main', 78)); console.log(m.toString());
import React from 'react'; import iconSvg from '../icons/normalized/comment-outline.svg'; function IconRender(props) { const paths = /^\<svg [^>]+\>(.*)<\/svg>/ig.exec(iconSvg)[1] return ( <svg {...props} xmlns="http://www.w3.org/2000/svg" baseProfile="full" viewBox="0 0 24 24" className={`react-pretty-icons react-pretty-icons__comment-outline ${props.className}`} dangerouslySetInnerHTML={{__html: paths}} /> ) } export default IconRender
/** * @mixin * Binds a timeout, causing the message * to be removed after a given duration * * @see MessageMixin */ var MessageTimeoutMixin = { /** * Automatically (and `Conditionally`) starts the timer * @see this._start */ componentDidMount: function() { var duration = this.props.attributes.duration; // This is a feature: // Only start the auto timer if the duration was provided or if the // supplied duration was not null. This allows conditional timers // for messages applying this mixin ;) if ( duration == null || duration == undefined ) this._start(); }, /** * Removes timeout binding during the phase * @see this._stop */ componentWillUnmount: function() { this._stop(); }, /** * Starts the timer * @see this._removeHandler */ _start: function() { var duration = this.props.attributes.duration; this.$timer = setTimeout(this._removeHandler, duration); }, /** * Clears the timer only if the binding exists * (to avoid errors). */ _stop: function() { if ( this.$timer ) clearTimeout(this.$timer); } }; module.exports = MessageTimeoutMixin;
/* YUI 3.6.0 (build 5521) Copyright 2012 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add("yui-throttle",function(a){ /*! Based on work by Simon Willison: http://gist.github.com/292562 */ a.throttle=function(c,b){b=(b)?b:(a.config.throttleTime||150);if(b===-1){return(function(){c.apply(null,arguments);});}var d=a.Lang.now();return(function(){var e=a.Lang.now();if(e-d>b){d=e;c.apply(null,arguments);}});};},"3.6.0",{requires:["yui-base"]});
import React from 'react' const ColumnSummary = React.lazy(() => import('./columnSummary')) const Column = React.lazy(() => import('./column')) const Career = React.lazy(() => import('./career')) const Recruitment = React.lazy(() => import('./recruitment')) const AddRecruitment = React.lazy(() => import('./recruitment/add')) const EditRecruitment = React.lazy(() => import('./recruitment/edit')) const OwnRecruitment = React.lazy(() => import('./recruitment/own')) const Recommendation = React.lazy(() => import('./recommendation')) const AddRecommendation = React.lazy(() => import('./recommendation/add')) const EditRecommendation = React.lazy(() => import('./recommendation/edit')) const OwnRecommendation = React.lazy(() => import('./recommendation/own')) const Profile = React.lazy(() => import('./profile')) const EditProfile = React.lazy(() => import('./profile/edit')) const SearchProfile = React.lazy(() => import('./profile/search')) const Study = React.lazy(() => import('./study')) const Matching = React.lazy(() => import('./matching')) export { ColumnSummary, Column, Career, Recruitment, AddRecruitment, EditRecruitment, OwnRecruitment, Recommendation, AddRecommendation, EditRecommendation, OwnRecommendation, Profile, EditProfile, SearchProfile, Study, Matching, }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Actors = [{ id: 1, name: "Tim Robbins", dob: "10/16/1958", num_credits: 73, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTI1OTYxNzAxOF5BMl5BanBnXkFtZTYwNTE5ODI4._V1_.jpg" }, { id: 2, name: "Morgan Freeman", dob: "06/01/1937", num_credits: 120, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTc0MDMyMzI2OF5BMl5BanBnXkFtZTcwMzM2OTk1MQ@@._V1_UX214_CR0,0,214,317_AL_.jpg" }, { id: 3, name: "Christian Bale", dob: "01/30/1974", num_credits: 51, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTkxMzk4MjQ4MF5BMl5BanBnXkFtZTcwMzExODQxOA@@._V1_UX214_CR0,0,214,317_AL_.jpg" }, { id: 4, name: "Aaron Eckhart", dob: "03/12/1968", num_credits: 40, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTc4MTAyNzMzNF5BMl5BanBnXkFtZTcwMzQ5MzQzMg@@._V1_UY317_CR6,0,214,317_AL_.jpg" }, { id: 5, name: "Ryan Gosling", dob: "11/12/1980", num_credits: 42, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMTQzMjkwNTQ2OF5BMl5BanBnXkFtZTgwNTQ4MTQ4MTE@._V1_UY317_CR18,0,214,317_AL_.jpg" }, { id: 6, name: "Emma Stone", dob: "11/06/1988", num_credits: 41, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMjI4NjM1NDkyN15BMl5BanBnXkFtZTgwODgyNTY1MjE@._V1.._UX214_CR0,0,214,317_AL_.jpg" }, { id: 7, name: "Steve Carell", dob: "08/16/1962", num_credits: 72, image: "https://images-na.ssl-images-amazon.com/images/M/MV5BMjAzMjkzNzA0M15BMl5BanBnXkFtZTcwNzMyNjU3MQ@@._V1_UY317_CR6,0,214,317_AL_.jpg" }]; exports.default = Actors;
/*! * dyCalendar is a JavaScript library for creating Calendar. * * Author: Yusuf Shakeel * https://github.com/yusufshakeel * * GitHub Link: https://github.com/yusufshakeel/dyCalendarJS * * MIT license * Copyright (c) 2016 Yusuf Shakeel * * Date: 2014-08-17 sunday */ /*! dyCalendarJS | (c) 2016 Yusuf Shakeel | https://github.com/yusufshakeel/dyCalendarJS */ (function (global) { "use strict"; var //this will be used by the user. dycalendar = {}, //window document document = global.document, //starting year START_YEAR = 1900, //end year END_YEAR = 9999, //name of the months monthName = { full: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], mmm: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] }, //name of the days dayName = { full: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], d: ['S', 'M', 'T', 'W', 'T', 'F', 'S'], dd: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'], ddd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'] }; /** * this function will create month table. * * @param object data this contains the calendar data * @param object option this is the settings object * @return html */ function createMonthTable(data, option) { var table, tr, td, r, c, count; table = document.createElement("table"); tr = document.createElement("tr"); //create 1st row for the day letters for (c = 0; c <= 6; c = c + 1) { td = document.createElement("td"); td.innerHTML = "SMTWTFS"[c]; tr.appendChild(td); } table.appendChild(tr); //create 2nd row for dates tr = document.createElement("tr"); //blank td for (c = 0; c <= 6; c = c + 1) { if (c === data.firstDayIndex) { break; } td = document.createElement("td"); tr.appendChild(td); } //remaing td of dates for the 2nd row count = 1; while (c <= 6) { td = document.createElement("td"); td.innerHTML = count; if (data.today.date === count && data.today.monthIndex === data.monthIndex && option.highlighttoday === true) { td.setAttribute("class", "dycalendar-today-date"); } if (option.date === count && option.month === data.monthIndex && option.highlighttargetdate === true) { td.setAttribute("class", "dycalendar-target-date"); } tr.appendChild(td); count = count + 1; c = c + 1; } table.appendChild(tr); //create remaining rows for (r = 3; r <= 7; r = r + 1) { tr = document.createElement("tr"); for (c = 0; c <= 6; c = c + 1) { if (count > data.totaldays) { table.appendChild(tr); return table; } td = document.createElement('td'); td.innerHTML = count; if (data.today.date === count && data.today.monthIndex === data.monthIndex && option.highlighttoday === true) { td.setAttribute("class", "dycalendar-today-date"); } if (option.date === count && option.month === data.monthIndex && option.highlighttargetdate === true) { td.setAttribute("class", "dycalendar-target-date"); } count = count + 1; tr.appendChild(td); } table.appendChild(tr); } return table; } /** * this function will draw Calendar Month Table * * @param object data this contains the calendar data * @param object option this is the settings object * @return html */ function drawCalendarMonthTable(data, option) { var table, div, container, elem; //get table table = createMonthTable(data, option); //calendar container container = document.createElement("div"); container.setAttribute("class", "dycalendar-month-container"); //-------------------------- Header ------------------ //header div div = document.createElement("div"); div.setAttribute("class", "dycalendar-header"); div.setAttribute("data-option", JSON.stringify(option)); //prev button if (option.prevnextbutton === "show") { elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-prev-next-btn prev-btn"); elem.setAttribute("data-date", option.date); elem.setAttribute("data-month", option.month); elem.setAttribute("data-year", option.year); elem.setAttribute("data-btn", "prev"); elem.innerHTML = "&lt;"; //add prev button span to header div div.appendChild(elem); } //month span elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-span-month-year"); if (option.monthformat === "mmm") { elem.innerHTML = data.monthName + " " + data.year; } else if (option.monthformat === "full") { elem.innerHTML = data.monthNameFull + " " + data.year; } //add month span to header div div.appendChild(elem); //next button if (option.prevnextbutton === "show") { elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-prev-next-btn next-btn"); elem.setAttribute("data-date", option.date); elem.setAttribute("data-month", option.month); elem.setAttribute("data-year", option.year); elem.setAttribute("data-btn", "next"); elem.innerHTML = "&gt;"; //add prev button span to header div div.appendChild(elem); } //add header div to container container.appendChild(div); //-------------------- Today button ---------------- //today button div if (option.todaybutton === "show") { div = document.createElement("div"); div.setAttribute("class", "dycalendar-today-btn"); div.setAttribute("data-option", JSON.stringify(option)); //today button elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-today-btn today-btn"); elem.setAttribute("data-date", option.date); elem.setAttribute("data-month", option.month); elem.setAttribute("data-year", option.year); elem.setAttribute("data-btn", "today"); elem.innerHTML = "Today"; //add prev button span to header div div.appendChild(elem); container.appendChild(div); } //-------------------------- Body ------------------ //body div div = document.createElement("div"); div.setAttribute("class", "dycalendar-body"); div.appendChild(table); //add body div to container div container.appendChild(div); //return container return container; } /** * this function will draw Calendar Day * * @param object data this contains the calendar data * @param object option this is the settings object * @return html */ function drawCalendarDay(data, option) { var div, container, elem; //calendar container container = document.createElement("div"); container.setAttribute("class", "dycalendar-day-container"); //-------------------------- Header ------------------ //header div div = document.createElement("div"); div.setAttribute("class", "dycalendar-header"); //day span elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-span-day"); if (option.dayformat === "ddd") { elem.innerHTML = dayName.ddd[data.targetedDayIndex]; } else if (option.dayformat === "full") { elem.innerHTML = dayName.full[data.targetedDayIndex]; } //add day span to footer div div.appendChild(elem); //add header div to container container.appendChild(div); //-------------------------- Body ------------------ //body div div = document.createElement("div"); div.setAttribute("class", "dycalendar-body"); //date span elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-span-date"); elem.innerHTML = data.date; //add date span to body div div.appendChild(elem); //add body div to container container.appendChild(div); //-------------------------- Footer ------------------ //footer div div = document.createElement("div"); div.setAttribute("class", "dycalendar-footer"); //month span elem = document.createElement("span"); elem.setAttribute("class", "dycalendar-span-month-year"); if (option.monthformat === "mmm") { elem.innerHTML = data.monthName + " " + data.year; } else if (option.monthformat === "full") { elem.innerHTML = data.monthNameFull + " " + data.year; } //add month span to footer div div.appendChild(elem); //add footer div to container container.appendChild(div); //return container return container; } /** * this function will extend source object with defaults object. * * @param object source this is the source object * @param object defaults this is the default object * @return object */ function extendSource(source, defaults) { var property; for (property in defaults) { if (source.hasOwnProperty(property) === false) { source[property] = defaults[property]; } } return source; } /** * This function will return calendar detail. * * @param integer year 1900-9999 (optional) if not set will consider * the current year. * @param integer month 0-11 (optional) 0 = Jan, 1 = Feb, ... 11 = Dec, * if not set will consider the current month. * @param integer date 1-31 (optional) * @return boolean|object if error return false, else calendar detail */ function getCalendar(year, month, date) { var dateObj = new Date(), dateString, result = {}, idx; if (year < START_YEAR || year > END_YEAR) { global.console.error("Invalid Year"); return false; } if (month > 11 || month < 0) { global.console.error("Invalid Month"); return false; } if (date > 31 || date < 1) { global.console.error("Invalid Date"); return false; } result.year = year; result.month = month; result.date = date; //today result.today = {}; dateString = dateObj.toString().split(" "); idx = dayName.ddd.indexOf(dateString[0]); result.today.dayIndex = idx; result.today.dayName = dateString[0]; result.today.dayFullName = dayName.full[idx]; idx = monthName.mmm.indexOf(dateString[1]); result.today.monthIndex = idx; result.today.monthName = dateString[1]; result.today.monthNameFull = monthName.full[idx]; result.today.date = dateObj.getDate(); result.today.year = dateString[3]; //get month-year first day dateObj.setDate(1); dateObj.setMonth(month); dateObj.setFullYear(year); dateString = dateObj.toString().split(" "); idx = dayName.ddd.indexOf(dateString[0]); result.firstDayIndex = idx; result.firstDayName = dateString[0]; result.firstDayFullName = dayName.full[idx]; idx = monthName.mmm.indexOf(dateString[1]); result.monthIndex = idx; result.monthName = dateString[1]; result.monthNameFull = monthName.full[idx]; //get total days for the month-year dateObj.setFullYear(year); dateObj.setMonth(month + 1); dateObj.setDate(0); result.totaldays = dateObj.getDate(); //get month-year targeted date dateObj.setFullYear(year); dateObj.setMonth(month); dateObj.setDate(date); dateString = dateObj.toString().split(" "); idx = dayName.ddd.indexOf(dateString[0]); result.targetedDayIndex = idx; result.targetedDayName = dateString[0]; result.targetedDayFullName = dayName.full[idx]; return result; } /** * this function will handle the on click event. */ function onClick() { document.body.onclick = function (e) { //get event object (window.event for IE compatibility) e = global.event || e; var //get target dom object reference targetDomObject = e.target || e.srcElement, //other variables date, month, year, btn, option, dateObj; const today = new Date(); //prev-next button click //extra checks to make sure object exists and contains the class of interest if ((targetDomObject) && (targetDomObject.classList) && (targetDomObject.classList.contains("dycalendar-prev-next-btn"))) { date = parseInt(targetDomObject.getAttribute("data-date")); month = parseInt(targetDomObject.getAttribute("data-month")); year = parseInt(targetDomObject.getAttribute("data-year")); btn = targetDomObject.getAttribute("data-btn"); option = JSON.parse(targetDomObject.parentElement.getAttribute("data-option")); if (btn === "prev") { month = month - 1; if (month < 0) { year = year - 1; month = 11; } } else if (btn === "next") { month = month + 1; if (month > 11) { year = year + 1; month = 0; } } option.date = date; option.month = month; option.year = year; drawCalendar(option); } //today button click //extra checks to make sure object exists and contains the class of interest if ((targetDomObject) && (targetDomObject.classList) && (targetDomObject.classList.contains("dycalendar-today-btn"))) { date = parseInt(targetDomObject.getAttribute("data-date")); month = parseInt(targetDomObject.getAttribute("data-month")); year = parseInt(targetDomObject.getAttribute("data-year")); btn = targetDomObject.getAttribute("data-btn"); option = JSON.parse(targetDomObject.parentElement.getAttribute("data-option")); date = today.getDate(); month = today.getMonth(); year = today.getFullYear(); option.date = date; option.month = month; option.year = year; drawCalendar(option); } //month click //extra checks to make sure object exists and contains the class of interest if ((targetDomObject) && (targetDomObject.classList) && (targetDomObject.classList.contains("dycalendar-span-month-year"))) { option = JSON.parse(targetDomObject.parentElement.getAttribute("data-option")); dateObj = new Date(); option.date = dateObj.getDate(); option.month = dateObj.getMonth(); option.year = dateObj.getFullYear(); drawCalendar(option); } }; } //------------------------------ dycalendar.draw() ---------------------- /** * this function will draw the calendar based on user preferences. * * option = { * target : "#id|.class" //(mandatory) for id use #id | for class use .class * type : "calendar-type" //(optional) values: "day|month" (default "day") * month : "integer" //(optional) value 0-11, where 0 = January, ... 11 = December (default current month) * year : "integer" //(optional) example 1990. (default current year) * date : "integer" //(optional) example 1-31. (default current date) * monthformat : "full" //(optional) values: "mmm|full" (default "full") * dayformat : "full" //(optional) values: "ddd|full" (default "full") * highlighttoday : boolean //(optional) (default false) if true will highlight today's date * highlighttargetdate : boolean //(optional) (default false) if true will highlight targeted date of the month year * prevnextbutton : "hide" //(optional) (default "hide") (values: "show|hide") if set to "show" it will show the nav button (prev|next) * } * * @param object option user preferences * @return boolean true if success, false otherwise */ dycalendar.draw = function (option) { //check if option is passed or not if (typeof option === "undefined") { global.console.error("Option missing"); return false; } var self = this, //pointing at dycalendar object dateObj = new Date(), //default settings defaults = { type: "day", month: dateObj.getMonth(), year: dateObj.getFullYear(), date: dateObj.getDate(), monthformat: "full", dayformat: "full", highlighttoday: false, highlighttargetdate: false, prevnextbutton: "hide" }; //extend user options with predefined options option = extendSource(option, defaults); drawCalendar(option); }; //------------------------------ dycalendar.draw() ends here ------------ /** * this function will draw the calendar inside the target container. */ function drawCalendar(option) { var //variables for creating calendar calendar, calendarHTML, targetedElementBy = "id", targetElem, //other variables i, len, elemArr; //find target element by if (option.target[0] === "#") { targetedElementBy = "id"; } else if (option.target[0] === ".") { targetedElementBy = "class"; } targetElem = option.target.substring(1); //get calendar HTML switch (option.type) { case "day": //get calendar detail calendar = getCalendar(option.year, option.month, option.date); //get calendar html calendarHTML = drawCalendarDay(calendar, option); break; case "month": //get calendar detail calendar = getCalendar(option.year, option.month, option.date); //get calendar html calendarHTML = drawCalendarMonthTable(calendar, option); break; default: global.console.error("Invalid type"); return false; } //draw calendar if (targetedElementBy === "id") { document.getElementById(targetElem).innerHTML = calendarHTML.outerHTML; } else if (targetedElementBy === "class") { elemArr = document.getElementsByClassName(targetElem); for (i = 0, len = elemArr.length; i < len; i = i + 1) { elemArr[i].innerHTML = calendarHTML.outerHTML; } } } //events onClick(); //attach to global window object global.dycalendar = dycalendar; }(typeof window !== "undefined" ? window : this));
import React from 'react'; import { NavigationContainer } from '@react-navigation/native'; import { createStackNavigator } from '@react-navigation/stack'; const AppStack = createStackNavigator(); import Incidents from './pages/incidents'; import Detail from './pages/detail'; export default function Routes() { return ( <NavigationContainer> <AppStack.Navigator screenOptions={{ headerShown: false }}> <AppStack.Screen name="Incidents" component={Incidents} /> <AppStack.Screen name="Detail" component={Detail} /> </AppStack.Navigator> </NavigationContainer> ) }
window.d3 = undefined; import SummaryOutput from '_OfferSummary'; import StackedBar from '/_StackedBar'; import SliderPanel from './_SliderPanel'; import AnalyticPanel from './_Analytic';
// This file is derived from the Cesium code base under Apache 2 license // See LICENSE.md and https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md import {GL} from '@loaders.gl/math'; // math.gl/geometry; import Tile3DFeatureTable from '../classes/tile-3d-feature-table'; // import Tile3DBatchTable from '../classes/tile-3d-batch-table'; import {parse3DTileHeaderSync} from './helpers/parse-3d-tile-header'; import {parse3DTileTablesHeaderSync, parse3DTileTablesSync} from './helpers/parse-3d-tile-tables'; import {parse3DTileGLTFViewSync, extractGLTF, GLTF_FORMAT} from './helpers/parse-3d-tile-gltf-view'; export async function parseBatchedModel3DTile(tile, arrayBuffer, byteOffset, options) { return parseBatchedModel3DTileSync(tile, arrayBuffer, byteOffset, options); } export function parseBatchedModel3DTileSync(tile, arrayBuffer, byteOffset, options) { byteOffset = parse3DTileHeaderSync(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileTablesHeaderSync(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileTablesSync(tile, arrayBuffer, byteOffset, options); byteOffset = parse3DTileGLTFViewSync(tile, arrayBuffer, byteOffset, options); const featureTable = new Tile3DFeatureTable(tile.featureTableJson, tile.featureTableBinary); tile.rtcCenter = featureTable.getGlobalProperty('RTC_CENTER', GL.FLOAT, 3); extractGLTF(tile, GLTF_FORMAT.EMBEDDED, options); /* TODO - Remove. This was a shot in the dark, didn't work... if (tile.rtcCenter) { const instanceTransform = new Matrix4(); Ellipsoid.WGS84.eastNorthUpToFixedFrame(tile.rtcCenter, instanceTransform); const modelMatrix = new Matrix4(); instanceTransform.getRotationMatrix3(modelMatrix); tile.instances = [{modelMatrix: modelMatrix.invert()}]; } */ return byteOffset; }
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * Assume F is a Function object. When the [[HasInstance]] method of F is called with value V, the following steps are taken: i) If V is not an object, return false * * @path ch15/15.3/15.3.5/S15.3.5.3_A1_T2.js * @description V is string */ FACTORY = Function("name","this.name=name;"); //CHECK#1 if (("1" instanceof FACTORY)!==false) { $ERROR('#1: Assume F is a Function object. When the [[HasInstance]] method of F is called with value V, the following steps are taken: i) If V is not an object, return false'); }
webpackJsonp([10],{DT89:function(t,e,a){var n=a("tqyE");"string"==typeof n&&(n=[[t.i,n,""]]),n.locals&&(t.exports=n.locals);a("rjj0")("0f4de138",n,!0)},IEOF:function(t,e,a){var n=a("nt/b");"string"==typeof n&&(n=[[t.i,n,""]]),n.locals&&(t.exports=n.locals);a("rjj0")("f6dc08fc",n,!0)},fA0Y:function(t,e,a){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var n=a("woOf"),r=a.n(n),i=a("5aCZ"),o=a("KQHe"),s=a("+mJe"),c=a("RUzx"),l=a.n(c),p=(a("tLvy"),a("vHhr")),u=a("E4LH"),m=a("viA7"),f=a("LkbC"),d=a("zmr2"),_=a("TIfe"),h=a("3qhk"),b=a("EAZf"),g=a.n(b),v=(a("7+uW"),{status:"draft",title:"",content:"",content_short:"",source_uri:"",image_uri:"",source_name:"",display_time:void 0,id:void 0,platforms:["a-platform"],comment_disabled:!1}),y=function(t,e){var a,n,r;try{n=t.toString().split(".")[1].length}catch(t){n=0}try{r=e.toString().split(".")[1].length}catch(t){r=0}return a=Math.pow(10,Math.max(n,r)),parseInt((t*a+e*a)/a*1e4)/1e4},D=function(t,e){var a,n,r,i;try{n=t.toString().split(".")[1].length}catch(t){n=0}try{r=e.toString().split(".")[1].length}catch(t){r=0}return a=Math.pow(10,Math.max(n,r)),i=n>=r?n:r,parseInt(1e4*((t*a-e*a)/a).toFixed(i))/1e4},w=function(t,e){var a=0;try{a+=t.toString().split(".")[1].length}catch(t){}try{a+=e.toString().split(".")[1].length}catch(t){}return parseInt(Number(t.toString().replace(".",""))*Number(e.toString().replace(".",""))/Math.pow(10,a)*1e4)/1e4},x={name:"articleDetail",components:{Tinymce:i.a,MDinput:s.a,Upload:o.a,Multiselect:l.a,Sticky:p.a,Viewer:g.a,BasicInfo:h.default},data:function(){var t=this,e=function(e,a,n){""===a?(t.$message({message:e.field+"为必传项",type:"error"}),n(null)):n()},a=function(t,e,a){return e?/^(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(e)?a():a(new Error("请填写正确的信息")):a(new Error("此项不能为空"))},n=function(t,e,a){return e?a():a(new Error("此项不能为空"))};return{customerData:{customer_name:"",car_type:"",product_class_number:"",car_price:"",loan_prize:"",loan_rate:"",loan_date:"",loan_bank:"",first_pay:"",first_pay_ratio:"",integration_principal:"",finance_driving:"",finance_deposit_bank:"",finance_name:"",finance_account:"",finance_date:"",finance_amount:"",finance_apply_description:"",return_car_principal:"",bank_lending:"",return_car_rate:"",car_final_pay:"",remittance_total_money:"",gross_profit_rate:"",car_name:"",business_place:"",credit_city:""},requestData:{token:Object(_.a)(),work_id:this.$route.query.id,item_instance_id:this.$route.query.item_instance_id},ifResult:{},maskResult:{},search_type:"1",labelwidth:"82px",space:"200px",images:[{src:"http://test-linrun.anjietest-feature.ifcar99.com/uploads/image/20171218/090f27f1048014138a65e18b9486a92f.JPG"},{src:"http://test-linrun.anjietest-feature.ifcar99.com/uploads/image/20171218/045b6526879073d440c470d1e78969fa.JPG"},{src:"http://test-linrun.anjietest-feature.ifcar99.com/uploads/image/20171218/043147fb1aa26f82167a73b535ea4686.JPG"}],divgutter:20,cartype:"1",imgs1:[],imgs2:[],postForm:r()({},v),fetchSuccess:!0,loading:!1,userLIstOptions:[],isEdit:!1,platformsOptions:[{key:"a-platform",name:"a-platform"},{key:"b-platform",name:"b-platform"},{key:"c-platform",name:"c-platform"}],rules:{image_uri:[{validator:e}],title:[{validator:e}],content:[{validator:e}],source_uri:[{validator:function(e,a,n){a?Object(u.a)(a)?n():(t.$message({message:"外链url填写不正确",type:"error"}),n(null)):n()},trigger:"blur"}],return_car_rate:[{validator:a,trigger:"blur"}],integration_principal:[{validator:a,trigger:"blur"}],car_final_pay:[{validator:function(t,e,a){return e?/^(\-)?(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(e)?a():a(new Error("请填写正确的信息")):a(new Error("此项不能为空"))},trigger:"blur"}],car_name:[{validator:n,trigger:"blur"}],finance_account:[{validator:function(t,e,a){var n=e.replace(/\s/g,"");if(""==n)return a(new Error("此项不能为空"));if(n.length<16||n.length>19)return a(new Error("银行卡号长度必须在16到19之间"));if(!/^\d*$/.exec(n))return a(new Error("银行卡号必须全为数字"));return-1=="10,18,30,35,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,58,60,62,65,68,69,84,87,88,94,95,98,99".indexOf(n.substring(0,2))?a(new Error("银行卡号开头两位不符合规范")):function(t){for(var e=t.substr(t.length-1,1),a=t.substr(0,t.length-1),n=new Array,r=a.length-1;r>-1;r--)n.push(a.substr(r,1));for(var i=new Array,o=new Array,s=new Array,c=0;c<n.length;c++)(c+1)%2==1?2*parseInt(n[c])<9?i.push(2*parseInt(n[c])):o.push(2*parseInt(n[c])):s.push(n[c]);for(var l=new Array,p=new Array,u=0;u<o.length;u++)l.push(parseInt(o[u])%10),p.push(parseInt(o[u])/10);for(var m=0,f=0,d=0,_=0,h=0,b=0;b<i.length;b++)m+=parseInt(i[b]);for(var g=0;g<s.length;g++)f+=parseInt(s[g]);for(var v=0;v<l.length;v++)d+=parseInt(l[v]),_+=parseInt(p[v]);return h=parseInt(m)+parseInt(f)+parseInt(d)+parseInt(_),e==10-(parseInt(h)%10==0?10:parseInt(h)%10)}(n)?a():a(new Error("银行卡号不正确"))},trigger:"change"}],finance_name:[{validator:n,trigger:"blur"}],business_place:[{validator:n,trigger:"blur"}],finance_date:[{type:"date",message:"请选择日期",trigger:"change"}],finance_deposit_bank:[{validator:n,trigger:"blur"}],finance_apply_description:[{validator:function(t,e,a){return a()},trigger:"blur"}]}}},filters:{statusFilter:function(t){return{published:"success",draft:"info",deleted:"danger"}[t]},typeFilter:function(t){return calendarTypeKeyValue[t]},hasBondsman:function(t){return"1"==t?"有担保人":"无担保人"},maritalStatus:function(t){return"1"==t?"已婚":"2"==t?"未婚":"3"==t?"离婚":"4"==t?"丧偶":void 0},hasInsurance:function(t){return"1"==t?"有保险":"无保险"},carType:function(t){return"XC"==t?"新车":"二手车"},bankType:function(t){return"01"==t?"济南市中工行":"02"==t?"济南乐源支行":"03"==t?"临沂经开行":void 0}},computed:{pagedata:function(){return{token:Object(_.a)(),work_id:this.$route.query.id,item_instance_id:this.$route.query.item_instance_id,integration_principal:this.customerData.integration_principal,return_car_principal:this.returnMoney,finance_driving:this.financeDriving,return_car_rate:this.customerData.return_car_rate,gross_profit_rate:this.grossProfitRate,car_name:this.customerData.car_name,remittance_total_money:this.financeAmount,finance_deposit_bank:this.customerData.finance_deposit_bank,bank_lending:this.bankLending,finance_account:this.customerData.finance_account,finance_date:Date.parse(this.customerData.finance_date)/1e3,finance_name:this.customerData.finance_name,business_place:this.customerData.business_place,car_final_pay:this.customerData.car_final_pay,finance_apply_description:this.customerData.finance_apply_description}},contentShortLength:function(){return this.postForm.content_short.length},returnMoney:function(){this.customerData.return_car_principal;if(this.customerData.loan_prize&&this.customerData.return_car_rate&&/^(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(this.customerData.return_car_rate)){return w(Number(this.customerData.loan_prize),this.toPoint(this.customerData.return_car_rate)).toFixed(2)}return""},financeDriving:function(){return this.customerData.loan_prize},grossProfitRate:function(){this.customerData.gross_profit_rate;if(this.customerData.loan_rate&&this.customerData.return_car_rate&&/^(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(this.customerData.return_car_rate)){return D(Number(this.customerData.loan_rate),Number(this.customerData.return_car_rate))}return""},bankLending:function(){this.customerData.bank_lending;if("03"==this.customerData.loan_bank){if(""!=this.customerData.integration_principal&&this.customerData.integration_principal&&this.customerData.loan_prize&&this.customerData.loan_rate){if(/^(\-)?(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(this.customerData.integration_principal)){var t=y(Number(this.customerData.loan_prize),Number(this.customerData.integration_principal));return"12个月"==this.customerData.loan_date?e=y(this.toPoint(this.customerData.loan_rate),.9642):"24个月"==this.customerData.loan_date?e=y(this.toPoint(this.customerData.loan_rate),.934):"36个月"==this.customerData.loan_date&&(e=y(this.toPoint(this.customerData.loan_rate),.91)),a=w(t,e),a.toFixed(2)}return""}return""}if(""!=this.customerData.integration_principal&&this.customerData.integration_principal&&this.customerData.loan_prize&&this.customerData.loan_rate){if(/^(\-)?(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(this.customerData.integration_principal)){var e,a;t=y(Number(this.customerData.loan_prize),Number(this.customerData.integration_principal));return"12个月"==this.customerData.loan_date?e=y(this.toPoint(this.customerData.loan_rate),.967):"24个月"==this.customerData.loan_date?e=y(this.toPoint(this.customerData.loan_rate),.934):"36个月"==this.customerData.loan_date&&(e=y(this.toPoint(this.customerData.loan_rate),.905)),a=w(t,e),this.numChange(a).toFixed(2)}return""}return""},financeAmount:function(){this.customerData.remittance_total_mone;if(this.customerData.loan_prize&&this.returnMoney&&this.customerData.car_final_pay&&/^(\-)?(0|[1-9][0-9]*)(\.\d{1,2})?$/.test(this.customerData.car_final_pay)){var t=y(Number(this.customerData.loan_prize),Number(this.returnMoney));return D(t,Number(this.customerData.car_final_pay)).toFixed(2)}return""}},created:function(){this.isEdit?this.fetchData():this.postForm=r()({},v),this.getDetailInfo(),this.getAuditProcess()},methods:{getDetailInfo:function(){var t=this,e={data:this.requestData,success:function(e){if(t.ifResult=e,200==e.error_no){var a=["customer_name","car_type","product_class_number","car_price","loan_prize","loan_bank","loan_date","loan_rate","first_pay","first_pay_ratio","credit_city"];for(var n in a)""==e.result[a[n]]||null==e.result[a[n]]?t.customerData[a[n]]="- - -":t.customerData[a[n]]=e.result[a[n]];""==e.result.product_class_number||null==e.result.product_class_number?t.customerData.product_class_number="XC":t.customerData.product_class_number=e.result.product_class_number,""==e.result.loan_bank||null==e.result.loan_bank?t.customerData.loan_bank="01":t.customerData.loan_bank=e.result.loan_bank,""==e.result.loan_date||null==e.result.loan_date?t.customerData.loan_date="12个月":t.customerData.loan_date=e.result.loan_date}else t.$alert(e.error_msg,"申请打款",{confirmButtonText:"确定",beforeClose:function(t,e,a){a()}})},error:function(t){}};d.a.getArtificalOneDetail(e)},getAuditProcess:function(){var t=this,e={data:this.requestData,success:function(e){t.maskResult=e},error:function(){}};d.a.getAuditProcess(e)},submitData:function(t){var e=this,a={data:this.pagedata,success:function(a){200==a.error_no?e.$alert("成功提交","申请打款",{confirmButtonText:"确定",beforeClose:function(t,a,n){"confirm"==t?(n(),e.$router.push({path:"/work/applyremittance"})):"cancel"==t&&n()}}):"资料不完整"==a.error_msg?e.$alert(a.error_msg,"打款审核",{confirmButtonText:"确定",beforeClose:function(a,n,r){"confirm"==a?(r(),e.$refs[t].validate(function(t){if(!t)return!1})):"cancel"==a&&r()}}):e.$alert(a.error_msg,"审核打款",{confirmButtonText:"确定",beforeClose:function(t,e,a){a()}})},error:function(t){}};this.$confirm("是否确定提交","提示",{confirmButtonText:"确定",cancelButtonText:"取消"}).then(function(){e.$refs.customerData.validate(function(t){t?Number(e.customerData.return_car_rate)>Number(e.customerData.loan_rate)?e.$alert("返车行利率不能大于总利率","申请打款",{confirmButtonText:"确定",beforeClose:function(t,e,a){a()}}):d.a.applyRemittance(a):e.$alert("信息不完整,请检查信息","申请打款",{confirmButtonText:"确定"})})}).catch(function(){})},resetForm:function(t){this.$refs[t].resetFields()},numChange:function(t){var e=parseInt(parseInt(t)/100);return t<=100*e?100*e:100*(e+1)},toPoint:function(t){return t/=100},show:function(){this.$el.querySelector(".images").$viewer.show()},fetchData:function(){var t=this;Object(m.a)().then(function(e){t.postForm=e.data}).catch(function(e){t.fetchSuccess=!1})},submitForm:function(){var t=this;this.postForm.display_time=parseInt(this.display_time/1e3),this.$refs.postForm.validate(function(e){if(!e)return!1;t.loading=!0,t.$notify({title:"成功",message:"发布文章成功",type:"success",duration:2e3}),t.postForm.status="published",t.loading=!1})},draftForm:function(){0!==this.postForm.content.length&&0!==this.postForm.title.length?(this.$message({message:"保存成功",type:"success",showClose:!0,duration:1e3}),this.postForm.status="draft"):this.$message({message:"请填写必要的标题和内容",type:"warning"})},getRemoteUserList:function(t){var e=this;Object(f.a)(t).then(function(t){t.data.items&&(e.userLIstOptions=t.data.items.map(function(t){return{key:t.name}}))})}},watch:{"customerData.return_car_rate":function(){Number(this.customerData.return_car_rate)>Number(this.customerData.loan_rate)&&this.$alert("返车行利率不能大于总利率","申请打款",{confirmButtonText:"确定",beforeClose:function(t,e,a){a()}})}}},I={render:function(){var t=this,e=t.$createElement,a=t._self._c||e;return a("div",{staticClass:"createPost-container createPost-container-one"},[a("el-tabs",{staticStyle:{"background-color":"#ffffff","padding-left":"50px"},model:{value:t.search_type,callback:function(e){t.search_type=e},expression:"search_type"}},[a("el-tab-pane",{attrs:{label:"申请打款",name:"1"}}),t._v(" "),a("el-tab-pane",{attrs:{label:"客户详情",name:"2"}})],1),t._v(" "),"1"==t.search_type?a("el-form",{ref:"customerData",staticClass:"form-container",attrs:{model:t.customerData,rules:t.rules}},[a("div",{staticClass:"createPost-main-container"},[a("el-row",{attrs:{gutter:t.divgutter}},[a("div",{staticClass:"postInfo-container postInfo-container-one"},[a("el-row",{attrs:{gutter:t.divgutter}},[a("el-col",{staticStyle:{"padding-left":"30px","padding-top":"10px"},attrs:{span:12}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%","margin-left":"31px"},attrs:{"label-width":t.labelwidth,label:"业务团队:"}},[a("span",{domProps:{textContent:t._s(t.customerData.credit_city)}})])],1)],1)],1)]),t._v(" "),a("el-row",{attrs:{gutter:t.divgutter}},[a("el-col",{staticStyle:{background:"#fff",padding:"40px 25px","padding-bottom":"46px"},attrs:{span:5}},[a("div",{staticClass:"postInfo-container postInfo-container-one"},[a("el-row",{attrs:{gutter:t.divgutter}},[a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"90%"},attrs:{"label-width":t.labelwidth,label:"客户姓名"}},[a("span",{domProps:{textContent:t._s(t.customerData.customer_name)}})])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"车辆型号"}},[a("span",{domProps:{textContent:t._s(t.customerData.car_type)}})])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"车辆类型"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t._f("carType")(t.customerData.product_class_number))+"\n\t\t\t ")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"车辆价格"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t.customerData.car_price)+"元\n\t\t\t ")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"贷款额"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t.customerData.loan_prize)+"元\n\t\t\t ")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"贷款银行"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t._f("bankType")(t.customerData.loan_bank))+"\n\t\t\t ")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"贷款期数"}},[a("span",{domProps:{textContent:t._s(t.customerData.loan_date)}})])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"利率"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t.customerData.loan_rate)+"%\n\t\t\t ")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"首付款"}},[a("span",[t._v("\n\t\t\t \t"+t._s(t.customerData.first_pay)+"元\n \t\t\t\t\t")])])],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"首付比例"}},[a("span",[t._v("\n\t\t\t "+t._s(t.customerData.first_pay_ratio)+"%\n\t\t\t ")])])],1)],1)],1)]),t._v(" "),a("el-col",{staticStyle:{background:"#F5F6FA","padding-right":"0px"},attrs:{span:19}},[a("div",{staticClass:"postInfo-container applyremittance",staticStyle:{background:"#fff","margin-bottom":"0px",padding:"40px","padding-bottom":"0px"}},[a("el-row",{attrs:{gutter:t.divgutter}},[a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"融入本金",prop:"integration_principal"}},[a("el-input",{attrs:{placeholder:"请输入融入本金(必填)"},model:{value:t.customerData.integration_principal,callback:function(e){t.$set(t.customerData,"integration_principal",e)},expression:"customerData.integration_principal"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"返车行金额"}},[a("el-input",{attrs:{disabled:"disabled",placeholder:"自动计算"},model:{value:t.returnMoney,callback:function(e){t.returnMoney=e},expression:"returnMoney"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"打给车行"}},[a("el-input",{attrs:{disabled:"disabled",placeholder:"请输入打给车行(必填)"},model:{value:t.financeDriving,callback:function(e){t.financeDriving=e},expression:"financeDriving"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"返车行利率",prop:"return_car_rate"}},[a("el-input",{attrs:{placeholder:"请输入返车行利率(必填)"},model:{value:t.customerData.return_car_rate,callback:function(e){t.$set(t.customerData,"return_car_rate",e)},expression:"customerData.return_car_rate"}},[a("template",{slot:"append"},[t._v("%")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"毛利率"}},[a("el-input",{attrs:{disabled:"disabled",placeholder:"自动计算"},model:{value:t.grossProfitRate,callback:function(e){t.grossProfitRate=e},expression:"grossProfitRate"}},[a("template",{slot:"append"},[t._v("%")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"车行全称",prop:"car_name"}},[a("el-input",{attrs:{placeholder:"请输入车行全称(必填)"},model:{value:t.customerData.car_name,callback:function(e){t.$set(t.customerData,"car_name",e)},expression:"customerData.car_name"}})],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"合计打款"}},[a("el-input",{attrs:{disabled:"disabled",placeholder:"自动计算"},model:{value:t.financeAmount,callback:function(e){t.financeAmount=e},expression:"financeAmount"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"开户行",prop:"finance_deposit_bank"}},[a("el-input",{attrs:{placeholder:"请输入开户行(必填)"},model:{value:t.customerData.finance_deposit_bank,callback:function(e){t.$set(t.customerData,"finance_deposit_bank",e)},expression:"customerData.finance_deposit_bank"}})],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"银行放款额"}},[a("el-input",{attrs:{disabled:"disabled",placeholder:"自动计算"},model:{value:t.bankLending,callback:function(e){t.bankLending=e},expression:"bankLending"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"账号",prop:"finance_account"}},[a("el-input",{attrs:{placeholder:"请输入账号(必填)"},model:{value:t.customerData.finance_account,callback:function(e){t.$set(t.customerData,"finance_account",e)},expression:"customerData.finance_account"}})],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"打款日期",prop:"finance_date"}},[a("el-col",{staticStyle:{"padding-left":"0px","padding-right":"0px"},attrs:{span:24}},[a("el-date-picker",{staticStyle:{width:"80%"},attrs:{type:"date",placeholder:"选择日期"},model:{value:t.customerData.finance_date,callback:function(e){t.$set(t.customerData,"finance_date",e)},expression:"customerData.finance_date"}})],1)],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"打款户名",prop:"finance_name"}},[a("el-input",{attrs:{placeholder:"请输入打款户名(必填)"},model:{value:t.customerData.finance_name,callback:function(e){t.$set(t.customerData,"finance_name",e)},expression:"customerData.finance_name"}})],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"业务发生地",prop:"business_place"}},[a("el-input",{attrs:{placeholder:"请输入业务发生地(必填)"},model:{value:t.customerData.business_place,callback:function(e){t.$set(t.customerData,"business_place",e)},expression:"customerData.business_place"}})],1)],1),t._v(" "),a("el-col",{attrs:{span:8}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"车商尾款",prop:"car_final_pay"}},[a("el-input",{attrs:{placeholder:"请输入车商尾款(必填)"},model:{value:t.customerData.car_final_pay,callback:function(e){t.$set(t.customerData,"car_final_pay",e)},expression:"customerData.car_final_pay"}},[a("template",{slot:"append"},[t._v("元")])],2)],1)],1),t._v(" "),a("el-col",{attrs:{span:24}},[a("el-form-item",{staticClass:"postInfo-container-item",staticStyle:{width:"100%"},attrs:{"label-width":t.labelwidth,label:"备注",prop:"finance_apply_description"}},[a("el-input",{attrs:{type:"textarea",rows:3,placeholder:"( 选填 )"},model:{value:t.customerData.finance_apply_description,callback:function(e){t.$set(t.customerData,"finance_apply_description",e)},expression:"customerData.finance_apply_description"}})],1)],1)],1)],1),t._v(" "),a("div",{staticStyle:{overflow:"hidden",background:"#fff","padding-bottom":"22px","padding-right":"40px"}},[a("el-button",{staticStyle:{float:"right",width:"120px",height:"40px"},attrs:{type:"primary"},on:{click:function(e){t.submitData("customerData")}}},[t._v("提交申请")]),t._v(" "),a("el-button",{staticStyle:{float:"right",width:"120px",height:"40px","margin-right":"40px"},on:{click:function(e){t.resetForm("customerData")}}},[t._v("重置信息")])],1)])],1)],1)]):a("BasicInfo",{attrs:{ifResult:t.ifResult,maskResult:t.maskResult}})],1)},staticRenderFns:[]},k=a("VU/8")(x,I,!1,function(t){a("IEOF"),a("DT89")},"data-v-713efcfc",null);e.default=k.exports},"nt/b":function(t,e,a){(t.exports=a("FZ+f")(!1)).push([t.i,'\n@charset "UTF-8";\n.title-prompt[data-v-713efcfc] {\n position: absolute;\n right: 0px;\n font-size: 12px;\n top: 10px;\n color: #ff4949;\n}\n.createPost-container[data-v-713efcfc] {\n position: relative;\n /*来源信息公用样式*/\n /*右侧部分的内容*/\n}\n.createPost-container .createPost-main-container[data-v-713efcfc] {\n padding: 40px 10px 20px 10px;\n}\n.createPost-container .createPost-main-container .postInfo-container[data-v-713efcfc] {\n position: relative;\n margin-bottom: 10px;\n}\n.createPost-container .createPost-main-container .postInfo-container[data-v-713efcfc]:after {\n content: "";\n display: table;\n clear: both;\n}\n.createPost-container .createPost-main-container .postInfo-container .postInfo-container-item[data-v-713efcfc] {\n float: left;\n}\n.createPost-container .createPost-main-container .editor-container[data-v-713efcfc] {\n min-height: 500px;\n margin: 0 0 30px;\n}\n.createPost-container .createPost-main-container .editor-container .editor-upload-btn-container[data-v-713efcfc] {\n text-align: right;\n margin-right: 10px;\n}\n.createPost-container .createPost-main-container .editor-container .editor-upload-btn-container .editor-upload-btn[data-v-713efcfc] {\n display: inline-block;\n}\n.createPost-container .word-counter[data-v-713efcfc] {\n width: 40px;\n position: absolute;\n right: -10px;\n top: 0px;\n}\n.createPost-container .pl[data-v-713efcfc] {\n width: 100%;\n padding-left: 10px;\n padding-right: 10px;\n font-size: 14px;\n color: #4A4A4A;\n margin-bottom: 22px;\n position: relative;\n}\n.createPost-container .pl span[data-v-713efcfc] {\n display: inline-block;\n}\n.createPost-container .pl .title[data-v-713efcfc] {\n position: absolute;\n}\n.createPost-container .pl .text[data-v-713efcfc] {\n /*\tmargin-left: 95px;*/\n}\n.createPost-container .right-box[data-v-713efcfc] {\n padding-left: 50px;\n position: relative;\n}\n.createPost-container .right-box p[data-v-713efcfc] {\n margin: 0;\n padding: 0;\n text-align: right;\n}\n.createPost-container .right-box .el-steps[data-v-713efcfc] {\n margin-left: 110px;\n}\n.createPost-container .right-box .el-times[data-v-713efcfc] {\n width: 100px;\n position: absolute;\n top: 0;\n left: 0px;\n}\n.createPost-container .right-box .time[data-v-713efcfc] {\n height: 127px;\n}\n.createPost-container .right-box .time-year[data-v-713efcfc] {\n font-size: 18px;\n color: #4A4A4A;\n}\n.createPost-container .right-box .time-hour[data-v-713efcfc] {\n margin-top: 10px;\n}\n.createPost-container .createPost-container .createPost-container-one[data-v-713efcfc] {\n padding-top: 10px;\n}\n.createPost-container .postInfo-container-one .el-form-item[data-v-713efcfc] {\n margin-bottom: 0px;\n}\n',""])},tqyE:function(t,e,a){(t.exports=a("FZ+f")(!1)).push([t.i,"\nbody{ background: #F5F6FA;\n}\n.createPost-container .createPost-main-container .postInfo-container-one{\n \tbackground: #fff;\n}\n.el-col .el-col-one{\n \tbackground: #fff;\n}\n.postInfo-container-one{\n \tbackground: #fff;\n}\n.el-form-item__label{\n \ttext-align: left;\n}\n.applyremittance .postInfo-container-item .el-form-item__content{\n \tline-height: 36px;\n \tmargin-bottom: 20px;\n \tcolor:#4A4A4A;\n}\n.createPost-container-one .postInfo-container .el-form-item{\n \tmargin-bottom: 0px;\n}\n.postInfo-container-one .postInfo-container-item .el-form-item__label{\n \tline-height: normal;\n}\n.postInfo-container-one .postInfo-container-item .el-form-item__content{\n line-height: normal;\n \tmargin-bottom: 20px;\n \tcolor:#4A4A4A;\n}\n",""])}});
/** * @fileoverview Contains utils for manipulating server data. */ /** * Contains all Student fields. */ const STUDENT_FIELDS = [ 'id', 'firstName', 'lastName', 'birthDate', 'hobbies', 'photo' ]; /** * Converts the Student persisted into the expected GraphQL type. * * @param {Student} entity The Student from the database */ const entityToStudent = entity => STUDENT_FIELDS.reduce((acc, field) => { const value = entity[field.toLowerCase()]; acc[field] = field === 'hobbies' ? value && JSON.parse(value) : value; return acc; }, {}); module.exports = { entityToStudent };
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.MacroStore = void 0; const exceptions_1 = require("../exceptions"); class MacroStore { constructor() { this.macrosValues = {}; this.macroFormatters = []; } addMacroValue(name, value) { } escapeRegExp(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } add(macro) { if (this.macroFormatters.find(f => f.prefix === macro.prefix)) { throw new exceptions_1.MacroError(`MacroFormatter with prefix "${macro.prefix}" is already registered`); } this.macroFormatters.push(macro); } format(value) { // Values first const macroKeys = Object.keys(this.macrosValues); macroKeys.forEach(key => { console.log(`{${this.escapeRegExp(key)}}`); var re = new RegExp(`{${this.escapeRegExp(key)}}`); value = value.replace(re, this.macrosValues['är du go eller']); }); // Formatters this.macroFormatters.forEach(formatter => { const rex = new RegExp(`{${this.escapeRegExp(formatter.prefix)}:([^}]+?)}`, ''); var result = rex.exec(value); while (result) { value = value.replace(result[0], formatter.format(result[1])); result = rex.exec(value); } }); return value; } } exports.MacroStore = MacroStore;
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See http://js.arcgis.com/3.15/esri/copyright.txt and http://www.arcgis.com/apps/webappbuilder/copyright.txt for details. //>>built define("dojo/_base/declare dojo/_base/Deferred dojo/_base/lang dojo/dom-construct dojo/dom-class dojo/aspect dojo/keys dojo/query dijit/Dialog dijit/form/Select dojo/_base/lang".split(" "),function(g,h,k,c,f,l,e,m,n,p,d){return g([n],{baseClass:"jimu-coordinate-control",numberOfInputs:0,selectOptions:{},comboOptions:{},dfd:null,constructor:function(a){d.mixin(this,a);this.numberOfInputs=a.options.length;this.selectOptions=a.options},postCreate:function(){this.inherited("postCreate",arguments);this.closable= !1;this.closeButtonNode.style.display="none";"DartTheme"===this.theme&&f.add(this.containerNode,"coordinateControlDialog");this.message=c.create("div",{style:"margin-bottom: 5px"},this.containerNode,"first");this.message.innerHTML=this.numberOfInputs+" "+this.nls.multipleNotationLabel;this.comboOptions=new p({style:{width:"99%"},"aria-label":this.numberOfInputs+" "+this.nls.multipleNotationLabel},c.create("div",{},this.containerNode,"last"));this.own(l.after(this.comboOptions,"onChange",k.hitch(this, this._onComboOptionsChanged)));for(var a=0;a<this.selectOptions.length;a++)this.comboOptions.addOption({value:this.selectOptions[a].name,label:this.selectOptions[a].notationType});this.buttonDiv=c.create("div",{"class":"buttonContainer",style:"margin-top:10px;"+(window.isRTL?"text-align:left":"text-align:right")},this.containerNode,"last");this.okButton=c.create("div",{innerHTML:this.nls.applyButtonLabel,"class":"jimu-btn",role:"button",tabindex:"0","aria-label":this.nls.applyButtonLabel,onclick:d.hitch(this, function(){this.hide();this.dfd.resolve()}),onkeypress:d.hitch(this,function(b){if(b.keyCode===e.ENTER||b.keyCode===e.SPACE)this.hide(),this.dfd.resolve()})},this.buttonDiv,"first");this.cancelButton=c.create("div",{innerHTML:this.nls.cancelButtonLabel,"class":"jimu-btn",style:"margin: 0 5px 0 5px",role:"button",tabindex:"0","aria-label":this.nls.cancelButtonLabel,onclick:d.hitch(this,function(){this.hide();this.dfd.cancel()}),onkeypress:d.hitch(this,function(b){if(b.keyCode===e.ENTER||b.keyCode=== e.SPACE)this.hide(),this.dfd.cancel()})},this.buttonDiv,"last")},show:function(){this.inherited("show",arguments);this.dfd=new h;var a=this._getDOMElement(".dijitSelectLabel",this.comboOptions.domNode);a&&f.add(a,"dijitSelectLabelConfirmNotation");return this.dfd},_onComboOptionsChanged:function(){var a=this._getDOMElement(".dijitSelectLabel",this.comboOptions.domNode);a&&f.add(a,"dijitSelectLabelConfirmNotation")},_getDOMElement:function(a,b){return(a=m(a,b))&&1===a.length?a[0]:null}})});
export default /* glsl */` #ifdef USE_ENVMAP #ifdef ENV_WORLDPOS vec3 cameraToFrag; if ( isOrthographic ) { cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); } else { cameraToFrag = normalize( vWorldPosition - cameraPosition ); } // Transforming Normal Vectors with the Inverse Transformation vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); #ifdef ENVMAP_MODE_REFLECTION vec3 reflectVec = reflect( cameraToFrag, worldNormal ); #else vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); #endif #else vec3 reflectVec = vReflect; #endif #ifdef ENVMAP_TYPE_CUBE vec4 envColor = textureCube( envMap, vec3( flipEnvMap * reflectVec.x, reflectVec.yz ) ); #elif defined( ENVMAP_TYPE_CUBE_UV ) vec4 envColor = textureCubeUV( envMap, reflectVec, 0.0 ); #else vec4 envColor = vec4( 0.0 ); #endif #ifdef ENVMAP_BLENDING_MULTIPLY outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_MIX ) outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); #elif defined( ENVMAP_BLENDING_ADD ) outgoingLight += envColor.xyz * specularStrength * reflectivity; #endif #endif `;
/** * Copyright 2020 Google Inc. All rights reserved. * * 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. */ import { isNode } from '../environment.js'; /* Use the global version if we're in the browser, else load the node-fetch module. */ export const getFetch = async () => { return isNode ? await import('node-fetch') : globalThis.fetch; };
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import createSagaMiddleware from 'redux-saga'; import rootReducer from './root-reducer'; import rootSaga from './root-saga'; const sagaMiddleware = createSagaMiddleware(); const promiseMiddleware = store => next => action => { if (isPromise(action.payload)) { const currentView = store.getState().viewChangeCounter; const skipTracking = action.skipTracking; action.payload.then( res => { const currentState = store.getState() if (!skipTracking && currentState.viewChangeCounter !== currentView) { return } action.payload = res; store.dispatch(action); }, error => { const currentState = store.getState() if (!skipTracking && currentState.viewChangeCounter !== currentView) { return } action.error = true; action.payload = error; store.dispatch(action); } ); return; } next(action); }; const middlewares = [thunk, promiseMiddleware, sagaMiddleware]; const bindMiddleware = middleware => { if (process.env.NODE_ENV !== 'production') { const { composeWithDevTools } = require('redux-devtools-extension'); return composeWithDevTools(applyMiddleware(...middleware)); } return applyMiddleware(...middleware); }; function isPromise(v) { return v && typeof v.then === 'function'; } const store = createStore(rootReducer, bindMiddleware(middlewares)); sagaMiddleware.run(rootSaga); export default store;
import _ from 'lodash'; import { createScopedStore } from '@stackstorm/module-store'; import flexTableReducer from '@stackstorm/module-flex-table/flex-table.reducer'; const historyReducer = (state = {}, input) => { let { filter = undefined, filters = undefined, executions = [], childExecutions = {}, groups = null, execution = undefined, } = state; state = { ...state, filter, filters, executions, childExecutions, groups, execution, }; switch (input.type) { case 'FETCH_FILTERS': { switch(input.status) { case 'success': filters = Object.keys(input.payload) .filter((key) => Array.isArray(input.payload[key]) && input.payload[key].length > 1) .map((key) => ({ key, label: key .replace(/_/g, ' ') .replace(/\w\S*/g, (word) => word.charAt(0).toUpperCase() + word.substr(1).toLowerCase()) , items: input.payload[key], })) ; break; case 'error': break; default: break; } return { ...state, filters, }; } case 'FETCH_GROUPS': { switch(input.status) { case 'success': executions = input.payload; groups = makeGroups(executions); break; case 'error': break; default: break; } return { ...state, executions, groups, }; } case 'FETCH_EXECUTION': { switch(input.status) { case 'success': execution = input.payload; break; case 'error': break; default: break; } return { ...state, execution, }; } case 'FETCH_EXECUTION_CHILDREN': { const { status, id, expanded, payload } = input; if (expanded) { switch(status) { case 'success': childExecutions = { ...childExecutions, [id]: _.sortBy(payload, 'start_timestamp'), }; break; case 'error': break; default: break; } } else { childExecutions = { ...childExecutions, }; delete childExecutions[id]; } return { ...state, childExecutions, }; } case 'CREATE_EXECUTION': { const { record } = input; if (record.parent) { if (childExecutions[record.parent]) { const index = childExecutions[record.parent].findIndex(({ id }) => id === record.id); if (index === -1) { childExecutions = { ...childExecutions, [record.parent]: _.sortBy([ ...childExecutions[record.parent], record, ], 'start_timestamp'), }; } } } else { const index = executions.findIndex(({ id }) => id === record.id); if (index === -1) { executions = _.sortBy([ record, ...executions ], 'start_timestamp'); groups = makeGroups(executions); } } return { ...state, executions, childExecutions, groups, }; } case 'UPDATE_EXECUTION': { const { record } = input; if (execution.id === record.id) { execution = record; } if (record.parent) { if (childExecutions[record.parent]) { childExecutions = { ...childExecutions, [record.parent]: [ ...childExecutions[record.parent], ], }; const index = childExecutions[record.parent].findIndex(({ id }) => id === record.id); if (index > -1) { childExecutions[record.parent][index] = record; } else { childExecutions[record.parent] = _.sortBy([ ...childExecutions[record.parent], record, ], 'start_timestamp'); } } } else { const index = executions.findIndex(({ id }) => id === record.id); if (index > -1) { executions = [ ...executions ]; executions[index] = record; groups = makeGroups(executions); } else { executions = [ record, ...executions ]; groups = makeGroups(executions); } } return { ...state, executions, childExecutions, groups, execution, }; } case 'DELETE_EXECUTION': { const { record } = input; const index = executions.findIndex(({ id }) => id === record.id); if (index > -1) { executions = executions.filter(({ id }) => id !== record.id); groups = makeGroups(executions); } for (const id in childExecutions) { const index = childExecutions[id].findIndex(({ id }) => id === record.id); if (index > -1) { childExecutions = { ...childExecutions }; childExecutions[id] = childExecutions[id].filter(({ id }) => id !== record.id); } } return { ...state, executions, childExecutions, groups, }; } case 'UPDATE_FILTER': { const { value } = input; filter = value; return { ...state, filter, }; } default: return state; } }; const reducer = (state = {}, action) => { state = flexTableReducer(state, action); state = historyReducer(state, action); return state; }; const store = createScopedStore('history', reducer); export default store; function makeGroups(executions) { const groups = _(executions) .sortBy('start_timestamp') .reverse() .groupBy((execution) => { const date = new Date(execution.start_timestamp).toDateString(); const time = new Date(date).toISOString(); return time; }) .value() ; return Object.keys(groups).map((date) => ({ date, executions: groups[date] })); }
/* * simpleWeather modified to use the darksky API * Author: Charles Lenk */ /*! simpleWeather v3.1.0 - http://simpleweatherjs.com */ (function($) { 'use strict'; function getAltTemp(unit, temp) { if(unit === 'f') { return Math.round((5.0/9.0)*(temp-32.0)); } else { return Math.round((9.0/5.0)*temp+32.0); } } function getDay(secondsFromEpoch) { let days =["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; let date = new Date(); date.setTime(secondsFromEpoch * 1000); return days[date.getDay()]; } $.extend({ simpleWeather: function(options){ options = $.extend({ location: '', unit: 'f', apiKey: '', success: function(weather){}, error: function(message){} }, options); if (!(/^(\-?\d+(\.\d+)?),\s*(\-?\d+(\.\d+)?)$/.test(options.location))) { options.error('Location invalid. Must be formatted latitude,longitude'); } let units = options.unit.toLowerCase() === 'f' ? 'us' : 'si'; let weatherUrl = 'https://api.darksky.net/forecast/' + options.apiKey + '/' + options.location + '/?units=' + units + '&exclude=minutely,hourly,alerts,flags'; $.ajax({ url: weatherUrl, jsonp: "callback", dataType: "jsonp", data: { format: "json" }, success: function(result) { if (result !== null) { let compass = ['N', 'NNE', 'NE', 'ENE', 'E', 'ESE', 'SE', 'SSE', 'S', 'SSW', 'SW', 'WSW', 'W', 'WNW', 'NW', 'NNW', 'N']; let weather = {}; weather.time = result.currently.time; weather.temp = Math.round(result.currently.temperature); weather.currently = result.currently.summary; weather.icon = result.currently.icon; weather.high = Math.round(result.daily.data[0].temperatureHigh); weather.low = Math.round(result.daily.data[0].temperatureLow); weather.humidity = result.currently.humidity; weather.visibility = result.currently.visibility; weather.sunrise = result.daily.data[0].sunriseTime; weather.sunset = result.daily.data[0].sunsetTime; weather.timezone = result.timezone; weather.summary = result.daily.summary; weather.units = { temp: options.unit.toUpperCase(), distance: options.unit === "f" ? "mi" : "km", speed: options.unit === "f" ? "mph" : "m/s", }; weather.wind = { direction: compass[Math.round(result.currently.windBearing / 22.5)], speed: Math.round(result.currently.windSpeed) }; weather.alt = { temp: getAltTemp(options.unit, weather.temp), high: getAltTemp(options.unit, weather.high), low: getAltTemp(options.unit, weather.low), unit: options.unit === 'f' ? "C" : "F" }; weather.forecast = []; for (var i = 0; i < result.daily.data.length; i++) { let forecast = {}; forecast.time = result.daily.data[i].time; forecast.high = Math.round(result.daily.data[i].temperatureHigh); forecast.low = Math.round(result.daily.data[i].temperatureLow); forecast.day = getDay(result.daily.data[i].time); forecast.icon = result.daily.data[i].icon; forecast.alt = { high: getAltTemp(options.unit, forecast.high), low: getAltTemp(options.unit, forecast.low) }; weather.forecast.push(forecast); } options.success(weather); } else { options.error('There was a problem retrieving the latest weather information.'); } } }); return this; } }); })(jQuery);
import BulkOperations from "./bulk_operations"; frappe.provide('frappe.views'); frappe.views.ListView = class ListView extends frappe.views.BaseList { static load_last_view() { const route = frappe.get_route(); const doctype = route[1]; if (route.length === 2) { // List/{doctype} => List/{doctype}/{last_view} or List const user_settings = frappe.get_user_settings(doctype); const last_view = user_settings.last_view; frappe.set_route('List', doctype, frappe.views.is_valid(last_view) ? last_view : 'List'); return true; } return false; } constructor(opts) { super(opts); this.show(); } has_permissions() { const can_read = frappe.perm.has_perm(this.doctype, 0, 'read'); return can_read; } show() { if (!this.has_permissions()) { frappe.set_route(''); frappe.msgprint(__(`Not permitted to view ${this.doctype}`)); return; } this.init().then(() => { if (frappe.route_options) { this.set_filters_from_route_options(); return; } else { this.refresh(); } }); } get view_user_settings() { return this.user_settings[this.view_name] || {}; } setup_defaults() { super.setup_defaults(); this.view_name = 'List'; // initialize with saved filters const saved_filters = this.view_user_settings.filters; if (saved_filters) { this.filters = this.validate_filters(saved_filters); } else { // filters in listview_settings const filters = (this.settings.filters || []).map(f => { if (f.length === 3) { f = [this.doctype, f[0], f[1], f[2]]; } return f; }); this.filters = filters; } // initialize with saved order by this.sort_by = this.view_user_settings.sort_by || 'modified'; this.sort_order = this.view_user_settings.sort_order || 'desc'; // build menu items this.menu_items = this.menu_items.concat(this.get_menu_items()); this.actions_menu_items = this.get_actions_menu_items(); this.patch_refresh_and_load_lib(); } on_sort_change(sort_by, sort_order) { this.sort_by = sort_by; this.sort_order = sort_order; super.on_sort_change(); } validate_filters(filters) { const valid_fields = this.meta.fields.map(df => df.fieldname); return filters .filter(f => valid_fields.includes(f[1])) .uniqBy(f => f[1]); } setup_page() { this.parent.list_view = this; super.setup_page(); } setup_page_head() { super.setup_page_head(); this.set_primary_action(); this.set_actions_menu_items(); } set_actions_menu_items() { this.actions_menu_items.map(item => { const $item = this.page.add_actions_menu_item(item.label, item.action, item.standard); if (item.class) { $item.addClass(item.class); } }); } show_restricted_list_indicator_if_applicable() { const match_rules_list = frappe.perm.get_match_rules(this.doctype); if(match_rules_list.length) { this.restricted_list = $('<button class="restricted-list form-group">Restricted</button>') .prepend('<span class="octicon octicon-lock"></span>') .click(() => this.show_restrictions(match_rules_list)) .appendTo(this.page.page_form); } } show_restrictions(match_rules_list=[]) { frappe.msgprint(frappe.render_template('list_view_permission_restrictions', { condition_list: match_rules_list }), 'Restrictions'); } set_fields() { let fields = [].concat( frappe.model.std_fields_list, this.get_fields_in_list_view(), [this.meta.title_field, this.meta.image_field], (this.settings.add_fields || []), this.meta.track_seen ? '_seen' : null, this.sort_by, 'enabled', 'disabled' ); fields.forEach(f => this._add_field(f)); } patch_refresh_and_load_lib() { // throttle refresh for 1s this.refresh = this.refresh.bind(this); this.refresh = frappe.utils.throttle(this.refresh, 1000); this.load_lib = new Promise(resolve => { if (this.required_libs) { frappe.require(this.required_libs, resolve); } else { resolve(); } }); // call refresh every 5 minutes const interval = 5 * 60 * 1000; setInterval(() => { // don't call if route is different if (frappe.get_route_str() === this.page_name) { this.refresh(); } }, interval); } set_primary_action() { if (this.can_create) { this.page.set_primary_action(__('New'), () => { this.make_new_doc(); }, 'octicon octicon-plus'); } else { this.page.clear_primary_action(); } } make_new_doc() { const doctype = this.doctype; const options = {}; this.filter_area.get().forEach(f => { if (f[2] === "=" && frappe.model.is_non_std_field(f[1])) { options[f[1]] = f[3]; } }); frappe.new_doc(doctype, options); } setup_view() { this.setup_columns(); this.render_header(); this.render_skeleton(); this.setup_events(); this.settings.onload && this.settings.onload(this); this.show_restricted_list_indicator_if_applicable(); } setup_freeze_area() { this.$freeze = $(`<div class="freeze flex justify-center align-center text-muted">${__('Loading')}...</div>`) .hide(); this.$result.append(this.$freeze); } setup_columns() { // setup columns for list view this.columns = []; const get_df = frappe.meta.get_docfield.bind(null, this.doctype); // 1st column: title_field or name if (this.meta.title_field) { this.columns.push({ type: 'Subject', df: get_df(this.meta.title_field) }); } else { this.columns.push({ type: 'Subject', df: { label: __('Name'), fieldname: 'name' } }); } // 2nd column: Status indicator if (frappe.has_indicator(this.doctype)) { // indicator this.columns.push({ type: 'Status' }); } const fields_in_list_view = this.get_fields_in_list_view(); // Add rest from in_list_view docfields this.columns = this.columns.concat( fields_in_list_view .filter(df => { if (frappe.has_indicator(this.doctype) && df.fieldname === 'status') { return false; } if (!df.in_list_view) { return false; } return df.fieldname !== this.meta.title_field; }) .map(df => ({ type: 'Field', df })) ); // limit to 4 columns this.columns = this.columns.slice(0, 4); } get_no_result_message() { const new_button = this.can_create ? `<p><button class="btn btn-primary btn-sm btn-new-doc"> ${__('Make a new {0}', [__(this.doctype)])} </button></p>` : ''; return `<div class="msg-box no-border"> <p>${__('No {0} found', [__(this.doctype)])}</p> ${new_button} </div>`; } freeze() { this.$result.find('.list-count').html(`<span>${__('Refreshing')}...</span>`); } get_args() { const args = super.get_args(); return Object.assign(args, { with_comment_count: true }); } toggle_result_area() { super.toggle_result_area(); this.toggle_actions_menu_button( this.$result.find('.list-row-check:checked').length > 0 ); } toggle_actions_menu_button(toggle) { if (toggle) { this.page.show_actions_menu(); this.page.clear_primary_action(); } else { this.page.hide_actions_menu(); this.set_primary_action(); } } render_header() { if (this.$result.find('.list-row-head').length === 0) { // append header once this.$result.prepend(this.get_header_html()); } } render_skeleton() { const $row = this.get_list_row_html_skeleton('<div><input type="checkbox" /></div>'); this.$result.append($row); } before_render() { this.settings.before_render && this.settings.before_render(); frappe.model.user_settings.save(this.doctype, 'last_view', this.view_name); this.save_view_user_settings({ filters: this.filter_area.get(), sort_by: this.sort_selector.sort_by, sort_order: this.sort_selector.sort_order }); } render() { this.$result.find('.list-row-container').remove(); if (this.data.length > 0) { // append rows this.$result.append( this.data.map(doc => this.get_list_row_html(doc)).join('') ); } this.on_row_checked(); this.render_count(); this.render_tags(); } render_count() { this.get_count_html() .then(html => { this.$result.find('.list-count').html(html); }); } render_tags() { const $list_rows = this.$result.find('.list-row-container'); this.data.forEach((d, i) => { let tag_html = $(`<div class='tag-row'> <div class='list-tag hidden-xs'></div> </div>`).appendTo($list_rows.get(i)); // add tags let tag_editor = new frappe.ui.TagEditor({ parent: tag_html.find('.list-tag'), frm: { doctype: this.doctype, docname: d.name }, list_sidebar: this.list_sidebar, user_tags: d._user_tags, on_change: (user_tags) => { d._user_tags = user_tags; } }); tag_editor.wrapper.on('click', '.tagit-label', (e) => { const $this = $(e.currentTarget); this.filter_area.add(this.doctype, '_user_tags', '=', $this.text()); }); }); } get_header_html() { const subject_field = this.columns[0].df; let subject_html = ` <input class="level-item list-check-all hidden-xs" type="checkbox" title="${__("Select All")}"> <span class="level-item list-liked-by-me"> <i class="octicon octicon-heart text-extra-muted" title="${__("Likes")}"></i> </span> <span class="level-item">${__(subject_field.label)}</span> `; const $columns = this.columns.map(col => { let classes = [ 'list-row-col ellipsis', col.type == 'Subject' ? 'list-subject level' : 'hidden-xs', frappe.model.is_numeric_field(col.df) ? 'text-right' : '' ].join(' '); return ` <div class="${classes}"> ${col.type === 'Subject' ? subject_html : ` <span>${__(col.df && col.df.label || col.type)}</span>`} </div> `; }).join(''); return this.get_header_html_skeleton($columns, '<span class="list-count"></span>'); } get_header_html_skeleton(left = '', right = '') { return ` <header class="level list-row list-row-head text-muted small"> <div class="level-left list-header-subject"> ${left} </div> <div class="level-left checkbox-actions"> <div class="level list-subject"> <input class="level-item list-check-all hidden-xs" type="checkbox" title="${__("Select All")}"> <span class="level-item list-header-meta"></span> </div> </div> <div class="level-right"> ${right} </div> </header> `; } get_left_html(doc) { return this.columns.map(col => this.get_column_html(col, doc)).join(''); } get_right_html(doc) { return this.get_meta_html(doc); } get_list_row_html(doc) { return this.get_list_row_html_skeleton(this.get_left_html(doc), this.get_right_html(doc)); } get_list_row_html_skeleton(left = '', right = '') { return ` <div class="list-row-container"> <div class="level list-row small"> <div class="level-left ellipsis"> ${left} </div> <div class="level-right text-muted ellipsis"> ${right} </div> </div> </div> `; } get_column_html(col, doc) { if (col.type === 'Status') { return ` <div class="list-row-col hidden-xs ellipsis"> ${this.get_indicator_html(doc)} </div> `; } const df = col.df || {}; const label = df.label; const fieldname = df.fieldname; const value = doc[fieldname] || ''; // listview_setting formatter const formatters = this.settings.formatters; const format = () => { if (formatters && formatters[fieldname]) { return formatters[fieldname](value, df, doc); } else if (df.fieldtype === 'Code') { return value; } else { return frappe.format(value, df, null, doc); } }; const field_html = () => { let html; const _value = typeof value === 'string' ? frappe.utils.escape_html(value) : value; if (df.fieldtype === 'Image') { html = df.options ? `<img src="${doc[df.options]}" style="max-height: 30px; max-width: 100%;">` : `<div class="missing-image small"> <span class="octicon octicon-circle-slash"></span> </div>`; } else if (df.fieldtype === 'Select') { html = `<span class="filterable indicator ${frappe.utils.guess_colour(_value)} ellipsis" data-filter="${fieldname},=,${value}"> ${__(_value)} </span>`; } else if (df.fieldtype === 'Link') { html = `<a class="filterable text-muted ellipsis" data-filter="${fieldname},=,${value}"> ${_value} </a>`; } else if (df.fieldtype === 'Text Editor') { html = `<span class="text-muted ellipsis"> ${_value} </span>`; } else { html = `<a class="filterable text-muted ellipsis" data-filter="${fieldname},=,${value}"> ${format()} </a>`; } return `<span class="ellipsis" title="${__(label) + ': ' + _value}"> ${html} </span>`; }; const class_map = { Subject: 'list-subject level', Field: 'hidden-xs' }; const css_class = [ 'list-row-col ellipsis', class_map[col.type], frappe.model.is_numeric_field(df) ? 'text-right' : '' ].join(' '); const html_map = { Subject: this.get_subject_html(doc), Field: field_html() }; const column_html = html_map[col.type]; return ` <div class="${css_class}"> ${column_html} </div> `; } get_meta_html(doc) { let html = ''; if (doc[this.meta.title_field || ''] !== doc.name) { html += ` <div class="level-item hidden-xs hidden-sm ellipsis"> <a class="text-muted ellipsis" href="${this.get_form_link(doc)}"> ${doc.name} </a> </div> `; } const modified = comment_when(doc.modified, true); const last_assignee = JSON.parse(doc._assign || '[]').slice(-1)[0]; const assigned_to = last_assignee ? `<span class="filterable" data-filter="_assign,like,%${last_assignee}%"> ${frappe.avatar(last_assignee)} </span>` : `<span class="avatar avatar-small avatar-empty"></span>`; const comment_count = `<span class="${!doc._comment_count ? 'text-extra-muted' : ''} comment-count"> <i class="octicon octicon-comment-discussion"></i> ${doc._comment_count > 99 ? "99+" : doc._comment_count} </span>`; html += ` <div class="level-item hidden-xs list-row-activity"> ${modified} ${assigned_to} ${comment_count} </div> <div class="level-item visible-xs text-right"> ${this.get_indicator_dot(doc)} </div> `; return html; } get_count_html() { const current_count = this.data.length; return frappe.call({ type: 'GET', method: this.method, args: { doctype: this.doctype, filters: this.get_filters_for_args(), fields: [`count(${frappe.model.get_full_column_name('name', this.doctype)}) as total_count`] } }).then(r => { const count = r.message.values[0][0] || current_count; const str = __('{0} of {1}', [current_count, count]); const html = `<span>${str}</span>`; return html; }); } get_form_link(doc) { const docname = doc.name.match(/[%'"]/) ? encodeURIComponent(doc.name) : doc.name; return '#Form/' + this.doctype + '/' + docname; } get_subject_html(doc) { let user = frappe.session.user; let subject_field = this.columns[0].df; let value = doc[subject_field.fieldname] || doc.name; let subject = strip_html(value); let escaped_subject = frappe.utils.escape_html(value); const liked_by = JSON.parse(doc._liked_by || '[]'); let heart_class = liked_by.includes(user) ? 'liked-by' : 'text-extra-muted not-liked'; const seen = JSON.parse(doc._seen || '[]') .includes(user) ? '' : 'bold'; let subject_html = ` <input class="level-item list-row-checkbox hidden-xs" type="checkbox" data-name="${doc.name}"> <span class="level-item" style="margin-bottom: 1px;"> <i class="octicon octicon-heart like-action ${heart_class}" data-name="${doc.name}" data-doctype="${this.doctype}" data-liked-by="${encodeURI(doc._liked_by) || '[]'}" > </i> <span class="likes-count"> ${ liked_by.length > 99 ? __("99") + '+' : __(liked_by.length || '')} </span> </span> <span class="level-item ${seen} ellipsis" title="${escaped_subject}"> <a class="ellipsis" href="${this.get_form_link(doc)}" title="${escaped_subject}"> ${subject} </a> </span> `; return subject_html; } get_indicator_html(doc) { const indicator = frappe.get_indicator(doc, this.doctype); if (indicator) { return `<span class="indicator ${indicator[1]} filterable" data-filter='${indicator[2]}'> ${__(indicator[0])} <span>`; } return ''; } get_indicator_dot(doc) { const indicator = frappe.get_indicator(doc, this.doctype); if (!indicator) return ''; return `<span class='indicator ${indicator[1]}' title='${__(indicator[0])}'></span>`; } setup_events() { this.setup_filterable(); this.setup_list_click(); this.setup_tag_event(); this.setup_new_doc_event(); this.setup_check_events(); this.setup_like(); this.setup_realtime_updates(); } setup_filterable() { // filterable events this.$result.on('click', '.filterable', e => { if (e.metaKey || e.ctrlKey) return; e.stopPropagation(); const $this = $(e.currentTarget); const filters = $this.attr('data-filter').split('|'); const filters_to_apply = filters.map(f => { f = f.split(','); if (f[2] === 'Today') { f[2] = frappe.datetime.get_today(); } else if (f[2] == 'User') { f[2] = frappe.session.user; } return [this.doctype, f[0], f[1], f.slice(2).join(',')]; }); this.filter_area.add(filters_to_apply); }); } setup_list_click() { this.$result.on('click', '.list-row', (e) => { const $target = $(e.target); // tick checkbox if Ctrl/Meta key is pressed if (e.ctrlKey || e.metaKey && !$target.is('a')) { const $list_row = $(e.currentTarget); const $check = $list_row.find('.list-row-checkbox'); $check.prop('checked', !$check.prop('checked')); e.preventDefault(); this.on_row_checked(); return; } // don't open form when checkbox, like, filterable are clicked if ($target.hasClass('filterable') || $target.hasClass('octicon-heart') || $target.is(':checkbox') || $target.is('a')) { return; } // open form const $row = $(e.currentTarget); const link = $row.find('.list-subject a').get(0); if (link) { window.location.href = link.href; return false; } }); } setup_check_events() { this.$result.on('change', 'input[type=checkbox]', e => { const $target = $(e.currentTarget); if ($target.is('.list-header-subject .list-check-all')) { const $check = this.$result.find('.checkbox-actions .list-check-all'); $check.prop('checked', $target.prop('checked')); $check.trigger('change'); } else if ($target.is('.checkbox-actions .list-check-all')) { const $check = this.$result.find('.list-header-subject .list-check-all'); $check.prop('checked', $target.prop('checked')); this.$result.find('.list-row-checkbox') .prop('checked', $target.prop('checked')); } this.on_row_checked(); }); this.$result.on('click', '.list-row-checkbox', e => { const $target = $(e.currentTarget); // shift select checkboxes if (e.shiftKey && this.$checkbox_cursor && !$target.is(this.$checkbox_cursor)) { const name_1 = this.$checkbox_cursor.data().name; const name_2 = $target.data().name; const index_1 = this.data.findIndex(d => d.name === name_1); const index_2 = this.data.findIndex(d => d.name === name_2); let [min_index, max_index] = [index_1, index_2]; if (min_index > max_index) { [min_index, max_index] = [max_index, min_index]; } let docnames = this.data.slice(min_index + 1, max_index).map(d => d.name); const selector = docnames.map(name => `.list-row-checkbox[data-name="${name}"]`).join(','); this.$result.find(selector).prop('checked', true); } this.$checkbox_cursor = $target; }); } setup_like() { this.$result.on('click', '.like-action', frappe.ui.click_toggle_like); this.$result.on('click', '.list-liked-by-me', e => { const $this = $(e.currentTarget); $this.toggleClass('active'); if ($this.hasClass('active')) { this.filter_area.add(this.doctype, '_liked_by', 'like', '%' + frappe.session.user + '%'); } else { this.filter_area.remove('_liked_by'); } }); frappe.ui.setup_like_popover(this.$result, '.liked-by'); } setup_new_doc_event() { this.$no_result.find('.btn-new-doc').click(() => this.make_new_doc()); } setup_tag_event() { this.list_sidebar.parent.on('click', '.list-tag-preview', () => { this.toggle_tags(); }); } setup_realtime_updates() { frappe.realtime.on('list_update', data => { const { doctype, name } = data; if (doctype !== this.doctype) return; // filters to get only the doc with this name const call_args = this.get_call_args(); call_args.args.filters.push([this.doctype, 'name', '=', name]); call_args.args.start = 0; frappe.call(call_args) .then(({ message }) => { if (!message) return; const data = frappe.utils.dict(message.keys, message.values); if (!(data && data.length)) return; const datum = data[0]; const index = this.data.findIndex(d => d.name === datum.name); if (index === -1) { // append new data this.data.push(datum); } else { // update this data in place this.data[index] = datum; } this.data.sort((a, b) => { const a_value = a[this.sort_by] || ''; const b_value = b[this.sort_by] || ''; let return_value = 0; if (a_value > b_value) { return_value = 1; } if (b_value > a_value) { return_value = -1; } if (this.sort_order === 'desc') { return_value = -return_value; } return return_value; }); this.render(); }); }); } on_row_checked() { this.$list_head_subject = this.$list_head_subject || this.$result.find('header .list-header-subject'); this.$checkbox_actions = this.$checkbox_actions || this.$result.find('header .checkbox-actions'); this.$checks = this.$result.find('.list-row-checkbox:checked'); this.$list_head_subject.toggle(this.$checks.length === 0); this.$checkbox_actions.toggle(this.$checks.length > 0); if (this.$checks.length === 0) { this.$list_head_subject.find('.list-select-all').prop('checked', false); } else { this.$checkbox_actions.find('.list-header-meta').html( __('{0} items selected', [this.$checks.length]) ); this.$checkbox_actions.show(); this.$list_head_subject.hide(); } this.toggle_actions_menu_button(this.$checks.length > 0); } toggle_tags() { this.$result.toggleClass('tags-shown'); } get_checked_items(only_docnames) { const docnames = Array.from(this.$checks || []) .map(check => $(check).data().name); if (only_docnames) return docnames; return this.data.filter(d => docnames.includes(d.name)); } save_view_user_settings(obj) { return frappe.model.user_settings.save(this.doctype, this.view_name, obj); } on_update() { } get_menu_items() { const doctype = this.doctype; const items = []; if (frappe.model.can_import(doctype)) { items.push({ label: __('Import'), action: () => frappe.set_route('List', 'Data Import', { reference_doctype: doctype }), standard: true }); } if (frappe.model.can_set_user_permissions(doctype)) { items.push({ label: __('User Permissions'), action: () => frappe.set_route('List', 'User Permission', { allow: doctype }), standard: true }); } if (frappe.user_roles.includes('System Manager')) { items.push({ label: __('Role Permissions Manager'), action: () => frappe.set_route('permission-manager', { doctype }), standard: true }); items.push({ label: __('Customize'), action: () => frappe.set_route('Form', 'Customize Form', { doc_type: doctype }), standard: true }); } items.push({ label: __('Toggle Sidebar'), action: () => this.toggle_side_bar(), standard: true }); // add to desktop items.push({ label: __('Add to Desktop'), action: () => frappe.add_to_desktop(doctype, doctype), standard: true }); if (frappe.user.has_role('System Manager') && frappe.boot.developer_mode === 1) { // edit doctype items.push({ label: __('Edit DocType'), action: () => frappe.set_route('Form', 'DocType', doctype), standard: true }); } return items; } get_actions_menu_items() { const doctype = this.doctype; const actions_menu_items = []; const bulk_operations = new BulkOperations({ doctype: this.doctype }); const is_field_editable = (field_doc) => { return field_doc.fieldname && frappe.model.is_value_type(field_doc) && field_doc.fieldtype !== 'Read Only' && !field_doc.hidden && !field_doc.read_only; }; const has_editable_fields = (doctype) => { return frappe.meta.get_docfields(doctype).some(field_doc => is_field_editable(field_doc)); }; const has_submit_permission = (doctype) => { return frappe.perm.has_perm(doctype, 0, 'submit'); }; // utility const bulk_assignment = () => { return { label: __('Assign To'), action: () => bulk_operations.assign(this.get_checked_items(true), this.refresh), standard: true }; }; const bulk_printing = () => { return { label: __('Print'), action: () => bulk_operations.print(this.get_checked_items()), standard: true }; }; const bulk_delete = () => { return { label: __('Delete'), action: () => { const docnames = this.get_checked_items(true); frappe.confirm(__('Delete {0} items permanently?', [docnames.length]), () => bulk_operations.delete(docnames, this.refresh)); }, standard: true, }; }; const bulk_cancel = () => { return { label: __('Cancel'), action: () => { const docnames = this.get_checked_items(true); if (docnames.length > 0) { frappe.confirm(__('Cancel {0} documents?', [docnames.length]), () => bulk_operations.submit_or_cancel(docnames, 'cancel', this.refresh)); } }, standard: true }; }; const bulk_submit = () => { return { label: __('Submit'), action: () => { const docnames = this.get_checked_items(true); if (docnames.length > 0) { frappe.confirm(__('Submit {0} documents?', [docnames.length]), () => bulk_operations.submit_or_cancel(docnames, 'submit', this.refresh)); } }, standard: true }; }; const bulk_edit = () => { return { label: __('Edit'), action: () => { let field_mappings = {}; frappe.meta.get_docfields(doctype).forEach(field_doc => { if (is_field_editable(field_doc)) { field_mappings[field_doc.label] = Object.assign({}, field_doc); } }); const docnames = this.get_checked_items(true); bulk_operations.edit(docnames, field_mappings, this.refresh); }, standard: true }; }; // bulk edit if (has_editable_fields(doctype)) { actions_menu_items.push(bulk_edit()); } // bulk assignment actions_menu_items.push(bulk_assignment()); // bulk printing if (frappe.model.can_print(doctype)) { actions_menu_items.push(bulk_printing()); } // Bulk submit if (frappe.model.is_submittable(doctype) && has_submit_permission(doctype)) { actions_menu_items.push(bulk_submit()); } // Bulk cancel if (frappe.model.can_cancel(doctype)) { actions_menu_items.push(bulk_cancel()); } // bulk delete if (frappe.model.can_delete(doctype)) { actions_menu_items.push(bulk_delete()); } return actions_menu_items; } set_filters_from_route_options() { const filters = []; for (let field in frappe.route_options) { var value = frappe.route_options[field]; var doctype = null; // if `Child DocType.fieldname` if (field.includes('.')) { doctype = field.split('.')[0]; field = field.split('.')[1]; } // find the table in which the key exists // for example the filter could be {"item_code": "X"} // where item_code is in the child table. // we can search all tables for mapping the doctype if (!doctype) { doctype = frappe.meta.get_doctype_for_field(this.doctype, field); } if (doctype) { if ($.isArray(value)) { filters.push([doctype, field, value[0], value[1]]); } else { filters.push([doctype, field, "=", value]); } } } frappe.route_options = null; this.filter_area.clear(false) .then(() => { this.filter_area.add(filters); }); } static trigger_list_update(data) { const doctype = data.doctype; if (!doctype) return; frappe.provide('frappe.views.trees'); // refresh tree view if (frappe.views.trees[doctype]) { frappe.views.trees[doctype].tree.refresh(); return; } // refresh list view const page_name = frappe.get_route_str(); const list_view = frappe.views.list_view[page_name]; list_view && list_view.on_update(data); } }; $(document).on('save', (event, doc) => { frappe.views.ListView.trigger_list_update(doc); });
/* */ "format cjs"; /** * @license * Copyright 2016 Google Inc. All Rights Reserved. * * 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. */ import MDCComponent from '@material/base/component'; import {getTransformPropertyName} from './util'; import {MDCMenuFoundation, AnchorMargin} from './foundation'; import {Corner, CornerBit} from './constants'; /** * @extends MDCComponent<!MDCMenuFoundation> */ class MDCMenu extends MDCComponent { /** @param {...?} args */ constructor(...args) { super(...args); /** @private {!Element} */ this.previousFocus_; } /** * @param {!Element} root * @return {!MDCMenu} */ static attachTo(root) { return new MDCMenu(root); } /** @return {boolean} */ get open() { return this.foundation_.isOpen(); } /** @param {boolean} value */ set open(value) { if (value) { this.foundation_.open(); } else { this.foundation_.close(); } } /** @param {{focusIndex: ?number}=} options */ show({focusIndex = null} = {}) { this.foundation_.open({focusIndex: focusIndex}); } hide() { this.foundation_.close(); } /** * @param {Corner} corner Default anchor corner alignment of top-left * menu corner. */ setAnchorCorner(corner) { this.foundation_.setAnchorCorner(corner); } /** * @param {AnchorMargin} margin */ setAnchorMargin(margin) { this.foundation_.setAnchorMargin(margin); } /** * Return the item container element inside the component. * @return {?Element} */ get itemsContainer_() { return this.root_.querySelector(MDCMenuFoundation.strings.ITEMS_SELECTOR); } /** * Return the items within the menu. Note that this only contains the set of elements within * the items container that are proper list items, and not supplemental / presentational DOM * elements. * @return {!Array<!Element>} */ get items() { const {itemsContainer_: itemsContainer} = this; return [].slice.call(itemsContainer.querySelectorAll('.mdc-list-item[role]')); } /** * Return the item within the menu that is selected. * @param {number} index * @return {?Element} */ getOptionByIndex(index) { const items = this.items; if (index < items.length) { return this.items[index]; } else { return null; } } /** @param {number} index */ set selectedItemIndex(index) { this.foundation_.setSelectedIndex(index); } /** @return {number} */ get selectedItemIndex() { return this.foundation_.getSelectedIndex(); } /** @param {!boolean} rememberSelection */ set rememberSelection(rememberSelection) { this.foundation_.setRememberSelection(rememberSelection); } /** @param {boolean} quickOpen */ set quickOpen(quickOpen) { this.foundation_.setQuickOpen(quickOpen); } /** @return {!MDCMenuFoundation} */ getDefaultFoundation() { return new MDCMenuFoundation({ addClass: (className) => this.root_.classList.add(className), removeClass: (className) => this.root_.classList.remove(className), hasClass: (className) => this.root_.classList.contains(className), hasNecessaryDom: () => Boolean(this.itemsContainer_), getAttributeForEventTarget: (target, attributeName) => target.getAttribute(attributeName), getInnerDimensions: () => { const {itemsContainer_: itemsContainer} = this; return {width: itemsContainer.offsetWidth, height: itemsContainer.offsetHeight}; }, hasAnchor: () => this.root_.parentElement && this.root_.parentElement.classList.contains('mdc-menu-anchor'), getAnchorDimensions: () => this.root_.parentElement.getBoundingClientRect(), getWindowDimensions: () => { return {width: window.innerWidth, height: window.innerHeight}; }, getNumberOfItems: () => this.items.length, registerInteractionHandler: (type, handler) => this.root_.addEventListener(type, handler), deregisterInteractionHandler: (type, handler) => this.root_.removeEventListener(type, handler), registerBodyClickHandler: (handler) => document.body.addEventListener('click', handler), deregisterBodyClickHandler: (handler) => document.body.removeEventListener('click', handler), getIndexForEventTarget: (target) => this.items.indexOf(target), notifySelected: (evtData) => this.emit(MDCMenuFoundation.strings.SELECTED_EVENT, { index: evtData.index, item: this.items[evtData.index], }), notifyCancel: () => this.emit(MDCMenuFoundation.strings.CANCEL_EVENT, {}), saveFocus: () => { this.previousFocus_ = document.activeElement; }, restoreFocus: () => { if (this.previousFocus_) { this.previousFocus_.focus(); } }, isFocused: () => document.activeElement === this.root_, focus: () => this.root_.focus(), getFocusedItemIndex: () => this.items.indexOf(document.activeElement), focusItemAtIndex: (index) => this.items[index].focus(), isRtl: () => getComputedStyle(this.root_).getPropertyValue('direction') === 'rtl', setTransformOrigin: (origin) => { this.root_.style[`${getTransformPropertyName(window)}-origin`] = origin; }, setPosition: (position) => { this.root_.style.left = 'left' in position ? position.left : null; this.root_.style.right = 'right' in position ? position.right : null; this.root_.style.top = 'top' in position ? position.top : null; this.root_.style.bottom = 'bottom' in position ? position.bottom : null; }, setMaxHeight: (height) => { this.root_.style.maxHeight = height; }, setAttrForOptionAtIndex: (index, attr, value) => this.items[index].setAttribute(attr, value), rmAttrForOptionAtIndex: (index, attr) => this.items[index].removeAttribute(attr), addClassForOptionAtIndex: (index, className) => this.items[index].classList.add(className), rmClassForOptionAtIndex: (index, className) => this.items[index].classList.remove(className), }); } } export {MDCMenuFoundation, MDCMenu, AnchorMargin, Corner, CornerBit};
const { Event } = require('klasa'); const { MessageEmbed } = require('discord.js'); module.exports = class extends Event { constructor(...args) { super(...args, { event: 'guildBoostRemove' }); } async run(member) { if (member.guild.settings.get('channels.log') && member.guild.settings.get('logs.events.guildBoostRemove')) await this.serverLog(member); return; } async serverLog(member) { const embed = new MessageEmbed() .setAuthor(`${member.displayName} (${member.user.tag}) `, member.user.displayAvatarURL()) .setTimestamp() .setFooter(member.guild.language.get('GUILD_LOG_BOOSTREMOVE')); const logChannel = await this.client.channels.cache.get(member.guild.settings.get('channels.log')); if (logChannel) await logChannel.send('', { disableEveryone: true, embed: embed }); return; } };
app.directive("contactForm", function() { return { restrict : "EACM", templateUrl : "./src/script/module/view/contactForm.html" }; });
require('should') const CONFIG = require('config') const setLabel = require('../../lib/label/set')(CONFIG) const { randomString, sandboxEntity } = require('../../lib/tests_utils') const language = 'fr' describe('label set', function () { this.timeout(20 * 1000) it('should be a function', done => { setLabel.should.be.a.Function() done() }) it('should rejected if not passed an entity', done => { setLabel() .catch(err => { err.message.should.equal('invalid entity') done() }) .catch(done) }) it('should rejected if not passed a language', done => { setLabel(sandboxEntity) .catch(err => { err.message.should.equal('invalid language') done() }) .catch(done) }) it('should rejected if not passed a label', done => { setLabel(sandboxEntity, language) .catch(err => { err.message.should.equal('invalid label') done() }) .catch(done) }) it('should set a label', done => { const label = `Bac à Sable (${randomString()})` setLabel(sandboxEntity, 'fr', label) .then(res => { res.success.should.equal(1) done() }) .catch(done) }) })
import styled from 'styled-components'; const Paragraph = styled.p` display: flex; justify-content: flex-start; align-items: center; margin: 0 0 24px 0; `; export default Paragraph;
"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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports._polyhedron = exports.Polyhedron = void 0; const mobius_sim_1 = require("@design-automation/mobius-sim"); const THREE = __importStar(require("three")); const chk = __importStar(require("../../../_check_types")); const _enum_1 = require("./_enum"); // ================================================================================================ /** * Creates positions in a polyhedron pattern. * \n * The five regular polyhedrons can be generated: * - Tetrahedron (4 triangular faces) * - Cube (4 square faces) * - Octahedron (8 triangular faces) * - Icosahedron (20 triangular faces) * - Dodecahedron (12 pentagon faces) * \n * The `origin` parameter specifies the centre of the polyhedron for which positions will be * generated. The origin can be specified as either a |coordinate| or a |plane|. If a coordinate * is given, then a plane will be automatically generated, aligned with the global XY plane. * \n * The positions will be generated for a polyhedron aligned with the origin XY plane. * So if the origin plane is rotated, then the polyhedron will also be rotated. * \n * The `radius` parameter specifies the size of the polyhedron. * All positions that are generated are projected onto the surface of a sphere, * with the specified `radius`. * \n * The faces of the regular polyhedron can be further subdivided by specifying the level of * `detail`. (When subdivided, it will no longer be regular polyhedrons.) * \n * For tetrahedrons, octahedrons, and icosahedrons, the `detail` subdivides as follows: * - Detail = 0: No subdivision * - Detail = 1: Each triangle edge is subdivided into two edges. * - Detail = 2: Each triangle edge is subdivided into three edges. * - etc * \n * Cubes and dodecahedrons do not have triangular faces. So in these cases, the first level of * `detail` converts each non-triangular face into triangles by adding a position at the centre of * the face. The `detail` subdivides as follows: * - Detail= 0: No subdivision. * - Detail = 1: Convert non-triangular faces into triangles. * - Detail = 2: Each triangle edge is subdivided into two edges. * - Detail = 3: Each triangle edge is subdivided into three edges. * - etc * \n * The positions can either be returned as a flat list or as nested lists. * The nested lists represent the faces of the polyhedron. * However, note that only the positions are returned. * If you want to have polygon faces, you need to generate polygons from the positions. * \n * For example, calling the function with `detail = 0` and `method = 'flat_tetra'`, * will result in the following positions: * ``` * posis = ["ps0", "ps1", "ps2", "ps3"] * ``` * If you change the method to `method = 'face_tetra'`, then you will get the following nested lists. * ``` * posis = [ * ["ps2", "ps1", "ps0"], * ["ps0", "ps3", "ps2"], * ["ps1", "ps3", "ps0"], * ["ps2", "ps3", "ps1"] * ] * ``` * Notice that the number of positions is the same in both cases * (i.e. in both cases there are 4 positions: 'ps0', 'ps1', 'ps2', 'ps3'). * When `face_tetra` is selected selected, the positions are organised into 4 lists, * representing the 4 faces of the tetrahedron. * \n * The nested lists can be passed to the `make.Polygon` function in order to generated polygonal faces. * Here is an example: * \n * ``` * posis = pattern.Polyhedron(XY, 10, 0, 'face_tetra') * pgons = make.Polygon(posis) * ``` * \n * ![Tetrahedron with triangular faces](assets/typedoc-json/docMDimgs/polyhedron_tetra.png) * \n * @param __model__ * @param origin A |coordinate| or a |plane|, specifying the origin of the polyhedron. * If a coordinate is given, then the plane is assumed to be aligned with the global XY plane. * @param radius The radius of the polyhedron. * @param detail The level of detail for the polyhedron. * @param method Enum: The Type of polyhedron to generate. * @returns Entities, a list of positions. * @example `posis = pattern.Polyhedron(XY, 20, 0, 'face_tetra')` * @example_info Creates positions in a regular tetrahedron pattern, with a radius of 20. The * positions are returned as nested lists, where each list contains the positions for one face. */ function Polyhedron(__model__, origin, radius, detail, method) { // --- Error Check --- if (__model__.debug) { const fn_name = 'pattern.Polyhedron'; chk.checkArgs(fn_name, 'origin', origin, [chk.isXYZ, chk.isPln]); chk.checkArgs(fn_name, 'radius', radius, [chk.isNum]); chk.checkArgs(fn_name, 'detail', detail, [chk.isInt]); if (detail > 6) { throw new Error('pattern.Polyhedron: The "detail" argument is too high, the maximum is 6.'); } } // --- Error Check --- // create the matrix one time let matrix = null; const origin_is_plane = (0, mobius_sim_1.getArrDepth)(origin) === 2; if (origin_is_plane) { matrix = (0, mobius_sim_1.xfromSourceTargetMatrix)(mobius_sim_1.XYPLANE, origin); } else { matrix = new THREE.Matrix4(); matrix.makeTranslation(...origin); } // make polyhedron posis const posis_i = _polyhedron(__model__, matrix, radius, detail, method); return (0, mobius_sim_1.idsMakeFromIdxs)(mobius_sim_1.EEntType.POSI, posis_i); } exports.Polyhedron = Polyhedron; // create the polyhedron function _polyhedron(__model__, matrix, radius, detail, method) { // create the posis let xyzs; let faces; switch (method) { case _enum_1._EPolyhedronMethod.FLAT_TETRA: case _enum_1._EPolyhedronMethod.FACE_TETRA: [xyzs, faces] = _polyhedronCreate(_polyhedronTetra(), radius, detail); break; case _enum_1._EPolyhedronMethod.FLAT_CUBE: case _enum_1._EPolyhedronMethod.FACE_CUBE: [xyzs, faces] = _polyhedronCreate(_polyhedronCube(), radius, detail); break; case _enum_1._EPolyhedronMethod.FLAT_OCTA: case _enum_1._EPolyhedronMethod.FACE_OCTA: [xyzs, faces] = _polyhedronCreate(_polyhedronOcta(), radius, detail); break; case _enum_1._EPolyhedronMethod.FLAT_ICOSA: case _enum_1._EPolyhedronMethod.FACE_ICOSA: [xyzs, faces] = _polyhedronCreate(_polyhedronIcosa(), radius, detail); break; case _enum_1._EPolyhedronMethod.FLAT_DODECA: case _enum_1._EPolyhedronMethod.FACE_DODECA: [xyzs, faces] = _polyhedronCreate(_polyhedronDodeca(), radius, detail); break; default: throw new Error('pattern.Polyhedron: method not recognised.'); } // make posis const posis_i = []; for (const xyz of xyzs) { const posi_i = __model__.modeldata.geom.add.addPosi(); const xyz_xform = (0, mobius_sim_1.multMatrix)(xyz, matrix); __model__.modeldata.attribs.posis.setPosiCoords(posi_i, xyz_xform); posis_i.push(posi_i); } // if the method is flat, then we are done, return the posis switch (method) { case _enum_1._EPolyhedronMethod.FLAT_TETRA: case _enum_1._EPolyhedronMethod.FLAT_CUBE: case _enum_1._EPolyhedronMethod.FLAT_OCTA: case _enum_1._EPolyhedronMethod.FLAT_ICOSA: case _enum_1._EPolyhedronMethod.FLAT_DODECA: return posis_i; } // if we want faces, then make lists of posis for each face const faces_posis_i = []; for (const face of faces) { const face_posis_i = []; for (const i of face) { face_posis_i.push(posis_i[i]); } faces_posis_i.push(face_posis_i); } return faces_posis_i; } exports._polyhedron = _polyhedron; // Create a tetrahedron function _polyhedronTetra() { // copied from threejs const xyzs = [ [1, 1, 1], [-1, -1, 1], [-1, 1, -1], [1, -1, -1] ]; const faces = [ [2, 1, 0], [0, 3, 2], [1, 3, 0], [2, 3, 1] ]; return [xyzs, faces]; } // Create a cube function _polyhedronCube() { const xyzs = [ [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1], [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1], ]; const faces = [ [0, 1, 2, 3], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7], [7, 6, 5, 4] ]; return [xyzs, faces]; } // Create a Octahedron function _polyhedronOcta() { // copied from threejs const xyzs = [ [1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1] ]; const faces = [ [0, 2, 4], [0, 4, 3], [0, 3, 5], [0, 5, 2], [1, 2, 5], [1, 5, 3], [1, 3, 4], [1, 4, 2] ]; return [xyzs, faces]; } // Create a Icosahedron function _polyhedronIcosa() { // copied from threejs const t = (1 + Math.sqrt(5)) / 2; const xyzs = [ [-1, t, 0], [1, t, 0], [-1, -t, 0], [1, -t, 0], [0, -1, t], [0, 1, t], [0, -1, -t], [0, 1, -t], [t, 0, -1], [t, 0, 1], [-t, 0, -1], [-t, 0, 1] ]; const faces = [ [0, 11, 5], [0, 5, 1], [0, 1, 7], [0, 7, 10], [0, 10, 11], [1, 5, 9], [5, 11, 4], [11, 10, 2], [10, 7, 6], [7, 1, 8], [3, 9, 4], [3, 4, 2], [3, 2, 6], [3, 6, 8], [3, 8, 9], [4, 9, 5], [2, 4, 11], [6, 2, 10], [8, 6, 7], [9, 8, 1] ]; return [xyzs, faces]; } // Create a Dodecahedron function _polyhedronDodeca() { // copied from threejs const t = (1 + Math.sqrt(5)) / 2; const r = 1 / t; const xyzs = [ // (±1, ±1, ±1) [-1, -1, -1], [-1, -1, 1], [-1, 1, -1], [-1, 1, 1], [1, -1, -1], [1, -1, 1], [1, 1, -1], [1, 1, 1], // (0, ±1/φ, ±φ) [0, -r, -t], [0, -r, t], [0, r, -t], [0, r, t], // (±1/φ, ±φ, 0) [-r, -t, 0], [-r, t, 0], [r, -t, 0], [r, t, 0], // (±φ, 0, ±1/φ) [-t, 0, -r], [t, 0, -r], [-t, 0, r], [t, 0, r] ]; const faces = [ // [3, 11, 7], [3, 7, 15], [3, 15, 13], // [7, 19, 17], [7, 17, 6], [7, 6, 15], // [17, 4, 8], [17, 8, 10], [17, 10, 6], // [8, 0, 16], [8, 16, 2], [8, 2, 10], // [0, 12, 1], [0, 1, 18], [0, 18, 16], // [6, 10, 2], [6, 2, 13], [6, 13, 15], // [2, 16, 18], [2, 18, 3], [2, 3, 13], // [18, 1, 9], [18, 9, 11], [18, 11, 3], // [4, 14, 12], [4, 12, 0], [4, 0, 8], // [11, 9, 5], [11, 5, 19], [11, 19, 7], // [19, 5, 14], [19, 14, 4], [19, 4, 17], // [1, 12, 14], [1, 14, 5], [1, 5, 9] [3, 11, 7, 15, 13], [7, 19, 17, 6, 15], [17, 4, 8, 10, 6], [8, 0, 16, 2, 10], [0, 12, 1, 18, 16], [6, 10, 2, 13, 15], [2, 16, 18, 3, 13], [18, 1, 9, 11, 3], [4, 14, 12, 0, 8], [11, 9, 5, 19, 7], [19, 5, 14, 4, 17], [1, 12, 14, 5, 9] ]; return [xyzs, faces]; } // Subdivide and apply radius function _polyhedronCreate(xyzs_faces, radius, detail) { const xyzs = xyzs_faces[0]; const faces = xyzs_faces[1]; // subdiv const [new_xyzs, new_faces] = _polyhedronSubDdiv(xyzs, faces, detail); // apply radius _polyhedronApplyRadiusXyzs(new_xyzs, radius); // return return [new_xyzs, new_faces]; } // Subdiv all faces function _polyhedronSubDdiv(xyzs, faces, detail) { if (detail === 0) { return [xyzs, faces]; } const new_faces = []; for (const face of faces) { if (face.length > 3) { const mid = [0, 0, 0]; for (const xyz_i of face) { mid[0] = mid[0] + xyzs[xyz_i][0]; mid[1] = mid[1] + xyzs[xyz_i][1]; mid[2] = mid[2] + xyzs[xyz_i][2]; } mid[0] = mid[0] / face.length; mid[1] = mid[1] / face.length; mid[2] = mid[2] / face.length; const mid_i = xyzs.push(mid) - 1; for (let i = 0; i < face.length; i++) { const tri_face = [mid_i, face[i], face[(i + 1) % face.length]]; const subdiv_faces = _polyhedronSubDdivTriFace(xyzs, tri_face, detail - 1); subdiv_faces.map(subdiv_face => new_faces.push(subdiv_face)); } } else { const subdiv_faces = _polyhedronSubDdivTriFace(xyzs, face, detail); subdiv_faces.map(subdiv_face => new_faces.push(subdiv_face)); } } // merge xyzs const new_xyzs = _polyhedronMergeXyzs(xyzs, new_faces); // return return [new_xyzs, new_faces]; } // Subdivide one face function _polyhedronSubDdivTriFace(xyzs, face, detail) { const a = xyzs[face[0]]; const b = xyzs[face[1]]; const c = xyzs[face[2]]; const cols = detail + 1; // we use this multidimensional array as a data structure for creating the subdivision const xyzs_i = []; // construct all of the xyzs for this subdivision for (let i = 0; i <= cols; i++) { xyzs_i[i] = []; const aj = _polyhedronLerp(a, c, i / cols); const bj = _polyhedronLerp(b, c, i / cols); const rows = cols - i; for (let j = 0; j <= rows; j++) { let xyz_i; if (j === 0 && i === cols) { xyz_i = xyzs.push(aj) - 1; } else { xyz_i = xyzs.push(_polyhedronLerp(aj, bj, j / rows)) - 1; } xyzs_i[i][j] = xyz_i; } } // construct all of the tri faces const new_faces = []; for (let i = 0; i < cols; i++) { for (let j = 0; j < 2 * (cols - i) - 1; j++) { const new_face = []; const k = Math.floor(j / 2); if (j % 2 === 0) { new_face.push(xyzs_i[i][k + 1]); new_face.push(xyzs_i[i + 1][k]); new_face.push(xyzs_i[i][k]); } else { new_face.push(xyzs_i[i][k + 1]); new_face.push(xyzs_i[i + 1][k + 1]); new_face.push(xyzs_i[i + 1][k]); } new_faces.push(new_face); } } return new_faces; } function _polyhedronMergeXyzs(xyzs, faces) { // iterate over the xyzs const xyz_i_old_new_map = new Map(); const new_xyzs = []; for (let i = 0; i < xyzs.length; i++) { if (!xyz_i_old_new_map.has(i)) { const new_i = new_xyzs.push(xyzs[i]) - 1; xyz_i_old_new_map.set(i, new_i); for (let j = i + 1; j < xyzs.length; j++) { const dist_sq = Math.abs(xyzs[i][0] - xyzs[j][0]) + Math.abs(xyzs[i][1] - xyzs[j][1]) + Math.abs(xyzs[i][2] - xyzs[j][2]); if (dist_sq < 1e-6) { xyz_i_old_new_map.set(j, new_i); } } } } // update indexes for (const face of faces) { for (let i = 0; i < face.length; i++) { face[i] = xyz_i_old_new_map.get(face[i]); } } // return return new_xyzs; } function _polyhedronApplyRadiusXyzs(xyzs, radius) { // iterate over the xyzs and apply the radius to each xyz for (const xyz of xyzs) { const scale = radius / Math.sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1] + xyz[2] * xyz[2]); xyz[0] = xyz[0] * scale; xyz[1] = xyz[1] * scale; xyz[2] = xyz[2] * scale; } } function _polyhedronLerp(a, b, alpha) { // interpolate between two points return [ a[0] + (b[0] - a[0]) * alpha, a[1] + (b[1] - a[1]) * alpha, a[2] + (b[2] - a[2]) * alpha ]; } //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiUG9seWhlZHJvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9tb2R1bGVzL2Z1bmN0aW9ucy9wYXR0ZXJuL1BvbHloZWRyb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztBQUFBLDhEQVd1QztBQUN2Qyw2Q0FBK0I7QUFFL0IsMkRBQTZDO0FBQzdDLG1DQUE2QztBQUk3QyxtR0FBbUc7QUFDbkc7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O0dBbUZHO0FBQ0gsU0FBZ0IsVUFBVSxDQUFDLFNBQWtCLEVBQUUsTUFBcUIsRUFBRSxNQUFjLEVBQUUsTUFBYyxFQUM1RixNQUEwQjtJQUM5QixzQkFBc0I7SUFDdEIsSUFBSSxTQUFTLENBQUMsS0FBSyxFQUFFO1FBQ2pCLE1BQU0sT0FBTyxHQUFHLG9CQUFvQixDQUFDO1FBQ3JDLEdBQUcsQ0FBQyxTQUFTLENBQUMsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLEVBQUUsQ0FBQyxHQUFHLENBQUMsS0FBSyxFQUFFLEdBQUcsQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDO1FBQ2pFLEdBQUcsQ0FBQyxTQUFTLENBQUMsT0FBTyxFQUFFLFFBQVEsRUFBRSxNQUFNLEVBQUUsQ0FBQyxHQUFHLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQztRQUN0RCxHQUFHLENBQUMsU0FBUyxDQUFDLE9BQU8sRUFBRSxRQUFRLEVBQUUsTUFBTSxFQUFFLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUM7UUFDdEQsSUFBSSxNQUFNLEdBQUcsQ0FBQyxFQUFFO1lBQ1osTUFBTSxJQUFJLEtBQUssQ0FBQywwRUFBMEUsQ0FBQyxDQUFDO1NBQy9GO0tBQ0o7SUFDRCxzQkFBc0I7SUFDdEIsNkJBQTZCO0lBQzdCLElBQUksTUFBTSxHQUFrQixJQUFJLENBQUM7SUFDakMsTUFBTSxlQUFlLEdBQUcsSUFBQSx3QkFBVyxFQUFDLE1BQU0sQ0FBQyxLQUFLLENBQUMsQ0FBQztJQUNsRCxJQUFJLGVBQWUsRUFBRTtRQUNqQixNQUFNLEdBQUcsSUFBQSxvQ0FBdUIsRUFBQyxvQkFBTyxFQUFFLE1BQWdCLENBQUMsQ0FBQztLQUMvRDtTQUFNO1FBQ0gsTUFBTSxHQUFHLElBQUksS0FBSyxDQUFDLE9BQU8sRUFBRSxDQUFDO1FBQzdCLE1BQU0sQ0FBQyxlQUFlLENBQUMsR0FBRyxNQUFjLENBQUMsQ0FBQztLQUM3QztJQUNELHdCQUF3QjtJQUN4QixNQUFNLE9BQU8sR0FBd0IsV0FBVyxDQUFDLFNBQVMsRUFBRSxNQUFNLEVBQUUsTUFBTSxFQUFFLE1BQU0sRUFBRSxNQUFNLENBQUMsQ0FBQztJQUM1RixPQUFPLElBQUEsNEJBQWUsRUFBQyxxQkFBUSxDQUFDLElBQUksRUFBRSxPQUFPLENBQVksQ0FBQztBQUM5RCxDQUFDO0FBekJELGdDQXlCQztBQUNELHdCQUF3QjtBQUN4QixTQUFnQixXQUFXLENBQUMsU0FBa0IsRUFBRSxNQUFxQixFQUFFLE1BQWMsRUFBRSxNQUFjLEVBQ2pHLE1BQTBCO0lBQzFCLG1CQUFtQjtJQUNuQixJQUFJLElBQVksQ0FBQztJQUNqQixJQUFJLEtBQWlCLENBQUM7SUFDdEIsUUFBUSxNQUFNLEVBQUU7UUFDWixLQUFLLDBCQUFrQixDQUFDLFVBQVUsQ0FBQztRQUNuQyxLQUFLLDBCQUFrQixDQUFDLFVBQVU7WUFDOUIsQ0FBQyxJQUFJLEVBQUUsS0FBSyxDQUFDLEdBQUcsaUJBQWlCLENBQUMsZ0JBQWdCLEVBQUUsRUFBRSxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUM7WUFDdEUsTUFBTTtRQUNWLEtBQUssMEJBQWtCLENBQUMsU0FBUyxDQUFDO1FBQ2xDLEtBQUssMEJBQWtCLENBQUMsU0FBUztZQUM3QixDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsR0FBRyxpQkFBaUIsQ0FBQyxlQUFlLEVBQUUsRUFBRSxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUM7WUFDckUsTUFBTTtRQUNWLEtBQUssMEJBQWtCLENBQUMsU0FBUyxDQUFDO1FBQ2xDLEtBQUssMEJBQWtCLENBQUMsU0FBUztZQUM3QixDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsR0FBRyxpQkFBaUIsQ0FBQyxlQUFlLEVBQUUsRUFBRSxNQUFNLEVBQUUsTUFBTSxDQUFDLENBQUM7WUFDckUsTUFBTTtRQUNWLEtBQUssMEJBQWtCLENBQUMsVUFBVSxDQUFDO1FBQ25DLEtBQUssMEJBQWtCLENBQUMsVUFBVTtZQUM5QixDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsR0FBRyxpQkFBaUIsQ0FBQyxnQkFBZ0IsRUFBRSxFQUFFLE1BQU0sRUFBRSxNQUFNLENBQUMsQ0FBQztZQUN0RSxNQUFNO1FBQ1YsS0FBSywwQkFBa0IsQ0FBQyxXQUFXLENBQUM7UUFDcEMsS0FBSywwQkFBa0IsQ0FBQyxXQUFXO1lBQy9CLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxHQUFHLGlCQUFpQixDQUFDLGlCQUFpQixFQUFFLEVBQUUsTUFBTSxFQUFFLE1BQU0sQ0FBQyxDQUFDO1lBQ3ZFLE1BQU07UUFDVjtZQUNJLE1BQU0sSUFBSSxLQUFLLENBQUMsNENBQTRDLENBQUMsQ0FBQztLQUNyRTtJQUNELGFBQWE7SUFDYixNQUFNLE9BQU8sR0FBYSxFQUFFLENBQUM7SUFDN0IsS0FBSyxNQUFNLEdBQUcsSUFBSSxJQUFJLEVBQUU7UUFDcEIsTUFBTSxNQUFNLEdBQVcsU0FBUyxDQUFDLFNBQVMsQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLE9BQU8sRUFBRSxDQUFDO1FBQzlELE1BQU0sU0FBUyxHQUFTLElBQUEsdUJBQVUsRUFBQyxHQUFHLEVBQUUsTUFBTSxDQUFDLENBQUM7UUFDaEQsU0FBUyxDQUFDLFNBQVMsQ0FBQyxPQUFPLENBQUMsS0FBSyxDQUFDLGFBQWEsQ0FBQyxNQUFNLEVBQUUsU0FBUyxDQUFDLENBQUM7UUFDbkUsT0FBTyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQztLQUN4QjtJQUNELDREQUE0RDtJQUM1RCxRQUFRLE1BQU0sRUFBRTtRQUNaLEtBQUssMEJBQWtCLENBQUMsVUFBVSxDQUFDO1FBQ25DLEtBQUssMEJBQWtCLENBQUMsU0FBUyxDQUFDO1FBQ2xDLEtBQUssMEJBQWtCLENBQUMsU0FBUyxDQUFDO1FBQ2xDLEtBQUssMEJBQWtCLENBQUMsVUFBVSxDQUFDO1FBQ25DLEtBQUssMEJBQWtCLENBQUMsV0FBVztZQUMvQixPQUFPLE9BQU8sQ0FBQztLQUN0QjtJQUNELDJEQUEyRDtJQUMzRCxNQUFNLGFBQWEsR0FBZSxFQUFFLENBQUM7SUFDckMsS0FBSyxNQUFNLElBQUksSUFBSSxLQUFLLEVBQUU7UUFDdEIsTUFBTSxZQUFZLEdBQWEsRUFBRSxDQUFDO1FBQ2xDLEtBQUssTUFBTSxDQUFDLElBQUksSUFBSSxFQUFFO1lBQ2xCLFlBQVksQ0FBQyxJQUFJLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7U0FDakM7UUFDRCxhQUFhLENBQUMsSUFBSSxDQUFDLFlBQVksQ0FBQyxDQUFDO0tBQ3BDO0lBQ0QsT0FBTyxhQUFhLENBQUM7QUFDekIsQ0FBQztBQXhERCxrQ0F3REM7QUFDRCx1QkFBdUI7QUFDdkIsU0FBUyxnQkFBZ0I7SUFDckIsc0JBQXNCO0lBQ3RCLE1BQU0sSUFBSSxHQUFXO1FBQ2pCLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDVCxDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNiLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxDQUFDO1FBQ2IsQ0FBQyxDQUFDLEVBQUUsQ0FBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUM7S0FDaEIsQ0FBQztJQUNGLE1BQU0sS0FBSyxHQUFlO1FBQ3RCLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDVCxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ1QsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNULENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7S0FDWixDQUFDO0lBQ0YsT0FBTyxDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQztBQUN6QixDQUFDO0FBQ0QsZ0JBQWdCO0FBQ2hCLFNBQVMsZUFBZTtJQUNwQixNQUFNLElBQUksR0FBVztRQUNqQixDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQztRQUNsRCxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFHLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFHLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRyxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRyxDQUFDLENBQUM7S0FDckQsQ0FBQztJQUNGLE1BQU0sS0FBSyxHQUFlO1FBQ3RCLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ1osQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDWixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNaLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ1osQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDWixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztLQUNmLENBQUM7SUFDRixPQUFPLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxDQUFDO0FBQ3pCLENBQUM7QUFDRCxzQkFBc0I7QUFDdEIsU0FBUyxlQUFlO0lBQ3BCLHNCQUFzQjtJQUN0QixNQUFNLElBQUksR0FBVztRQUNqQixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNqQyxDQUFDLENBQUMsRUFBRSxDQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxDQUFDO0tBQ3RDLENBQUM7SUFDRixNQUFNLEtBQUssR0FBZTtRQUN0QixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQy9CLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO0tBQ3ZCLENBQUM7SUFDRixPQUFPLENBQUMsSUFBSSxFQUFFLEtBQUssQ0FBQyxDQUFDO0FBQ3pCLENBQUM7QUFDRCx1QkFBdUI7QUFDdkIsU0FBUyxnQkFBZ0I7SUFDckIsc0JBQXNCO0lBQ3RCLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQyxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUM7SUFDakMsTUFBTSxJQUFJLEdBQVc7UUFDakIsQ0FBQyxDQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ3JDLENBQUMsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUM7UUFDbkMsQ0FBQyxDQUFDLEVBQUUsQ0FBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUM7UUFDdkMsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO0tBQ3hDLENBQUM7SUFDRixNQUFNLEtBQUssR0FBZTtRQUN0QixDQUFDLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsQ0FBQztRQUN6RCxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUN6RCxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNyRCxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztLQUMxRCxDQUFDO0lBQ0YsT0FBTyxDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQztBQUN6QixDQUFDO0FBQ0Qsd0JBQXdCO0FBQ3hCLFNBQVMsaUJBQWlCO0lBQ3RCLHNCQUFzQjtJQUN0QixNQUFNLENBQUMsR0FBVyxDQUFDLENBQUMsR0FBRyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDO0lBQ3pDLE1BQU0sQ0FBQyxHQUFXLENBQUMsR0FBRyxDQUFDLENBQUM7SUFDeEIsTUFBTSxJQUFJLEdBQVc7UUFDakIsZUFBZTtRQUNmLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUM5QixDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUMxQixDQUFDLENBQUMsRUFBRSxDQUFFLENBQUMsRUFBRSxDQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUMxQixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ3RCLGdCQUFnQjtRQUNoQixDQUFDLENBQUMsRUFBRSxDQUFFLENBQUMsRUFBRSxDQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUMxQixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ3RCLGdCQUFnQjtRQUNoQixDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUMxQixDQUFDLENBQUMsRUFBRSxDQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO1FBQ3RCLGdCQUFnQjtRQUNoQixDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFFLENBQUMsQ0FBQztRQUMxQixDQUFDLENBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxDQUFDO0tBQ3pCLENBQUM7SUFDRixNQUFNLEtBQUssR0FBZTtRQUN0Qix1Q0FBdUM7UUFDdkMsdUNBQXVDO1FBQ3ZDLHdDQUF3QztRQUN4QyxzQ0FBc0M7UUFDdEMsdUNBQXVDO1FBQ3ZDLHVDQUF1QztRQUN2Qyx1Q0FBdUM7UUFDdkMsd0NBQXdDO1FBQ3hDLHNDQUFzQztRQUN0Qyx3Q0FBd0M7UUFDeEMseUNBQXlDO1FBQ3pDLHFDQUFxQztRQUNyQyxDQUFDLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFLEVBQUUsRUFBRSxFQUFFLENBQUM7UUFDbEIsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO1FBQ2xCLENBQUMsRUFBRSxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxFQUFFLENBQUMsQ0FBQztRQUNqQixDQUFDLENBQUMsRUFBRSxDQUFDLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUM7UUFDakIsQ0FBQyxDQUFDLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRSxFQUFFLEVBQUUsRUFBRSxDQUFDO1FBQ2xCLENBQUMsQ0FBQyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsQ0FBQztRQUNsQixDQUFDLENBQUMsRUFBRSxFQUFFLEVBQUUsRUFBRSxFQUFFLENBQUMsRUFBRSxFQUFFLENBQUM7UUFDbEIsQ0FBQyxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFLEVBQUUsQ0FBQyxDQUFDO1FBQ2pCLENBQUMsQ0FBQyxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztRQUNqQixDQUFDLEVBQUUsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLEVBQUUsRUFBRSxDQUFDLENBQUM7UUFDakIsQ0FBQyxFQUFFLEVBQUUsQ0FBQyxFQUFFLEVBQUUsRUFBRSxDQUFDLEVBQUUsRUFBRSxDQUFDO1FBQ2xCLENBQUMsQ0FBQyxFQUFFLEVBQUUsRUFBRSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQztLQUVwQixDQUFDO0lBQ0YsT0FBTyxDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQztBQUN6QixDQUFDO0FBQ0QsNkJBQTZCO0FBQzdCLFNBQVMsaUJBQWlCLENBQUMsVUFBZ0MsRUFBRSxNQUFjLEVBQUUsTUFBYztJQUN2RixNQUFNLElBQUksR0FBVyxVQUFVLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDbkMsTUFBTSxLQUFLLEdBQWUsVUFBVSxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQ3hDLFNBQVM7SUFDVCxNQUFNLENBQUMsUUFBUSxFQUFFLFNBQVMsQ0FBQyxHQUEwQixrQkFBa0IsQ0FBQyxJQUFJLEVBQUUsS0FBSyxFQUFFLE1BQU0sQ0FBQyxDQUFDO0lBQzdGLGVBQWU7SUFDZiwwQkFBMEIsQ0FBQyxRQUFRLEVBQUUsTUFBTSxDQUFDLENBQUM7SUFDN0MsU0FBUztJQUNULE9BQU8sQ0FBQyxRQUFRLEVBQUUsU0FBUyxDQUFDLENBQUM7QUFDakMsQ0FBQztBQUNELG1CQUFtQjtBQUNuQixTQUFTLGtCQUFrQixDQUFDLElBQVksRUFBRSxLQUFpQixFQUFFLE1BQWM7SUFDdkUsSUFBSSxNQUFNLEtBQUssQ0FBQyxFQUFFO1FBQUUsT0FBTyxDQUFDLElBQUksRUFBRSxLQUFLLENBQUMsQ0FBQztLQUFFO0lBQzNDLE1BQU0sU0FBUyxHQUFlLEVBQUUsQ0FBQztJQUNqQyxLQUFLLE1BQU0sSUFBSSxJQUFJLEtBQUssRUFBRTtRQUN0QixJQUFJLElBQUksQ0FBQyxNQUFNLEdBQUcsQ0FBQyxFQUFFO1lBQ2pCLE1BQU0sR0FBRyxHQUFTLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLENBQUMsQ0FBQztZQUM1QixLQUFLLE1BQU0sS0FBSyxJQUFJLElBQUksRUFBRTtnQkFDdEIsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7Z0JBQ2pDLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUNqQyxHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLElBQUksQ0FBQyxLQUFLLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQzthQUNwQztZQUNELEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQztZQUM5QixHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUM7WUFDOUIsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxJQUFJLENBQUMsTUFBTSxDQUFDO1lBQzlCLE1BQU0sS0FBSyxHQUFXLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxDQUFDO1lBQ3pDLEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxJQUFJLENBQUMsTUFBTSxFQUFFLENBQUMsRUFBRSxFQUFFO2dCQUNsQyxNQUFNLFFBQVEsR0FBYSxDQUFDLEtBQUssRUFBRSxJQUFJLENBQUMsQ0FBQyxDQUFDLEVBQUUsSUFBSSxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxHQUFHLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDO2dCQUN6RSxNQUFNLFlBQVksR0FBZSx5QkFBeUIsQ0FBQyxJQUFJLEVBQUUsUUFBUSxFQUFFLE1BQU0sR0FBRyxDQUFDLENBQUMsQ0FBQztnQkFDdkYsWUFBWSxDQUFDLEdBQUcsQ0FBQyxXQUFXLENBQUMsRUFBRSxDQUFDLFNBQVMsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUMsQ0FBQzthQUNoRTtTQUNKO2FBQU07WUFDSCxNQUFNLFlBQVksR0FBZSx5QkFBeUIsQ0FBQyxJQUFJLEVBQUUsSUFBSSxFQUFFLE1BQU0sQ0FBQyxDQUFDO1lBQy9FLFlBQVksQ0FBQyxHQUFHLENBQUMsV0FBVyxDQUFDLEVBQUUsQ0FBQyxTQUFTLENBQUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxDQUFDLENBQUM7U0FDaEU7S0FDSjtJQUNELGFBQWE7SUFDYixNQUFNLFFBQVEsR0FBVyxvQkFBb0IsQ0FBQyxJQUFJLEVBQUUsU0FBUyxDQUFDLENBQUM7SUFDL0QsU0FBUztJQUNULE9BQU8sQ0FBQyxRQUFRLEVBQUUsU0FBUyxDQUFDLENBQUM7QUFDakMsQ0FBQztBQUNELHFCQUFxQjtBQUNyQixTQUFTLHlCQUF5QixDQUFDLElBQVksRUFBRSxJQUFjLEVBQUUsTUFBYztJQUMzRSxNQUFNLENBQUMsR0FBUyxJQUFJLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7SUFDOUIsTUFBTSxDQUFDLEdBQVMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO0lBQzlCLE1BQU0sQ0FBQyxHQUFTLElBQUksQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztJQUM5QixNQUFNLElBQUksR0FBRyxNQUFNLEdBQUcsQ0FBQyxDQUFDO0lBQ3hCLHNGQUFzRjtJQUN0RixNQUFNLE1BQU0sR0FBZSxFQUFFLENBQUM7SUFDOUIsaURBQWlEO0lBQ2pELEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsSUFBSSxJQUFJLEVBQUUsQ0FBQyxFQUFFLEVBQUU7UUFDNUIsTUFBTSxDQUFDLENBQUMsQ0FBQyxHQUFHLEVBQUUsQ0FBQztRQUNmLE1BQU0sRUFBRSxHQUFHLGVBQWUsQ0FBQyxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsR0FBRyxJQUFJLENBQUMsQ0FBQztRQUMzQyxNQUFNLEVBQUUsR0FBRyxlQUFlLENBQUMsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEdBQUcsSUFBSSxDQUFDLENBQUM7UUFDM0MsTUFBTSxJQUFJLEdBQUcsSUFBSSxHQUFHLENBQUMsQ0FBQztRQUN0QixLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLElBQUksSUFBSSxFQUFFLENBQUMsRUFBRSxFQUFFO1lBQzVCLElBQUksS0FBYSxDQUFDO1lBQ2xCLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEtBQUssSUFBSSxFQUFFO2dCQUN2QixLQUFLLEdBQUcsSUFBSSxDQUFDLElBQUksQ0FBQyxFQUFFLENBQUMsR0FBRyxDQUFDLENBQUM7YUFDN0I7aUJBQU07Z0JBQ0gsS0FBSyxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLEVBQUUsRUFBRSxFQUFFLEVBQUUsQ0FBQyxHQUFHLElBQUksQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDO2FBQzVEO1lBQ0QsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLEtBQUssQ0FBQztTQUN4QjtLQUNKO0lBQ0QsaUNBQWlDO0lBQ2pDLE1BQU0sU0FBUyxHQUFlLEVBQUUsQ0FBQztJQUNqQyxLQUFLLElBQUksQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsSUFBSSxFQUFFLENBQUMsRUFBRSxFQUFFO1FBQzNCLEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxDQUFDLEdBQUcsQ0FBQyxJQUFJLEdBQUcsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsRUFBRSxFQUFFO1lBQ3pDLE1BQU0sUUFBUSxHQUFhLEVBQUUsQ0FBQztZQUM5QixNQUFNLENBQUMsR0FBRyxJQUFJLENBQUMsS0FBSyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQztZQUM1QixJQUFJLENBQUMsR0FBRyxDQUFDLEtBQUssQ0FBQyxFQUFFO2dCQUNiLFFBQVEsQ0FBQyxJQUFJLENBQUMsTUFBTSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUNoQyxRQUFRLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztnQkFDaEMsUUFBUSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQzthQUMvQjtpQkFBTTtnQkFDSCxRQUFRLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQztnQkFDaEMsUUFBUSxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUNwQyxRQUFRLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQzthQUNuQztZQUNELFNBQVMsQ0FBQyxJQUFJLENBQUMsUUFBUSxDQUFDLENBQUM7U0FDNUI7S0FDSjtJQUNELE9BQU8sU0FBUyxDQUFDO0FBQ3JCLENBQUM7QUFDRCxTQUFTLG9CQUFvQixDQUFDLElBQVksRUFBRSxLQUFpQjtJQUN6RCx3QkFBd0I7SUFDeEIsTUFBTSxpQkFBaUIsR0FBd0IsSUFBSSxHQUFHLEVBQUUsQ0FBQztJQUN6RCxNQUFNLFFBQVEsR0FBVyxFQUFFLENBQUM7SUFDNUIsS0FBSyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsQ0FBQyxHQUFHLElBQUksQ0FBQyxNQUFNLEVBQUUsQ0FBQyxFQUFFLEVBQUU7UUFDbEMsSUFBSSxDQUFDLGlCQUFpQixDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsRUFBRTtZQUMzQixNQUFNLEtBQUssR0FBVyxRQUFRLENBQUMsSUFBSSxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLENBQUMsQ0FBQztZQUNqRCxpQkFBaUIsQ0FBQyxHQUFHLENBQUMsQ0FBQyxFQUFFLEtBQUssQ0FBQyxDQUFDO1lBQ2hDLEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxHQUFHLENBQUMsRUFBRSxDQUFDLEdBQUcsSUFBSSxDQUFDLE1BQU0sRUFBRSxDQUFDLEVBQUUsRUFBRTtnQkFDdEMsTUFBTSxPQUFPLEdBQ1QsSUFBSSxDQUFDLEdBQUcsQ0FBQyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO29CQUNqQyxJQUFJLENBQUMsR0FBRyxDQUFDLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsR0FBRyxJQUFJLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7b0JBQ2pDLElBQUksQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxHQUFHLElBQUksQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDO2dCQUN0QyxJQUFJLE9BQU8sR0FBRyxJQUFJLEVBQUU7b0JBQ2hCLGlCQUFpQixDQUFDLEdBQUcsQ0FBQyxDQUFDLEVBQUUsS0FBSyxDQUFDLENBQUM7aUJBQ25DO2FBQ0o7U0FDSjtLQUNKO0lBQ0QsaUJBQWlCO0lBQ2pCLEtBQUssTUFBTSxJQUFJLElBQUksS0FBSyxFQUFFO1FBQ3RCLEtBQUssSUFBSSxDQUFDLEdBQUcsQ0FBQyxFQUFFLENBQUMsR0FBRyxJQUFJLENBQUMsTUFBTSxFQUFFLENBQUMsRUFBRSxFQUFFO1lBQ2xDLElBQUksQ0FBQyxDQUFDLENBQUMsR0FBRyxpQkFBaUIsQ0FBQyxHQUFHLENBQUMsSUFBSSxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7U0FDNUM7S0FDSjtJQUNELFNBQVM7SUFDVCxPQUFPLFFBQVEsQ0FBQztBQUNwQixDQUFDO0FBQ0QsU0FBUywwQkFBMEIsQ0FBQyxJQUFZLEVBQUUsTUFBYztJQUM1RCx5REFBeUQ7SUFDekQsS0FBSyxNQUFNLEdBQUcsSUFBSSxJQUFJLEVBQUU7UUFDcEIsTUFBTSxLQUFLLEdBQ1AsTUFBTSxHQUFHLElBQUksQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEdBQUcsQ0FBQyxDQUFDLENBQUMsR0FBRyxHQUFHLENBQUMsQ0FBQyxDQUFDLENBQUMsQ0FBQztRQUM1RSxHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEtBQUssQ0FBQztRQUN4QixHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEtBQUssQ0FBQztRQUN4QixHQUFHLENBQUMsQ0FBQyxDQUFDLEdBQUcsR0FBRyxDQUFDLENBQUMsQ0FBQyxHQUFHLEtBQUssQ0FBQztLQUMzQjtBQUNMLENBQUM7QUFDRCxTQUFTLGVBQWUsQ0FBQyxDQUFPLEVBQUUsQ0FBTyxFQUFFLEtBQWE7SUFDcEQsaUNBQWlDO0lBQ2pDLE9BQU87UUFDSCxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsS0FBSztRQUM1QixDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsS0FBSztRQUM1QixDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUMsQ0FBQyxDQUFDLEdBQUcsS0FBSztLQUMvQixDQUFDO0FBQ04sQ0FBQyJ9
/* eslint-env mocha */ /* eslint-env browser */ import assert from 'assert'; import { TextureAtlas } from '.'; import TextureAtlasJsonDef from './TextureAtlasJsonDef'; describe('TextureAtlasJsonDef', () => { describe('new TextureAtlasJsonDef(jsonDef)', () => { let jsonDef; before((done) => { window.fetch(('/assets/nobinger.json')) .then(response => response.json()) .then((json) => { jsonDef = new TextureAtlasJsonDef(json); done(); }); }); it('jsonDef', () => { assert.ok(jsonDef.meta); }); it('frameNames', () => assert.deepEqual(jsonDef.frameNames, [ 'nobinger-blau.png', 'nobinger-gold.png', 'nobinger-grau.png', 'nobinger-gruen.png', 'nobinger-lila.png', 'nobinger-rot.png', ])); }); describe('TextureAtlas.load', () => { let atlas; before((done) => { TextureAtlas.load('/assets/nobinger.json').then((textureAtlas) => { atlas = textureAtlas; done(); }); }); it('jsonDef.meta.format', () => assert.equal(atlas.jsonDef.meta.format, 'RGBA8888')); it('root texture', () => { const tex = atlas.rootTexture; assert.ok(tex); assert.equal(tex.root, tex); assert.equal(tex.width, 128); assert.equal(tex.height, 256); }); it('frame: nobinger-blau.png', () => { const tex = atlas.frame('nobinger-blau.png'); assert.ok(tex); assert(tex.root !== tex); assert.equal(tex.width, 55); assert.equal(tex.height, 61); }); it('add frame alias', () => { atlas.addFrameAlias('blau', 'nobinger-blau.png'); assert.equal(atlas.frame('blau'), atlas.frame('nobinger-blau.png')); assert.deepEqual(atlas.frameNames().sort(), [ 'nobinger-blau.png', 'nobinger-gold.png', 'nobinger-grau.png', 'nobinger-gruen.png', 'nobinger-lila.png', 'nobinger-rot.png', 'blau', ].sort()); }); it('frameNames sequence', () => { assert.deepEqual(atlas.frameNames('(blau|gold)').sort(), [ 'nobinger-blau.png', 'nobinger-gold.png', 'blau', ].sort()); }); }); });
import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray'; import React from 'react'; import PropTypes from 'prop-types'; import TableFooterRow from './TableFooterRow'; function appendExpandIconColumn(columns) { var expandIconCol = { key: 'expand-icon-placeholder', render: function render() { return null; } }; return [expandIconCol].concat(_toConsumableArray(columns)); } export default function TableFooter(props, _ref) { var table = _ref.table; var columnManager = table.columnManager, components = table.components; var _table$props = table.props, prefixCls = _table$props.prefixCls, data = _table$props.data, expandIconAsCell = _table$props.expandIconAsCell; var fixed = props.fixed, onHover = props.onHover; var leafColumns = void 0; if (fixed === 'left') { leafColumns = columnManager.leftLeafColumns(); if (expandIconAsCell) { leafColumns = appendExpandIconColumn(leafColumns); } } else if (fixed === 'right') { leafColumns = columnManager.rightLeafColumns(); } else { leafColumns = columnManager.leafColumns(); if (expandIconAsCell) { leafColumns = appendExpandIconColumn(leafColumns); } } var FooterWrapper = components.footer.wrapper; return React.createElement( FooterWrapper, { className: prefixCls + '-tfoot' }, React.createElement(TableFooterRow, { prefixCls: prefixCls, columns: leafColumns, components: components, fixed: fixed, data: data, onHover: columnManager.isAnyColumnsFixed() ? onHover : null }) ); } TableFooter.propTypes = { fixed: PropTypes.string, columns: PropTypes.array.isRequired, onHover: PropTypes.func }; TableFooter.contextTypes = { table: PropTypes.any };
// @flow import { darken, lighten } from 'polished'; const colors = { almostBlack: '#111319', lightBlack: '#2F3336', almostWhite: '#E6E6E6', slate: '#9BA6B2', slateLight: '#DAE1E9', slateDark: '#4E5C6E', smoke: '#F4F7FA', smokeLight: '#F9FBFC', smokeDark: '#E8EBED', white: '#FFF', white10: 'rgba(255, 255, 255, 0.1)', white50: 'rgba(255, 255, 255, 0.5)', black: '#000', black05: 'rgba(0, 0, 0, 0.05)', black10: 'rgba(0, 0, 0, 0.1)', black50: 'rgba(0, 0, 0, 0.50)', primary: '#0366d6', yellow: '#FBCA04', warmGrey: '#EDF2F7', danger: '#D0021B', warning: '#f08a24', success: '#2f3336', info: '#a0d3e8', }; const spacing = { padding: '1.5vw 1.875vw', vpadding: '1.5vw', hpadding: '1.875vw', sidebarWidth: '280px', sidebarMinWidth: '250px', sidebarMaxWidth: '350px', }; export const base = { ...colors, ...spacing, fontFamily: "-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen, Ubuntu,Cantarell,'Open Sans','Helvetica Neue',sans-serif", fontWeight: 400, backgroundTransition: 'background 100ms ease-in-out', zIndex: 100, selected: colors.primary, buttonBackground: colors.primary, buttonText: colors.white, }; export const light = { ...base, background: colors.white, link: colors.almostBlack, text: colors.almostBlack, textSecondary: colors.slateDark, textTertiary: colors.slate, placeholder: '#B1BECC', sidebarBackground: colors.warmGrey, sidebarItemBackground: colors.black05, sidebarText: 'rgb(78, 92, 110)', menuBackground: colors.white, menuShadow: '0 0 0 1px rgba(0, 0, 0, 0.05), 0 4px 8px rgba(0, 0, 0, 0.08), 0 2px 4px rgba(0, 0, 0, 0.08)', divider: colors.slateLight, inputBorder: colors.slateLight, inputBorderFocused: colors.slate, listItemHoverBackground: colors.warmGrey, toolbarBackground: colors.lightBlack, toolbarInput: colors.white10, toolbarItem: colors.white, tableDivider: colors.smokeDark, tableSelected: colors.primary, tableSelectedBackground: '#E5F7FF', buttonNeutralBackground: colors.white, buttonNeutralText: colors.almostBlack, tooltipBackground: colors.almostBlack, tooltipText: colors.white, blockToolbarBackground: colors.smoke, blockToolbarTrigger: colors.slate, blockToolbarTriggerIcon: colors.white, blockToolbarItem: colors.almostBlack, quote: colors.slateLight, codeBackground: colors.smoke, codeBorder: colors.smokeDark, embedBorder: '#DDD #DDD #CCC', horizontalRule: colors.smokeDark, }; export const dark = { ...base, background: colors.almostBlack, link: colors.almostWhite, text: colors.almostWhite, textSecondary: lighten(0.2, colors.slate), textTertiary: colors.slate, placeholder: darken(0.5, '#B1BECC'), sidebarBackground: colors.black50, sidebarItemBackground: colors.black50, sidebarText: colors.slate, menuBackground: lighten(0.015, colors.almostBlack), menuShadow: '0 0 0 1px rgba(0, 0, 0, 0.1), 0 8px 16px rgba(0, 0, 0, 0.3), 0 2px 4px rgba(0, 0, 0, 0.08), inset 0 0 1px rgba(255,255,255,.2)', divider: darken(0.2, colors.slate), inputBorder: colors.slateDark, inputBorderFocused: colors.slate, listItemHoverBackground: colors.black50, toolbarBackground: colors.white, toolbarInput: colors.black10, toolbarItem: colors.lightBlack, tableDivider: colors.lightBlack, tableSelected: colors.primary, tableSelectedBackground: '#002333', buttonNeutralBackground: colors.almostBlack, buttonNeutralText: colors.white, tooltipBackground: colors.white, tooltipText: colors.lightBlack, blockToolbarBackground: colors.white, blockToolbarTrigger: colors.almostWhite, blockToolbarTriggerIcon: colors.almostBlack, blockToolbarItem: colors.lightBlack, quote: colors.almostWhite, codeBackground: colors.almostBlack, codeBorder: colors.black50, embedBorder: colors.black50, horizontalRule: darken(0.2, colors.slate), }; export default light;
function __processArg(obj, key) { var arg = null; if (obj) { arg = obj[key] || null; delete obj[key]; } return arg; } function Controller() { require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments)); this.__controllerPath = "phone/peekAndPop"; this.args = arguments[0] || {}; if (arguments[0]) { { __processArg(arguments[0], "__parentSymbol"); } { __processArg(arguments[0], "$model"); } { __processArg(arguments[0], "__itemTemplate"); } } var $ = this; var exports = {}; $.__views.peekAndPop = Ti.UI.createWindow({ backgroundColor: "black", title: "Peek and Pop", id: "peekAndPop" }); $.__views.peekAndPop && $.addTopLevelView($.__views.peekAndPop); $.__views.__alloyId133 = Ti.UI.createLabel({ width: 250, height: 125, color: "#333", backgroundColor: "#eee", borderRadius: 4, textAlign: Ti.UI.TEXT_ALIGNMENT_CENTER, text: "To be added ⚒", id: "__alloyId133" }); $.__views.peekAndPop.add($.__views.__alloyId133); exports.destroy = function() {}; _.extend($, $.__views); require("log"); !function() {}(); _.extend($, exports); } var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._; module.exports = Controller;
/** * @module ui/montage-studio-loader.reel */ var Loader = require("../loader.reel").Loader; // Constants var OFF_CLASS_NAME = "off", ANI_CLASS_NAME = "ani", TRIANGLES_CLASS_NAME = "tri", LOADER_STATE_INIT = 0, LOADER_STATE_ANIMATING = 1, LOADER_STATE_STOPPED = 2; /** * @class MontageStudioLoader * @extends Component */ var MontageStudioLoader = exports.MontageStudioLoader = Loader.specialize(/** @lends MontageStudioLoader# */ { hasTemplate: { value: true }, _state: { value: null }, state: { set: function (state) { if (this._state !== state) { this._state = state; } }, get: function () { if (this._state === null) { this._state = LOADER_STATE_INIT; } return this._state; } }, _shouldRotate: { value: false }, animationInterval: { value: 3500 }, minimumFirstLoadingDuration: { value: 6000 }, enterDocument: { value: function (firsTime) { Loader.prototype.enterDocument.call(this, firsTime); if (firsTime) { this.startAnimation(); } } }, exitDocument: { value: function () { if (this.state === LOADER_STATE_ANIMATING) { this.stopAnimation(); } } }, startAnimation: { value: function () { if (this.state !== LOADER_STATE_STOPPED) { var self = this; this._animationIntervalTimeoutID = setTimeout(function () { if (self.state === LOADER_STATE_STOPPED) return; self.state = LOADER_STATE_ANIMATING; self.needsDraw = true; }, this.animationInterval); } } }, stopAnimation: { value: function () { if (this.state === LOADER_STATE_ANIMATING) { if (this._animationIntervalTimeoutID) { clearTimeout(this._animationIntervalTimeoutID); this._animationIntervalTimeoutID = null; } this.state = LOADER_STATE_STOPPED; this.needsDraw = true; } } }, draw: { value: function () { Loader.prototype.draw.call(this); if (this.state === LOADER_STATE_ANIMATING) { this._logoTrianglesElement.classList.remove(OFF_CLASS_NAME); this._logoWtrianglesElement.classList.remove(OFF_CLASS_NAME); this._logoSVGContainerElement.classList.add(ANI_CLASS_NAME); this._logoWtrianglesElement.classList.add(ANI_CLASS_NAME); this._logoLinesElement.classList.add(OFF_CLASS_NAME); var triangles = document.getElementsByClassName(TRIANGLES_CLASS_NAME), tPrefix = "t"; for (var i = 0; i < triangles.length; i++) { triangles[i].classList.add(tPrefix + (i + 1)); } } else if (this.state === LOADER_STATE_STOPPED) { // Avoid memory leak this._logoTrianglesElement = null; this._logoWtrianglesElement = null; this._logoSVGContainerElement = null; this._logoWtrianglesElement = null; this._logoLinesElement = null; this.element.classList.add(OFF_CLASS_NAME); } } } });
/* global __filename */ import { getLogger } from '@jitsi/logger'; import Listenable from '../util/Listenable'; import * as JingleSessionState from './JingleSessionState'; const logger = getLogger(__filename); /** * JingleSession provides an API to manage a single Jingle session. We will * have different implementations depending on the underlying interface used * (i.e. WebRTC and ORTC) and here we hold the code common to all of them. */ export default class JingleSession extends Listenable { /* eslint-disable max-params */ /** * Creates new <tt>JingleSession</tt>. * @param {string} sid the Jingle session identifier * @param {string} localJid our JID * @param {string} remoteJid the JID of the remote peer * @param {XmppConnection} connection the XMPP connection * @param {Object} mediaConstraints the media constraints object passed to the PeerConnection onCreateAnswer/Offer. * @param {Object} pcConfig The {@code RTCConfiguration} object passed to the PeerConnection's constructor. * @param {boolean} isInitiator indicates if it will be the side which initiates the session. */ constructor( sid, localJid, remoteJid, connection, mediaConstraints, pcConfig, isInitiator) { super(); this.sid = sid; this.localJid = localJid; this.remoteJid = remoteJid; this.connection = connection; this.mediaConstraints = mediaConstraints; this.pcConfig = pcConfig; /** * Indicates whether this instance is an initiator or an answerer of * the Jingle session. * @type {boolean} */ this.isInitiator = isInitiator; /** * Whether to use dripping or not. Dripping is sending trickle * candidates not one-by-one. */ this.usedrip = true; /** * When dripping is used, stores ICE candidates which are to be sent. */ this.dripContainer = []; /** * The chat room instance associated with the session. * @type {ChatRoom} */ this.room = null; /** * The signaling layer. * @type {SignalingLayerImpl | null} * @private */ this._signalingLayer = null; /** * Jingle session state - uninitialized until {@link initialize} is * called @type {JingleSessionState} */ this.state = null; /** * The RTC service instance * @type {RTC} */ this.rtc = null; } /** * Returns XMPP address of this session's initiator. * @return {string} */ get initiatorJid() { return this.isInitiator ? this.localJid : this.remoteJid; } /** * Returns XMPP address of this session's responder. * @return {string} */ get responderJid() { return this.isInitiator ? this.remoteJid : this.localJid; } /* eslint-enable max-params */ /** * Prepares this object to initiate a session. * @param {ChatRoom} room the chat room for the conference associated with * this session * @param {RTC} rtc the RTC service instance * @param {SignalingLayerImpl} signalingLayer - The signaling layer instance. * @param {object} options - the options, see implementing class's * {@link #doInitialize} description for more details. */ initialize(room, rtc, signalingLayer, options) { if (this.state !== null) { const errmsg = `attempt to initiate on session ${this.sid} in state ${this.state}`; logger.error(errmsg); throw new Error(errmsg); } // TODO decouple from room this.room = room; this.rtc = rtc; this._signalingLayer = signalingLayer; this.state = JingleSessionState.PENDING; this.doInitialize(options); } /** * The implementing class finishes initialization here. Called at the end of * {@link initialize}. * @param {Object} options - The options specific to the implementing class. * @protected */ doInitialize(options) { } // eslint-disable-line no-unused-vars, no-empty-function, max-len /* eslint-disable no-unused-vars, no-empty-function */ /** * Adds the ICE candidates found in the 'contents' array as remote * candidates? * Note: currently only used on transport-info * * @param contents */ addIceCandidates(contents) {} /* eslint-enable no-unused-vars, no-empty-function */ /** * Returns current state of this <tt>JingleSession</tt> instance. * @returns {JingleSessionState} the current state of this session instance. */ getState() { return this.state; } /* eslint-disable no-unused-vars, no-empty-function */ /** * Handles an 'add-source' event. * * @param contents an array of Jingle 'content' elements. */ addSources(contents) {} /** * Handles a 'remove-source' event. * * @param contents an array of Jingle 'content' elements. */ removeSources(contents) {} /** * Terminates this Jingle session by sending session-terminate * @param success a callback called once the 'session-terminate' packet has * been acknowledged with RESULT. * @param failure a callback called when either timeout occurs or ERROR * response is received. * @param {Object} options * @param {string} [options.reason] XMPP Jingle error condition * @param {string} [options.reasonDescription] some meaningful error message * @param {boolean} [options.requestRestart=false] set to true to ask Jicofo to start a new session one this once is * terminated. * @param {boolean} [options.sendSessionTerminate=true] set to false to skip * sending session-terminate. It may not make sense to send it if the XMPP * connection has been closed already or if the remote peer has disconnected */ terminate(success, failure, options) {} /** * Handles an offer from the remote peer (prepares to accept a session). * @param jingle the 'jingle' XML element. * @param success callback called when we the incoming session has been * accepted * @param failure callback called when we fail for any reason, will supply * error object with details(which is meant more to be printed to the logger * than analysed in the code, as the error is unrecoverable anyway) */ acceptOffer(jingle, success, failure) {} /** * Returns the JID of the initiator of the jingle session. */ _getInitiatorJid() { return this.isInitiator ? this.localJid : this.remoteJid; } /* eslint-enable no-unused-vars, no-empty-function */ }
import { createApp } from 'vue' import App from './App.vue' import router from '@/router' import store from '@/store' import vant from '@/vant' import wave from '@/directive/wave' import 'swiper/swiper.min.css' import '@/assets/styles/style.scss' store.dispatch('user/loginStatus') const app = createApp(App) .use(router) .use(store) .use(vant) .directive('wave', wave) .mount('#app')
console.log("From app.js");
'use strict'; //Global variables var photoOne = document.getElementById('photo1'); var photoTwo = document.getElementById('photo2'); var photoThree = document.getElementById('photo3'); var photoBin = document.getElementById('photoBin'); var marketBlurb = document.getElementById('verbage'); var resultsSection = document.getElementById('list'); var pixArray = []; var picArrayContainers = [photoOne, photoTwo, photoThree]; var voteRounds = 25; //Image Generation Constructor function Picture(src, nom) { this.src = `./img/${src}.jpg`; this.title = nom; this.alt = nom; this.viewed = 0; //Tallies how many times a particular image was displayed this.clicked = 0; //Tallies how many times a particular image was clicked on. pixArray.push(this); } //Helper functions //Random Index Generator function function randomIndex(max) { return Math.floor(Math.random() * Math.floor(max)); } //Image Generator Engine, displaying non-matching images function picSelect() { var currentImages = []; for (var i = 0; i < picArrayContainers.length; i++) { var currentRandomIndex = randomIndex(pixArray.length); // console.log('outside while', currentRandomIndex); while (currentImages.includes(currentRandomIndex)) { // console.log('inside while', currentRandomIndex); currentRandomIndex = randomIndex(pixArray.length); // console.log('new random inside while', currentRandomIndex); // console.log(currentImages); } currentImages.push(currentRandomIndex); // console.log(currentImages); picArrayContainers[i].src = pixArray[currentRandomIndex].src; picArrayContainers[i].title = pixArray[currentRandomIndex].title; picArrayContainers[i].alt = pixArray[currentRandomIndex].alt; pixArray[currentRandomIndex].viewed++; } // console.table(pixArray); } //Event Handler function handleClick(event) { voteRounds--; if (voteRounds !== 0) { console.log(event.target.title); //Cleaner console display var vote = event.target.title; //Creates a tally mechanism for the image that was clicked on. console.log(vote, ' was clicked.'); for (var i = 0; i < pixArray.length; i++) { if (vote === pixArray[i].title) { pixArray[i].clicked++; } } picSelect(); // console.log('You clicked me!!'); //Proof of Life //Prove all pictures made it into the array } else { photoBin.removeEventListener('click', handleClick); // console.log('i stopped'); analysis(); hide(photoBin); hide(marketBlurb); var preserveResults = JSON.stringify(pixArray); localStorage.setItem('results', preserveResults); } } // Hide an element function hide(elem) { elem.style.display = 'none'; } function analysis() { var ulEl = document.createElement('ul'); for (var i = 0; i < pixArray.length; i++) { var liEl = document.createElement('li'); liEl.textContent = `${pixArray[i].title}: ${pixArray[i].clicked} clicks & ${pixArray[i].viewed} views`; ulEl.appendChild(liEl); } resultsSection.appendChild(ulEl); } // //Major Functions // Image Instantiator Function function createOnPageLoad() { new Picture('bag', 'R2-D2 Roller Luggage'); new Picture('banana', 'Banana Slicer'); new Picture('bathroom', 'Toilet Paper and Tablet Holder'); new Picture('boots', 'Open-toed Wellies'); new Picture('breakfast', 'Breakfast Station'); new Picture('bubblegum', 'Meatball Bubblegum'); new Picture('chair', 'Camel-seat Chair'); new Picture('cthulhu', 'Cthulhu Action Figure'); new Picture('dog-duck', 'Doggie Duck Muzzle'); new Picture('dragon', 'Canned Dragon Meat'); new Picture('pen', 'Plasticware Pen Toppers'); new Picture('pet-sweep', 'Pet Duster Boots'); new Picture('scissors', 'Pizza Scissors'); new Picture('shark', 'Shark Sleeping bag'); new Picture('sweep', 'Baby Creeper Sweeper'); new Picture('tauntaun', 'Star Wars Tauntaun Sleeping Bag'); new Picture('unicorn', 'Canned Unicorn Meat'); new Picture('usb', 'USB Tentacle'); new Picture('water-can', 'Recursive Water Can'); new Picture('wine-glass', 'Wine Sniffer Snifter'); } //Function Calls function prevResultsCheck() { var fetchResults = localStorage.getItem('results', preserveResults); if (fetchResults) { pixArray = JSON.parse(fetchResults); } } createOnPageLoad(); } //Event Listener //Wrap the event Listener in a function that limits its use to the number of voting rounds specified by the user photoBin.addEventListener('click', handleClick); //Generate Image set picSelect();
// DO NOT EDIT! This test has been generated by tools/gentest.py. // OffscreenCanvas test in a worker:2d.fillRect.nonfinite // Description:fillRect() with Infinity/NaN is ignored // Note: importScripts("/resources/testharness.js"); importScripts("/common/canvas-tests.js"); var t = async_test("fillRect() with Infinity/NaN is ignored"); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); ctx.fillStyle = '#0f0'; ctx.fillRect(0, 0, 100, 50); ctx.fillStyle = '#f00'; ctx.fillRect(Infinity, 0, 100, 50); ctx.fillRect(-Infinity, 0, 100, 50); ctx.fillRect(NaN, 0, 100, 50); ctx.fillRect(0, Infinity, 100, 50); ctx.fillRect(0, -Infinity, 100, 50); ctx.fillRect(0, NaN, 100, 50); ctx.fillRect(0, 0, Infinity, 50); ctx.fillRect(0, 0, -Infinity, 50); ctx.fillRect(0, 0, NaN, 50); ctx.fillRect(0, 0, 100, Infinity); ctx.fillRect(0, 0, 100, -Infinity); ctx.fillRect(0, 0, 100, NaN); ctx.fillRect(Infinity, Infinity, 100, 50); ctx.fillRect(Infinity, Infinity, Infinity, 50); ctx.fillRect(Infinity, Infinity, Infinity, Infinity); ctx.fillRect(Infinity, Infinity, 100, Infinity); ctx.fillRect(Infinity, 0, Infinity, 50); ctx.fillRect(Infinity, 0, Infinity, Infinity); ctx.fillRect(Infinity, 0, 100, Infinity); ctx.fillRect(0, Infinity, Infinity, 50); ctx.fillRect(0, Infinity, Infinity, Infinity); ctx.fillRect(0, Infinity, 100, Infinity); ctx.fillRect(0, 0, Infinity, Infinity); _assertPixel(offscreenCanvas, 50,25, 0,255,0,255, "50,25", "0,255,0,255"); t.done(); }); done();
/* * Jexl * Copyright 2020 Tom Shawver */ const numericRegex = /^-?(?:(?:[0-9]*\.[0-9]+)|[0-9]+)$/ const identRegex = /^[a-zA-Z_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$][a-zA-Z0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF$]*$/ const escEscRegex = /\\\\/ const whitespaceRegex = /^\s*$/ const preOpRegexElems = [ // Strings "'(?:(?:\\\\')|[^'])*'", '"(?:(?:\\\\")|[^"])*"', // Whitespace '\\s+', // Booleans '\\btrue\\b', '\\bfalse\\b' ] const postOpRegexElems = [ // Identifiers '[a-zA-Z_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\\$][a-zA-Z0-9_\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF\\$]*', // Numerics (without negative symbol) '(?:(?:[0-9]*\\.[0-9]+)|[0-9]+)' ] const minusNegatesAfter = [ 'binaryOp', 'unaryOp', 'openParen', 'openBracket', 'question', 'colon' ] /** * Lexer is a collection of stateless, statically-accessed functions for the * lexical parsing of a Jexl string. Its responsibility is to identify the * "parts of speech" of a Jexl expression, and tokenize and label each, but * to do only the most minimal syntax checking; the only errors the Lexer * should be concerned with are if it's unable to identify the utility of * any of its tokens. Errors stemming from these tokens not being in a * sensible configuration should be left for the Parser to handle. * @type {{}} */ class Lexer { constructor(grammar) { this._grammar = grammar } /** * Splits a Jexl expression string into an array of expression elements. * @param {string} str A Jexl expression string * @returns {Array<string>} An array of substrings defining the functional * elements of the expression. */ getElements(str) { const regex = this._getSplitRegex() return str.split(regex).filter((elem) => { // Remove empty strings return elem }) } /** * Converts an array of expression elements into an array of tokens. Note that * the resulting array may not equal the element array in length, as any * elements that consist only of whitespace get appended to the previous * token's "raw" property. For the structure of a token object, please see * {@link Lexer#tokenize}. * @param {Array<string>} elements An array of Jexl expression elements to be * converted to tokens * @returns {Array<{type, value, raw}>} an array of token objects. */ getTokens(elements) { const tokens = [] let negate = false for (let i = 0; i < elements.length; i++) { if (this._isWhitespace(elements[i])) { if (tokens.length) { tokens[tokens.length - 1].raw += elements[i] } } else if (elements[i] === '-' && this._isNegative(tokens)) { negate = true } else { if (negate) { elements[i] = '-' + elements[i] negate = false } tokens.push(this._createToken(elements[i])) } } // Catch a - at the end of the string. Let the parser handle that issue. if (negate) { tokens.push(this._createToken('-')) } return tokens } /** * Converts a Jexl string into an array of tokens. Each token is an object * in the following format: * * { * type: <string>, * [name]: <string>, * value: <boolean|number|string>, * raw: <string> * } * * Type is one of the following: * * literal, identifier, binaryOp, unaryOp * * OR, if the token is a control character its type is the name of the element * defined in the Grammar. * * Name appears only if the token is a control string found in * {@link grammar#elements}, and is set to the name of the element. * * Value is the value of the token in the correct type (boolean or numeric as * appropriate). Raw is the string representation of this value taken directly * from the expression string, including any trailing spaces. * @param {string} str The Jexl string to be tokenized * @returns {Array<{type, value, raw}>} an array of token objects. * @throws {Error} if the provided string contains an invalid token. */ tokenize(str) { const elements = this.getElements(str) return this.getTokens(elements) } /** * Creates a new token object from an element of a Jexl string. See * {@link Lexer#tokenize} for a description of the token object. * @param {string} element The element from which a token should be made * @returns {{value: number|boolean|string, [name]: string, type: string, * raw: string}} a token object describing the provided element. * @throws {Error} if the provided string is not a valid expression element. * @private */ _createToken(element) { const token = { type: 'literal', value: element, raw: element } if (element[0] === '"' || element[0] === "'") { token.value = this._unquote(element) } else if (element.match(numericRegex)) { token.value = parseFloat(element) } else if (element === 'true' || element === 'false') { token.value = element === 'true' } else if (this._grammar[element]) { token.type = this._grammar[element].type } else if (element.match(identRegex)) { token.type = 'identifier' } else { throw new Error(`Invalid expression token: ${element}`) } return token } /** * Escapes a string so that it can be treated as a string literal within a * regular expression. * @param {string} str The string to be escaped * @returns {string} the RegExp-escaped string. * @see https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions * @private */ _escapeRegExp(str) { str = str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') if (str.match(identRegex)) { str = '\\b' + str + '\\b' } return str } /** * Gets a RegEx object appropriate for splitting a Jexl string into its core * elements. * @returns {RegExp} An element-splitting RegExp object * @private */ _getSplitRegex() { if (!this._splitRegex) { // Sort by most characters to least, then regex escape each const elemArray = Object.keys(this._grammar) .sort((a, b) => { return b.length - a.length }) .map((elem) => { return this._escapeRegExp(elem) }, this) this._splitRegex = new RegExp( '(' + [ preOpRegexElems.join('|'), elemArray.join('|'), postOpRegexElems.join('|') ].join('|') + ')' ) } return this._splitRegex } /** * Determines whether the addition of a '-' token should be interpreted as a * negative symbol for an upcoming number, given an array of tokens already * processed. * @param {Array<Object>} tokens An array of tokens already processed * @returns {boolean} true if adding a '-' should be considered a negative * symbol; false otherwise * @private */ _isNegative(tokens) { if (!tokens.length) return true return minusNegatesAfter.some( (type) => type === tokens[tokens.length - 1].type ) } /** * A utility function to determine if a string consists of only space * characters. * @param {string} str A string to be tested * @returns {boolean} true if the string is empty or consists of only spaces; * false otherwise. * @private */ _isWhitespace(str) { return !!str.match(whitespaceRegex) } /** * Removes the beginning and trailing quotes from a string, unescapes any * escaped quotes on its interior, and unescapes any escaped escape * characters. Note that this function is not defensive; it assumes that the * provided string is not empty, and that its first and last characters are * actually quotes. * @param {string} str A string whose first and last characters are quotes * @returns {string} a string with the surrounding quotes stripped and escapes * properly processed. * @private */ _unquote(str) { const quote = str[0] const escQuoteRegex = new RegExp('\\\\' + quote, 'g') return str .substr(1, str.length - 2) .replace(escQuoteRegex, quote) .replace(escEscRegex, '\\') } } module.exports = Lexer
define( (require, exports) => { const buildRoutes = require('./routes'); return { title: 'Profiles', buildRoutes, navUrl: () => '#/profiles', icon: 'user', statusCss: () => '' }; } );
UE.plugins["wordcount"]=function(){var d=this;d.setOpt({wordCount:true,maximumWords:10000,wordCountMsg:d.options.wordCountMsg||d.getLang("wordCountMsg"),wordOverFlowMsg:d.options.wordOverFlowMsg||d.getLang("wordOverFlowMsg")});var b=d.options,a=b.maximumWords,e=b.wordCountMsg,c=b.wordOverFlowMsg;if(!b.wordCount){return;}d.commands["wordcount"]={queryCommandValue:function(j,h){var i,f,g;if(h){g=new RegExp("[\r\t\n]","g");f=this.getContentTxt().replace(g,"");return f.length;}g=new RegExp("[\r\t\n]","g");f=this.getContentTxt().replace(g,"");i=f.length;if(a-i<0){d.fireEvent("wordcountoverflow");return c;}return e.replace("{#leave}",a-i>=0?a-i:0).replace("{#count}",i);}};};
import { combine as c } from '@reatom/core' const countersShape0 = combine({ counter, counterDoubled }) const countersShape1 = combine('myName', { counter, counterDoubled }) const countersShape2 = c({ counter, counterDoubled }) const countersShape3 = c('myName', { counter, counterDoubled }) const countersShape4 = c(['myName'], { counter, counterDoubled })
import React, { Component } from 'react'; import LoginModalContainer from 'containers/modal/LoginModalContainer'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import * as baseActions from 'store/modules/base'; import { inform } from 'lib/shouldCancel'; class Base extends Component { initialize = () => { const { BaseActions } = this.props; if(localStorage.logged === "true") { BaseActions.tempLogin(); } BaseActions.checkLogin(); } componentDidMount() { this.initialize(); inform(); } render() { return ( <div> <LoginModalContainer/> { /* 전역적으로 사용되는 컴포넌트들이 있다면 여기서 렌더링합니다. */} </div> ) } } export default connect( null, (dispatch) => ({ BaseActions: bindActionCreators(baseActions, dispatch) }) )(Base);
var partition__copy_8hpp = [ [ "PartitionCopyable", "partition__copy_8hpp.html#ga5c959d0ba6110faea7e16a61ac9215cc", null ], [ "partition_copy", "partition__copy_8hpp.html#ga798952e773075c765b42436bf6ffd872", null ] ];
// Copyright (C) 2020 Rick Waldron. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-atomics.waitasync description: > Throws a TypeError if index arg can not be converted to an Integer info: | Atomics.waitAsync( typedArray, index, value, timeout ) 1. Return DoWait(async, typedArray, index, value, timeout). DoWait ( mode, typedArray, index, value, timeout ) 2. Let i be ? ValidateAtomicAccess(typedArray, index). ValidateAtomicAccess( typedArray, requestIndex ) 2. Let accessIndex be ? ToIndex(requestIndex). ToIndex ( value ) 2. Else, a. Let integerIndex be ? ToInteger(value). ToInteger(value) 1. Let number be ? ToNumber(argument). Symbol --> Throw a TypeError exception. features: [Atomics.waitAsync, SharedArrayBuffer, Symbol, Symbol.toPrimitive, TypedArray, computed-property-names, Atomics, BigInt] ---*/ assert.sameValue(typeof Atomics.waitAsync, 'function'); const i64a = new BigInt64Array( new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT * 4) ); const poisonedValueOf = { valueOf() { throw new Test262Error('should not evaluate this code'); } }; const poisonedToPrimitive = { [Symbol.toPrimitive]() { throw new Test262Error('should not evaluate this code'); } }; assert.throws(Test262Error, function() { Atomics.waitAsync(i64a, poisonedValueOf, poisonedValueOf, poisonedValueOf); }, '`Atomics.waitAsync(i64a, poisonedValueOf, poisonedValueOf, poisonedValueOf)` throws Test262Error'); assert.throws(Test262Error, function() { Atomics.waitAsync(i64a, poisonedToPrimitive, poisonedToPrimitive, poisonedToPrimitive); }, '`Atomics.waitAsync(i64a, poisonedToPrimitive, poisonedToPrimitive, poisonedToPrimitive)` throws Test262Error'); assert.throws(TypeError, function() { Atomics.waitAsync(i64a, Symbol('1'), poisonedValueOf, poisonedValueOf); }, '`Atomics.waitAsync(i64a, Symbol("1"), poisonedValueOf, poisonedValueOf)` throws TypeError'); assert.throws(TypeError, function() { Atomics.waitAsync(i64a, Symbol('2'), poisonedToPrimitive, poisonedToPrimitive); }, '`Atomics.waitAsync(i64a, Symbol("2"), poisonedToPrimitive, poisonedToPrimitive)` throws TypeError');
import "core-js/stable"; import "regenerator-runtime/runtime"; import "dotenv/config"; import server from "server"; const PORT = process.env.PORT || 3000; server.listen(PORT);
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ // This is a traditional Vietnamese typewriter layout. Keyboards['vi-Typewriter'] = { label: 'Vietnamese', shortLabel: 'Vi', menuLabel: 'Tiếng Việt', imEngine: 'vietnamese', needsCandidatePanel: true, width: 10, types: ['text', 'url', 'email'], lang: 'vi', alt: { 'đ': 'z', 'ư': 'f', 'ơ': 'j', 'ă': 'w', '.': ',?!-;:' }, keys: [ [ { value: 'a' }, { value: 'đ' }, { value: 'e' }, { value: 'r' }, { value: 't' } , { value: 'y' }, { value: 'u' }, { value: 'i' }, { value: 'o' }, { value: 'p' } ], [ { value: 'q' }, { value: 's' }, { value: 'd' }, { value: 'ư' }, { value: 'g' } , { value: 'h' }, { value: 'ơ' }, { value: 'k' }, { value: 'l' }, { value: 'm' } ], [ { value: '⇪', ratio: 1.5, keyCode: KeyEvent.DOM_VK_CAPS_LOCK }, { value: 'ă' }, { value: 'x' }, { value: 'c' }, { value: 'v' }, { value: 'b' }, { value: 'n' }, { value: '^', keyCode: 94 }, { value: '⌫', ratio: 1.5, keyCode: KeyEvent.DOM_VK_BACK_SPACE } ], [ { value: '&nbsp', ratio: 8, keyCode: KeyboardEvent.DOM_VK_SPACE }, { value: '↵', ratio: 2, keyCode: KeyEvent.DOM_VK_RETURN } ] ] };
goog.provide('os.olm.render.BaseShape'); goog.require('goog.Disposable'); goog.require('goog.asserts'); goog.require('ol.Feature'); goog.require('ol.events'); goog.require('ol.layer.Vector'); goog.require('ol.render.EventType'); goog.require('ol.source.Vector'); /** * @constructor * @extends {goog.Disposable} * @param {ol.style.Style|Array<ol.style.Style>} style Style. * @abstract */ os.olm.render.BaseShape = function(style) { /** * @private e @type {ol.PluggableMap} */ this.map_ = null; /** * @private * @type {ol.style.Style|Array<ol.style.Style>} */ this.style_ = style; /** * Draw overlay where our sketch features are drawn. * @type {ol.layer.Vector} * @private */ this.overlay_ = new ol.layer.Vector({ source: new ol.source.Vector({ useSpatialIndex: false, wrapX: os.map.PROJECTION.canWrapX() }), style: style, updateWhileAnimating: true, updateWhileInteracting: true }); /** * @type {ol.Feature} * @private */ this.feature_ = new ol.Feature(); }; goog.inherits(os.olm.render.BaseShape, goog.Disposable); /** * @inheritDoc */ os.olm.render.BaseShape.prototype.disposeInternal = function() { this.setMap(null); }; /** * @protected */ os.olm.render.BaseShape.prototype.render = function() { var geom = this.getGeometry(); var overlaySource = this.overlay_.getSource(); overlaySource.clear(true); if (this.map_ !== null && geom) { this.feature_.setGeometry(geom); this.feature_.setStyle(this.getStyle()); overlaySource.addFeature(this.feature_); } }; /** * @return {ol.PluggableMap} The map */ os.olm.render.BaseShape.prototype.getMap = function() { return this.map_; }; /** * @param {ol.PluggableMap} map Map. * * @suppress {accessControls} */ os.olm.render.BaseShape.prototype.setMap = function(map) { this.overlay_.setMap(map); // update the wrap value in the event that the projection has changed since creation this.overlay_.getSource().wrapX_ = os.map.PROJECTION.canWrapX(); this.map_ = map; this.render(); }; /** * @return {ol.geom.Geometry} The geometry to draw */ os.olm.render.BaseShape.prototype.getGeometry = goog.abstractMethod; /** * @return {ol.style.Style|Array<ol.style.Style>} The style */ os.olm.render.BaseShape.prototype.getStyle = function() { return this.style_; };
import React from 'react'; import timeago from 'timeago.js'; import styled from 'styled-components'; import Profile from './Profile'; import { VerifyButton } from './Buttons.js'; import { CollapsableText } from './CollapsableText'; import Reactions from './Reactions'; const Message = styled.p` font-size: 1.5rem; margin: 20px; overflow-wrap: break-word; white-space: pre-wrap; word-break: break-word; margin: 0px 0px 10px 50px; padding: 10px; border-radius: 10px; @media (max-width: 770px) { font-size: 1rem; margin: 8px 0px 10px 45px; padding: 10px; } `; const ReplyContainer = styled.div` @media (max-width: 770px) { margin-left: 0px; } `; const ReplyProfile = styled(Profile)` display: flex; `; const Reply = ({ id, from, entityInfo, createdAt, onVerify, family, message, reactions, onShowLikers, disabledInteractions, style = {}, }) => ( <ReplyContainer> <ReplyProfile from={from} entityInfo={entityInfo}> {reactions && ( <Reactions id={id} reactions={reactions} disabledInteractions={disabledInteractions} onShowLikers={onShowLikers} style={{ fontSize: '1rem' }} /> )} <span>{timeago().format(createdAt)}</span> <VerifyButton onClick={onVerify} /> </ReplyProfile> <Message> <CollapsableText text={message} /> </Message> </ReplyContainer> ); export default Reply;
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /* skin.js ========= In this file we interact with the CKEditor JavaScript API to register the skin and enable additional skin related features. The level of complexity of this file depends on the features available in the skin. There is only one mandatory line of code to be included here, which is setting CKEDITOR.skin.name. All the rest is optional, but recommended to be implemented as they make higher quality skins. For this skin, the following tasks are achieved in this file: 1. Register the skin. 2. Register browser specific skin files. 3. Define the "Chameleon" feature. 4. Register the skin icons, to have them used on the development version of the skin. */ // 1. Register the skin // ---------------------- // The CKEDITOR.skin.name property must be set to the skin name. This is a // lower-cased name, which must match the skin folder name as well as the value // used on config.skin to tell the editor to use the skin. // // This is the only mandatory property to be defined in this file. CKEDITOR.skin.name = 'icy_orange'; // 2. Register browser specific skin files // ----------------------------------------- // (http://docs.cksource.com/CKEditor_4.x/Skin_SDK/Browser_Hacks) // // To help implementing browser specific "hacks" to the skin files and have it // easy to maintain, it is possible to have dedicated files for such browsers, // for both the main skin CSS files: editor.css and dialog.css. // // The browser files must be named after the main file names, appended by an // underscore and the browser name (e.g. editor_ie.css, dialog_ie8.css). // // The accepted browser names must match the CKEDITOR.env properties. The most // common names are: ie, opera, webkit and gecko. Check the documentation for // the complete list: // http://docs.ckeditor.com/#!/api/CKEDITOR.env // // Internet explorer is an expection and the browser version is also accepted // (ie7, ie8, ie9, ie10), as well as a special name for IE in Quirks mode (iequirks). // // The available browser specific files must be set separately for editor.css // and dialog.css. CKEDITOR.skin.ua_editor = 'ie,iequirks,ie7,ie8,gecko'; CKEDITOR.skin.ua_dialog = 'ie,iequirks,ie7,ie8,opera'; // 3. Define the "Chameleon" feature // ----------------------------------- // (http://docs.cksource.com/CKEditor_4.x/Skin_SDK/Chameleon) // // "Chameleon" is a unique feature available in CKEditor. It makes it possible // to end users to specify which color to use as the basis for the editor UI. // It is enough to set config.uiColor to any color value and voila, the UI is // colored. // // The only detail here is that the skin itself must be compatible with the // Chameleon feature. That's because the skin CSS files are the responsible to // apply colors in the UI and each skin do that in different way and on // different places. // // Implementing the Chameleon feature requires a bit of JavaScript programming. // The CKEDITOR.skin.chameleon function must be defined. It must return the CSS // "template" to be used to change the color of a specific CKEditor instance // available in the page. When a color change is required, this template is // appended to the page holding the editor, overriding styles defined in the // skin files. // // The "$color" placeholder can be used in the returned string. It'll be // replaced with the desired color. CKEDITOR.skin.chameleon = (function() { // This method can be used to adjust colour brightness of various element. // Colours are accepted in 7-byte hex format, for example: #00ff00. // Brightness ratio must be a float number within [-1, 1], // where -1 is black, 1 is white and 0 is the original colour. var colorBrightness = (function() { function channelBrightness( channel, ratio ) { return ( '0' + ( ratio < 0 ? 0 | channel * ( 1 + ratio ) : 0 | channel + ( 255 - channel ) * ratio ).toString( 16 ) ).slice( -2 ); } return function( hexColor, ratio ) { var channels = hexColor.match( /[^#]./g ); for ( var i = 0 ; i < 3 ; i++ ) channels[ i ] = channelBrightness( parseInt( channels[ i ], 16 ), ratio ); return '#' + channels.join( '' ); }; })(), // Use this function just to avoid having to repeat all these rules on // several places of our template. verticalGradient = (function() { var template = new CKEDITOR.template( 'background:#{to};'+ 'background-image:-webkit-gradient(linear,lefttop,leftbottom,from({from}),to({to}));'+ 'background-image:-moz-linear-gradient(top,{from},{to});'+ 'background-image:-webkit-linear-gradient(top,{from},{to});'+ 'background-image:-o-linear-gradient(top,{from},{to});'+ 'background-image:-ms-linear-gradient(top,{from},{to});'+ 'background-image:linear-gradient(top,{from},{to});'+ 'filter:progid:DXImageTransform.Microsoft.gradient(gradientType=0,startColorstr=\'{from}\',endColorstr=\'{to}\');' ); return function( from, to ) { return template.output( { from: from, to: to } ); }; })(), // Style templates for various user interface parts: // * Default editor template. // * Default panel template. templates = { editor: new CKEDITOR.template( '{id}.cke_chrome [border-color:{defaultBorder};] ' + '{id} .cke_top [ ' + '{defaultGradient}' + 'border-bottom-color:{defaultBorder};' + '] ' + '{id} .cke_bottom [' + '{defaultGradient}' + 'border-top-color:{defaultBorder};' + '] ' + '{id} .cke_resizer [border-right-color:{ckeResizer}] ' + // Dialogs. '{id} .cke_dialog_title [' + '{defaultGradient}' + 'border-bottom-color:{defaultBorder};' + '] ' + '{id} .cke_dialog_footer [' + '{defaultGradient}' + 'outline-color:{defaultBorder};' + 'border-top-color:{defaultBorder};' + // IE7 doesn't use outline. '] ' + '{id} .cke_dialog_tab [' + '{lightGradient}' + 'border-color:{defaultBorder};' + '] ' + '{id} .cke_dialog_tab:hover [' + '{mediumGradient}' + '] ' + '{id} .cke_dialog_contents [' + 'border-top-color:{defaultBorder};' + '] ' + '{id} .cke_dialog_tab_selected, {id} .cke_dialog_tab_selected:hover [' + 'background:{dialogTabSelected};' + 'border-bottom-color:{dialogTabSelectedBorder};' + '] ' + '{id} .cke_dialog_body [' + 'background:{dialogBody};' + 'border-color:{defaultBorder};' + '] ' + // Toolbars, buttons. '{id} .cke_toolgroup [' + '{lightGradient}' + 'border-color:{defaultBorder};' + '] ' + '{id} a.cke_button_off:hover, {id} a.cke_button_off:focus, {id} a.cke_button_off:active [' + '{mediumGradient}' + '] ' + '{id} .cke_button_on [' + '{ckeButtonOn}' + '] ' + '{id} .cke_toolbar_separator [' + 'background-color: {ckeToolbarSeparator};' + '] ' + // Combo buttons. '{id} .cke_combo_button [' + 'border-color:{defaultBorder};' + '{lightGradient}' + '] ' + '{id} a.cke_combo_button:hover, {id} a.cke_combo_button:focus, {id} .cke_combo_on a.cke_combo_button [' + 'border-color:{defaultBorder};' + '{mediumGradient}' + '] ' + // Elementspath. '{id} .cke_path_item [' + 'color:{elementsPathColor};' + '] ' + '{id} a.cke_path_item:hover, {id} a.cke_path_item:focus, {id} a.cke_path_item:active [' + 'background-color:{elementsPathBg};' + '] ' + '{id}.cke_panel [' + 'border-color:{defaultBorder};' + '] ' ), panel: new CKEDITOR.template( // Panel drop-downs. '.cke_panel_grouptitle [' + '{lightGradient}' + 'border-color:{defaultBorder};' + '] ' + // Context menus. '.cke_menubutton_icon [' + 'background-color:{menubuttonIcon};' + '] ' + '.cke_menubutton:hover .cke_menubutton_icon, .cke_menubutton:focus .cke_menubutton_icon, .cke_menubutton:active .cke_menubutton_icon [' + 'background-color:{menubuttonIconHover};' + '] ' + '.cke_menuseparator [' + 'background-color:{menubuttonIcon};' + '] ' + // Color boxes. 'a:hover.cke_colorbox, a:focus.cke_colorbox, a:active.cke_colorbox [' + 'border-color:{defaultBorder};' + '] ' + 'a:hover.cke_colorauto, a:hover.cke_colormore, a:focus.cke_colorauto, a:focus.cke_colormore, a:active.cke_colorauto, a:active.cke_colormore [' + 'background-color:{ckeColorauto};' + 'border-color:{defaultBorder};' + '] ' ) }; return function( editor, part ) { var uiColor = editor.uiColor, // The following are CSS styles used in templates. // Styles are generated according to current editor.uiColor. templateStyles = { // CKEditor instances have a unique ID, which is used as class name into // the outer container of the editor UI (e.g. ".cke_1"). // // The Chameleon feature is available for each CKEditor instance, // independently. Because of this, we need to prefix all CSS selectors with // the unique class name of the instance. id: '.' + editor.id, // These styles are used by various UI elements. defaultBorder: colorBrightness( uiColor, -0.1 ), defaultGradient: verticalGradient( colorBrightness( uiColor, 0.9 ), uiColor ), lightGradient: verticalGradient( colorBrightness( uiColor, 1 ), colorBrightness( uiColor, 0.7 ) ), mediumGradient: verticalGradient( colorBrightness( uiColor, 0.8 ), colorBrightness( uiColor, 0.5 ) ), // These are for specific UI elements. ckeButtonOn: verticalGradient( colorBrightness( uiColor, 0.6 ), colorBrightness( uiColor, 0.7 ) ), ckeResizer: colorBrightness( uiColor, -0.4 ), ckeToolbarSeparator: colorBrightness( uiColor, 0.5 ), ckeColorauto: colorBrightness( uiColor, 0.8 ), dialogBody: colorBrightness( uiColor, 0.7 ), // Use gradient instead of simple hex to avoid further filter resetting in IE. dialogTabSelected: verticalGradient( '#FFFFFF', '#FFFFFF' ), dialogTabSelectedBorder: '#FFF', elementsPathColor: colorBrightness( uiColor, -0.6 ), elementsPathBg: uiColor, menubuttonIcon: colorBrightness( uiColor, 0.5 ), menubuttonIconHover: colorBrightness( uiColor, 0.3 ) }; return templates[ part ] .output( templateStyles ) .replace( /\[/g, '{' ) // Replace brackets with braces. .replace( /\]/g, '}' ); }; })(); // %REMOVE_START% // 4. Register the skin icons for development purposes only // ---------------------------------------------------------- // (http://docs.cksource.com/CKEditor_4.x/Skin_SDK/Icons) // // Note: As "moono" is the default CKEditor skin, it provides no custom icons, // thus this code is commented out. // // This code is here just to make the skin work fully when using its "source" // version. Without this, the skin will still work, but its icons will not be // used (again, on source version only). // // This block of code is not necessary on the release version of the skin. // Because of this it is very important to include it inside the REMOVE_START // and REMOVE_END comment markers, so the skin builder will properly clean // things up. // // If a required icon is not available here, the plugin defined icon will be // used instead. This means that a skin is not required to provide all icons. // Actually, it is not required to provide icons at all. // (function() { // The available icons. This list must match the file names (without // extension) available inside the "icons" folder. var icons = ( 'about,anchor-rtl,anchor,bgcolor,bidiltr,bidirtl,blockquote,' + 'bold,bulletedlist-rtl,bulletedlist,button,checkbox,copy-rtl,copy,' + 'creatediv,cut-rtl,cut,docprops-rtl,docprops,find-rtl,find,flash,form,' + 'hiddenfield,horizontalrule,icons,iframe,image,imagebutton,indent-rtl,' + 'indent,italic,justifyblock,justifycenter,justifyleft,justifyright,' + 'link,maximize,newpage-rtl,newpage,numberedlist-rtl,numberedlist,' + 'outdent-rtl,outdent,pagebreak-rtl,pagebreak,paste-rtl,paste,' + 'pastefromword-rtl,pastefromword,pastetext-rtl,pastetext,placeholder,preview-rtl,' + 'preview,print,radio,redo-rtl,redo,removeformat,replace,save,scayt,' + 'select-rtl,select,selectall,showblocks-rtl,showblocks,smiley,' + 'source-rtl,source,specialchar,spellchecker,strike,subscript,' + 'superscript,table,templates-rtl,templates,textarea-rtl,textarea,' + 'textcolor,textfield,underline,undo-rtl,undo,unlink' ).split( ',' ); var iconsFolder = CKEDITOR.getUrl( CKEDITOR.skin.path() + 'icons/' ); for ( var i = 0; i < icons.length; i++ ) { CKEDITOR.skin.addIcon( icons[ i ], iconsFolder + icons[ i ] + '.png' ); } })(); // %REMOVE_END%
module.exports = { "parser":"babel-eslint", "extends":"airbnb-base", "env":{ "browser":true, "node":true }, rules:{ "linebreak-style": 0 } }
{ appDir: '..', baseUrl: 'js', dir: '../../../build_stage/calendar', fileExclusionRegExp: /^\.|^build$|^test$/, mainConfigFile: '../js/main.js', optimize: 'none', logLevel: 2, // Be sure to normalize all define() calls by extracting // dependencies so Function toString is not needed, and // lower capability devices like Tarako can optimize // memory by discarding function sources. This is // automatically done when an 'optimize' value other than // 'none' is used. This setting makes sure it happens for // builds where 'none' is used for 'optimize'. normalizeDirDefines: 'all', modules: [ { create: true, name: 'bundle', include: [ 'ext/curl', 'main', 'views/errors', 'views/month', 'views/month_day_agenda', 'views/time_header' ] }, { create: true, name: 'lazy_loaded', include: [ 'views/current_time', 'views/week', 'views/advanced_settings', 'views/create_account', 'views/day', 'views/modify_account', 'views/modify_event', 'views/settings', 'views/view_event' ], exclude: ['bundle'] }, { name: 'caldav_worker', include: [ // This is needed so that we can use the rjs api right off the bat // in the worker rather than needing to load it via importScripts // before calling require, define, etc. 'ext/alameda', // We need to load the caldav wrapper and external libs dynamically // since we have to prime the global environment for the caldav // and ical libraries before loading them (they use the global // variable window to figure out that they're in the browser vs. node // env which isn't a worker default). We should fix that upstream. 'service/caldav', 'worker/initialize' ], exclude: [ 'ext/caldav', 'ext/ical' ] }, { name: 'ext/caldav' }, { name: 'ext/ical' } ], paths: { prim: 'empty:', shared: '../shared/js' }, // Keeping build dir since Makefile cleans it up and // preps build dir with the shared directory keepBuildDir: true, removeCombined: true }
"use strict"; var _getClassName2 = _interopRequireDefault(require("@dr.pogodin/babel-plugin-react-css-modules/dist/browser/getClassName")); require("./foo.css"); require("./bar.css"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } const _styleModuleImportMap = { "./foo.css": { "b": "foo__b" }, "./bar.css": { "a": "bar__a" } }; const styleNameA = 'a'; const styleNameB = 'b'; <div className={(0, _getClassName2.default)(styleNameA, _styleModuleImportMap, { "autoResolveMultipleImports": true, "handleMissingStyleName": "throw" })}></div>; <div className={(0, _getClassName2.default)(styleNameB, _styleModuleImportMap, { "autoResolveMultipleImports": true, "handleMissingStyleName": "throw" })}></div>;
const CACHE_NAME = "static-cache-v2"; const DATA_CACHE_NAME = "data-cache-v1"; const FILES_TO_CACHE = [ "/", "/index.html", "/manifest.webmanifest", "/index.js", "/db.js", "/styles.css", "/icons/icon-192x192.png", "/icons/icon-512x512.png" ]; // install self.addEventListener("install", function (evt) { // pre cache all static assets evt.waitUntil( caches.open(CACHE_NAME).then((cache) => cache.addAll(FILES_TO_CACHE)) ); // tell the browser to activate this service worker immediately once it // has finished installing self.skipWaiting(); }); // activate self.addEventListener("activate", function(evt) { evt.waitUntil( caches.keys().then(keyList => { return Promise.all( keyList.map(key => { if (key !== CACHE_NAME && key !== DATA_CACHE_NAME) { console.log("Removing old cache data", key); return caches.delete(key); } }) ); }) ); self.clients.claim(); }); // fetch self.addEventListener("fetch", function(evt) { if (evt.request.url.includes("/api/")) { evt.respondWith( caches.open(DATA_CACHE_NAME).then(cache => { return fetch(evt.request) .then(response => { // If the response was good, clone it and store it in the cache. if (response.status === 200) { cache.put(evt.request.url, response.clone()); } return response; }) .catch(err => { // Network request failed, try to get it from the cache. return cache.match(evt.request); }); }).catch(err => console.log(err)) ); return; } evt.respondWith( caches.open(CACHE_NAME).then(cache => { return cache.match(evt.request).then(response => { return response || fetch(evt.request); }); }) ); });
/* * [Česky] * Projekt: Robot Karel * Copyright: Viz KOPIROVANI v kořenovém adresáři projektu * * [English] * Project: Karel, the Robot * Copyright: See COPYING in the top level directory */ // JavaScript - ovládání editoru // POZNÁMKA: Řetězec načtený z příkazového pole je vnitřně udržován ve formě // escape(), protože Konqueror (KDE JavaScript) neumí pracovat s Unicode. // =========================================================================== // =~ Globální nastavení ~==================================================== // Ukládat, nebo neukládat syntakticky chybné příkazy? nastaveni.ukladat_syntakticky_chybne = true; // =========================================================================== // =~ Globální proměnné ~===================================================== // Editor editor = new Object(); // Panel nástrojů editor.nastroje = new Array( [ "novy", "tip-novy", "Nový příkaz", "Vytvoř nový příkaz" ], null, [ "ulozit", "tip-ulozit-prikaz", "Ulož příkaz", "Ulož příkaz do slovníku" ], [ "ulozit-jako", "tip-ulozit-jako", "Ulož příkaz nově", "Ulož příkaz pod novým jménem" ] ); editor.nastroje.id_prefix = "editor-"; editor.nastroje.mys = "editor.mys_nastroje"; // Myš nad nástroji editor.mys_nastroje = new Mys(new Tooltip()); // Zobrazený příkaz včetně textového obsahu (pro účely zjištění změny) editor.zobrazeny = { prikaz: null, obsah: null, zmeneny: false }; // =========================================================================== // =~ Základní funkce pro práci se slovníkem ~================================ editor.mys_nastroje.proved_zvyrazneni = function(info, detail) { return true; } editor.mys_nastroje.prekresli_stav = function(nastroj, detail, zvyraznen, stisknut, vybran) { tvoric.zvyraznovac( editor.nastroje.id_prefix+nastroj, zvyraznen, stisknut, vybran); } editor.mys_nastroje.vyber = function(nastroj, detail) { switch ( nastroj ) { case "novy": editor.prikaz_novy(); break; case "ulozit": case "ulozit-jako": editor.prikaz_uloz( (nastroj == "ulozit-jako") ); break; default: ladici_vypis(CHYBA, "editor.mys_nastroje.vyber", nastroj, "vybrán neznámý příkaz"); } return false; } editor.mys_nastroje.tooltip.obnov = function (tooltip, info, detail) { tvoric.obnov_tooltip( tooltip, detail.ikona, detail.nadpis, detail.popis ); } // Zruš ukazatel změny příkazu editor.zrus_zmenu = function() { nastav_text(document.getElementById('zmeneny-prikaz'), ''); this.zobrazeny.zmeneny = false; } // Editovaný text s upravenými konci řádku editor.editovany_text = function (text) { var element = document.getElementById('editace'); if ( text ) { element.value = unescape(text); } else { // Konqueror neumí správně nahrazovat, proto řetězec zpracováváme v escape // módu var obsah = escape(element.value); return obsah.replace(/%0D(%0A)?/g, "%0A"); } } // Nastaví jméno zobrazeného příkazu editor.zobrazene_jmeno = function (text) { nastav_text(document.getElementById('zobrazeny-prikaz'), text); } // Nastav (obnov) ukazatel změny příkazu editor.nastav_zmenu = function () { if ( this.zobrazeny.obsah != this.editovany_text() ) { nastav_text(document.getElementById('zmeneny-prikaz'), '+'); this.zobrazeny.zmeneny = true; } else { this.zrus_zmenu(); } return this.zobrazeny.zmeneny; } // Kontrola změny příkazu a uložení změn. Vrací true, pokud se může pokračovat editor.kontrola_zmeny = function () { if ( this.nastav_zmenu() ) { var jmeno = "Nový příkaz"; if ( this.zobrazeny.prikaz ) { jmeno = "Zobrazený příkaz " + this.zobrazeny.prikaz.jmeno; } var uzivatel_chce = window.confirm( jmeno + " byl změněn.\n\nPřejete si ho uložit?\n" + "(OK=Ano, Storno=Ne)" ); if ( uzivatel_chce ) { return editor.prikaz_uloz(); } else { var uzivatel_chce = window.confirm( jmeno + " nebyl uložen. Přesto pokračovat?" ); if ( !uzivatel_chce ) { return false; } } } return true; } // =========================================================================== // =~ Formátování chyb ~====================================================== // Zobrazení chyby při ukládání příkazu editor.formatuj_chybu_ukladani = function (text, uloz_nove, nove_jmeno, cislo_radky, telo, ulozit) { var text_radky = ""; var prikaz_radky = ""; var varovani = ""; if ( cislo_radky != undefined && cislo_radky != null && cislo_radky >= 0 ) { text_radky = " na řádce " + (cislo_radky+1); if ( telo && cislo_radky < telo.length ) { prikaz_radky = ": " + prikazy.formatovac.zformatuj_jednu_radku(telo[cislo_radky]); } } if ( !ulozit ) { varovani = "\n\nZměny příkazu nebyly uloženy."; } if ( nove_jmeno ) { return "Ukládaný příkaz " + nove_jmeno + " má chybu" + text_radky + prikaz_radky + ".\n" + text + varovani; } else if ( uloz_nove && this.zobrazeny.prikaz ) { return "Zobrazený příkaz " + this.zobrazeny.prikaz.jmeno + " má chybu" + text_radky + prikaz_radky + ".\n" + text + varovani; } else { return "Ukládaný příkaz má" + text_radky + " chybu" + prikaz_radky + ".\n" + text + varovani; } } // Zobrazení chyby při zobrazení příkazu editor.formatuj_chybu_zobrazeni = function (text, jmeno, cislo_radky, telo) { var text_radky = ""; var prikaz_radky = ""; if ( cislo_radky != undefined && cislo_radky != null ) { text_radky = " na řádce " + (cislo_radky+1); if ( telo && cislo_radky < telo.length ) { prikaz_radky = ": " + prikazy.formatovac.zformatuj_jednu_radku(telo[cislo_radky]); } } return "Zobrazovaný příkaz " + jmeno + " má chybu" + text_radky + prikaz_radky + ".\n" + text; } // =========================================================================== // =~ Příkazy editace ~======================================================= // Nový příkaz editor.prikaz_novy = function (bez_kontroly) { if ( !bez_kontroly && !this.kontrola_zmeny() ) return; var jmeno; var i = 1; do { jmeno = "NOVÝ PŘÍKAZ"; if ( i > 1 ) jmeno += " "+i; for ( var j = prikazy.seznam.length-1; j >= 0 && !prikazy.seznam[j].systemovy; j-- ) { if ( jmeno == prikazy.seznam[j].jmeno ) break; } if ( j < 0 || j >= 0 && prikazy.seznam[j].systemovy ) break; i++; } while ( true ); // Struktura nového příkazu pro zformátování. Zformátování je nutné, protože // se obsah uchovává ve formě escape() var prikaz = { jmeno: jmeno }; prikaz.telo = [ [ prikazy.NAZEV, prikaz ], [ prikazy.KONEC ] ]; var obsah = new Obsah(); var vysledek = prikazy.formatovac.zformatuj_prikaz(prikaz, obsah); this.zobrazene_jmeno(prikazy.zadny_prikaz); this.zobrazeny.prikaz = null; this.zobrazeny.obsah = obsah.obsah(); this.editovany_text( this.zobrazeny.obsah ); this.zrus_zmenu(); } // Zkontroluj, jestli se nepřepisuje nějaký příkaz. Vrací false, pokud se nemá // přepisovat; true, pokud se normálně pokračuje; nebo příkaz pro smazání, pokud // se přepisuje editor.kontrola_prepsani = function (uloz_nove, novy_prikaz) { var smaz_prikaz; for ( var i = prikazy.seznam.length-1; i >= 0; i-- ) { var prikaz = prikazy.seznam[i]; if ( prikaz.zobrazit ) { if ( prikaz.jmeno == novy_prikaz.jmeno && this.zobrazeny.prikaz != prikaz ) { if ( !window.confirm("Opravdu má být přepsán příkaz " + prikaz.jmeno + "?") ) { return false; } else { if ( !uloz_nove && this.zobrazeny.prikaz ) { // Po změně musíme smazat původní příkaz smaz_prikaz = this.zobrazeny.prikaz; this.zobrazeny.prikaz = prikaz; return smaz_prikaz; } else { this.zobrazeny.prikaz = prikaz; return true; } } } } } return true; } // Proveď uložení příkazu editor.proved_ulozeni = function (uloz_nove, novy_prikaz, obsah) { if ( uloz_nove || !this.zobrazeny.prikaz ) { prikazy.pridej_novy(novy_prikaz); } else { prikazy.zmen_prikaz(this.zobrazeny.prikaz, novy_prikaz); } this.zobrazeny.obsah = obsah; this.zobrazeny.prikaz = novy_prikaz; this.zobrazene_jmeno(novy_prikaz.jmeno); } // Ulož příkaz. Vrací true, pokud se může pokračovat editor.prikaz_uloz = function (uloz_nove) { if ( !prikazy.test_spusteni() ) return false; var text = this.editovany_text(); var vysledek = new Vysledek(); var uloz_nove_prikaz = (!uloz_nove ? this.zobrazeny.prikaz : undefined); vysledek.nastav( prikazy.rozpoznavac.rozpoznej( text, uloz_nove_prikaz ) ); var novy_prikaz = vysledek.hodnota.prikaz; var obsah = vysledek.hodnota.obsah; var cislo_radky = vysledek.hodnota.cislo_radky; var ulozit = false; if ( !vysledek.byla_chyba() ) { var novy_obsah = new Obsah(); vysledek.nastav( prikazy.formatovac.zformatuj_prikaz(novy_prikaz, novy_obsah) ); obsah = novy_obsah.obsah(); cislo_radky = vysledek.hodnota.cislo_radky; // Uložit příkaz, stejně jako ve verzi 1.2, nebo neuložit? if ( nastaveni.ukladat_syntakticky_chybne ) { ulozit = true; } else { ulozit = !vysledek.byla_chyba(); } } vysledek.chyba.formatuj = function (text) { return editor.formatuj_chybu_ukladani(text, uloz_nove, novy_prikaz.jmeno, cislo_radky, novy_prikaz.telo, ulozit); } // Obnov obsah editovacího pole if ( obsah != this.editovany_text() ) { this.editovany_text( obsah ); } // Kontrola přepsání zobrazeného příkazu if ( novy_prikaz.jmeno ) { if ( uloz_nove && this.zobrazeny.prikaz && this.zobrazeny.prikaz.jmeno == novy_prikaz.jmeno ) { uloz_nove = false; } } vysledek.zobraz_chybu(); if ( ulozit ) { var smaz_prikaz; var vyber_prikaz; // Kontrola přepsání smaz_prikaz = this.kontrola_prepsani(uloz_nove, novy_prikaz); if ( !smaz_prikaz ) { ulozit = false; } // Zjisti, jestli se má udržet nějaký výběr if ( ulozit && !uloz_nove && smaz_prikaz instanceof Object && prikazy.vybrany_prikaz() == smaz_prikaz.jmeno ) { vyber_prikaz = novy_prikaz.jmeno; } // Smaž příkaz, pokud je co smazat if ( smaz_prikaz instanceof Object ) { prikazy.nahrad_telo( smaz_prikaz, novy_prikaz ); prikazy.proved_smazani( smaz_prikaz ); } // Ulož nový příkaz if ( ulozit ) { this.proved_ulozeni( uloz_nove, novy_prikaz, obsah ); } // Obnov výběr příkazu if ( vyber_prikaz && vyber_prikaz != prikazy.vybrany_prikaz() ) { prikazy.vyber_prikaz(vyber_prikaz); } } // end if ( !chyba.byla_chyba() ) // Indikuj změnu obsahu a vrať výsledek - true, pokud bylo uloženo return !this.nastav_zmenu(); } // Příkaz byl doplněn, obnov zobrazení editor.prikaz_upraven = function (prikaz) { if ( this.zobrazeny.prikaz == prikaz ) { var obsah = new Obsah(); prikazy.formatovac.zformatuj_prikaz( this.zobrazeny.prikaz, obsah ); this.zobrazeny.obsah = obsah.obsah(); if ( this.nastav_zmenu() ) { // Pokud nebyl příkaz změněný, zobraz nový obsah this.editovany_text( obsah.obsah() ); this.nastav_zmenu(); } } } // Zobrazit vybraný příkaz editor.zobraz_vybrany_prikaz = function () { if ( !this.kontrola_zmeny() ) return; // Kontrola vybraného příkazu je nutná i zde, protože se výběr mohl // uložením změnit var jmeno = prikazy.vybrany_prikaz(); if ( !(jmeno && prikazy.prikaz[jmeno]) ) { alert( "Není vybrán žádný příkaz.\n\n" + "Příkaz vyberte klepnutím myši." ); return; } var prikaz = prikazy.prikaz[jmeno]; var vysledek = new Vysledek(); var obsah = new Obsah(); var chyba = new Chyba(); vysledek.nastav( prikazy.formatovac.zformatuj_prikaz(prikaz, obsah) ); vysledek.chyba.formatuj = function (text) { return editor.formatuj_chybu_zobrazeni(text, prikaz.jmeno, vysledek.hodnota.cislo_radky, prikaz.telo); } this.zobrazeny.prikaz = prikaz; this.zobrazene_jmeno(prikaz.jmeno); this.zobrazeny.obsah = obsah.obsah(); this.editovany_text( obsah.obsah() ); this.nastav_zmenu(); vysledek.zobraz_chybu(); } // Příkaz byl smazán editor.smaz_prikaz = function (prikaz) { if ( this.zobrazeny.prikaz == prikaz ) { this.zobrazeny.prikaz = null; this.zobrazeny.obsah = null; this.zobrazene_jmeno(prikazy.zadny_prikaz); this.nastav_zmenu(); } }
var path = require('path'); // debug 模式, 会输出一些调试用的 log exports.DEBUG = true; // ==== 服务器相关的配置 ==================================================== // 服务器运行的端口 exports.PORT = 8091; // 数据库的名字为 xzone, 账号为 xzone_user 密码: HeMHFxTAMPAjlRVH // 可以自行修改 exports.DB_URI = 'mongodb://xzone_user:HeMHFxTAMPAjlRVH@127.0.0.1:27017/xzone'; // 文件保存的根目录 exports.FILE_SAVE_ROOT = '/home/swall/xzone/'; // 上传的文件保存的目录, 相对于 FILE_SAVE_ROOT // 文件上传后会保存到 FILE_SAVE_ROOT + FILE_SAVE_DIR 下 exports.FILE_SAVE_DIR = '/data/files/'; // 批量下载时打包成zip包的保存目录, 相对于 FILE_SAVE_ROOT exports.FILE_ZIP_DIR = '/data/zip/'; // jodconverter 的路径, 用于把doc转换为pdf exports.JOD_CONVERTER = path.join(__dirname, '../../lib/jodconverter-core-3.0-beta-4.jar'); // ==== 应用自身相关的配置 ==================================================== // 应用运行的域名 exports.APP_DOMAIN = 'http://xzone.codewalle.com'; // cookie 的加密key exports.COOKIE_SECRET= 'xzone_HeMHFxTAMPAjlRVH_secret'; // cookie 的有效时间 exports.COOKIE_TIME = 24 * 60 * 60 * 1000; // 24 小时 exports.STATIC_FILE_EXPIRES = 7 * 24 * 60 * 60 * 1000; // 静态文件的过期时间 // 默认每个用户的空间大小 3G exports.DEFAULT_USER_SPACE = 3 * 1024 * 1024 * 1024; // 允许新媒体跨域上传和下载资源的 host exports.XHR2_ALLOW_ORIGIN = [ 'http://media.71xiaoxue.com', 'http://swall.codewalle.com' ]; // 下载的接口列表 exports.DOWNLOAD_APIS = [ '/api/file/download', '/api/file/batchDownload' ]; // 多媒体的上传接口 exports.MEDIA_UPLOAD_CGI = '/api/media/upload'; // 多媒体下载接口 exports.MEDIA_DOWNLOAD_CGI = '/api/media/download'; exports.AUTH_TYPE = 'self';// auto, sso, qq, self, huairou // 一些页面 url 的常量 exports.INDEX_PAGE = '/index.html'; exports.LOGIN_PAGE = '/login.html'; exports.LOGIN_FAIL_PAGE = '/loginfail.html'; exports.NOT_FOUND_PAGE = '/404.html'; // ==== User Center 相关的配置 ==================================================== // 默认新建用户的密码 exports.DEFAULT_USER_PWD = '8888'; // ==== SSO登陆相关的配置 ==================================================== // CAS 的配置以及登录成功后的跳转 URL exports.CAS_BASE_URL = 'http://dand.71xiaoxue.com:80/sso.web'; // 这里要改为对应域名 exports.CAS_SERVICE = '/api/user/loginSuccess'; // 获取用户详细资料的CGI exports.CAS_USER_INFO_CGI = 'http://mapp.71xiaoxue.com/components/getUserInfo.htm'; // 获取用户组织列表单cgi exports.CAS_ORG_TREE_CGI = 'http://mapp.71xiaoxue.com/components/getOrgTree.htm'; // ==== QQ登陆相关的配置 ==================================================== // QQ 互联的 appid exports.QQ_CONNECT_APPID = '100548719'; // appkey exports.QQ_CONNECT_APPKEY = '9e47324ac7fed9f8364d4982ccf3037e'; // 登陆成功的回调地址 exports.QQ_CONNECT_CALLBACK = '/api/user/loginSuccessWithQQ'; exports.QQ_CONNECT_SITE = 'https://graph.qq.com'; exports.QQ_CONNECT_AUTH_PATH = '/oauth2.0/authorize'; exports.QQ_CONNECT_TOKEN_PATH = '/oauth2.0/token'; exports.QQ_CONNECT_OPENID_PATH = '/oauth2.0/me'; exports.QQ_CONNECT_USERINFO_PATH = '/user/get_user_info';
__NUXT_JSONP__("/107/3", (function(a,b,c,d,e,f,g,h){return {data:[{metaTitle:b,metaDesc:c,verseId:d,surahId:107,currentSurah:{number:"107",name:"الماعون",name_latin:"Al-Ma'un",number_of_ayah:"7",text:{"1":"اَرَءَيْتَ الَّذِيْ يُكَذِّبُ بِالدِّيْنِۗ","2":"فَذٰلِكَ الَّذِيْ يَدُعُّ الْيَتِيْمَۙ","3":"وَلَا يَحُضُّ عَلٰى طَعَامِ الْمِسْكِيْنِۗ","4":"فَوَيْلٌ لِّلْمُصَلِّيْنَۙ","5":"الَّذِيْنَ هُمْ عَنْ صَلَاتِهِمْ سَاهُوْنَۙ","6":"الَّذِيْنَ هُمْ يُرَاۤءُوْنَۙ","7":"وَيَمْنَعُوْنَ الْمَاعُوْنَ ࣖ"},translations:{id:{name:"Barang Yang Berguna",text:{"1":"Tahukah kamu (orang) yang mendustakan agama?","2":"Maka itulah orang yang menghardik anak yatim,","3":"dan tidak mendorong memberi makan orang miskin.","4":"Maka celakalah orang yang salat,","5":"(yaitu) orang-orang yang lalai terhadap salatnya,","6":"yang berbuat ria,","7":"dan enggan (memberikan) bantuan."}}},tafsir:{id:{kemenag:{name:"Kemenag",source:"Aplikasi Quran Kementrian Agama Republik Indonesia",text:{"1":"Dalam ayat ini, Allah menghadapkan pertanyaan kepada Nabi Muhammad, \"Apakah engkau mengetahui orang yang mendustakan agama dan yang dimaksud dengan orang yang mendustakan agama?\" Pertanyaan ini dijawab pada ayat-ayat berikut.","2":"Allah lalu menjelaskan bahwa sebagian dari sifat-sifat orang yang mendustakan agama ialah orang-orang yang menolak dan membentak anak-anak yatim yang datang kepadanya untuk memohon belas-kasihnya demi kebutuhan hidupnya. Penolakannya itu sebagai penghinaan dan takabur terhadap anak-anak yatim itu.","3":"Allah menegaskan lebih lanjut sifat pendusta itu, yaitu dia tidak mengajak orang lain untuk membantu dan memberi makan orang miskin. Bila tidak mau mengajak orang memberi makan dan membantu orang miskin berarti ia tidak melakukannya sama sekali. Berdasarkan keterangan di atas, bila seorang tidak sanggup membantu orang-orang miskin maka hendaklah ia menganjurkan orang lain agar melakukan usaha yang mulia itu.","4":e,"5":e,"6":"Allah selanjutnya menambah penjelasan tentang sifat orang pendusta agama, yaitu mereka melakukan perbuatan-perbuatan lahir hanya semata karena ria, tidak terkesan pada jiwanya untuk meresapi rahasia dan hikmahnya.","7":"Allah menambahkan lagi dalam ayat ini sifat pendusta itu, yaitu mereka tidak mau memberikan barang-barang yang diperlukan oleh orang-orang yang membutuhkannya, sedang barang itu tak pantas ditahan, seperti periuk, kapuk, cangkul, dan lain-lain. \n\nKeadaan orang yang membesarkan agama berbeda dengan keadaan orang yang mendustakan agama, karena yang pertama tampak dalam tata hidupnya yang jujur, adil, kasih sayang, pemurah, dan lain-lain. Sedangkan sifat pendusta agama ialah ria, curang, aniaya, takabur, kikir, memandang rendah orang lain, tidak mementingkan yang lain kecuali dirinya sendiri, bangga dengan harta dan kedudukan, serta tidak mau mengeluarkan sebahagian dari hartanya, baik untuk keperluan perseorangan maupun untuk masyarakat."}}}}},jsonldBreadcrumb:{"@context":f,"@type":"BreadcrumbList",itemListElement:[{"@type":a,position:1,name:"Home",item:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F"},{"@type":a,position:2,name:"QS 107",item:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F107\u002F"},{"@type":a,position:d,name:"QS 107:3",item:g}]},jsonLdArticle:{"@context":f,"@type":"NewsArticle",mainEntityOfPage:{"@type":"WebPage","@id":g},headline:b,image:["http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002Fmeta-image.png"],datePublished:h,dateModified:h,author:{"@type":"Person",name:"Irfan Maulana"},description:c,publisher:{"@type":"Organization",name:"mazipan",logo:{"@type":"ImageObject",url:"http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002Ficon.png"}}}}],fetch:[],mutations:[]}}("ListItem","Ayat ke 3, Quran Surat Al-Ma'un الماعون (Barang Yang Berguna) | e-AlQuran","Ayat ke 3, Quran Surat Al-Ma'un الماعون (Barang Yang Berguna) beserta terjemahan dan tafsir dari Kemenag, ",3,"Dalam ayat-ayat ini, Allah mengungkapkan satu ancaman yaitu celakalah orang-orang yang mengerjakan salat dengan tubuh dan lidahnya, tidak sampai ke hatinya. Dia lalai dan tidak menyadari apa yang diucapkan lidahnya dan yang dikerjakan oleh anggota tubuhnya. Ia rukuk dan sujud dalam keadaan lalai, ia mengucapkan takbir tetapi tidak menyadari apa yang diucapkannya. Semua itu adalah hanya gerak biasa dan kata-kata hafalan semata-mata yang tidak mempengaruhi apa-apa, tidak ubahnya seperti robot.\n\nPerilaku tersebut ditujukan kepada orang-orang yang mendustakan agama, yaitu orang munafik. Ancaman itu tidak ditujukan kepada orang-orang muslim yang awam, tidak mengerti bahasa Arab, dan tidak tahu tentang arti dari apa yang dibacanya. Jadi orang-orang awam yang tidak memahami makna dari apa yang dibacanya dalam salat tidak termasuk orang-orang yang lalai seperti yang disebut dalam ayat ini.","https:\u002F\u002Fschema.org","http:\u002F\u002Fquran.almazayaislamicschool.sch.id\u002F107\u002F3\u002F","2020-08-14T03:42:32.790Z")));
import React from 'react'; import { Icon } from './Icon'; import { a, b, cr, dw, me, bgd } from './fragments'; export var TwoToneLiveHelp = /*#__PURE__*/ function TwoToneLiveHelp(props) { return React.createElement(Icon, props, React.createElement("path", { opacity: ".3", d: "M5 18h4.83L12 20.17l1.59-1.59.58-.58H19V4H5zm8-1" + me + "M12 5c2.21 0 4 1.79 4 4 0 2.5-3 2.75-3 5h-2c0-3.25 3-3 3-5 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4z" }), React.createElement("path", { d: "M21 4" + b + dw + "v14" + cr + "h4l3 3 3-3h4" + a + "zm-2 14" + bgd })); };
/** * @see https://github.com/eslint/eslint/blob/master/tests/lib/rules/require-jsdoc.js */ export default { invalid: [ { code: ` function quux (foo) { }`, errors: [ { line: 2, message: 'Missing JSDoc comment.' } ] }, { code: 'function myFunction() {}', errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionDeclaration' }] }, { code: `/** * Description for A. */ class A { constructor(xs) { this.a = xs; } }`, errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionExpression' }], options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `class A { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, errors: [{ message: 'Missing JSDoc comment.', type: 'ClassDeclaration' }], options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, errors: [{ message: 'Missing JSDoc comment.', type: 'ClassDeclaration' }], options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `export class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, errors: [{ message: 'Missing JSDoc comment.', type: 'ClassDeclaration' }], options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { sourceType: 'module' } }, { code: `export default class A extends B { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, errors: [{ message: 'Missing JSDoc comment.', type: 'ClassDeclaration' }], options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { sourceType: 'module' } }, { code: 'var myFunction = () => {}', errors: [{ message: 'Missing JSDoc comment.', type: 'ArrowFunctionExpression' }], options: [{ require: { ArrowFunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: 'var myFunction = () => () => {}', errors: [{ message: 'Missing JSDoc comment.', type: 'ArrowFunctionExpression' }], options: [{ require: { ArrowFunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: 'var foo = function() {}', errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionExpression' }], options: [{ require: { FunctionExpression: true } }] }, { code: 'const foo = {bar() {}}', errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionExpression' }], options: [{ require: { FunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: 'var foo = {bar: function() {}}', errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionExpression' }], options: [{ require: { FunctionExpression: true } }] }, { code: ` function foo (abc) {} `, errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionDeclaration' }], settings: { jsdoc: { exemptEmptyFunctions: false } } }, { code: ` function foo () { return true; } `, errors: [{ message: 'Missing JSDoc comment.', type: 'FunctionDeclaration' }], settings: { jsdoc: { exemptEmptyFunctions: false } } } ], valid: [{ code: ` var array = [1,2,3]; array.forEach(function() {}); /** * @class MyClass **/ function MyClass() {} /** Function doing something */ function myFunction() {} /** Function doing something */ var myFunction = function() {}; /** Function doing something */ Object.myFunction = function () {}; var obj = { /** * Function doing something **/ myFunction: function () {} }; /** @func myFunction */ function myFunction() {} /** @method myFunction */ function myFunction() {} /** @function myFunction */ function myFunction() {} /** @func myFunction */ var myFunction = function () {} /** @method myFunction */ var myFunction = function () {} /** @function myFunction */ var myFunction = function () {} /** @func myFunction */ Object.myFunction = function() {} /** @method myFunction */ Object.myFunction = function() {} /** @function myFunction */ Object.myFunction = function() {} (function(){})(); var object = { /** * @func myFunction - Some function */ myFunction: function() {} } var object = { /** * @method myFunction - Some function */ myFunction: function() {} } var object = { /** * @function myFunction - Some function */ myFunction: function() {} } var array = [1,2,3]; array.filter(function() {}); Object.keys(this.options.rules || {}).forEach(function(name) {}.bind(this)); var object = { name: 'key'}; Object.keys(object).forEach(function() {}) ` }, { code: 'function myFunction() {}', options: [{ require: { ClassDeclaration: true, FunctionDeclaration: false, MethodDefinition: true } }] }, { code: 'var myFunction = function() {}', options: [{ require: { ClassDeclaration: true, FunctionDeclaration: false, MethodDefinition: true } }] }, { code: ` /** * Description for A. */ class A { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `/** * Description for A. */ class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `/** * Description for A. */ export default class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6, sourceType: 'module' } }, { code: `/** * Description for A. */ export class App extends Component { /** * Description for constructor. * @param {object[]} xs - xs */ constructor(xs) { this.a = xs; } }`, options: [{ require: { ClassDeclaration: true, MethodDefinition: true } }], parserOptions: { ecmaVersion: 6, sourceType: 'module' } }, { code: `class A { constructor(xs) { this.a = xs; } }`, options: [{ require: { ClassDeclaration: false, MethodDefinition: false } }], parserOptions: { ecmaVersion: 6 } }, { code: `/** Function doing something */ var myFunction = () => {}`, options: [{ require: { ArrowFunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `/** Function doing something */ var myFunction = () => () => {}`, options: [{ require: { ArrowFunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: 'setTimeout(() => {}, 10);', options: [{ require: { ArrowFunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `/** JSDoc Block */ var foo = function() {}`, options: [{ require: { FunctionExpression: true } }] }, { code: `const foo = {/** JSDoc Block */ bar() {}}`, options: [{ require: { FunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: `var foo = {/** JSDoc Block */ bar: function() {}}`, options: [{ require: { FunctionExpression: true } }] }, { code: ' var foo = { [function() {}]: 1 };', options: [{ require: { FunctionExpression: true } }], parserOptions: { ecmaVersion: 6 } }, { code: ` function foo () {} `, settings: { jsdoc: { exemptEmptyFunctions: true } } }, { code: ` function foo () { return; } `, settings: { jsdoc: { exemptEmptyFunctions: true } } } ] };
/* 4 Debe modificarse el desarrollo del punto anterior para permitir: ● Cargar un array con x múltiplos del número n, siendo que x y n son valores que ingresa el usuario por teclado. Se deben imprimir los valores calculados. ● Repetir el proceso hasta que el usuario ingrese 0 para la cantidad de múltiplos a generar, es decir, cuando x = 0. */ function multiplosEnArray(numeroN,limiteMultiplos) { let items = []; let i = 1; let limite = 0; let multiplo = numeroN while (limite < limiteMultiplos) { items.push(multiplo) i++; multiplo = numeroN * i; limite++; } return console.log("Numero de multiples pedidos = "+limiteMultiplos+ " Los multiplos de "+numeroN+" son ",items); } multiplosEnArray(2,0);
/* global AJS */ /** * Utility functions for translating or interpolating text. * @module jira/util/formatter */ define('jira/util/formatter', ['exports', 'jira/util/data/meta'], function (exports, Meta) { 'use strict'; /** * Takes a string with placeholder markers and a variable number of arguments * to substitute in to it, and returns an interpolated string. * @type {function} * @returns {string} an interpolated string */ var formatText = AJS.format.bind(AJS); /** * @note This function's implementation will only ever be invoked * during tests or other scenarios where web-resource transformations * did not occur to actually replace the untranslated text before * getting to production. * @param {string} i18nString the translation string from the .properties file. * the string can mark placeholders in the form of \{0\}, \{1\}, etc. * @param {...string} [subValues] any number of values to substitute in to the * translation string. * @returns {string} a translated string with any values substituted * in the order they were provided. */ function getTranslatedText() { return AJS.I18n.getText.apply(AJS.I18n, arguments); } // Only supports formatting integers to match the user locale. // Can be extended to support more complex formatting, and decimals, if necessary. function formatNumber(integer) { var groupSeparator = Meta.get('user-locale-group-separator') || ''; // Replace every character boundary that is not a word boundary, and is followed by a multiple of 3 of digits, // with the groupSeparator return integer.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, groupSeparator); } /** * A generic formatter. Exposed so as to support the web-resource manager's * substitution of {@link #I18n.getText} calls with formatting calls. * Do not use this function directly. Use {@link #formatText} instead. * @private * @type {function} */ exports.format = formatText; exports.formatNumber = formatNumber; exports.formatText = formatText; exports.I18n = {}; exports.I18n.getText = getTranslatedText; });
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([["chunk-c8ee2132"],{1876:function(e,t,i){"use strict";i.r(t);var s=function(){var e=this,t=e.$createElement,i=e._self._c||t;return i("div",{staticClass:"components-container"},[e._m(0),e._v(" "),i("div",{staticClass:"editor-container"},[i("dropzone",{attrs:{id:"myVueDropzone",url:"https://httpbin.org/post"},on:{"dropzone-removedFile":e.dropzoneR,"dropzone-success":e.dropzoneS}})],1)])},n=[function(){var e=this,t=e.$createElement,i=e._self._c||t;return i("aside",[e._v("\n Based on "),i("a",{staticClass:"link-type",attrs:{href:"https://github.com/rowanwins/vue-dropzone"}},[e._v(" dropzone ")]),e._v(".\n Because my business has special needs, and has to upload images to qiniu, so instead of a third party, I chose encapsulate it by myself. It is very simple, you can see the detail code in @/components/Dropzone.\n ")])}],o=function(){var e=this,t=e.$createElement,i=e._self._c||t;return i("div",{ref:e.id,staticClass:"dropzone",attrs:{id:e.id,action:e.url}},[i("input",{attrs:{type:"file",name:"file"}})])},a=[],d=(i("c5f6"),i("79e3")),l=i.n(d);i("7bc13");l.a.autoDiscover=!1;var r={props:{id:{type:String,required:!0},url:{type:String,required:!0},clickable:{type:Boolean,default:!0},defaultMsg:{type:String,default:"上传图片"},acceptedFiles:{type:String,default:""},thumbnailHeight:{type:Number,default:200},thumbnailWidth:{type:Number,default:200},showRemoveLink:{type:Boolean,default:!0},maxFilesize:{type:Number,default:2},maxFiles:{type:Number,default:3},autoProcessQueue:{type:Boolean,default:!0},useCustomDropzoneOptions:{type:Boolean,default:!1},defaultImg:{default:"",type:[String,Array]},couldPaste:{type:Boolean,default:!1}},data:function(){return{dropzone:"",initOnce:!0}},watch:{defaultImg:function(e){0!==e.length?this.initOnce&&(this.initImages(e),this.initOnce=!1):this.initOnce=!1}},mounted:function(){var e=document.getElementById(this.id),t=this;this.dropzone=new l.a(e,{clickable:this.clickable,thumbnailWidth:this.thumbnailWidth,thumbnailHeight:this.thumbnailHeight,maxFiles:this.maxFiles,maxFilesize:this.maxFilesize,dictRemoveFile:"Remove",addRemoveLinks:this.showRemoveLink,acceptedFiles:this.acceptedFiles,autoProcessQueue:this.autoProcessQueue,dictDefaultMessage:'<i style="margin-top: 3em;display: inline-block" class="material-icons">'+this.defaultMsg+"</i><br>Drop files here to upload",dictMaxFilesExceeded:"只能一个图",previewTemplate:'<div class="dz-preview dz-file-preview"> <div class="dz-image" style="width:'+this.thumbnailWidth+"px;height:"+this.thumbnailHeight+'px" ><img style="width:'+this.thumbnailWidth+"px;height:"+this.thumbnailHeight+'px" data-dz-thumbnail /></div> <div class="dz-details"><div class="dz-size"><span data-dz-size></span></div> <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div> <div class="dz-error-message"><span data-dz-errormessage></span></div> <div class="dz-success-mark"> <i class="material-icons">done</i> </div> <div class="dz-error-mark"><i class="material-icons">error</i></div></div>',init:function(){var e=this,i=t.defaultImg;if(i)if(Array.isArray(i)){if(0===i.length)return;i.map((function(i,s){var n={name:"name"+s,size:12345,url:i};return e.options.addedfile.call(e,n),e.options.thumbnail.call(e,n,i),n.previewElement.classList.add("dz-success"),n.previewElement.classList.add("dz-complete"),t.initOnce=!1,!0}))}else{var s={name:"name",size:12345,url:i};this.options.addedfile.call(this,s),this.options.thumbnail.call(this,s,i),s.previewElement.classList.add("dz-success"),s.previewElement.classList.add("dz-complete"),t.initOnce=!1}},accept:function(e,t){t()},sending:function(e,i,s){t.initOnce=!1}}),this.couldPaste&&document.addEventListener("paste",this.pasteImg),this.dropzone.on("success",(function(e){t.$emit("dropzone-success",e,t.dropzone.element)})),this.dropzone.on("addedfile",(function(e){t.$emit("dropzone-fileAdded",e)})),this.dropzone.on("removedfile",(function(e){t.$emit("dropzone-removedFile",e)})),this.dropzone.on("error",(function(e,i,s){t.$emit("dropzone-error",e,i,s)})),this.dropzone.on("successmultiple",(function(e,i,s){t.$emit("dropzone-successmultiple",e,i,s)}))},destroyed:function(){document.removeEventListener("paste",this.pasteImg),this.dropzone.destroy()},methods:{removeAllFiles:function(){this.dropzone.removeAllFiles(!0)},processQueue:function(){this.dropzone.processQueue()},pasteImg:function(e){var t=(e.clipboardData||e.originalEvent.clipboardData).items;"file"===t[0].kind&&this.dropzone.addFile(t[0].getAsFile())},initImages:function(e){var t=this;if(e)if(Array.isArray(e))e.map((function(e,i){var s={name:"name"+i,size:12345,url:e};return t.dropzone.options.addedfile.call(t.dropzone,s),t.dropzone.options.thumbnail.call(t.dropzone,s,e),s.previewElement.classList.add("dz-success"),s.previewElement.classList.add("dz-complete"),!0}));else{var i={name:"name",size:12345,url:e};this.dropzone.options.addedfile.call(this.dropzone,i),this.dropzone.options.thumbnail.call(this.dropzone,i,e),i.previewElement.classList.add("dz-success"),i.previewElement.classList.add("dz-complete")}}}},c=r,p=(i("1b95"),i("2877")),u=Object(p["a"])(c,o,a,!1,null,"2bb8ff5e",null),m=u.exports,h={name:"DropzoneDemo",components:{Dropzone:m},methods:{dropzoneS:function(e){console.log(e),this.$message({message:"Upload success",type:"success"})},dropzoneR:function(e){console.log(e),this.$message({message:"Delete success",type:"success"})}}},f=h,z=Object(p["a"])(f,s,n,!1,null,null,null);t["default"]=z.exports},"1b95":function(e,t,i){"use strict";i("4e00")},"4e00":function(e,t,i){}}]);