code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/*global define*/ define({ "_widgetLabel": "グリッド オーバーレイ", "description": "座標グリッド オーバーレイを表示するカスタム Web AppBuilder ウィジェットです。" });
tmcgee/cmv-wab-widgets
wab/2.15/widgets/GridOverlay/nls/ja/strings.js
JavaScript
mit
213
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : (factory()); }(this, (function () { 'use strict'; var foo = 42; assert.equal( foo, 42 ); })));
Victorystick/rollup
test/form/side-effect/_expected/umd.js
JavaScript
mit
270
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * Changes may cause incorrect behavior and will be lost if the code is * regenerated. */ 'use strict'; /** * The resource limits. * */ class ResourceLimits { /** * Create a ResourceLimits. * @member {number} [memoryInGB] The memory limit in GB of this container * instance. * @member {number} [cpu] The CPU limit of this container instance. */ constructor() { } /** * Defines the metadata of ResourceLimits * * @returns {object} metadata of ResourceLimits * */ mapper() { return { required: false, serializedName: 'ResourceLimits', type: { name: 'Composite', className: 'ResourceLimits', modelProperties: { memoryInGB: { required: false, serializedName: 'memoryInGB', type: { name: 'Number' } }, cpu: { required: false, serializedName: 'cpu', type: { name: 'Number' } } } } }; } } module.exports = ResourceLimits;
lmazuel/azure-sdk-for-node
lib/services/containerinstanceManagement/lib/models/resourceLimits.js
JavaScript
mit
1,320
#!/usr/bin/env node /*! * Module dependencies. */ var CLI = require('../lib/cli'), argv = require('optimist').boolean('d') .boolean('device') .boolean('e') .boolean('emulator') .boolean('V') .boolean('verbose') .boolean('v') .boolean('version') .boolean('h') .boolean('help') .argv; /*! * Run the command-line client. */ var cli = new CLI().argv(argv);
makileeshao/e-grocery
temp/phonegap.min.js
JavaScript
mit
665
const {app, ipcMain, webContents, BrowserWindow} = require('electron') const {getAllWebContents} = process.atomBinding('web_contents') const renderProcessPreferences = process.atomBinding('render_process_preferences').forAllWebContents() const {Buffer} = require('buffer') const fs = require('fs') const path = require('path') const url = require('url') // TODO(zcbenz): Remove this when we have Object.values(). const objectValues = function (object) { return Object.keys(object).map(function (key) { return object[key] }) } // Mapping between extensionId(hostname) and manifest. const manifestMap = {} // extensionId => manifest const manifestNameMap = {} // name => manifest const generateExtensionIdFromName = function (name) { return name.replace(/[\W_]+/g, '-').toLowerCase() } const isWindowOrWebView = function (webContents) { const type = webContents.getType() return type === 'window' || type === 'webview' } // Create or get manifest object from |srcDirectory|. const getManifestFromPath = function (srcDirectory) { let manifest let manifestContent try { manifestContent = fs.readFileSync(path.join(srcDirectory, 'manifest.json')) } catch (readError) { console.warn(`Reading ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(readError.stack || readError) throw readError } try { manifest = JSON.parse(manifestContent) } catch (parseError) { console.warn(`Parsing ${path.join(srcDirectory, 'manifest.json')} failed.`) console.warn(parseError.stack || parseError) throw parseError } if (!manifestNameMap[manifest.name]) { const extensionId = generateExtensionIdFromName(manifest.name) manifestMap[extensionId] = manifestNameMap[manifest.name] = manifest Object.assign(manifest, { srcDirectory: srcDirectory, extensionId: extensionId, // We can not use 'file://' directly because all resources in the extension // will be treated as relative to the root in Chrome. startPage: url.format({ protocol: 'chrome-extension', slashes: true, hostname: extensionId, pathname: manifest.devtools_page }) }) return manifest } else if (manifest && manifest.name) { console.warn(`Attempted to load extension "${manifest.name}" that has already been loaded.`) } } // Manage the background pages. const backgroundPages = {} const startBackgroundPages = function (manifest) { if (backgroundPages[manifest.extensionId] || !manifest.background) return let html let name if (manifest.background.page) { name = manifest.background.page html = fs.readFileSync(path.join(manifest.srcDirectory, manifest.background.page)) } else { name = '_generated_background_page.html' const scripts = manifest.background.scripts.map((name) => { return `<script src="${name}"></script>` }).join('') html = new Buffer(`<html><body>${scripts}</body></html>`) } const contents = webContents.create({ partition: 'persist:__chrome_extension', isBackgroundPage: true, commandLineSwitches: ['--background-page'] }) backgroundPages[manifest.extensionId] = { html: html, webContents: contents, name: name } contents.loadURL(url.format({ protocol: 'chrome-extension', slashes: true, hostname: manifest.extensionId, pathname: name })) } const removeBackgroundPages = function (manifest) { if (!backgroundPages[manifest.extensionId]) return backgroundPages[manifest.extensionId].webContents.destroy() delete backgroundPages[manifest.extensionId] } const sendToBackgroundPages = function (...args) { for (const page of objectValues(backgroundPages)) { page.webContents.sendToAll(...args) } } // Dispatch web contents events to Chrome APIs const hookWebContentsEvents = function (webContents) { const tabId = webContents.id sendToBackgroundPages('CHROME_TABS_ONCREATED') webContents.on('will-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONBEFORENAVIGATE', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.on('did-navigate', (event, url) => { sendToBackgroundPages('CHROME_WEBNAVIGATION_ONCOMPLETED', { frameId: 0, parentFrameId: -1, processId: webContents.getProcessId(), tabId: tabId, timeStamp: Date.now(), url: url }) }) webContents.once('destroyed', () => { sendToBackgroundPages('CHROME_TABS_ONREMOVED', tabId) }) } // Handle the chrome.* API messages. let nextId = 0 ipcMain.on('CHROME_RUNTIME_CONNECT', function (event, extensionId, connectInfo) { const page = backgroundPages[extensionId] if (!page) { console.error(`Connect to unknown extension ${extensionId}`) return } const portId = ++nextId event.returnValue = {tabId: page.webContents.id, portId: portId} event.sender.once('render-view-deleted', () => { if (page.webContents.isDestroyed()) return page.webContents.sendToAll(`CHROME_PORT_DISCONNECT_${portId}`) }) page.webContents.sendToAll(`CHROME_RUNTIME_ONCONNECT_${extensionId}`, event.sender.id, portId, connectInfo) }) ipcMain.on('CHROME_I18N_MANIFEST', function (event, extensionId) { event.returnValue = manifestMap[extensionId] }) ipcMain.on('CHROME_RUNTIME_SENDMESSAGE', function (event, extensionId, message) { const page = backgroundPages[extensionId] if (!page) { console.error(`Connect to unknown extension ${extensionId}`) return } page.webContents.sendToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, event.sender.id, message) }) ipcMain.on('CHROME_TABS_SEND_MESSAGE', function (event, tabId, extensionId, isBackgroundPage, message) { const contents = webContents.fromId(tabId) if (!contents) { console.error(`Sending message to unknown tab ${tabId}`) return } const senderTabId = isBackgroundPage ? null : event.sender.id contents.sendToAll(`CHROME_RUNTIME_ONMESSAGE_${extensionId}`, senderTabId, message) }) ipcMain.on('CHROME_TABS_EXECUTESCRIPT', function (event, requestId, tabId, extensionId, details) { const contents = webContents.fromId(tabId) if (!contents) { console.error(`Sending message to unknown tab ${tabId}`) return } let code, url if (details.file) { const manifest = manifestMap[extensionId] code = String(fs.readFileSync(path.join(manifest.srcDirectory, details.file))) url = `chrome-extension://${extensionId}${details.file}` } else { code = details.code url = `chrome-extension://${extensionId}/${String(Math.random()).substr(2, 8)}.js` } contents.send('CHROME_TABS_EXECUTESCRIPT', event.sender.id, requestId, extensionId, url, code) }) // Transfer the content scripts to renderer. const contentScripts = {} const injectContentScripts = function (manifest) { if (contentScripts[manifest.name] || !manifest.content_scripts) return const readArrayOfFiles = function (relativePath) { return { url: `chrome-extension://${manifest.extensionId}/${relativePath}`, code: String(fs.readFileSync(path.join(manifest.srcDirectory, relativePath))) } } const contentScriptToEntry = function (script) { return { matches: script.matches, js: script.js.map(readArrayOfFiles), runAt: script.run_at || 'document_idle' } } try { const entry = { extensionId: manifest.extensionId, contentScripts: manifest.content_scripts.map(contentScriptToEntry) } contentScripts[manifest.name] = renderProcessPreferences.addEntry(entry) } catch (e) { console.error('Failed to read content scripts', e) } } const removeContentScripts = function (manifest) { if (!contentScripts[manifest.name]) return renderProcessPreferences.removeEntry(contentScripts[manifest.name]) delete contentScripts[manifest.name] } // Transfer the |manifest| to a format that can be recognized by the // |DevToolsAPI.addExtensions|. const manifestToExtensionInfo = function (manifest) { return { startPage: manifest.startPage, srcDirectory: manifest.srcDirectory, name: manifest.name, exposeExperimentalAPIs: true } } // Load the extensions for the window. const loadExtension = function (manifest) { startBackgroundPages(manifest) injectContentScripts(manifest) } const loadDevToolsExtensions = function (win, manifests) { if (!win.devToolsWebContents) return manifests.forEach(loadExtension) const extensionInfoArray = manifests.map(manifestToExtensionInfo) win.devToolsWebContents.executeJavaScript(`DevToolsAPI.addExtensions(${JSON.stringify(extensionInfoArray)})`) } app.on('web-contents-created', function (event, webContents) { if (!isWindowOrWebView(webContents)) return hookWebContentsEvents(webContents) webContents.on('devtools-opened', function () { loadDevToolsExtensions(webContents, objectValues(manifestMap)) }) }) // The chrome-extension: can map a extension URL request to real file path. const chromeExtensionHandler = function (request, callback) { const parsed = url.parse(request.url) if (!parsed.hostname || !parsed.path) return callback() const manifest = manifestMap[parsed.hostname] if (!manifest) return callback() const page = backgroundPages[parsed.hostname] if (page && parsed.path === `/${page.name}`) { return callback({ mimeType: 'text/html', data: page.html }) } fs.readFile(path.join(manifest.srcDirectory, parsed.path), function (err, content) { if (err) { return callback(-6) // FILE_NOT_FOUND } else { return callback(content) } }) } app.on('session-created', function (ses) { ses.protocol.registerBufferProtocol('chrome-extension', chromeExtensionHandler, function (error) { if (error) { console.error(`Unable to register chrome-extension protocol: ${error}`) } }) }) // The persistent path of "DevTools Extensions" preference file. let loadedExtensionsPath = null app.on('will-quit', function () { try { const loadedExtensions = objectValues(manifestMap).map(function (manifest) { return manifest.srcDirectory }) if (loadedExtensions.length > 0) { try { fs.mkdirSync(path.dirname(loadedExtensionsPath)) } catch (error) { // Ignore error } fs.writeFileSync(loadedExtensionsPath, JSON.stringify(loadedExtensions)) } else { fs.unlinkSync(loadedExtensionsPath) } } catch (error) { // Ignore error } }) // We can not use protocol or BrowserWindow until app is ready. app.once('ready', function () { // Load persisted extensions. loadedExtensionsPath = path.join(app.getPath('userData'), 'DevTools Extensions') try { const loadedExtensions = JSON.parse(fs.readFileSync(loadedExtensionsPath)) if (Array.isArray(loadedExtensions)) { for (const srcDirectory of loadedExtensions) { // Start background pages and set content scripts. const manifest = getManifestFromPath(srcDirectory) loadExtension(manifest) } } } catch (error) { // Ignore error } // The public API to add/remove extensions. BrowserWindow.addDevToolsExtension = function (srcDirectory) { const manifest = getManifestFromPath(srcDirectory) if (manifest) { loadExtension(manifest) for (const webContents of getAllWebContents()) { if (isWindowOrWebView(webContents)) { loadDevToolsExtensions(webContents, [manifest]) } } return manifest.name } } BrowserWindow.removeDevToolsExtension = function (name) { const manifest = manifestNameMap[name] if (!manifest) return removeBackgroundPages(manifest) removeContentScripts(manifest) delete manifestMap[manifest.extensionId] delete manifestNameMap[name] } BrowserWindow.getDevToolsExtensions = function () { const extensions = {} Object.keys(manifestNameMap).forEach(function (name) { const manifest = manifestNameMap[name] extensions[name] = {name: manifest.name, version: manifest.version} }) return extensions } })
gabriel/electron
lib/browser/chrome-extension.js
JavaScript
mit
12,158
/** * @fileoverview client模式,serve时js文件处理 * @author liweitao */ 'use strict'; module.exports = function ($, appConf, moduleConf, args) { return function (mod, modulePath, appPath) { return new Promise(function (resolve, reject) { var vfs = require('vinyl-fs'); var path = require('path'); var athenaMate = require('../athena_mate'); var useBabel = moduleConf.support.useBabel || { enable: false }; var enableBabel = useBabel.enable; var jsxPragma = useBabel.jsxPragma || 'Nerv.createElement' athenaMate.concat({ cwd: appPath, pageFiles: args.pageFiles, module: moduleConf.module, map: path.join('dist', 'map.json'), dest: 'dist', end: function () { vfs.src(path.join(modulePath, 'dist', '_static', 'js', '**', '*.js')) .pipe($.if(enableBabel, athenaMate.babel({ config: { presets: [ require('babel-preset-es2015'), require('babel-preset-stage-0') ], plugins: [ require('babel-plugin-transform-es3-member-expression-literals'), require('babel-plugin-transform-es3-property-literals'), [require('babel-plugin-transform-react-jsx'), { pragma: jsxPragma }] ] }, fileTest: useBabel.test || /\.js/, exclude: useBabel.exclude || [] }))) .pipe(athenaMate.replace({ cwd: appPath, module: moduleConf.module, serve: true })) .pipe(vfs.dest(path.join(appPath, '.temp', appConf.app, moduleConf.module, 'js'))) .on('end', function () { resolve(); }) .on('error', function (err) { reject(err); }); } }); }); }; };
JDC-FD/athena-html
lib/build/tasks/serve_js.js
JavaScript
mit
1,970
/* * Routes handlers */ var exec = require('child_process').exec, child_process = require('child_process'), fs = require('fs'), child_processes = []; // Basic routing module.exports = function(app) { app.get("/", getHomePage); app.post("/add", postAddScraper); } function getHomePage(req, res) { var port = res.app.settings.config.server.port; res.render('index', { port: port }); } function postAddScraper(req, res) { var url = req.body.url, auth_user = req.body.auth_user, auth_pass = req.body.auth_pass, depth = parseInt(req.body.create_crawler_depth), create_sitemap = req.body.create_crawler_sitemap == 1, clean = req.body.clean_crawl == 1, config = res.app.settings.config; var child = child_process.fork("crawling-daemon.js"); // setup config child.send({ action: "setConfig", config: config }); if (auth_user!="" && auth_pass!="") { child.send({ action: "setAuth", auth_user: auth_user, auth_pass: auth_pass }); } child.send({ action: "start", url: url, clean: clean, depth: depth }); child.on("message", function(data) { switch (data.message) { case "auth-required": data.row_id = data.host.replace(/\./g,""); res.render("partials/scraper-stats-row", {data: data, layout: false}, function(err, html) { if (err != null) { return; } data.html = html; io.sockets.emit('auth-required', data); }); break; case "general-stats": data.row_id = data.host.replace(/\./g,""); res.render("partials/scraper-stats-row", {data: data, layout: false}, function(err, html) { if (err != null) { return; } data.html = html; io.sockets.emit('general-stats', data); }); break; case "done-crawling": case "stop-crawling": if (create_sitemap) { child.send({ action: "createSitemap" }); } else { child.kill(); // Terminate crawling daemon } io.sockets.emit(data.message, data); // done-crawling | stop-crawling break; // @TODO: Implement case "recrawl": break; case "sitemap-created": var sitemap_path = "public/sitemaps/"; fs.exists(sitemap_path, function(exists) { if (!exists) { fs.mkdir(sitemap_path, writeSitemap); } else { writeSitemap(); } // Terminate crawling daemon child.kill(); }); function writeSitemap() { sitemap_path += "sitemap_"+ data.host +".xml"; fs.writeFile(sitemap_path, data.content, function(err) { if(err) { console.log(err); } else { io.sockets.emit('sitemap-ready', { host: data.host, path: sitemap_path.replace("public/", "") }) } }); } break; default: io.sockets.emit(data.message, data); break; } }) res.redirect("/"); }
ecdeveloper/node-web-crawler
routes/index.js
JavaScript
mit
2,818
MSG.title = "Webduino Blockly 課程 1-3:控制兩顆 LED 燈"; MSG.subTitle = "課程 1-3:控制兩顆 LED 燈"; MSG.demoDescription = "點選下圖左右兩顆燈泡,分別控制兩顆 LED 的開或關";
Ye-Yong-Chi/webduino-blockly
msg/tutorials/led-3/zh-hant.js
JavaScript
mit
212
/*global require*/ require({ baseUrl : '.', paths : { domReady : '../../ThirdParty/requirejs-2.1.20/domReady', Cesium : '../../Source' } }, [ 'CesiumViewer' ], function() { });
srujant/MLNews
static/js/cesium/Apps/CesiumViewer/CesiumViewerStartup.js
JavaScript
mit
226
import requestAnimationFrame from 'requestanimationframe' import { DistributeHeight } from './DistributeHeight' export class Resize { constructor () { this.ticking = false // Create an instance of DistributeHeight for each element $('[data-distribute-height]').each((index, element) => { element.distributeHeight = new DistributeHeight($(element)) }) this.calculate = () => { $('[data-distribute-height]').each((index, element) => { element.distributeHeight.setHeights() }) this.ticking = false } } resize () { $(window).on('load resize', () => { this.tick() }) } tick () { if (!this.ticking) { requestAnimationFrame(this.calculate) this.ticking = true } } }
carakas/forkcms
src/Frontend/Themes/Bootstrap4/src/Js/Utilities/Resize.js
JavaScript
mit
767
/*! * froala_editor v3.0.6 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2019 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * Arabic */ FE.LANGUAGE['ar'] = { translation: { // Place holder 'Type something': "\u0627\u0643\u062A\u0628 \u0634\u064A\u0626\u0627", // Basic formatting 'Bold': "\u063A\u0627\u0645\u0642", 'Italic': "\u0645\u0627\u0626\u0644", 'Underline': "\u062A\u0633\u0637\u064A\u0631", 'Strikethrough': "\u064A\u062A\u0648\u0633\u0637 \u062E\u0637", // Main buttons 'Insert': "\u0625\u062F\u0631\u0627\u062C", 'Delete': "\u062D\u0630\u0641", 'Cancel': "\u0625\u0644\u063A\u0627\u0621", 'OK': "\u0645\u0648\u0627\u0641\u0642", 'Back': "\u0638\u0647\u0631", 'Remove': "\u0625\u0632\u0627\u0644\u0629", 'More': "\u0623\u0643\u062B\u0631", 'Update': "\u0627\u0644\u062A\u062D\u062F\u064A\u062B", 'Style': "\u0623\u0633\u0644\u0648\u0628", // Font 'Font Family': "\u0639\u0627\u0626\u0644\u0629 \u0627\u0644\u062E\u0637", 'Font Size': "\u062D\u062C\u0645 \u0627\u0644\u062E\u0637", // Colors 'Colors': "\u0627\u0644\u0623\u0644\u0648\u0627\u0646", 'Background': "\u0627\u0644\u062E\u0644\u0641\u064A\u0629", 'Text': "\u0627\u0644\u0646\u0635", 'HEX Color': 'عرافة اللون', // Paragraphs 'Paragraph Format': "\u062A\u0646\u0633\u064A\u0642 \u0627\u0644\u0641\u0642\u0631\u0629", 'Normal': "\u0637\u0628\u064A\u0639\u064A", 'Code': "\u0643\u0648\u062F", 'Heading 1': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 1", 'Heading 2': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 2", 'Heading 3': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 3", 'Heading 4': "\u0627\u0644\u0639\u0646\u0627\u0648\u064A\u0646 4", // Style 'Paragraph Style': "\u0646\u0645\u0637 \u0627\u0644\u0641\u0642\u0631\u0629", 'Inline Style': "\u0627\u0644\u0646\u0645\u0637 \u0627\u0644\u0645\u0636\u0645\u0646", // Alignment 'Align': "\u0645\u062D\u0627\u0630\u0627\u0629", 'Align Left': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0633\u0627\u0631", 'Align Center': "\u062A\u0648\u0633\u064A\u0637", 'Align Right': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0646\u0635 \u0644\u0644\u064A\u0645\u064A\u0646", 'Align Justify': "\u0636\u0628\u0637", 'None': "\u0644\u0627 \u0634\u064A\u0621", // Lists 'Ordered List': "\u0642\u0627\u0626\u0645\u0629 \u0645\u0631\u062A\u0628\u0629", 'Default': 'الافتراضي', 'Lower Alpha': 'أقل ألفا', 'Lower Greek': 'أقل اليونانية', 'Lower Roman': 'انخفاض الروماني', 'Upper Alpha': 'العلوي ألفا', 'Upper Roman': 'الروماني العلوي', 'Unordered List': "\u0642\u0627\u0626\u0645\u0629 \u063A\u064A\u0631 \u0645\u0631\u062A\u0628\u0629", 'Circle': 'دائرة', 'Disc': 'القرص', 'Square': 'ميدان', // Line height 'Line Height': 'ارتفاع خط', 'Single': 'غير مرتبطة', 'Double': 'مزدوج', // Indent 'Decrease Indent': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629", 'Increase Indent': "\u0632\u064A\u0627\u062F\u0629 \u0627\u0644\u0645\u0633\u0627\u0641\u0629 \u0627\u0644\u0628\u0627\u062F\u0626\u0629", // Links 'Insert Link': "\u0625\u062F\u0631\u0627\u062C \u0631\u0627\u0628\u0637", 'Open in new tab': "\u0641\u062A\u062D \u0641\u064A \u0639\u0644\u0627\u0645\u0629 \u062A\u0628\u0648\u064A\u0628 \u062C\u062F\u064A\u062F\u0629", 'Open Link': "\u0627\u0641\u062A\u062D \u0627\u0644\u0631\u0627\u0628\u0637", 'Edit Link': "\u0627\u0631\u062A\u0628\u0627\u0637 \u062A\u062D\u0631\u064A\u0631", 'Unlink': "\u062D\u0630\u0641 \u0627\u0644\u0631\u0627\u0628\u0637", 'Choose Link': "\u0627\u062E\u062A\u064A\u0627\u0631 \u0635\u0644\u0629", // Images 'Insert Image': "\u0625\u062F\u0631\u0627\u062C \u0635\u0648\u0631\u0629", 'Upload Image': "\u062A\u062D\u0645\u064A\u0644 \u0635\u0648\u0631\u0629", 'By URL': "\u0628\u0648\u0627\u0633\u0637\u0629 URL", 'Browse': "\u062A\u0635\u0641\u062D", 'Drop image': "\u0625\u0633\u0642\u0627\u0637 \u0635\u0648\u0631\u0629", 'or click': "\u0623\u0648 \u0627\u0646\u0642\u0631 \u0641\u0648\u0642", 'Manage Images': "\u0625\u062F\u0627\u0631\u0629 \u0627\u0644\u0635\u0648\u0631", 'Loading': "\u062A\u062D\u0645\u064A\u0644", 'Deleting': "\u062D\u0630\u0641", 'Tags': "\u0627\u0644\u0643\u0644\u0645\u0627\u062A", 'Are you sure? Image will be deleted.': "\u0647\u0644 \u0623\u0646\u062A \u0645\u062A\u0623\u0643\u062F\u061F \u0633\u064A\u062A\u0645 \u062D\u0630\u0641 \u0627\u0644\u0635\u0648\u0631\u0629.", 'Replace': "\u0627\u0633\u062A\u0628\u062F\u0627\u0644", 'Uploading': "\u062A\u062D\u0645\u064A\u0644", 'Loading image': "\u0635\u0648\u0631\u0629 \u062A\u062D\u0645\u064A\u0644", 'Display': "\u0639\u0631\u0636", 'Inline': "\u0641\u064A \u062E\u0637", 'Break Text': "\u0646\u0635 \u0627\u0633\u062A\u0631\u0627\u062D\u0629", 'Alternative Text': "\u0646\u0635 \u0628\u062F\u064A\u0644", 'Change Size': "\u062A\u063A\u064A\u064A\u0631 \u062D\u062C\u0645", 'Width': "\u0639\u0631\u0636", 'Height': "\u0627\u0631\u062A\u0641\u0627\u0639", 'Something went wrong. Please try again.': ".\u062D\u062F\u062B \u062E\u0637\u0623 \u0645\u0627. \u062D\u0627\u0648\u0644 \u0645\u0631\u0629 \u0627\u062E\u0631\u0649", 'Image Caption': 'تعليق على الصورة', 'Advanced Edit': 'تعديل متقدم', // Video 'Insert Video': "\u0625\u062F\u0631\u0627\u062C \u0641\u064A\u062F\u064A\u0648", 'Embedded Code': "\u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629 \u0627\u0644\u0645\u0636\u0645\u0646\u0629", 'Paste in a video URL': 'لصق في عنوان ورل للفيديو', 'Drop video': 'انخفاض الفيديو', 'Your browser does not support HTML5 video.': 'متصفحك لا يدعم فيديو HTML5.', 'Upload Video': 'رفع فيديو', // Tables 'Insert Table': "\u0625\u062F\u0631\u0627\u062C \u062C\u062F\u0648\u0644", 'Table Header': "\u0631\u0623\u0633 \u0627\u0644\u062C\u062F\u0648\u0644", 'Remove Table': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062C\u062F\u0648\u0644", 'Table Style': "\u0646\u0645\u0637 \u0627\u0644\u062C\u062F\u0648\u0644", 'Horizontal Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0641\u0642\u064A\u0629", 'Row': "\u0635\u0641", 'Insert row above': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0639\u0644\u0649", 'Insert row below': "\u0625\u062F\u0631\u0627\u062C \u0635\u0641 \u0644\u0644\u0623\u0633\u0641\u0644", 'Delete row': "\u062D\u0630\u0641 \u0635\u0641", 'Column': "\u0639\u0645\u0648\u062F", 'Insert column before': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0633\u0627\u0631", 'Insert column after': "\u0625\u062F\u0631\u0627\u062C \u0639\u0645\u0648\u062F \u0644\u0644\u064A\u0645\u064A\u0646", 'Delete column': "\u062D\u0630\u0641 \u0639\u0645\u0648\u062F", 'Cell': "\u062E\u0644\u064A\u0629", 'Merge cells': "\u062F\u0645\u062C \u062E\u0644\u0627\u064A\u0627", 'Horizontal split': "\u0627\u0646\u0642\u0633\u0627\u0645 \u0623\u0641\u0642\u064A", 'Vertical split': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645 \u0627\u0644\u0639\u0645\u0648\u062F\u064A", 'Cell Background': "\u062E\u0644\u0641\u064A\u0629 \u0627\u0644\u062E\u0644\u064A\u0629", 'Vertical Align': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0639\u0645\u0648\u062F\u064A\u0629", 'Top': "\u0623\u0639\u0644\u0649", 'Middle': "\u0648\u0633\u0637", 'Bottom': "\u0623\u0633\u0641\u0644", 'Align Top': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0623\u0639\u0644\u0649", 'Align Middle': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0648\u0633\u0637", 'Align Bottom': "\u0645\u062D\u0627\u0630\u0627\u0629 \u0627\u0644\u0623\u0633\u0641\u0644", 'Cell Style': "\u0646\u0645\u0637 \u0627\u0644\u062E\u0644\u064A\u0629", // Files 'Upload File': "\u062A\u062D\u0645\u064A\u0644 \u0627\u0644\u0645\u0644\u0641", 'Drop file': "\u0627\u0646\u062E\u0641\u0627\u0636 \u0627\u0644\u0645\u0644\u0641", // Emoticons 'Emoticons': "\u0627\u0644\u0645\u0634\u0627\u0639\u0631", 'Grinning face': "\u064A\u0643\u0634\u0631 \u0648\u062C\u0647\u0647", 'Grinning face with smiling eyes': "\u0645\u0628\u062A\u0633\u0645\u0627 \u0648\u062C\u0647 \u0645\u0639 \u064A\u0628\u062A\u0633\u0645 \u0627\u0644\u0639\u064A\u0646", 'Face with tears of joy': "\u0648\u062C\u0647 \u0645\u0639 \u062F\u0645\u0648\u0639 \u0627\u0644\u0641\u0631\u062D", 'Smiling face with open mouth': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Smiling face with open mouth and smiling eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u064A\u0628\u062A\u0633\u0645", 'Smiling face with open mouth and cold sweat': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F", 'Smiling face with open mouth and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u064A\u0646\u064A\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0625\u062D\u0643\u0627\u0645", 'Smiling face with halo': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0647\u0627\u0644\u0629", 'Smiling face with horns': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0642\u0631\u0648\u0646", 'Winking face': "\u0627\u0644\u063A\u0645\u0632 \u0648\u062C\u0647", 'Smiling face with smiling eyes': "\u064A\u0628\u062A\u0633\u0645 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645", 'Face savoring delicious food': "\u064A\u0648\u0627\u062C\u0647 \u0644\u0630\u064A\u0630 \u0627\u0644\u0645\u0630\u0627\u0642 \u0644\u0630\u064A\u0630 \u0627\u0644\u0637\u0639\u0627\u0645", 'Relieved face': "\u0648\u062C\u0647 \u0628\u0627\u0644\u0627\u0631\u062A\u064A\u0627\u062D", 'Smiling face with heart-shaped eyes': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0628\u0639\u064A\u0646\u064A\u0646 \u0639\u0644\u0649 \u0634\u0643\u0644 \u0642\u0644\u0628", 'Smiling face with sunglasses': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0628\u062A\u0633\u0645 \u0645\u0639 \u0627\u0644\u0646\u0638\u0627\u0631\u0627\u062A \u0627\u0644\u0634\u0645\u0633\u064A\u0629", 'Smirking face': "\u0633\u0645\u064A\u0631\u0643\u064A\u0646\u062C \u0627\u0644\u0648\u062C\u0647", 'Neutral face': "\u0645\u062D\u0627\u064A\u062F \u0627\u0644\u0648\u062C\u0647", 'Expressionless face': "\u0648\u062C\u0647 \u0627\u0644\u062A\u0639\u0627\u0628\u064A\u0631", 'Unamused face': "\u0644\u0627 \u0645\u0633\u0644\u064A\u0627 \u0627\u0644\u0648\u062C\u0647", 'Face with cold sweat': "\u0648\u062C\u0647 \u0645\u0639 \u0639\u0631\u0642 \u0628\u0627\u0631\u062F", 'Pensive face': "\u0648\u062C\u0647 \u0645\u062A\u0623\u0645\u0644", 'Confused face': "\u0648\u062C\u0647 \u0627\u0644\u062E\u0644\u0637", 'Confounded face': "\u0648\u062C\u0647 \u0645\u0631\u062A\u0628\u0643", 'Kissing face': "\u062A\u0642\u0628\u064A\u0644 \u0627\u0644\u0648\u062C\u0647", 'Face throwing a kiss': "\u0645\u0648\u0627\u062C\u0647\u0629 \u0631\u0645\u064A \u0642\u0628\u0644\u0629", 'Kissing face with smiling eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u062A\u0628\u062A\u0633\u0645", 'Kissing face with closed eyes': "\u062A\u0642\u0628\u064A\u0644 \u0648\u062C\u0647 \u0645\u0639 \u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629", 'Face with stuck out tongue': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646", 'Face with stuck out tongue and winking eye': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0646 \u0627\u0644\u062A\u063A\u0627\u0636\u064A", 'Face with stuck out tongue and tightly-closed eyes': "\u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u062A\u0645\u0633\u0643 \u0628\u0647\u0627 \u0627\u0644\u0644\u0633\u0627\u0646 \u0648\u0627\u0644\u0639\u064A\u0648\u0646 \u0645\u063A\u0644\u0642\u0629 \u0628\u0623\u062D\u0643\u0627\u0645-", 'Disappointed face': "\u0648\u062C\u0647\u0627 \u062E\u064A\u0628\u0629 \u0623\u0645\u0644", 'Worried face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u0642\u0644\u0642\u0648\u0646", 'Angry face': "\u0648\u062C\u0647 \u063A\u0627\u0636\u0628", 'Pouting face': "\u0627\u0644\u0639\u0628\u0648\u0633 \u0648\u062C\u0647", 'Crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0627\u0644\u0648\u062C\u0647", 'Persevering face': "\u0627\u0644\u0645\u062B\u0627\u0628\u0631\u0629 \u0648\u062C\u0647\u0647", 'Face with look of triumph': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0646\u0638\u0631\u0629 \u0627\u0646\u062A\u0635\u0627\u0631", 'Disappointed but relieved face': "\u0628\u062E\u064A\u0628\u0629 \u0623\u0645\u0644 \u0648\u0644\u0643\u0646 \u064A\u0639\u0641\u0649 \u0648\u062C\u0647", 'Frowning face with open mouth': "\u0645\u0642\u0637\u0628 \u0627\u0644\u0648\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Anguished face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u0624\u0644\u0645", 'Fearful face': "\u0627\u0644\u0648\u062C\u0647 \u0627\u0644\u0645\u062E\u064A\u0641", 'Weary face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u0636\u062C\u0631", 'Sleepy face': "\u0648\u062C\u0647 \u0646\u0639\u0633\u0627\u0646", 'Tired face': "\u0648\u062C\u0647 \u0645\u062A\u0639\u0628", 'Grimacing face': "\u0648\u062E\u0631\u062C \u0633\u064A\u0633 \u0627\u0644\u0648\u062C\u0647", 'Loudly crying face': "\u0627\u0644\u0628\u0643\u0627\u0621 \u0628\u0635\u0648\u062A \u0639\u0627\u0644 \u0648\u062C\u0647\u0647", 'Face with open mouth': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645", 'Hushed face': "\u0648\u062C\u0647\u0627 \u0627\u0644\u062A\u0643\u062A\u0645", 'Face with open mouth and cold sweat': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0641\u062A\u062D \u0627\u0644\u0641\u0645 \u0648\u0627\u0644\u0639\u0631\u0642 \u0627\u0644\u0628\u0627\u0631\u062F", 'Face screaming in fear': "\u0648\u0627\u062C\u0647 \u064A\u0635\u0631\u062E \u0641\u064A \u062E\u0648\u0641", 'Astonished face': "\u0648\u062C\u0647\u0627 \u062F\u0647\u0634", 'Flushed face': "\u0627\u062D\u0645\u0631\u0627\u0631 \u0627\u0644\u0648\u062C\u0647", 'Sleeping face': "\u0627\u0644\u0646\u0648\u0645 \u0627\u0644\u0648\u062C\u0647", 'Dizzy face': "\u0648\u062C\u0647\u0627 \u0628\u0627\u0644\u062F\u0648\u0627\u0631", 'Face without mouth': "\u0648\u0627\u062C\u0647 \u062F\u0648\u0646 \u0627\u0644\u0641\u0645", 'Face with medical mask': "\u0648\u0627\u062C\u0647 \u0645\u0639 \u0642\u0646\u0627\u0639 \u0627\u0644\u0637\u0628\u064A\u0629", // Line breaker 'Break': "\u0627\u0644\u0627\u0646\u0642\u0633\u0627\u0645", // Math 'Subscript': "\u0645\u0646\u062E\u0641\u0636", 'Superscript': "\u062D\u0631\u0641 \u0641\u0648\u0642\u064A", // Full screen 'Fullscreen': "\u0643\u0627\u0645\u0644 \u0627\u0644\u0634\u0627\u0634\u0629", // Horizontal line 'Insert Horizontal Line': "\u0625\u062F\u0631\u0627\u062C \u062E\u0637 \u0623\u0641\u0642\u064A", // Clear formatting 'Clear Formatting': "\u0625\u0632\u0627\u0644\u0629 \u0627\u0644\u062A\u0646\u0633\u064A\u0642", // Save 'Save': "\u062D\u0641\u0638", // Undo, redo 'Undo': "\u062A\u0631\u0627\u062C\u0639", 'Redo': "\u0625\u0639\u0627\u062F\u0629", // Select all 'Select All': "\u062A\u062D\u062F\u064A\u062F \u0627\u0644\u0643\u0644", // Code view 'Code View': "\u0639\u0631\u0636 \u0627\u0644\u062A\u0639\u0644\u064A\u0645\u0627\u062A \u0627\u0644\u0628\u0631\u0645\u062C\u064A\u0629", // Quote 'Quote': "\u0627\u0642\u062A\u0628\u0633", 'Increase': "\u0632\u064A\u0627\u062F\u0629", 'Decrease': "\u0627\u0646\u062E\u0641\u0627\u0636", // Quick Insert 'Quick Insert': "\u0625\u062F\u0631\u0627\u062C \u0633\u0631\u064A\u0639", // Spcial Characters 'Special Characters': 'أحرف خاصة', 'Latin': 'لاتينية', 'Greek': 'الإغريقي', 'Cyrillic': 'السيريلية', 'Punctuation': 'علامات ترقيم', 'Currency': 'دقة', 'Arrows': 'السهام', 'Math': 'الرياضيات', 'Misc': 'متفرقات', // Print. 'Print': 'طباعة', // Spell Checker. 'Spell Checker': 'مدقق املائي', // Help 'Help': 'مساعدة', 'Shortcuts': 'اختصارات', 'Inline Editor': 'محرر مضمنة', 'Show the editor': 'عرض المحرر', 'Common actions': 'الإجراءات المشتركة', 'Copy': 'نسخ', 'Cut': 'يقطع', 'Paste': 'معجون', 'Basic Formatting': 'التنسيق الأساسي', 'Increase quote level': 'زيادة مستوى الاقتباس', 'Decrease quote level': 'انخفاض مستوى الاقتباس', 'Image / Video': 'صورة / فيديو', 'Resize larger': 'تغيير حجم أكبر', 'Resize smaller': 'تغيير حجم أصغر', 'Table': 'الطاولة', 'Select table cell': 'حدد خلية الجدول', 'Extend selection one cell': 'توسيع اختيار خلية واحدة', 'Extend selection one row': 'تمديد اختيار صف واحد', 'Navigation': 'التنقل', 'Focus popup / toolbar': 'التركيز المنبثقة / شريط الأدوات', 'Return focus to previous position': 'عودة التركيز إلى الموقف السابق', // Embed.ly 'Embed URL': 'تضمين عنوان ورل', 'Paste in a URL to embed': 'الصق في عنوان ورل لتضمينه', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'المحتوى الذي تم لصقه قادم من وثيقة كلمة ميكروسوفت. هل تريد الاحتفاظ بالتنسيق أو تنظيفه؟', 'Keep': 'احتفظ', 'Clean': 'نظيف', 'Word Paste Detected': 'تم اكتشاف معجون الكلمات', // Character Counter 'Characters': 'الشخصيات', // More Buttons 'More Text': 'المزيد من النص', 'More Paragraph': ' المزيد من الفقرة', 'More Rich': ' أكثر ثراء', 'More Misc': ' أكثر متفرقات' }, direction: 'rtl' }; }))); //# sourceMappingURL=ar.js.map
sufuf3/cdnjs
ajax/libs/froala-editor/3.0.6/js/languages/ar.js
JavaScript
mit
20,426
//copy codes from d3.js, add 4 functions: tickAttr, tickTextAttr, minorTickAttr and domainAttr; //axis() changes, need a raphael paper object param, return raphael set object. //examples in ../examples/axis/ to know the usage. //a basic part for other data visualization format /*global d3*/ /*! * Axis兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Axis', function (require) { /** * function from d3, get scaleRange of an ordinal scale * @param {Array} domain ordinal scale's range */ function d3_scaleExtent(domain) { var start = domain[0], stop = domain[domain.length - 1]; return start < stop ? [start, stop] : [stop, start]; } /** * function from d3, get scaleRange of a scale */ function d3_scaleRange(scale) { return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range()); } /** * function from d3, get subticks * @param scale, scale * @param ticks, major ticks of scale * @param m, number of subdivide */ function d3_svg_axisSubdivide(scale, ticks, m) { var subticks = []; if (m && ticks.length > 1) { var extent = d3_scaleExtent(scale.domain()), i = -1, n = ticks.length, d = (ticks[1] - ticks[0]) / ++m, j, v; while (++i < n) { for (j = m; --j > 0;) { if ((v = +ticks[i] - j * d) >= extent[0]) { subticks.push(v); } } } for (--i, j = 0; ++j < m && (v = +ticks[i] + j * d) < extent[1];) { subticks.push(v); } } return subticks; } var Axis = function () { var scale = d3.scale.linear(), orient = "bottom", tickMajorSize = 6, tickMinorSize = 6, tickEndSize = 6, tickPadding = 3, tickArguments_ = [10], tickFormat_, tickSubdivide = 0, tickAttr_ = {}, tickTextAttr_ = {}, minorTickAttr_ = {}, domainAttr_ = {}; /** * @param paper: raphael's paper object. * @return axisSet: raphael's set object. */ function axis(paper) { // Ticks for quantitative scale, or domain values for ordinal scale. var ticks = scale.ticks ? scale.ticks.apply(scale, tickArguments_) : scale.domain(), tickFormat = tickFormat_ === undefined ? (scale.tickFormat ? scale.tickFormat.apply(scale, tickArguments_) : String) : tickFormat_; var subticks = d3_svg_axisSubdivide(scale, ticks, tickSubdivide); var range = d3_scaleRange(scale); var axisSet = paper.set(); switch (orient) { case "bottom": subticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + tickMinorSize + "V0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + tickMajorSize + "V0") .attr(tickAttr_)); axisSet.push(paper .text(tickX, Math.max(tickMajorSize, 0) + tickPadding + 2, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "middle"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + range[0] + "," + tickEndSize + "V0H" + range[1] + "V" + tickEndSize) .attr(domainAttr_)); break; case "top": subticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + -tickMinorSize + "V0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickX = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickX + "," + -tickMajorSize + "V0") .attr(tickAttr_)); axisSet.push(paper .text(tickX, -(Math.max(tickMajorSize, 0) + tickPadding + 2), typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "middle"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + range[0] + "," + -tickEndSize + "V0H" + range[1] + "V" + -tickEndSize) .attr(domainAttr_)); break; case "left": subticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + -tickMinorSize + "," + tickY + "H0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + -tickMajorSize + "," + tickY + "H0") .attr(tickAttr_)); axisSet.push(paper .text(-(Math.max(tickMajorSize, 0) + tickPadding), tickY, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "end"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + -tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + -tickEndSize) .attr(domainAttr_)); break; case "right": subticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickMinorSize + "," + tickY + "H0") .attr(minorTickAttr_)); }); ticks.forEach(function (d, i, arr) { var tickY = scale.ticks ? scale(d) : scale(d) + scale.rangeBand() / 2; axisSet.push(paper .path("M" + tickMajorSize + "," + tickY + "H0") .attr(tickAttr_)); axisSet.push(paper .text(Math.max(tickMajorSize, 0) + tickPadding, tickY, typeof tickFormat === "function" ? tickFormat(d) : tickFormat) .attr({"text-anchor": "start"}) .attr(tickTextAttr_)); }); axisSet.push(paper .path("M" + tickEndSize + "," + range[0] + "H0V" + range[1] + "H" + tickEndSize) .attr(domainAttr_)); break; } return axisSet; } /** * get or set axis' scale. */ axis.scale = function (x) { if (!arguments.length) { return scale; } scale = x; return axis; }; /** * get or set axis' orinet: "bottom", "top", "left", "right", default orient is bottom. */ axis.orient = function (x) { if (!arguments.length) { return orient; } orient = x; return axis; }; /** * get or set axis' ticks number. */ axis.ticks = function () { if (!arguments.length) { return tickArguments_; } tickArguments_ = arguments; return axis; }; /** * get or set axis' ticks format function, it's a function change format style. * from one string format to another string format. */ axis.tickFormat = function (x) { if (!arguments.length) { return tickFormat_; } tickFormat_ = x; return axis; }; /** * get or set axis' tick size(length of tick line, unit: px). * @param arguments.length === 0, get axis' major tick size. * @param arguments.length === 1, set axis' all tick sizes as x. * @param arguments.length === 2, get axis' major tick size as x, minor and end size as y. * @param arguments.length === 3, get axis' major tick size as x, minor size as y, end size as z. */ axis.tickSize = function (x, y, z) { if (!arguments.length) { return tickMajorSize; } var n = arguments.length - 1; tickMajorSize = +x; tickMinorSize = n > 1 ? +y : tickMajorSize; tickEndSize = n > 0 ? +arguments[n] : tickMajorSize; return axis; }; /** * get or set axis' tick padding(the distance between tick text and axis). * @param x is a number, unit is px; */ axis.tickPadding = function (x) { if (!arguments.length) { return tickPadding; } tickPadding = +x; return axis; }; /** * get or set axis' sub tick divide number(divide number between two major ticks). */ axis.tickSubdivide = function (x) { if (!arguments.length) { return tickSubdivide; } tickSubdivide = +x; return axis; }; /** * get or set axis' tick attribute(Raphael format). */ axis.tickAttr = function (x) { if (!arguments.length) { return tickAttr_; } tickAttr_ = x; return axis; }; /** * get or set axis' tick text attribute(Raphael format). */ axis.tickTextAttr = function (x) { if (!arguments.length) { return tickTextAttr_; } tickTextAttr_ = x; return axis; }; /** * get or set axis' minor tick attribute(Raphael format). */ axis.minorTickAttr = function (x) { if (!arguments.length) { return minorTickAttr_; } minorTickAttr_ = x; return axis; }; /** * get or set axis' domain(axis line) attribute(Raphael format). */ axis.domainAttr = function (x) { if (!arguments.length) { return domainAttr_; } domainAttr_ = x; return axis; }; return axis; }; return Axis; }); /*global Raphael, d3, $, define, _ */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('StreamAxis', function (require) { var DataV = require('DataV'); DataV.Axis = require('Axis'); var Axis = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; } }); Axis.prototype.setSource = function (source, map) { map = this.map(map); this.grouped = _.groupBy(source, map.x); this.axis = _.keys(this.grouped); this.range = [0, this.axis.length - 1]; }; Axis.prototype.init = function () { var conf = this.defaults; this.paper = new Raphael(this.node[0], conf.legendBesidesWidth, conf.axisHeight); this.node.css({ "margin-top": "0px", "border-top": "1px solid #ddd", "height": conf.axisHeight + "px" }); }; Axis.prototype.render = function () { this.init(); this.clear(); //all date strings' format are same, string length are same var conf = this.defaults, that = this; var getPopPath = function (El) { //down pop var x = 0, y = 0, size = 4, cw = 23, bb = {height: 8}; if (El) { bb = El.getBBox(); bb.height *= 0.6; cw = bb.width / 2 - size; } return [ 'M', x, y, 'l', size, size, cw, 0, 'a', size, size, 0, 0, 1, size, size, 'l', 0, bb.height, 'a', size, size, 0, 0, 1, -size, size, 'l', -(size * 2 + cw * 2), 0, 'a', size, size, 0, 0, 1, -size, -size, 'l', 0, -bb.height, 'a', size, size, 0, 0, 1, size, -size, 'l', cw, 0, 'z' ].join(','); }; var left = conf.percentageWidth, right = conf.legendBesidesWidth - conf.percentageWidth; var tempWord = this.paper.text(0, 0, this.axis[0]); var tickNumber = Math.floor((right - left) / tempWord.getBBox().width / 2) + 1; tempWord.remove(); this.dateScale = d3.scale.linear() .domain([0, this.axis.length - 1]) .range([left, right]); DataV.Axis().scale(this.dateScale) .ticks(tickNumber) .tickSize(6, 3, 3) .tickAttr({"stroke": "none"}) .minorTickAttr({"stroke": "none"}) .domainAttr({"stroke": "none"}) .tickFormat(function (d) { return that.axis[d] || ""; })(this.paper); this.axisPopText = this.paper.text(0, 11, this.axis[0]) .attr({ "text-anchor": "middle", "fill": "#fff", "transform": "t" + left + ",0" }).hide(); this.axisPopBubble = this.paper.path(getPopPath(this.axisPopText)) .attr({ "fill": "#000", "transform": "t" + (-10000) + ",0" }).toBack() .hide(); }; Axis.prototype.hideTab = function () { this.axisPopText.hide(); this.axisPopBubble.hide(); }; Axis.prototype.showTab = function () { this.axisPopText.show(); this.axisPopBubble.show(); }; Axis.prototype.refreshTab = function (index) { var conf = this.defaults; var x = conf.chartWidth * index / (this.axis.length - 1); var transX = x + this.defaults.percentageWidth; this.axisPopText.attr({ "text": this.axis[index + this.range[0]] }).transform("t" + transX + ",0"); this.axisPopBubble.transform("t" + transX + ",0"); }; Axis.prototype.clear = function () { this.paper.clear(); }; return Axis; }); /*global Raphael, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Legend', function (require) { var DataV = require('DataV'); var Legend = DataV.extend(DataV.Chart, { initialize: function (container) { this.legendIndent = 20; this.node = $(container); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; this.defaults.highlightStyle = {"backgroundColor": "#dddddd"}; this.defaults.lowlightStyle = {"backgroundColor": "white"}; this.formatLabel = function (text) { return text; }; this.init(); } }); Legend.prototype.init = function () { var conf = this.defaults; this.legend = $("<div></div>"); this.legend.css({ "overflow": "hidden", "padding": "10px 0 10px 0", "width": conf.leftLegendWidth - this.legendIndent + "px" }); this.node.append(this.legend); this.initEvents(); }; Legend.prototype.setSource = function (source, map) { map = this.map(map); var groupedByType = _.groupBy(source, map.type); var sorted = _.sortBy(groupedByType, function (group) { return -DataV.sum(group, map.value); }); //this.list = _.keys(); this.list = sorted.map(function (d) { return d[0][map.type]; }); }; Legend.prototype.initEvents = function () { var that = this; that.on('hoverIn', function (index) { that.highlight(index); }).on('hoverOut', function (index) { that.lowlight(index); }).on('level_changed', function (start, end, needMore) { that.render(start, end, needMore); }); }; Legend.prototype.render = function (level) { var conf = this.defaults; conf.level = level || 0; var that = this; this.clear(); this.legends = []; var colorFunc = conf.colorFunc, hoverIn = function (e) { var index = e.data.index; that.fire('hoverIn', index); this.highlight(index); }, hoverOut = function (e) { var index = e.data.index; that.fire('hoverOut', index); this.lowlight(index); }; var ul = $("<ul></ul>").css({ "margin": "0 0 0 10px", "paddingLeft": 0 }); var selected; if (!conf.more) { selected = this.list.slice(0); } else { selected = DataV.more(this.list, conf.level, conf.max, function () { return conf.moreLabel; }); } var formatLabel = conf.formatLabel || this.formatLabel; for (var i = 0, l = selected.length; i < l; i++) { var color = colorFunc(i); var li = $('<li style="color: ' + color + '"><span style="color: black" title="' + selected[i] + '">' + formatLabel(selected[i]) + '</span></li>'); li.mouseenter({"index": i}, $.proxy(hoverIn, this)).mouseleave({"index": i}, $.proxy(hoverOut, this)); ul.append(li); this.legends.push(li); } ul.find("li").css({ "list-style-type": "square", "list-style-position": "inside", "white-space": "nowrap", "padding-left": 5 }); this.legend.append(ul); }; Legend.prototype.highlight = function (index) { if (typeof index !== 'undefined') { this.legends[index].css(this.defaults.highlightStyle); } }; Legend.prototype.lowlight = function (index) { if (typeof index !== 'undefined') { this.legends[index].css(this.defaults.lowlightStyle); } }; Legend.prototype.clear = function () { this.legend.empty(); }; var TopLegend = DataV.extend(DataV.Widget, { initialize: function (container) { this.node = $(container); this.defaults.r0 = 5; this.defaults.r1 = 7; } }); TopLegend.prototype.init = function () { var conf = this.owner.defaults; this.legend = $("<div></div>").css({ "width": conf.width, "backgroundColor": "#f4f4f4" }); this.node.append(this.legend); }; TopLegend.prototype.render = function () { this.init(); var that = this; var owner = this.owner, conf = owner.defaults; var r0 = this.defaults.r0; this.legends = []; this.paper = new Raphael(this.legend[0], conf.width, 50); var paper = this.paper; var m = [10, 20, 10, 20], left = m[3], top = m[0], lineHeight = 25, legendInterval = 10, lineWidth = conf.width, circleW = 18, colorFunc = owner.getColor(); var hoverIn = function () { var index = this.data("index"); that.owner.fire('hoverIn', index); that.highlight(index); }; var hoverOut = function () { var index = this.data("index"); that.owner.fire('hoverOut', index); that.lowlight(index); }; that.on('hoverIn', function (index) { that.highlight(index); }).on('hoverOut', function (index) { that.lowlight(index); }); var colorArray = owner.displayData.allInfos.map(function (item, index) { return colorFunc(index); }); for (var i = 0, l = owner.displayData.allInfos.length; i < l; i++) { var text = paper.text(0, 0, owner.getDisplayRowInfo(i).rowName).attr({ "font-size": conf.fontSize, "text-anchor": "start", "font-family": "微软雅黑" }); var box = text.getBBox(); if (left + circleW + box.width >= lineWidth - m[1]) { //new line left = m[3]; top += lineHeight; } var color = colorArray[owner.displayData.rowIndex[i].slicedData]; var circle = paper.circle(left + circleW / 2, top + lineHeight / 2, r0) .attr({ "stroke": "none", "fill": color }) .data("index", i) .hover(hoverIn, hoverOut); text.transform("t" + (left + circleW) + "," + (top + lineHeight / 2)); paper.rect(left + circleW, top, box.width, lineHeight).attr({ "stroke": "none", "fill": "#000", "opacity": 0 }) .data("index", i) .hover(hoverIn, hoverOut); that.legends.push({"text": text, "circle": circle}); left += legendInterval + circleW + box.width; } paper.setSize(lineWidth, top + lineHeight + m[2]); }; TopLegend.prototype.highlight = function (index) { this.legends[index].circle.animate({"r": this.defaults.r1, "opacity": 0.5}, 300); }; TopLegend.prototype.lowlight = function (index) { this.legends[index].circle.animate({"r": this.defaults.r0, "opacity": 1}, 300); }; return { Legend: Legend, TopLegend: TopLegend }; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Navi', function (require) { var DataV = require('DataV'); var Navi = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); } }); Navi.prototype.init = function () { this.naviBackWidth = 80; var conf = this.defaults; this.node.css({ "borderTop": "1px solid #ddd", "borderBottom": "1px solid #ddd", "padding": "5px 10px 10px 10px", "fontSize": conf.fontSize + 1, "fontFamily": "宋体" }); this.naviTrace = $("<div></div>").css({ "width": conf.legendBesidesWidth - this.naviBackWidth - 50, "margin-top": "5px" }); this.naviBack = $("<div></div>"); this.naviBack.html("返回上层").css({ "width": this.naviBackWidth + "px", "float": "right", "background-color": "#f4f4f4", "padding-top": "4px", "padding-bottom": "4px", "border": "1px solid #ddd", "border-radius": "2px", "cursor": "pointer", "text-align": "center", "visibility": "hidden" }); this.node.append(this.naviBack).append(this.naviTrace); var that = this; this.naviTrace.on("click", ".navi", function (e) { that.owner.fire('changeLevelTo', e.target.data('level')); }); this.naviBack.on("back", function () { that.owner.fire('changeLevel'); }); }; Navi.prototype.render = function () { this.init(); var level = this.defaults.level; this.clear(); for (var i = 0; i <= level; i++) { this.naviTrace.append($("<span> &gt; </span>")); var span = $("<span></span>").data("level", i).html("第" + (i + 1) + "层"); this.naviTrace.append(span); if (i !== level) { span.css({ "cursor": "pointer", "color": "#1E90FF" }).addClass("navi"); } } this.naviBack.css('visibility', level > 0 ? "visible" : "hidden"); }; Navi.prototype.clear = function () { this.naviTrace.empty(); }; return Navi; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Tip', function (require) { var DataV = require('DataV'); //floatTag var Tip = DataV.extend(DataV.Chart, { initialize: function (container) { this.container = container; this.node = DataV.FloatTag()(this.container); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; }, getContent: function (obj) { return obj[this.mapping.x]; } }); Tip.prototype.setSource = function (source, map) { var that = this; this.map(map); this.rawData = source; this.groupedByX = _.groupBy(source, this.mapping.x); this.groupedByType = _.groupBy(source, this.mapping.type); var sorted = _.sortBy(this.groupedByType, function (group) { return -DataV.sum(group, that.mapping.value); }); this.sorted = sorted; _.each(sorted, function (list, index) { that.groupedByType[list[0][that.mapping.type]].finalRank = index + 1; }); this.axis = _.keys(this.groupedByX); }; Tip.prototype.render = function () { this.hidden(); this.node.css(this.defaults.tipStyle); }; Tip.prototype.setContent = function (rowIndex, columnIndex) { var that = this; var conf = this.defaults; var getContent = conf.getContent || this.getContent; var column = this.groupedByX[this.axis[columnIndex]]; var values = this.sorted;//_.values(this.groupedByType); var types; if (!conf.more) { types = values; } else { types = DataV.more(values, conf.level, conf.max, function (remains) { var row = []; for (var i = 0; i < that.axis.length; i++) { var col = {}; col[that.mapping.type] = conf.moreLabel; col[that.mapping.x] = that.axis[i]; col[that.mapping.value] = NaN;// DataV.sum(_.pluck(remains, i), that.mapping.value); col.rate = DataV.sum(_.pluck(remains, i), "rate"); row.push(col); } return row; }); } var row = types[rowIndex]; var obj = row[columnIndex]; var index = _.indexOf(_.map(column, function (item) { return item[that.mapping.value]; }).sort(function (a, b) { return a > b ? -1 : 1; }), obj[that.mapping.value]); obj.rank = index === -1 ? NaN : index + 1; var html = getContent.call(this, obj); this.node.html(html); }; return Tip; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Percentage', function (require) { var DataV = require('DataV'); var Percentage = DataV.extend(DataV.Chart, { initialize: function (container) { this.node = $(container); this.limit = 20; this.from = 0; this.to = 0; /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; } }); Percentage.prototype.init = function () { var conf = this.defaults; this.paper = new Raphael(this.node[0], conf.percentageWidth, conf.chartHeight); this.node.css({ "width": conf.percentageWidth, "height": conf.chartHeight, "float": "left", "margin-bottom": "0px", "border-bottom": "0px", "padding-bottom": "0px" }); }; Percentage.prototype.setSource = function (source, map) { map = this.map(map); this.grouped = _.groupBy(source, map.type); this.types = _.keys(this.grouped); if (this.types.length > this.limit) { this.to = this.limit; } }; Percentage.prototype.render = function () { this.init(); var conf = this.defaults; var y = conf.fontSize * 2 / 3; if (!this.rect) {//init this.rect = this.paper.rect(0, 0, conf.percentageWidth, conf.chartHeight) .attr({ "fill": "#f4f4f4", "stroke": "#aaa", "stroke-width": 0.5 }); this.text = this.paper.text(conf.percentageWidth / 2, y, Math.round(100) + "%") .attr({"text-anchor": "middle"}); } // this.rect.animate({"y": (1 - maxY) * conf.chartHeight, "height": maxY * conf.chartHeight}, 750); // this.text.attr({ // "text": Math.round(maxY * 100) + "%" // }).animate({"y": y}, 300); }; return Percentage; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('HoverLine', function (require) { var DataV = require('DataV'); var HoverLine = DataV.extend(DataV.Chart, { initialize: function () { } }); HoverLine.prototype.render = function () { this.clear(); var paper = this.owner.paper; var conf = this.defaults; this.indicatorLine = paper.path("M0 0V" + conf.chartHeight).attr({ stroke: "none", "stroke-width": 1, "stroke-dasharray": "- " }); this.highlightLine = paper.path("M0 0V" + conf.chartHeight).attr({ stroke: "none", "stroke-width": 2 }); }; HoverLine.prototype.hidden = function () { this.indicatorLine.attr({"stroke": "none"}); this.highlightLine.attr({"stroke": "none"}); }; HoverLine.prototype.show = function () { this.indicatorLine.attr({"stroke": "#000"}); this.highlightLine.attr({"stroke": "white"}); }; HoverLine.prototype.refresh = function (columnIndex, rowIndex) { //refresh lines' position var owner = this.owner; var pathSource = owner.pathSource; var lineX = this.defaults.chartWidth * columnIndex / (owner.columnCount - 1); var pathSourceCell = pathSource[pathSource.length - 1][columnIndex]; this.indicatorLine.attr({ path: "M" + lineX + " " + (pathSourceCell.y0 - pathSourceCell.y) + "V" + pathSource[0][columnIndex].y0 }); if (typeof rowIndex !== 'undefined') { pathSourceCell = pathSource[rowIndex][columnIndex]; this.highlightLine.attr({ path: "M" + lineX + " " + (pathSourceCell.y0 - pathSourceCell.y) + "V" + pathSourceCell.y0 }); if (rowIndex === 0) { this.highlightLine.attr({"cursor": "pointer"}); } else { this.highlightLine.attr({"cursor": "auto"}); } } }; HoverLine.prototype.clear = function () { this.indicatorLine && this.indicatorLine.remove(); this.highlightLine && this.highlightLine.remove(); }; return HoverLine; }); /*global Raphael, d3, $, define, _ */ /*! * PathLabel的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('PathLabel', function (require) { var DataV = require('DataV'); //pathLabel var PathLabel = DataV.extend(DataV.Chart, { initialize: function () { /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; } }); PathLabel.prototype.render = function () { this.clear(); var that = this; var owner = this.owner; var paths = owner.paths; var conf = this.defaults; var pathSource = owner.pathSource; var labels = []; var getLabelLocation = function (locArray, el) { var x = 0, y = 0, i; var ratioMargin = 0.15; var index = 0; var max = 0; var box = el.getBBox(); var xInterval; var minTop, maxBottom; var showLabel = true; var loc; var height; xInterval = Math.ceil(box.width / (locArray[1].x - locArray[0].x) / 2); if (xInterval === 0) { xInterval = 1; } locArray.forEach(function (d, i, array) { var m = Math.max(ratioMargin * array.length, xInterval); if (i >= m && i <= array.length - m) { if (d.y > max) { minTop = d.y0 - d.y; maxBottom = d.y0; max = d.y; index = i; } } }); for (i = index - xInterval; i <= index + xInterval; i++) { if (i < 0 || i >= locArray.length) { height = 0; showLabel = false; break; } loc = locArray[i]; //top's y is small if (loc.y0 - loc.y > minTop) { minTop = loc.y0 - loc.y; } if (loc.y0 < maxBottom) { maxBottom = loc.y0; } } if (showLabel && maxBottom - minTop >= box.height * 0.8) { x = locArray[index].x; y = (minTop + maxBottom) / 2; } else { showLabel = false; } return { x: x, y: y, showLabel: showLabel }; }; var getPathLabel = this.defaults.getPathLabel || this.getPathLabel; var selected; //var values = _.values(this.groupedByType); var values = _.values(this.sorted); if (!conf.more) { selected = values.slice(0); } else { selected = DataV.more(values, conf.level, conf.max, function (remains) { var obj = {}; obj.type = conf.moreLabel; obj.rank = remains[0].rank; obj.sum = DataV.sum(remains, "sum"); return obj; }); } for (var i = 0, l = paths.length; i < l; i++) { var path = paths[i]; var row = selected[i]; var obj = { type: row.type, rank: row.rank, sum: row.sum, total: this.total }; var text = getPathLabel.call(this, obj); var label = owner.paper.text(0, 0, text).attr({ "textAnchor": "middle", "fill": "white", "fontSize": conf.fontSize, "fontFamily": "微软雅黑" }); label.labelLoc = getLabelLocation(pathSource[i], label); if (label.labelLoc.showLabel) { label.attr({ "x": label.labelLoc.x, "y": label.labelLoc.y }); } else { label.attr({"opacity": 0}); } path.attr({"cursor": "auto"}); label.attr({"cursor": "auto"}); labels.push(label); } this.labels = labels; }; /** * 生成标签的默认方法,可以通过`setOption({getPathLable: function});`覆盖。 * Properties: * - `type`, 条带类型 * - `rank`, 条带排名 * - `sum`, 当前条带总值 * - `total`, 所有条带总值 * @param {Object} obj 当前条带的对象 */ PathLabel.prototype.getPathLabel = function (obj) { return obj.type + " " + "排名: 第" + obj.rank; }; PathLabel.prototype.hidden = function () { this.labels.forEach(function (d) { d.hide(); }); }; PathLabel.prototype.show = function () { this.labels.forEach(function (d) { if (d.labelLoc.showLabel) { d.show(); } }); }; PathLabel.prototype.clear = function () { if (this.labels) { this.labels.forEach(function (d) { d.remove(); }); } }; PathLabel.prototype.setSource = function (source, map) { var that = this; this.map(map); this.groupedByType = _.groupBy(source, this.mapping.type); var sorted = _.sortBy(this.groupedByType, function (group, type) { var sum = DataV.sum(group, that.mapping.value); that.groupedByType[type].sum = sum; that.groupedByType[type].type = type; return -sum; }); this.sorted = sorted; this.types = _.keys(this.groupedByType); _.each(sorted, function (list, index) { that.groupedByType[list[0][that.mapping.type]].rank = index + 1; }); this.total = DataV.sum(_.map(that.groupedByType, function (group) { return group.sum; })); }; return PathLabel; }); /*global Raphael, d3, $, define, _ */ /*! * StreamLegend的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Cover', function (require) { var DataV = require('DataV'); //cover var Cover = DataV.extend(DataV.Chart, { initialize: function (container) { var conf = this.defaults; this.node = $(container); this.node.css({ "position": "absolute", "left": 0, "top": 0, "width": conf.chartWidth, "height": conf.chartHeight, "zIndex": 100, "visibility": "hidden" }).bind("mousemove", $.proxy(function (e) { this.mouse = {x: e.pageX, y: e.pageY}; e.stopPropagation(); }, this)).bind("mouseleave", $.proxy(function () { this.mouse = undefined; }, this)); } }); return Cover; }); /*global Raphael, d3, $, define, _ */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('Stream', function (require) { var DataV = require('DataV'); var HoverLine = require('HoverLine'); var PathLabel = require('PathLabel'); //streamChart var Stream = DataV.extend(DataV.Chart, { initialize: function (node, options) { this.node = this.checkContainer(node); /** * 类型纬度 */ this.dimension.type = { type: "string", required: true, index: 1 }; /** * 时间纬度 */ this.dimension.x = { type: "string", required: true, index: 0 }; /** * 值纬度 */ this.dimension.value = { type: "number", required: true, index: 2 }; this.defaults.width = 500; this.defaults.height = 300; this.defaults.offset = "expand";//zero, expand, silhou-ette, wiggle; this.defaults.order = "default";//default, reverse, inside-out //in this Stream application, it will always be default, the real order is adjusted in Stream's data-process. this.defaults.animateDuration = 750; this.defaults.animateOrder = undefined; this.paths = undefined; this.source = undefined; this.layoutData = undefined; this.pathSource = undefined; this.setOptions(options); this.createPaper(); } }); Stream.prototype.createPaper = function () { var conf = this.defaults; this.paper = new Raphael(this.node, conf.width, conf.height); }; Stream.prototype.setSource = function (source, map) { this.map(map); this.rawData = source; this.rawMap = map; var that = this; // 按类型分组 var grouped = _.groupBy(source, this.mapping.type); this.rowCount = _.keys(grouped).length; this.columnCount = _.keys(_.groupBy(source, this.mapping.x)).length; // 组内按横轴排序 _.forEach(grouped, function (group, type) { grouped[type] = _.sortBy(group, that.mapping.x); }); this.sorted = _.sortBy(grouped, function (group) { return 0 - DataV.sum(group, that.mapping.value); }); this.remaped = this.remapSource(); this.layoutData = this.getLayoutData(); }; Stream.prototype.remapSource = function () { var sorted = this.sorted; var remap = []; for (var j = 0; j < this.columnCount; j++) { var plucked = _.pluck(sorted, j); var sum = DataV.sum(plucked, this.mapping.value); for (var i = 0; i < this.rowCount; i++) { remap[i] = remap[i] || []; remap[i][j] = {}; remap[i][j].x = j; var rate = sorted[i][j][this.mapping.value] / sum; remap[i][j].y = rate; sorted[i][j].rate = rate; } } return remap; }; /*! * 获取等级数据 */ Stream.prototype.getLayoutData = function () { var conf = this.defaults; var remaped = this.remaped; var that = this; if (!conf.more) { return remaped; } else { return DataV.more(remaped, conf.level, conf.max, function (remains) { var obj = []; for (var i = 0; i < that.columnCount; i++) { obj.push({ x: i, y: DataV.sum(_.pluck(remains, i), 'y') }); } return obj; }); } }; Stream.prototype.layout = function () { var conf = this.defaults; d3.layout.stack().offset(conf.offset).order(conf.order)(this.layoutData); }; Stream.prototype.generateChartElements = function () { var conf = this.defaults; var paper = this.paper, paths = []; var area = this.generateArea(); var colorFunc = this.getColor(); // set div's background instread; paper.rect(0, 0, conf.chartWidth, conf.chartHeight).attr({ "stroke": "none", "fill": "#e0e0e0" }); for (var i = 0, l = this.layoutData.length; i < l; i++) { var areaString = area(this.pathSource[i]); var color = colorFunc(i); var path = paper.path(areaString).attr({ fill: color, stroke: color, "stroke-width": 1 }); paths[i] = path; } this.paths = paths; }; Stream.prototype.render = function (animate) { if (animate !== "animate") { this.clear(); this.layout(); this.generateChartElements(); } else { this.layout(); this.animate(); } //hoverLine this.hoverLine = this.own(new HoverLine()); this.hoverLine.render();//lines should be to front, so at last //pathLabel if (this.defaults.pathLabel) { this.pathLabel = this.own(new PathLabel()); this.pathLabel.setSource(this.rawData, this.rawMap); this.pathLabel.render(); } this.createInteractive(); }; Stream.prototype.animate = function () { var time = 0, area, colorFunc, color, i, l, _area, paths = [], order, anim, count = this.paths.length; var that = this; var animateCallback = function () { count -= 1; if (count > 0) { return; } that.animateCallback(); }; if (typeof this.defaults.animateDuration !== 'undefined') { time = this.defaults.animateDuration; } // if paths have not been created if (typeof this.paths === 'undefined') { this.generateChartElements(); } area = this.generateArea(); colorFunc = this.getColor(); if (typeof this.defaults.animateOrder !== 'undefined') { order = this.defaults.animateOrder; } else { order = d3.range(this.pathSource.length); } for (i = 0, l = this.pathSource.length; i < l; i++) { _area = area(this.pathSource[i]); paths.push(_area); } for (i = 0, l = this.pathSource.length; i < l; i++) { color = colorFunc(i); anim = Raphael.animation({"path": paths[i]}, time, animateCallback); this.paths[order[i]].animate(anim); } }; Stream.prototype.animateCallback = function () { var newOrderPaths = []; var that = this; if (typeof this.defaults.animateOrder !== 'undefined') { this.defaults.animateOrder.forEach(function (d, i) { newOrderPaths[i] = that.paths[d]; }); this.paths = newOrderPaths; } }; Stream.prototype.clear = function () { this.paper.clear(); }; Stream.prototype.getColor = function (colorJson) { var colorMatrix = DataV.getColor(); var color; var colorStyle = colorJson || {}; var colorMode = colorStyle.mode || 'default'; var i, l; switch (colorMode) { case "gradient": l = this.source.length; // 最大为 colorMatrix.length - 1 var colorL = Math.min(Math.round(l / 5), colorMatrix.length - 1); var testColor = [colorMatrix[0][0], colorMatrix[colorL][0]]; var test1 = DataV.gradientColor(testColor, "special"); var testColorMatrix = []; var testColorMatrix1 = []; for (i = 0; i < l; i++) { testColorMatrix.push([test1(i / (l - 1)), test1(i / (l - 1))]); } for (i = l - 1; i >= 0; i--) { testColorMatrix1.push(testColorMatrix[i]); } colorMatrix = testColorMatrix; break; case "random": case "default": break; } var ratio = colorStyle.ratio || 0; ratio = Math.max(ratio, 0); ratio = Math.min(ratio, 1); var colorArray = colorMatrix.map(function () { return d3.interpolateRgb.apply(null, [colorMatrix[i][0], colorMatrix[i][1]])(ratio); }); color = d3.scale.ordinal().range(colorArray); return color; }; /* */ Stream.prototype.getColor = function () { var count = this.layoutData.length; var color = this.defaults.gradientColor || ["#8be62f", "#1F4FD8"]; var gradientColor = DataV.gradientColor(color, "special"); var percent = 1 / count; var gotColors = []; for (var i = 0; i < count; i++) { gotColors.push(gradientColor(i * percent)); } var midderNum = Math.floor(count / 2); return function (num) { return num % 2 === 0 ? gotColors[midderNum + num / 2] : gotColors[midderNum - (num + 1) / 2]; }; }; Stream.prototype.getMaxY = function () { return d3.max(this.layoutData, function (d) { return d3.max(d, function (d) { return d.y0 + d.y; }); }); }; Stream.prototype.mapPathSource = function () { var conf = this.defaults, maxX = this.layoutData[0].length - 1, maxY = this.getMaxY(), width = conf.chartWidth, height = conf.chartHeight; this.pathSource = []; for (var i = 0, l = this.layoutData.length; i < l; i++) { this.pathSource[i] = []; for (var j = 0, l2 = this.layoutData[0].length; j < l2; j++) { var s = this.layoutData[i][j]; var ps = this.pathSource[i][j] = {}; ps.x = s.x * width / maxX; ps.y0 = height - s.y0 * height / maxY; ps.y = s.y * height / maxY; } } }; Stream.prototype.generateArea = function () { this.mapPathSource(); var area = d3.svg.area().x(function (d) { return d.x; }).y0(function (d) { return d.y0; }).y1(function (d) { return d.y0 - d.y; }); return area; }; Stream.prototype.highlight = function (index) { if (typeof index !== 'undefined') { this.paths[index].attr({"opacity": 0.5, "stroke-width": 0}); } }; Stream.prototype.lowlight = function (index) { if (typeof index !== 'undefined') { this.paths[index].attr({"opacity": 1, "stroke-width": 1}); } }; Stream.prototype.createInteractive = function () { $(this.paper.canvas).unbind();//prevent event rebind. //refactor stream chart's animate function, especially change the callback var stream = this; this.animateCallback = function () { var newOrderPaths = []; var that = this; if (typeof this.defaults.animateOrder !== 'undefined') { this.defaults.animateOrder.forEach(function (d, i) { newOrderPaths[i] = that.paths[d]; }); this.paths = newOrderPaths; } stream.cover.hidden(); if (typeof stream.cover.mouse !== 'undefined') { stream.hoverLine.show(); stream.floatTag.show(); var mouse = stream.cover.mouse; $(stream.paper.canvas).trigger("mousemove", [mouse.x, mouse.y]); $(stream.floatTag).trigger("mousemove", [mouse.x, mouse.y]); stream.cover.mouse = undefined; } stream.pathLabel.show(); }; //chart mouseenter var mouseenter = function () { stream.hoverLine.show(); stream.fire('enter'); }; //chart mouseleave var mouseleave = function () { stream.hoverLine.hidden(); //recover prepath; if (typeof stream.preIndex !== 'undefined') { stream.lowlight(stream.preIndex); } stream.fire('leave', stream.preIndex); stream.preIndex = undefined; }; //chart click var click = function () {}; //chart mousemove var mousemove = function (e, pageX, pageY) { var offset = $(this).parent().offset(); var x = (e.pageX || pageX) - offset.left, y = (e.pageY || pageY) - offset.top; var pathSource = stream.pathSource, rowIndex; var columnIndex = Math.floor((x / (stream.defaults.chartWidth / (stream.columnCount - 1) / 2) + 1) / 2); //get path and pathIndex for (var i = 0, l = pathSource.length; i < l; i++) { if (y >= pathSource[i][columnIndex].y0 - pathSource[i][columnIndex].y && y <= pathSource[i][columnIndex].y0) { rowIndex = i; break; } } //recover prepath; if (typeof stream.preIndex !== 'undefined') { stream.lowlight(stream.preIndex); } stream.highlight(rowIndex); stream.fire('move', stream.preIndex, rowIndex, columnIndex); //set indicator and highlight line new position stream.hoverLine.refresh(columnIndex, rowIndex); //customevent; if (stream.defaults.customEventHandle.mousemove) { stream.defaults.customEventHandle.mousemove.call(stream, {"timeIndex": columnIndex, "rowIndex": rowIndex}); } //change new path; stream.preIndex = rowIndex; }; $(this.paper.canvas).bind("mouseenter", mouseenter) .bind("mouseleave", mouseleave) .bind("click", click) .bind("mousemove", mousemove); }; return Stream; }); /*global $, define */ /*! * Stream的兼容定义 */ ;(function (name, definition) { if (typeof define === 'function') { // Module define(definition); } else { // Assign to common namespaces or simply the global object (window) this[name] = definition(function (id) { return this[id];}); } })('StreamComponent', function (require) { var DataV = require('DataV'); var Legend = require('Legend'); var Navi = require('Navi'); var Percentage = require('Percentage'); var Axis = require('StreamAxis'); var Tip = require('Tip'); var Stream = require('Stream'); var Cover = require('Cover'); /* * constructor * @param node the dom node or dom node Id * options options json object for determin stream style. * @example * create stream in a dom node with id "chart", width is 500; height is 600px; * "chart", {"width": 500, "height": 600} */ var StreamComponent = DataV.extend(DataV.Chart, { initialize: function (node, options) { this.type = "Stream"; this.node = this.checkContainer(node); this.defaults = {}; // Properties this.defaults.offset = "zero";//zero, expand, silhou-ette, wiggle;(d3 stack offset) this.defaults.order = "default";//default, reverse, descending, ascending, inside-out(d3 stack order, sort by index of maximum value, then use balanced weighting.), inside-out-reverse(inside-out like, sort by index of maximum value, not descending but ascending); this.defaults.normalized = false;//false, true; //ratio data or not; //this.defaults.rowDataOrder = "default"; //default, descending, ascending(according to digitdata row sum value); this.defaults.columnNameUsed = "auto"; this.defaults.rowNameUsed = "auto"; this.defaults.pathLabel = true; this.defaults.fontSize = 12; this.defaults.colorCount = 20; //this.defaults.axisTickNumber = 8; // axis ticks number this.defaults.indexMargin = 3; // if dates.length < indexMargin * 2 + 1, do not show label this.timeRange = []; // paper this.defaults.width = 800; this.defaults.height = 560;//if only width has value and autoHeight is true, then height will be width * heightWidthRatio. this.defaults.autoHeight = true; this.defaults.heightWidthRatio = 0.6; this.defaults.legendPosition = "top";//"top", "left" this.defaults.topLegendHeight = 50; this.defaults.leftLegendWidth = 150; this.defaults.showLegend = true; this.defaults.legendBesidesWidth = undefined; this.defaults.legendBesidesHeight = undefined; this.defaults.more = false; this.defaults.moreLabel = "more"; this.defaults.max = 20; this.defaults.level = 0; this.defaults.chartWidth = undefined;//depends on width, do not recommend to change this.defaults.chartHeight = undefined;// depends on height, do not recommend to change this.defaults.naviHeight = 20;//do not recommend to change this.defaults.showNavi = undefined;//ture if moreConfig.more == true, else false; this.defaults.axisHeight = 30;//do not recommend to change this.defaults.showAxis = true; this.defaults.showPercentage = undefined;//true if moreConfig.more == true, else false; this.defaults.percentageWidth = 40; this.defaults.customEventHandle = {"mousemove": null}; this.defaults.tipStyle = {}; this.setOptions(options); } }); StreamComponent.prototype.init = function () { var that = this; var getBack = function () { var naviCallBack = function () { that.cover.hidden(); if (typeof that.cover.mouse !== 'undefined') { that.hoverLine.show(); that.tip.show(); $(that.paper.canvas).trigger("mousemove",[that.cover.mouse.x, that.cover.mouse.y]); that.cover.mouse = undefined; } that.pathLabel.show(); }; that.cover.show(); that.cover.mouse = undefined; that.processData("slicedData"); that.render("renderComponents"); //hidden that.hoverLine.hidden(); that.tip.hidden(); that.pathLabel.hidden(); that.paths.forEach(function (d) { d.attr({transform: "s1,0.001,0,0"}); d.animate({transform: "t0,0"}, 750, "linear", naviCallBack); }); }; that.on('changeLevelTo', function (level) { that.defaults.level = level; getBack(that.defaults.moreConfig.level); }); that.on('back', function () { that.defaults.level = that.defaults.level - 1; getBack(that.defaults.level); }); that.legend.on('hoverIn', function (index) { that.stream.highlight(index); }).on('hoverOut', function (index) { that.stream.lowlight(index); }); that.stream.on('enter', function () { that.axis.showTab(); that.tip.show(); }).on('leave', function (index) { that.axis.hideTab(); that.tip.hidden(); if (index !== undefined) { that.legend.lowlight(index); } }).on('move', function (pre, rowIndex, columnIndex) { if (pre !== undefined) { that.legend.lowlight(pre); } if (typeof rowIndex === "undefined" || typeof columnIndex === "undefined") { return; } that.legend.highlight(rowIndex); that.tip.setContent(rowIndex, columnIndex); //axis pop bubble that.axis.refreshTab(columnIndex); }).on('level_changed', function (start, end, needMore) { that.legend.fire('level_changed', start, end, needMore); }); }; StreamComponent.prototype.setSource = function (source, map) { this.source = source; this.map = map; }; StreamComponent.prototype.layout = function () { var conf = this.defaults; if (!conf.showLegend) { conf.legendBesidesWidth = conf.width; conf.legendBesidesHeight = conf.height; } else { if (conf.legendPosition === "left") { conf.legendBesidesWidth = conf.width - conf.leftLegendWidth; conf.legendBesidesHeight = conf.height; } else { conf.legendBesidesWidth = conf.width; conf.legendBesidesHeight = conf.height - conf.topLegendHeight; } } conf.chartWidth = conf.legendBesidesWidth - 2 * conf.percentageWidth; conf.chartHeight = conf.legendBesidesHeight - (conf.showNavi ? conf.naviHeight : 0) - (conf.showAxis ? conf.axisHeight : 0); var node = $(this.node).css({ position: "relative", width: conf.width }); // 创建DOM节点 this.streamBox = $("<div></div>").addClass("stream"); this.legendBox = $("<div></div>").addClass("legend"); this.axisBox = $("<div></div>").addClass("axis"); this.naviBox = $("<div></div>").addClass("navi"); this.percentageBox = $("<div></div>").addClass("percentage"); this.container = $("<div></div>").addClass("container"); this.rightBox = $("<div></div>").addClass("right"); // cover can block stream paper when animating to prevent some default mouse event this.coverBox = $("<div></div>").addClass("cover"); // 插入DOM this.streamBox.append(this.coverBox); this.container.append(this.percentageBox).append(this.streamBox); this.rightBox.append(this.naviBox).append(this.container).append(this.axisBox); node.append(this.legendBox).append(this.rightBox); // 设置各个节点大小 this.streamBox.css({ "position": "relative", "float": "left", "width": conf.chartWidth, "height": conf.chartHeight }); this.percentageBox.css({ }); this.container.css({ "height": conf.chartHeight }); this.rightBox.css({ "float": "right", "width": conf.legendBesidesWidth }); this.legendBox.css({ "width": conf.leftLegendWidth - 4, "float": "left", "overflowX": "hidden" }); }; StreamComponent.prototype.draw = function () { var conf = this.defaults; //chart and paper this.stream = this.own(new Stream(this.streamBox, {"width": conf.chartWidth, "height": conf.chartHeight})); this.stream.setSource(this.source, this.map); this.stream.render(); this.legend = this.own(new Legend.Legend(this.legendBox)); this.legend.setOptions({ "colorFunc": this.stream.getColor() }); this.legend.setSource(this.source, this.map); this.legend.render(); this.percentage = this.own(new Percentage(this.percentageBox)); this.percentage.setSource(this.source, this.map); this.percentage.render(); this.axis = this.own(new Axis(this.axisBox)); this.axis.setSource(this.source, this.map); this.axis.render(); this.navi = this.own(new Navi(this.naviBox)); this.navi.render(); // cover can block stream paper when animating to prevent some default mouse event this.cover = this.own(new Cover(this.coverBox)); //floatTag this.tip = this.own(new Tip(this.streamBox)); this.tip.setSource(this.source, this.map); this.tip.render(); }; StreamComponent.prototype.render = function () { this.layout(); this.draw(); this.init(); }; StreamComponent.prototype.setCustomEvent = function (eventName, callback) { this.defaults.customEventHandle[eventName] = callback; }; /*! * 导出StreamComponent */ return StreamComponent; });
TBEDP/datavjs
build/stream_component.js
JavaScript
mit
61,243
var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var content; function readFileIfRequired(cb) { if (!content) { //<co id="callout-globals-nexttick-3-1" /> fs.readFile(__filename, 'utf8', function(err, data) { content = data; console.log('readFileIfRequired: readFile'); cb(err, content); }); } else { process.nextTick(function() { //<co id="callout-globals-nexttick-3-2" /> console.log('readFileIfRequired: cached'); cb(null, content); }); } } readFileIfRequired(function(err, data) { //<co id="callout-globals-nexttick-3-3" /> console.log('1. Length:', data.length); readFileIfRequired(function(err, data2) { console.log('2. Length:', data2.length); }); console.log('Reading file again...'); }); console.log('Reading file...');
alexyoung/nodeinpractice
listings/globals/nexttick-order.js
JavaScript
mit
824
function* f1() { a = (yield) ? 1 : 1; a = yield 1 ? 1 : 1; a = (yield 1) ? 1 : 1; a = 1 ? yield : yield; a = 1 ? yield 1 : yield 1; } function* f2() { a = yield* 1 ? 1 : 1; a = (yield* 1) ? 1 : 1; a = 1 ? yield* 1 : yield* 1; } async function f3() { a = await 1 ? 1 : 1; a = (await 1) ? 1 : 1; a = 1 ? await 1 : await 1; }
rattrayalex/prettier
tests/format/js/yield/conditional.js
JavaScript
mit
347
import React from 'react'; import PropTypes from 'prop-types'; const Soon = () => ( <div> <article className="glitch"> <span>ALWAYS Ɐ WIP</span> </article> </div> ); export default Soon;
Arlefreak/arlefreakClient
src/js/components/soon/index.js
JavaScript
mit
227
module.exports = { rules: { 'max-nested-callbacks': 0 } };
nhnent/tui.tree
test/.eslintrc.js
JavaScript
mit
67
function setup() { createCanvas(600, 400); noLoop(); noStroke(); textSize(20); loadJSON("data.json", drawData); } function draw() { background(255, 0, 0); console.log(int(random(0, 2))); } function drawData(data) { background(120, 180, 200); // person 1 bubble fill(155, 30, 180, 180); ellipse(250, 200, data.person1.age * 5, data.person1.age * 5); // person1.age = 30 fill(255); text(data.person1.name, 210, 200); // person1.name = Morgan // person 2 bubble fill(180, 180, 34, 180); ellipse(350, 200, data.person2.age * 5, data.person2.age * 5); // person2.age = 32 fill(255); text(data.person2.name, 330, 200); // person2.name = Joss }
Montana-Media-Arts/120_CreativeCoding_Fall2017
p5_CodeExamples/08_data/05_loadJSON_callback/sketch.js
JavaScript
mit
682
version https://git-lfs.github.com/spec/v1 oid sha256:c2c3856c7f168c79af5e259afd0648e280f99384ba53df89f67814f2bafd5c74 size 18348
yogeshsaroya/new-cdnjs
ajax/libs/tinymce/4.1.4/plugins/lists/plugin.js
JavaScript
mit
130
!function(){if(jQuery&&jQuery.fn&&jQuery.fn.select2&&jQuery.fn.select2.amd)var e=jQuery.fn.select2.amd;e.define("select2/i18n/hu",[],function(){return{errorLoading:function(){return"Az eredmények betöltése nem sikerült."},inputTooLong:function(e){return"Túl hosszú. "+(e.input.length-e.maximum)+" karakterrel több, mint kellene."},inputTooShort:function(e){return"Túl rövid. Még "+(e.minimum-e.input.length)+" karakter hiányzik."},loadingMore:function(){return"Töltés…"},maximumSelected:function(e){return"Csak "+e.maximum+" elemet lehet kiválasztani."},noResults:function(){return"Nincs találat."},searching:function(){return"Keresés…"}}}),e.define,e.require}();
GawainLynch/bolt
public/bolt/js/locale/select2/hu.min.js
JavaScript
mit
683
'use strict'; /** * @ngdoc function * @name ng.filter:limitTo * @function * * @description * Creates a new array or string containing only a specified number of elements. The elements * are taken from either the beginning or the end of the source array or string, as specified by * the value and sign (positive or negative) of `limit`. * * @param {Array|string} input Source array or string to be limited. * @param {string|number} limit The length of the returned array or string. If the `limit` number * is positive, `limit` number of items from the beginning of the source array/string are copied. * If the number is negative, `limit` number of items from the end of the source array/string * are copied. The `limit` will be trimmed if it exceeds `array.length` * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array * had less than `limit` elements. * * @example <doc:example> <doc:source> <script> function Ctrl($scope) { $scope.numbers = [1,2,3,4,5,6,7,8,9]; $scope.letters = "abcdefghi"; $scope.numLimit = 3; $scope.letterLimit = 3; } </script> <div ng-controller="Ctrl"> Limit {{numbers}} to: <input type="integer" ng-model="numLimit"> <p>Output numbers: {{ numbers | limitTo:numLimit }}</p> Limit {{letters}} to: <input type="integer" ng-model="letterLimit"> <p>Output letters: {{ letters | limitTo:letterLimit }}</p> </div> </doc:source> <doc:protractor> var numLimitInput = element(by.model('numLimit')); var letterLimitInput = element(by.model('letterLimit')); var limitedNumbers = element(by.binding('numbers | limitTo:numLimit')); var limitedLetters = element(by.binding('letters | limitTo:letterLimit')); it('should limit the number array to first three items', function() { expect(numLimitInput.getAttribute('value')).toBe('3'); expect(letterLimitInput.getAttribute('value')).toBe('3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]'); expect(limitedLetters.getText()).toEqual('Output letters: abc'); }); it('should update the output when -3 is entered', function() { numLimitInput.clear(); numLimitInput.sendKeys('-3'); letterLimitInput.clear(); letterLimitInput.sendKeys('-3'); expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: ghi'); }); it('should not exceed the maximum size of input array', function() { numLimitInput.clear(); numLimitInput.sendKeys('100'); letterLimitInput.clear(); letterLimitInput.sendKeys('100'); expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]'); expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi'); }); </doc:protractor> </doc:example> */ function limitToFilter(){ return function(input, limit) { if (!isArray(input) && !isString(input)) return input; limit = int(limit); if (isString(input)) { //NaN check on limit if (limit) { return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length); } else { return ""; } } var out = [], i, n; // if abs(limit) exceeds maximum length, trim it if (limit > input.length) limit = input.length; else if (limit < -input.length) limit = -input.length; if (limit > 0) { i = 0; n = limit; } else { i = input.length + limit; n = input.length; } for (; i<n; i++) { out.push(input[i]); } return out; }; }
toebu/angular.js
src/ng/filter/limitTo.js
JavaScript
mit
3,848
'use strict'; const expect = require('chai').expect; const LiveReloadServer = require('../../../../lib/tasks/server/livereload-server'); const MockUI = require('console-ui/mock'); const MockExpressServer = require('../../../helpers/mock-express-server'); const net = require('net'); const EOL = require('os').EOL; const path = require('path'); const MockWatcher = require('../../../helpers/mock-watcher'); const express = require('express'); const FSTree = require('fs-tree-diff'); const http = require('http'); describe('livereload-server', function() { let subject; let ui; let watcher; let httpServer; let app; beforeEach(function() { ui = new MockUI(); watcher = new MockWatcher(); httpServer = new MockExpressServer(); app = express(); subject = new LiveReloadServer({ app, ui, watcher, httpServer, analytics: { trackError() {} }, project: { liveReloadFilterPatterns: [], root: '/home/user/my-project', }, }); }); afterEach(function() { try { if (subject.liveReloadServer) { subject.liveReloadServer.close(); } } catch (err) { /* ignore */ } }); describe('start', function() { it('does not start the server if `liveReload` option is not true', function() { return subject .setupMiddleware({ liveReload: false, liveReloadPort: 4200, liveReloadPrefix: '/', }) .then(function() { expect(ui.output).to.contains('WARNING: Livereload server manually disabled.'); expect(!!subject.liveReloadServer).to.equal(false); }); }); it('informs of error during startup with custom port', function(done) { let preexistingServer = net.createServer(); preexistingServer.listen(1337); subject .setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', port: 4200, }) .catch(function(reason) { expect(reason).to.equal( `Livereload failed on http://localhost:1337. It is either in use or you do not have permission.` ); }) .finally(function() { preexistingServer.close(done); }); }); it('starts with custom host, custom port', function() { return subject .setupMiddleware({ liveReloadHost: '127.0.0.1', liveReload: true, liveReloadPort: 1377, liveReloadPrefix: '/', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.port).to.equal(1377); expect(subject.liveReloadServer.options.host).to.equal('127.0.0.1'); }); }); it('Livereload responds to livereload requests and returns livereload file', function(done) { let server = app.listen(4200); subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '_lr', port: 4200, }) .then(function() { http.get('http://localhost:4200/_lr/livereload.js', function(response) { expect(response.statusCode).to.equal(200); server.close(done); }); }); }); }); describe('start with https', function() { it('correctly runs in https mode', function() { return subject .setupMiddleware({ liveReload: true, liveReloadPort: 4200, liveReloadPrefix: '/', ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.key).to.be.an.instanceof(Buffer); expect(subject.liveReloadServer.options.cert).to.be.an.instanceof(Buffer); }); }); it('informs of error during startup', function(done) { let preexistingServer = net.createServer(); preexistingServer.listen(1337); subject .setupMiddleware({ liveReloadPort: 1337, liveReload: true, ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .catch(function(reason) { expect(reason).to.equal( `Livereload failed on https://localhost:1337. It is either in use or you do not have permission.` ); }) .finally(function() { preexistingServer.close(done); }); }); it('correctly runs in https mode with custom port', function() { return subject .setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', ssl: true, sslKey: 'tests/fixtures/ssl/server.key', sslCert: 'tests/fixtures/ssl/server.crt', port: 4200, }) .then(function() { expect(subject.liveReloadServer.options.key).to.be.an.instanceof(Buffer); expect(subject.liveReloadServer.options.cert).to.be.an.instanceof(Buffer); }); }); }); describe('express server restart', function() { it('triggers when the express server restarts', function() { let calls = 0; subject.didRestart = function() { calls++; }; return subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '/', port: 4200, }) .then(function() { subject.app.emit('restart'); expect(calls).to.equal(1); }); }); it('triggers when the express server restarts with custom port', function() { let calls = 0; subject.didRestart = function() { calls++; }; return subject .setupMiddleware({ liveReload: true, liveReloadPrefix: '/', liveReloadPort: 1337, port: 4200, }) .then(function() { subject.app.emit('restart'); expect(calls).to.equal(1); }); }); }); describe('livereload changes', function() { let liveReloadServer; let changedCount; let oldChanged; let stubbedChanged = function() { changedCount += 1; }; let trackCount; let oldTrack; let stubbedTrack = function() { trackCount += 1; }; let createStubbedGetDirectoryEntries = function(files) { return function() { return files.map(function(file) { return { relativePath: file, isDirectory() { return false; }, }; }); }; }; beforeEach(function() { subject.setupMiddleware({ liveReload: true, liveReloadPort: 4200, liveReloadPrefix: '/', port: 4200, }); liveReloadServer = subject.liveReloadServer; changedCount = 0; oldChanged = liveReloadServer.changed; liveReloadServer.changed = stubbedChanged; trackCount = 0; oldTrack = subject.analytics.track; subject.analytics.track = stubbedTrack; subject.tree = FSTree.fromEntries([]); }); afterEach(function() { liveReloadServer.changed = oldChanged; subject.analytics.track = oldTrack; subject.project.liveReloadFilterPatterns = []; }); describe('watcher events', function() { function watcherEventTest(eventName, expectedCount) { subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); subject.project.liveReloadFilterPatterns = []; watcher.emit(eventName, { directory: '/home/user/projects/my-project/tmp/something.tmp', }); return expect(changedCount).to.equal(expectedCount); } it('triggers a livereload change on a watcher change event', function() { return watcherEventTest('change', 1); }); it('triggers a livereload change on a watcher error event', function() { return watcherEventTest('error', 1); }); it('does not trigger a livereload change on other watcher events', function() { return watcherEventTest('not-an-event', 0); }); it('recovers from error when file is already cached in previous cache step', function() { let compileError = function() { try { throw new Error('Compile time error'); } catch (error) { return error; } }.apply(); subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); watcher.emit('error', compileError); expect(subject._hasCompileError).to.be.true; expect(changedCount).to.equal(1); watcher.emit('change', { directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(subject._hasCompileError).to.be.false; expect(changedCount).to.equal(2); }); describe('filter pattern', function() { it('shouldTriggerReload must be true if there are no liveReloadFilterPatterns', function() { subject.project.liveReloadFilterPatterns = []; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is true when no liveReloadFilterPatterns matches the filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is false when one or more of the liveReloadFilterPatterns matches filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(result).to.be.false; }); it('shouldTriggerReload writes a banner after skipping reload for a file', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(ui.output).to.equal( `Skipping livereload for: ${path.join('test', 'fixtures', 'proxy', 'file-a.js')}${EOL}` ); }); it('triggers the livereload server of a change when no pattern matches', function() { subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(1); expect(trackCount).to.equal(1); }); it('does not trigger livereload server of a change when there is a pattern match', function() { // normalize test regex for windows // path.normalize with change forward slashes to back slashes if test is running on windows // we then replace backslashes with double backslahes to escape the backslash in the regex let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(0); expect(trackCount).to.equal(0); }); }); }); describe('specific files', function() { let reloadedFiles; let stubbedChanged = function(options) { reloadedFiles = options.body.files; }; beforeEach(function() { liveReloadServer.changed = stubbedChanged; }); afterEach(function() { reloadedFiles = undefined; }); it('triggers livereload with modified files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); }); it('triggers livereload with deleted directories', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); // Pretend every files were removed from the tree. subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal([]); }); it('triggers livereload ignoring source map files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.css.map']; let expectedResult = ['assets/my-project.css']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(expectedResult); }); it('triggers livereload with "LiveReload files" if no results.directory was provided', function() { let changedOptions; subject.liveReloadServer = { changed(options) { changedOptions = options; }, }; subject.didChange({}); expect(changedOptions).to.deep.equal({ body: { files: ['LiveReload files'], }, }); }); }); }); describe('livereload changes with custom port', function() { let liveReloadServer; let changedCount; let oldChanged; let stubbedChanged = function() { changedCount += 1; }; let trackCount; let oldTrack; let stubbedTrack = function() { trackCount += 1; }; let createStubbedGetDirectoryEntries = function(files) { return function() { return files.map(function(file) { return { relativePath: file, isDirectory() { return false; }, }; }); }; }; beforeEach(function() { subject.setupMiddleware({ liveReload: true, liveReloadPort: 1337, liveReloadPrefix: '/', port: 4200, }); liveReloadServer = subject.liveReloadServer; changedCount = 0; oldChanged = liveReloadServer.changed; liveReloadServer.changed = stubbedChanged; trackCount = 0; oldTrack = subject.analytics.track; subject.analytics.track = stubbedTrack; subject.tree = FSTree.fromEntries([]); }); afterEach(function() { liveReloadServer.changed = oldChanged; subject.analytics.track = oldTrack; subject.project.liveReloadFilterPatterns = []; }); describe('watcher events', function() { function watcherEventTest(eventName, expectedCount) { subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); subject.project.liveReloadFilterPatterns = []; watcher.emit(eventName, { directory: '/home/user/projects/my-project/tmp/something.tmp', }); return expect(changedCount).to.equal(expectedCount); } it('triggers a livereload change on a watcher change event', function() { return watcherEventTest('change', 1); }); it('triggers a livereload change on a watcher error event', function() { return watcherEventTest('error', 1); }); it('does not trigger a livereload change on other watcher events', function() { return watcherEventTest('not-an-event', 0); }); it('recovers from error when file is already cached in previous cache step', function() { let compileError = function() { try { throw new Error('Compile time error'); } catch (error) { return error; } }.apply(); subject.getDirectoryEntries = createStubbedGetDirectoryEntries(['test/fixtures/proxy/file-a.js']); watcher.emit('error', compileError); expect(subject._hasCompileError).to.be.true; expect(changedCount).to.equal(1); watcher.emit('change', { directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(subject._hasCompileError).to.be.false; expect(changedCount).to.equal(2); }); describe('filter pattern', function() { it('shouldTriggerReload must be true if there are no liveReloadFilterPatterns', function() { subject.project.liveReloadFilterPatterns = []; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is true when no liveReloadFilterPatterns matches the filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/app/styles/app.css', }); expect(result).to.be.true; }); it('shouldTriggerReload is false when one or more of the liveReloadFilterPatterns matches filePath', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; let result = subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(result).to.be.false; }); it('shouldTriggerReload writes a banner after skipping reload for a file', function() { let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.shouldTriggerReload({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(ui.output).to.equal( `Skipping livereload for: ${path.join('test', 'fixtures', 'proxy', 'file-a.js')}${EOL}` ); }); it('triggers the livereload server of a change when no pattern matches', function() { subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(1); expect(trackCount).to.equal(1); }); it('does not trigger livereload server of a change when there is a pattern match', function() { // normalize test regex for windows // path.normalize with change forward slashes to back slashes if test is running on windows // we then replace backslashes with double backslahes to escape the backslash in the regex let basePath = path.normalize('test/fixtures/proxy').replace(/\\/g, '\\\\'); let filter = new RegExp(`^${basePath}`); subject.project.liveReloadFilterPatterns = [filter]; subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ filePath: '/home/user/my-project/test/fixtures/proxy/file-a.js', }); expect(changedCount).to.equal(0); expect(trackCount).to.equal(0); }); }); }); describe('specific files', function() { let reloadedFiles; let changedOptions; let stubbedChanged = function(options) { reloadedFiles = options.body.files; changedOptions = options; }; beforeEach(function() { liveReloadServer.changed = stubbedChanged; }); afterEach(function() { reloadedFiles = undefined; }); it('triggers livereload with modified files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); }); it('triggers livereload with deleted directories', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.js']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(changedFiles); // Pretend every files were removed from the tree. subject.getDirectoryEntries = createStubbedGetDirectoryEntries([]); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal([]); }); it('triggers livereload ignoring source map files', function() { let changedFiles = ['assets/my-project.css', 'assets/my-project.css.map']; let expectedResult = ['assets/my-project.css']; subject.getDirectoryEntries = createStubbedGetDirectoryEntries(changedFiles); subject.didChange({ directory: '/home/user/projects/my-project/tmp/something.tmp', }); expect(reloadedFiles).to.deep.equal(expectedResult); }); it('triggers livereload with "LiveReload files" if no results.directory was provided', function() { subject.didChange({}); expect(changedOptions).to.deep.equal({ body: { files: ['LiveReload files'], }, }); }); }); }); });
fpauser/ember-cli
tests/unit/tasks/server/livereload-server-test.js
JavaScript
mit
23,167
"use strict"; var chokidar = require("chokidar"), shell = require("shelljs"), files = { "./src/pages/schema-edit/parse-schema.js" : "./gen/parse-schema.js" }; exports.watch = function() { // Make sure files stay up to date in the /gen folder chokidar.watch(Object.keys(files)).on("all", function(event, file) { if(event !== "add" && event !== "change") { return; } file = "./" + file; shell.cp(file, files[file]); }); }; exports.copy = function() { Object.keys(files).forEach(function(file) { shell.cp(file, files[file]); }); };
tivac/anthracite
build/lib/files.js
JavaScript
mit
630
// Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. (function() { // Baseline setup // -------------- // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self == 'object' && self.self === self && self || typeof global == 'object' && global.global === global && global || this; // Save the previous value of the `_` variable. var previousUnderscore = root._; // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype; // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeCreate = Object.create; // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; // Export the Underscore object for **Node.js**, with // backwards-compatibility for their old module API. If we're in // the browser, add `_` as a global object. // (`nodeType` is checked to ensure that `module` // and `exports` are not HTML elements.) if (typeof exports != 'undefined' && !exports.nodeType) { if (typeof module != 'undefined' && !module.nodeType && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } // Current version. _.VERSION = '1.8.3'; // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; // The 2-parameter case has been omitted only because no current consumers // made use of it. case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; // An internal function to generate callbacks that can be applied to each // element in a collection, returning the desired result — either `identity`, // an arbitrary callback, a property matcher, or a property accessor. var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; // An external wrapper for the internal callback generator _.iteratee = function(value, context) { return cb(value, context, Infinity); }; // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. var restArgs = function(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); case 2: return func.call(this, arguments[0], arguments[1], rest); } var args = Array(startIndex + 1); for (index = 0; index < startIndex; index++) { args[index] = arguments[index]; } args[startIndex] = rest; return func.apply(this, args); }; }; // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object. // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094 var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = property('length'); var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Collection Functions // -------------------- // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Create a reducing function iterating left or right. var createReduce = function(dir) { // Wrap code that reassigns argument variables in a separate function than // the one that accesses `arguments.length` to avoid a perf hit. (#1991) var reducer = function(obj, iteratee, memo, initial) { var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; if (!initial) { memo = obj[keys ? keys[index] : index]; index += dir; } for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; }; return function(obj, iteratee, memo, context) { var initial = arguments.length >= 3; return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial); }; }; // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = _.values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; // Invoke a method (with arguments) on every item in a collection. _.invoke = restArgs(function(obj, method, args) { var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }); // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object') && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value != null && value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(v, index, list) { computed = iteratee(v, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = v; lastComputed = computed; } }); } return result; }; // Shuffle a collection. _.shuffle = function(obj) { return _.sample(obj, Infinity); }; // Sample **n** random values from a collection using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } var sample = isArrayLike(obj) ? _.clone(obj) : _.values(obj); var length = getLength(sample); n = Math.max(Math.min(n, length), 0); var last = length - 1; for (var index = 0; index < n; index++) { var rand = _.random(index, last); var temp = sample[index]; sample[index] = sample[rand]; sample[rand] = temp; } return sample.slice(0, n); }; // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { var index = 0; iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, key, list) { return { value: value, index: index++, criteria: iteratee(value, key, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; // An internal function used for aggregate "group by" operations. var group = function(behavior, partition) { return function(obj, iteratee, context) { var result = partition ? [[], []] : {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g; // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (_.isString(obj)) { // Keep surrogate pair characters together return obj.match(reStrSymbol); } if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = group(function(result, value, pass) { result[pass ? 0 : 1].push(value); }, true); // Array Functions // --------------- // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, output) { output = output || []; var idx = output.length; for (var i = 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { // Flatten current level of array or arguments object if (shallow) { var j = 0, len = value.length; while (j < len) output[idx++] = value[j++]; } else { flatten(value, shallow, strict, output); idx = output.length; } } else if (!strict) { output[idx++] = value; } } return output; }; // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; // Return a version of the array that does not contain the specified value(s). _.without = restArgs(function(array, otherArrays) { return _.difference(array, otherArrays); }); // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = restArgs(function(arrays) { return _.uniq(flatten(arrays, true, true)); }); // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; var j; for (j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = restArgs(function(array, rest) { rest = flatten(rest, true, true); return _.filter(array, function(value){ return !_.contains(rest, value); }); }); // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = restArgs(_.unzip); // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; // Generator function to create the findIndex and findLastIndex functions var createPredicateIndexFinder = function(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; }; // Returns the first index on an array-like that passes a predicate test _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; // Generator function to create the indexOf and lastIndexOf functions var createIndexFinder = function(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; }; // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } if (!step) { step = stop < start ? -1 : 1; } var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; // Split an **array** into several arrays containing **count** or less elements // of initial array _.chunk = function(array, count) { if (count == null || count < 1) return []; var result = []; var i = 0, length = array.length; while (i < length) { result.push(slice.call(array, i, i += count)); } return result; }; // Function (ahem) Functions // ------------------ // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. _.bind = restArgs(function(func, context, args) { if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var bound = restArgs(function(callArgs) { return executeBound(func, bound, context, this, args.concat(callArgs)); }); return bound; }); // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. _.partial = restArgs(function(func, boundArgs) { var placeholder = _.partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }); _.partial.placeholder = _; // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. _.bindAll = restArgs(function(obj, keys) { keys = flatten(keys, false, false); var index = keys.length; if (index < 1) throw new Error('bindAll must be passed function names'); while (index--) { var key = keys[index]; obj[key] = _.bind(obj[key], obj); } }); // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = restArgs(function(func, wait, args) { return setTimeout(function() { return func.apply(null, args); }, wait); }); // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; // but if you'd like to disable the execution on the leading edge, pass // `{leading: false}`. To disable execution on the trailing edge, ditto. _.throttle = function(func, wait, options) { var timeout, context, args, result; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function() { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; }; // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, result; var later = function(context, args) { timeout = null; if (args) result = func.apply(context, args); }; var debounced = restArgs(function(args) { var callNow = immediate && !timeout; if (timeout) clearTimeout(timeout); if (callNow) { timeout = setTimeout(later, wait); result = func.apply(this, args); } else if (!immediate) { timeout = _.delay(later, wait, this, args); } return result; }); debounced.cancel = function() { clearTimeout(timeout); timeout = null; }; return debounced; }; // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); _.restArgs = restArgs; // Object Functions // ---------------- // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; var collectNonEnumProps = function(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = _.isFunction(constructor) && constructor.prototype || ObjProto; // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } }; // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); // Ahem, IE < 9. if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}; for (var index = 0; index < length; index++) { var currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; // An internal function for creating assigner functions. var createAssigner = function(keysFunc, defaults) { return function(obj) { var length = arguments.length; if (defaults) obj = Object(obj); if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!defaults || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; // Internal pick helper function to determine if `obj` has key `key`. var keyInObj = function(value, key, obj) { return key in obj; }; // Return a copy of the object only containing the whitelisted properties. _.pick = restArgs(function(obj, keys) { var result = {}, iteratee = keys[0]; if (obj == null) return result; if (_.isFunction(iteratee)) { if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]); keys = _.allKeys(obj); } else { iteratee = keyInObj; keys = flatten(keys, false, false); obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }); // Return a copy of the object without the blacklisted properties. _.omit = restArgs(function(obj, keys) { var iteratee = keys[0], context; if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); if (keys.length > 1) context = keys[1]; } else { keys = _.map(flatten(keys, false, false), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }); // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. _.create = function(prototype, props) { var result = baseCreate(prototype); if (props) _.extendOwn(result, props); return result; }; // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; // Internal recursive comparison function for `isEqual`. var eq, deepEq; eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // A strict comparison is necessary because `null == undefined`. if (a == null || b == null) return a === b; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== 'function' && type !== 'object' && typeof b != 'object') return false; return deepEq(a, b, aStack, bStack); }; // Internal recursive comparison function for `isEqual`. deepEq = function(a, b, aStack, bStack) { // Unwrap any wrapped objects. if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case '[object RegExp]': // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case '[object String]': // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return '' + a === '' + b; case '[object Number]': // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { // Deep compare objects. var keys = _.keys(a), key; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (_.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; }; // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error', 'Symbol'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236). var nodelist = root.document && root.document.childNodes; if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } // Is a given object a finite number? _.isFinite = function(obj) { return !_.isSymbol(obj) && isFinite(obj) && !isNaN(parseFloat(obj)); }; // Is the given value `NaN`? _.isNaN = function(obj) { return _.isNumber(obj) && isNaN(obj); }; // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; // Utility Functions // ----------------- // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = property; // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; // List of HTML entities for escaping. var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; // Regexes for identifying a key that needs to be escaped var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, prop, fallback) { var value = object == null ? void 0 : object[prop]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { evaluate: /<%([\s\S]+?)%>/g, interpolate: /<%=([\s\S]+?)%>/g, escape: /<%-([\s\S]+?)%>/g }; // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. // NB: `oldSettings` only exists for backwards compatibility. _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escapeRegExp, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } // Adobe VMs need the match returned to produce the correct offset. return match; }); source += "';\n"; // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; var render; try { render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. // Helper function to continue chaining intermediate results. var chainResult = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return chainResult(this, func.apply(_, args)); }; }); }; // Add all of the Underscore functions to the wrapper object. _.mixin(_); // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return chainResult(this, obj); }; }); // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return chainResult(this, method.apply(this._wrapped, arguments)); }; }); // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers // as a named module because, like jQuery, it is a base library that is // popular enough to be bundled in a third party lib, but not be part of // an AMD load request. Those cases could generate an error when an // anonymous define() is called outside of a loader request. if (typeof define == 'function' && define.amd) { define('underscore', [], function() { return _; }); } }());
nino-c/plerp.org
src/static/site/js/underscore.js
JavaScript
mit
55,589
// moment.js locale configuration // locale : Marathi (mr) // author : Harshad Kale : https://github.com/kalehv (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { var symbolMap = { '1': '१', '2': '२', '3': '३', '4': '४', '5': '५', '6': '६', '7': '७', '8': '८', '9': '९', '0': '०' }, numberMap = { '१': '1', '२': '2', '३': '3', '४': '4', '५': '5', '६': '6', '७': '7', '८': '8', '९': '9', '०': '0' }; return moment.defineLocale('mr', { months : 'जानेवारी_फेब्रुवारी_मार्च_एप्रिल_मे_जून_जुलै_ऑगस्ट_सप्टेंबर_ऑक्टोबर_नोव्हेंबर_डिसेंबर'.split('_'), monthsShort: 'जाने._फेब्रु._मार्च._एप्रि._मे._जून._जुलै._ऑग._सप्टें._ऑक्टो._नोव्हें._डिसें.'.split('_'), weekdays : 'रविवार_सोमवार_मंगळवार_बुधवार_गुरूवार_शुक्रवार_शनिवार'.split('_'), weekdaysShort : 'रवि_सोम_मंगळ_बुध_गुरू_शुक्र_शनि'.split('_'), weekdaysMin : 'र_सो_मं_बु_गु_शु_श'.split('_'), longDateFormat : { LT : 'A h:mm वाजता', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, LT', LLLL : 'dddd, D MMMM YYYY, LT' }, calendar : { sameDay : '[आज] LT', nextDay : '[उद्या] LT', nextWeek : 'dddd, LT', lastDay : '[काल] LT', lastWeek: '[मागील] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s नंतर', past : '%s पूर्वी', s : 'सेकंद', m: 'एक मिनिट', mm: '%d मिनिटे', h : 'एक तास', hh : '%d तास', d : 'एक दिवस', dd : '%d दिवस', M : 'एक महिना', MM : '%d महिने', y : 'एक वर्ष', yy : '%d वर्षे' }, preparse: function (string) { return string.replace(/[१२३४५६७८९०]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, meridiem: function (hour, minute, isLower) { if (hour < 4) { return 'रात्री'; } else if (hour < 10) { return 'सकाळी'; } else if (hour < 17) { return 'दुपारी'; } else if (hour < 20) { return 'सायंकाळी'; } else { return 'रात्री'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); }));
ta2yak/boocle
public/bower_components/moment/locale/mr.js
JavaScript
mit
3,946
// Call spamassassin via spamd var sock = require('./line_socket'); var prettySize = require('./utils').prettySize; var defaults = { spamd_socket: 'localhost:783', max_size: 500000, old_headers_action: "rename", subject_prefix: "*** SPAM ***", }; exports.hook_data_post = function (next, connection) { var plugin = this; var config = this.config.get('spamassassin.ini'); setup_defaults(config); if (msg_too_big(config, connection, plugin)) return next(); var username = get_spamd_username(config, connection); var headers = get_spamd_headers(connection, username); var socket = get_spamd_socket(config, next, connection, plugin); socket.is_connected = false; var results_timeout = parseInt(config.main.results_timeout) || 300; socket.on('connect', function () { this.is_connected = true; // Reset timeout this.setTimeout(results_timeout * 1000); socket.write(headers.join("\r\n")); connection.transaction.message_stream.pipe(socket); }); var spamd_response = { headers: {} }; var state = 'line0'; var last_header; socket.on('line', function (line) { connection.logprotocol(plugin, "Spamd C: " + line); line = line.replace(/\r?\n/, ''); if (state === 'line0') { spamd_response.line0 = line; state = 'response'; } else if (state === 'response') { if (line.match(/\S/)) { var matches; if (matches = line.match(/Spam: (True|False) ; (-?\d+\.\d) \/ (-?\d+\.\d)/)) { spamd_response.flag = matches[1]; spamd_response.score = matches[2]; spamd_response.hits = matches[2]; // backwards compat spamd_response.reqd = matches[3]; spamd_response.flag = spamd_response.flag === 'True' ? 'Yes' : 'No'; } } else { state = 'headers'; } } else if (state === 'headers') { var m; // printable ASCII: [ -~] if (m = line.match(/^X-Spam-([ -~]+):(.*)/)) { // connection.logdebug(plugin, "header: " + line); last_header = m[1]; spamd_response.headers[m[1]] = m[2]; return; } var fold; if (last_header && (fold = line.match(/^(\s+.*)/))) { spamd_response.headers[last_header] += "\r\n" + fold[1]; return; } last_header = ''; } }); socket.on('end', function () { // Abort if the transaction is gone if (!connection.transaction) return next(); if (spamd_response.headers['Tests']) { spamd_response.tests = spamd_response.headers['Tests']; } if (spamd_response.tests === undefined) { // strip the 'tests' from the X-Spam-Status header var tests; if (spamd_response.headers['Status'] && tests = /tests=([^ ]+)/.exec(spamd_response.headers['Status'].replace(/\r?\n\t/g,''))) { spamd_response.tests = tests[1]; } } // do stuff with the results... connection.transaction.notes.spamassassin = spamd_response; plugin.fixup_old_headers(config.main.old_headers_action, connection.transaction); plugin.do_header_updates(connection, spamd_response, config); log_results(connection, plugin, spamd_response, config); var exceeds_err = score_too_high(config, connection, spamd_response); if (exceeds_err) return next(DENY, exceeds_err); munge_subject(connection, config, spamd_response.score); return next(); }); }; exports.fixup_old_headers = function (action, transaction) { var plugin = this; var headers = transaction.notes.spamassassin.headers; switch (action) { case "keep": break; case "drop": for (var key in headers) { if (!key) continue; transaction.remove_header('X-Spam-' + key); } break; case "rename": default: for (var key in headers) { if (!key) continue; key = 'X-Spam-' + key; var old_val = transaction.header.get(key); transaction.remove_header(key); if (old_val) { // plugin.logdebug(plugin, "header: " + key + ', ' + old_val); transaction.add_header(key.replace(/^X-/, 'X-Old-'), old_val); } } break; } }; function munge_subject(connection, config, score) { var munge = config.main.munge_subject_threshold; if (!munge) return; if (parseFloat(score) < parseFloat(munge)) return; var subj = connection.transaction.header.get('Subject'); var subject_re = new RegExp('^' + config.main.subject_prefix); if (subject_re.test(subj)) return; // prevent double munge connection.transaction.remove_header('Subject'); connection.transaction.add_header('Subject', config.main.subject_prefix + " " + subj); }; function setup_defaults(config) { for (var key in defaults) { config.main[key] = config.main[key] || defaults[key]; } ['reject_threshold', 'relay_reject_threshold', 'munge_subject_threshold', 'max_size'].forEach(function (item) { if (!config.main[item]) return; config.main[item] = Number(config.main[item]); }); }; exports.do_header_updates = function (connection, spamd_response, config) { var plugin = this; if (spamd_response.flag === 'Yes') { // X-Spam-Flag is added by SpamAssassin connection.transaction.remove_header('precedence'); connection.transaction.add_header('Precedence', 'junk'); } var modern = config.main.modern_status_syntax; for (var key in spamd_response.headers) { if (!key || key === '' || key === undefined) continue; var val = spamd_response.headers[key]; if (val === undefined) { val = ''; } if (key === 'Status' && !modern) { var legacy = spamd_response.headers[key].replace(/ score=/,' hits='); connection.transaction.add_header('X-Spam-Status', legacy); continue; } connection.transaction.add_header('X-Spam-' + key, val); } }; function score_too_high(config, connection, spamd_response) { var score = spamd_response.score; if (connection.relaying) { var rmax = config.main.relay_reject_threshold; if (rmax && (score >= rmax)) { return "spam score exceeded relay threshold"; } }; var max = config.main.reject_threshold; if (max && (score >= max)) { return "spam score exceeded threshold"; } return; } function get_spamd_username(config, connection) { var user = connection.transaction.notes.spamd_user; // 1st priority if (user && user !== undefined) return user; if (!config.main.spamd_user) return 'default'; // when not defined user = config.main.spamd_user; // Enable per-user SA prefs if (user === 'first-recipient') { // special cases return connection.transaction.rcpt_to[0].address(); } if (user === 'all-recipients') { throw "Unimplemented"; // TODO: pass the message through SA for each recipient. Then apply // the least strict result to the connection. That is useful when // one user blacklists a sender that another user wants to get mail // from. If this is something you care about, this is the spot. } return user; } function get_spamd_headers(connection, username) { // http://svn.apache.org/repos/asf/spamassassin/trunk/spamd/PROTOCOL var headers = [ 'HEADERS SPAMC/1.3', 'User: ' + username, '', 'X-Envelope-From: ' + connection.transaction.mail_from.address(), 'X-Haraka-UUID: ' + connection.transaction.uuid, ]; if (connection.relaying) { headers.push('X-Haraka-Relay: true'); } return headers; } function get_spamd_socket(config, next, connection, plugin) { // TODO: support multiple spamd backends var socket = new sock.Socket(); if (config.main.spamd_socket.match(/\//)) { // assume unix socket socket.connect(config.main.spamd_socket); } else { var hostport = config.main.spamd_socket.split(/:/); socket.connect((hostport[1] || 783), hostport[0]); } var connect_timeout = parseInt(config.main.connect_timeout) || 30; socket.setTimeout(connect_timeout * 1000); socket.on('timeout', function () { if (!this.is_connected) { connection.logerror(plugin, 'connection timed out'); } else { connection.logerror(plugin, 'timeout waiting for results'); } socket.end(); return next(); }); socket.on('error', function (err) { connection.logerror(plugin, 'connection failed: ' + err); // TODO: optionally DENYSOFT // TODO: add a transaction note return next(); }); return socket; }; function msg_too_big(config, connection, plugin) { if (!config.main.max_size) return false; var size = connection.transaction.data_bytes; var max = config.main.max_size; if (size > max) { connection.loginfo(plugin, 'skipping, size ' + prettySize(size) + ' exceeds max: ' + prettySize(max)); return true; } return false; }; function log_results(connection, plugin, spamd_response, config) { connection.loginfo(plugin, "status=" + spamd_response.flag + ', score=' + spamd_response.score + ', required=' + spamd_response.reqd + ', reject=' + ((connection.relaying) ? (config.main.relay_reject_threshold || config.main.reject_threshold) : config.main.reject_threshold) + ', tests="' + spamd_response.tests + '"'); };
eiriklv/Haraka
plugins/spamassassin.js
JavaScript
mit
10,175
"use strict"; var _foob, _foob$test; var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); }; (_foob = foob).add.apply(_foob, [foo, bar].concat(_toArray(numbers))); (_foob$test = foob.test).add.apply(_foob$test, [foo, bar].concat(_toArray(numbers)));
stefanpenner/6to5
test/fixtures/transformation/es6-spread/contexted-method-call-multiple-args/expected.js
JavaScript
mit
281
import { useState } from 'react' import { useRouter } from 'next/router' import Link from 'next/link' import { gql, useMutation } from '@apollo/client' import { getErrorMessage } from '../lib/form' import Field from '../components/field' const SignUpMutation = gql` mutation SignUpMutation($email: String!, $password: String!) { signUp(input: { email: $email, password: $password }) { user { id email } } } ` function SignUp() { const [signUp] = useMutation(SignUpMutation) const [errorMsg, setErrorMsg] = useState() const router = useRouter() async function handleSubmit(event) { event.preventDefault() const emailElement = event.currentTarget.elements.email const passwordElement = event.currentTarget.elements.password try { await signUp({ variables: { email: emailElement.value, password: passwordElement.value, }, }) router.push('/signin') } catch (error) { setErrorMsg(getErrorMessage(error)) } } return ( <> <h1>Sign Up</h1> <form onSubmit={handleSubmit}> {errorMsg && <p>{errorMsg}</p>} <Field name="email" type="email" autoComplete="email" required label="Email" /> <Field name="password" type="password" autoComplete="password" required label="Password" /> <button type="submit">Sign up</button> or{' '} <Link href="/signin"> <a>Sign in</a> </Link> </form> </> ) } export default SignUp
azukaru/next.js
examples/api-routes-apollo-server-and-client-auth/pages/signup.js
JavaScript
mit
1,642
const nest = require('depnest') const { h, Value } = require('mutant') exports.needs = nest({ 'app.sync.goTo': 'first', 'message.html.backlinks': 'first', 'message.html.author': 'first', 'message.html.meta': 'map', 'message.html.timestamp': 'first' }) exports.gives = nest('message.html.layout') exports.create = (api) => { return nest('message.html.layout', miniLayout) function miniLayout (msg, opts) { if (opts.layout !== 'mini') return var rawMessage = Value(null) return h('Message -mini', { attributes: { tabindex: '0' } }, [ h('section.timestamp', {}, api.message.html.timestamp(msg)), h('header.author', {}, api.message.html.author(msg, { size: 'mini' })), h('section.meta', {}, api.message.html.meta(msg, { rawMessage })), h('section.content', { 'ev-click': () => api.app.sync.goTo(msg) }, opts.content), h('section.raw-content', rawMessage) ]) } }
dominictarr/patchbay
message/html/layout/mini.js
JavaScript
mit
950
var gbxremote = require('gbxremote'), async = require('async'); module.exports = require('./core').extend({ init: function() { this._super(); this.options.port = 2350; this.options.port_query = 5000; this.gbxclient = false; }, reset: function() { this._super(); if(this.gbxclient) { this.gbxclient.terminate(); this.gbxclient = false; } }, run: function(state) { var self = this; var cmds = [ ['Connect'], ['Authenticate', this.options.login,this.options.password], ['GetStatus'], ['GetPlayerList',500,0], ['GetServerOptions'], ['GetCurrentChallengeInfo'], ['GetCurrentGameInfo'] ]; var results = []; async.eachSeries(cmds, function(cmdset,c) { var cmd = cmdset[0]; var params = cmdset.slice(1); if(cmd == 'Connect') { var client = self.gbxclient = gbxremote.createClient(self.options.port_query,self.options.host, function(err) { if(err) return self.fatal('GBX error '+JSON.stringify(err)); c(); }); client.on('error',function(){}); } else { self.gbxclient.methodCall(cmd, params, function(err, value) { if(err) return self.fatal('XMLRPC error '+JSON.stringify(err)); results.push(value); c(); }); } }, function() { var gamemode = ''; var igm = results[5].GameMode; if(igm == 0) gamemode="Rounds"; if(igm == 1) gamemode="Time Attack"; if(igm == 2) gamemode="Team"; if(igm == 3) gamemode="Laps"; if(igm == 4) gamemode="Stunts"; if(igm == 5) gamemode="Cup"; state.name = self.stripColors(results[3].Name); state.password = (results[3].Password != 'No password'); state.maxplayers = results[3].CurrentMaxPlayers; state.map = self.stripColors(results[4].Name); state.raw.gametype = gamemode; results[2].forEach(function(player) { state.players.push({name:self.stripColors(player.Name)}); }); self.finish(state); }); }, stripColors: function(str) { return str.replace(/\$([0-9a-f][^\$]?[^\$]?|[^\$]?)/g,''); } });
kyroskoh/node-gamedig
protocols/nadeo.js
JavaScript
mit
1,995
/** * Module dependencies. */ var http = require('http'); var read = require('fs').readFileSync; var parse = require('url').parse; var engine = require('engine.io'); var client = require('socket.io-client'); var clientVersion = require('socket.io-client/package').version; var Client = require('./client'); var Namespace = require('./namespace'); var Adapter = require('socket.io-adapter'); var debug = require('debug')('socket.io:server'); var url = require('url'); /** * Module exports. */ module.exports = Server; /** * Socket.IO client source. */ var clientSource = read(require.resolve('socket.io-client/socket.io.js'), 'utf-8'); /** * Server constructor. * * @param {http.Server|Number|Object} http server, port or options * @param {Object} options * @api public */ function Server(srv, opts){ if (!(this instanceof Server)) return new Server(srv, opts); if ('object' == typeof srv && !srv.listen) { opts = srv; srv = null; } opts = opts || {}; this.nsps = {}; this.path(opts.path || '/socket.io'); this.serveClient(false !== opts.serveClient); this.adapter(opts.adapter || Adapter); this.origins(opts.origins || '*:*'); this.sockets = this.of('/'); if (srv) this.attach(srv, opts); } /** * Server request verification function, that checks for allowed origins * * @param {http.IncomingMessage} request * @param {Function} callback to be called with the result: `fn(err, success)` */ Server.prototype.checkRequest = function(req, fn) { var origin = req.headers.origin || req.headers.referer; // file:// URLs produce a null Origin which can't be authorized via echo-back if ('null' == origin || null == origin) origin = '*'; if (!!origin && typeof(this._origins) == 'function') return this._origins(origin, fn); if (this._origins.indexOf('*:*') !== -1) return fn(null, true); if (origin) { try { var parts = url.parse(origin); parts.port = parts.port || 80; var ok = ~this._origins.indexOf(parts.hostname + ':' + parts.port) || ~this._origins.indexOf(parts.hostname + ':*') || ~this._origins.indexOf('*:' + parts.port); return fn(null, !!ok); } catch (ex) { } } fn(null, false); }; /** * Sets/gets whether client code is being served. * * @param {Boolean} whether to serve client code * @return {Server|Boolean} self when setting or value when getting * @api public */ Server.prototype.serveClient = function(v){ if (!arguments.length) return this._serveClient; this._serveClient = v; return this; }; /** * Old settings for backwards compatibility */ var oldSettings = { "transports": "transports", "heartbeat timeout": "pingTimeout", "heartbeat interval": "pingInterval", "destroy buffer size": "maxHttpBufferSize" }; /** * Backwards compatiblity. * * @api public */ Server.prototype.set = function(key, val){ if ('authorization' == key && val) { this.use(function(socket, next) { val(socket.request, function(err, authorized) { if (err) return next(new Error(err)); if (!authorized) return next(new Error('Not authorized')); next(); }); }); } else if ('origins' == key && val) { this.origins(val); } else if ('resource' == key) { this.path(val); } else if (oldSettings[key] && this.eio[oldSettings[key]]) { this.eio[oldSettings[key]] = val; } else { console.error('Option %s is not valid. Please refer to the README.', key); } return this; }; /** * Sets the client serving path. * * @param {String} pathname * @return {Server|String} self when setting or value when getting * @api public */ Server.prototype.path = function(v){ if (!arguments.length) return this._path; this._path = v.replace(/\/$/, ''); return this; }; /** * Sets the adapter for rooms. * * @param {Adapter} pathname * @return {Server|Adapter} self when setting or value when getting * @api public */ Server.prototype.adapter = function(v){ if (!arguments.length) return this._adapter; this._adapter = v; for (var i in this.nsps) { if (this.nsps.hasOwnProperty(i)) { this.nsps[i].initAdapter(); } } return this; }; /** * Sets the allowed origins for requests. * * @param {String} origins * @return {Server|Adapter} self when setting or value when getting * @api public */ Server.prototype.origins = function(v){ if (!arguments.length) return this._origins; this._origins = v; return this; }; /** * Attaches socket.io to a server or port. * * @param {http.Server|Number} server or port * @param {Object} options passed to engine.io * @return {Server} self * @api public */ Server.prototype.listen = Server.prototype.attach = function(srv, opts){ if ('function' == typeof srv) { var msg = 'You are trying to attach socket.io to an express' + 'request handler function. Please pass a http.Server instance.'; throw new Error(msg); } // handle a port as a string if (Number(srv) == srv) { srv = Number(srv); } if ('number' == typeof srv) { debug('creating http server and binding to %d', srv); var port = srv; srv = http.Server(function(req, res){ res.writeHead(404); res.end(); }); srv.listen(port); } // set engine.io path to `/socket.io` opts = opts || {}; opts.path = opts.path || this.path(); // set origins verification opts.allowRequest = this.checkRequest.bind(this); // initialize engine debug('creating engine.io instance with opts %j', opts); this.eio = engine.attach(srv, opts); // attach static file serving if (this._serveClient) this.attachServe(srv); // Export http server this.httpServer = srv; // bind to engine events this.bind(this.eio); return this; }; /** * Attaches the static file serving. * * @param {Function|http.Server} http server * @api private */ Server.prototype.attachServe = function(srv){ debug('attaching client serving req handler'); var url = this._path + '/socket.io.js'; var evs = srv.listeners('request').slice(0); var self = this; srv.removeAllListeners('request'); srv.on('request', function(req, res) { if (0 == req.url.indexOf(url)) { self.serve(req, res); } else { for (var i = 0; i < evs.length; i++) { evs[i].call(srv, req, res); } } }); }; /** * Handles a request serving `/socket.io.js` * * @param {http.Request} req * @param {http.Response} res * @api private */ Server.prototype.serve = function(req, res){ var etag = req.headers['if-none-match']; if (etag) { if (clientVersion == etag) { debug('serve client 304'); res.writeHead(304); res.end(); return; } } debug('serve client source'); res.setHeader('Content-Type', 'application/javascript'); res.setHeader('ETag', clientVersion); res.writeHead(200); res.end(clientSource); }; /** * Binds socket.io to an engine.io instance. * * @param {engine.Server} engine.io (or compatible) server * @return {Server} self * @api public */ Server.prototype.bind = function(engine){ this.engine = engine; this.engine.on('connection', this.onconnection.bind(this)); return this; }; /** * Called with each incoming transport connection. * * @param {engine.Socket} socket * @return {Server} self * @api public */ Server.prototype.onconnection = function(conn){ debug('incoming connection with id %s', conn.id); var client = new Client(this, conn); client.connect('/'); return this; }; /** * Looks up a namespace. * * @param {String} nsp name * @param {Function} optional, nsp `connection` ev handler * @api public */ Server.prototype.of = function(name, fn){ if (String(name)[0] !== '/') name = '/' + name; if (!this.nsps[name]) { debug('initializing namespace %s', name); var nsp = new Namespace(this, name); this.nsps[name] = nsp; } if (fn) this.nsps[name].on('connect', fn); return this.nsps[name]; }; /** * Closes server connection * * @api public */ Server.prototype.close = function(){ this.nsps['/'].sockets.forEach(function(socket){ socket.onclose(); }); this.engine.close(); if(this.httpServer){ this.httpServer.close(); } }; /** * Expose main namespace (/). */ ['on', 'to', 'in', 'use', 'emit', 'send', 'write'].forEach(function(fn){ Server.prototype[fn] = function(){ var nsp = this.sockets[fn]; return nsp.apply(this.sockets, arguments); }; }); Namespace.flags.forEach(function(flag){ Server.prototype.__defineGetter__(flag, function(name){ this.flags.push(name); return this; }); }); /** * BC with `io.listen` */ Server.listen = Server;
alexlevy0/socket.io
lib/index.js
JavaScript
mit
8,658
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../xml/xml"), require("../meta")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../xml/xml", "../meta"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineMode("markdown", function(cmCfg, modeCfg) { var htmlMode = CodeMirror.getMode(cmCfg, "text/html"); var htmlModeMissing = htmlMode.name == "null" function getMode(name) { if (CodeMirror.findModeByName) { var found = CodeMirror.findModeByName(name); if (found) name = found.mime || found.mimes[0]; } var mode = CodeMirror.getMode(cmCfg, name); return mode.name == "null" ? null : mode; } // Should characters that affect highlighting be highlighted separate? // Does not include characters that will be output (such as `1.` and `-` for lists) if (modeCfg.highlightFormatting === undefined) modeCfg.highlightFormatting = false; // Maximum number of nested blockquotes. Set to 0 for infinite nesting. // Excess `>` will emit `error` token. if (modeCfg.maxBlockquoteDepth === undefined) modeCfg.maxBlockquoteDepth = 0; // Should underscores in words open/close em/strong? if (modeCfg.underscoresBreakWords === undefined) modeCfg.underscoresBreakWords = true; // Use `fencedCodeBlocks` to configure fenced code blocks. false to // disable, string to specify a precise regexp that the fence should // match, and true to allow three or more backticks or tildes (as // per CommonMark). // Turn on task lists? ("- [ ] " and "- [x] ") if (modeCfg.taskLists === undefined) modeCfg.taskLists = false; // Turn on strikethrough syntax if (modeCfg.strikethrough === undefined) modeCfg.strikethrough = false; // Allow token types to be overridden by user-provided token types. if (modeCfg.tokenTypeOverrides === undefined) modeCfg.tokenTypeOverrides = {}; var tokenTypes = { header: "header", code: "comment", quote: "quote", list1: "variable-2", list2: "variable-3", list3: "keyword", hr: "hr", image: "image", imageAltText: "image-alt-text", imageMarker: "image-marker", formatting: "formatting", linkInline: "link", linkEmail: "link", linkText: "link", linkHref: "string", em: "em", strong: "strong", strikethrough: "strikethrough" }; for (var tokenType in tokenTypes) { if (tokenTypes.hasOwnProperty(tokenType) && modeCfg.tokenTypeOverrides[tokenType]) { tokenTypes[tokenType] = modeCfg.tokenTypeOverrides[tokenType]; } } var hrRE = /^([*\-_])(?:\s*\1){2,}\s*$/ , ulRE = /^[*\-+]\s+/ , olRE = /^[0-9]+([.)])\s+/ , taskListRE = /^\[(x| )\](?=\s)/ // Must follow ulRE or olRE , atxHeaderRE = modeCfg.allowAtxHeaderWithoutSpace ? /^(#+)/ : /^(#+)(?: |$)/ , setextHeaderRE = /^ *(?:\={1,}|-{1,})\s*$/ , textRE = /^[^#!\[\]*_\\<>` "'(~]+/ , fencedCodeRE = new RegExp("^(" + (modeCfg.fencedCodeBlocks === true ? "~~~+|```+" : modeCfg.fencedCodeBlocks) + ")[ \\t]*([\\w+#\-]*)"); function switchInline(stream, state, f) { state.f = state.inline = f; return f(stream, state); } function switchBlock(stream, state, f) { state.f = state.block = f; return f(stream, state); } function lineIsEmpty(line) { return !line || !/\S/.test(line.string) } // Blocks function blankLine(state) { // Reset linkTitle state state.linkTitle = false; // Reset EM state state.em = false; // Reset STRONG state state.strong = false; // Reset strikethrough state state.strikethrough = false; // Reset state.quote state.quote = 0; // Reset state.indentedCode state.indentedCode = false; if (htmlModeMissing && state.f == htmlBlock) { state.f = inlineNormal; state.block = blockNormal; } // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; // Mark this line as blank state.prevLine = state.thisLine state.thisLine = null return null; } function blockNormal(stream, state) { var sol = stream.sol(); var prevLineIsList = state.list !== false, prevLineIsIndentedCode = state.indentedCode; state.indentedCode = false; if (prevLineIsList) { if (state.indentationDiff >= 0) { // Continued list if (state.indentationDiff < 4) { // Only adjust indentation if *not* a code block state.indentation -= state.indentationDiff; } state.list = null; } else if (state.indentation > 0) { state.list = null; } else { // No longer a list state.list = false; } } var match = null; if (state.indentationDiff >= 4) { stream.skipToEnd(); if (prevLineIsIndentedCode || lineIsEmpty(state.prevLine)) { state.indentation -= 4; state.indentedCode = true; return tokenTypes.code; } else { return null; } } else if (stream.eatSpace()) { return null; } else if ((match = stream.match(atxHeaderRE)) && match[1].length <= 6) { state.header = match[1].length; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (!lineIsEmpty(state.prevLine) && !state.quote && !prevLineIsList && !prevLineIsIndentedCode && (match = stream.match(setextHeaderRE))) { state.header = match[0].charAt(0) == '=' ? 1 : 2; if (modeCfg.highlightFormatting) state.formatting = "header"; state.f = state.inline; return getType(state); } else if (stream.eat('>')) { state.quote = sol ? 1 : state.quote + 1; if (modeCfg.highlightFormatting) state.formatting = "quote"; stream.eatSpace(); return getType(state); } else if (stream.peek() === '[') { return switchInline(stream, state, footnoteLink); } else if (stream.match(hrRE, true)) { state.hr = true; return tokenTypes.hr; } else if ((lineIsEmpty(state.prevLine) || prevLineIsList) && (stream.match(ulRE, false) || stream.match(olRE, false))) { var listType = null; if (stream.match(ulRE, true)) { listType = 'ul'; } else { stream.match(olRE, true); listType = 'ol'; } state.indentation = stream.column() + stream.current().length; state.list = true; // While this list item's marker's indentation // is less than the deepest list item's content's indentation, // pop the deepest list item indentation off the stack. while (state.listStack && stream.column() < state.listStack[state.listStack.length - 1]) { state.listStack.pop(); } // Add this list item's content's indentation to the stack state.listStack.push(state.indentation); if (modeCfg.taskLists && stream.match(taskListRE, false)) { state.taskList = true; } state.f = state.inline; if (modeCfg.highlightFormatting) state.formatting = ["list", "list-" + listType]; return getType(state); } else if (modeCfg.fencedCodeBlocks && (match = stream.match(fencedCodeRE, true))) { state.fencedChars = match[1] // try switching mode state.localMode = getMode(match[2]); if (state.localMode) state.localState = CodeMirror.startState(state.localMode); state.f = state.block = local; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = -1 return getType(state); } return switchInline(stream, state, state.inline); } function htmlBlock(stream, state) { var style = htmlMode.token(stream, state.htmlState); if (!htmlModeMissing) { var inner = CodeMirror.innerMode(htmlMode, state.htmlState) if ((inner.mode.name == "xml" && inner.state.tagStart === null && (!inner.state.context && inner.state.tokenize.isInText)) || (state.md_inside && stream.current().indexOf(">") > -1)) { state.f = inlineNormal; state.block = blockNormal; state.htmlState = null; } } return style; } function local(stream, state) { if (state.fencedChars && stream.match(state.fencedChars, false)) { state.localMode = state.localState = null; state.f = state.block = leavingLocal; return null; } else if (state.localMode) { return state.localMode.token(stream, state.localState); } else { stream.skipToEnd(); return tokenTypes.code; } } function leavingLocal(stream, state) { stream.match(state.fencedChars); state.block = blockNormal; state.f = inlineNormal; state.fencedChars = null; if (modeCfg.highlightFormatting) state.formatting = "code-block"; state.code = 1 var returnType = getType(state); state.code = 0 return returnType; } // Inline function getType(state) { var styles = []; if (state.formatting) { styles.push(tokenTypes.formatting); if (typeof state.formatting === "string") state.formatting = [state.formatting]; for (var i = 0; i < state.formatting.length; i++) { styles.push(tokenTypes.formatting + "-" + state.formatting[i]); if (state.formatting[i] === "header") { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.header); } // Add `formatting-quote` and `formatting-quote-#` for blockquotes // Add `error` instead if the maximum blockquote nesting depth is passed if (state.formatting[i] === "quote") { if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.formatting + "-" + state.formatting[i] + "-" + state.quote); } else { styles.push("error"); } } } } if (state.taskOpen) { styles.push("meta"); return styles.length ? styles.join(' ') : null; } if (state.taskClosed) { styles.push("property"); return styles.length ? styles.join(' ') : null; } if (state.linkHref) { styles.push(tokenTypes.linkHref, "url"); } else { // Only apply inline styles to non-url text if (state.strong) { styles.push(tokenTypes.strong); } if (state.em) { styles.push(tokenTypes.em); } if (state.strikethrough) { styles.push(tokenTypes.strikethrough); } if (state.linkText) { styles.push(tokenTypes.linkText); } if (state.code) { styles.push(tokenTypes.code); } if (state.image) { styles.push(tokenTypes.image); } if (state.imageAltText) { styles.push(tokenTypes.imageAltText, "link"); } if (state.imageMarker) { styles.push(tokenTypes.imageMarker); } } if (state.header) { styles.push(tokenTypes.header, tokenTypes.header + "-" + state.header); } if (state.quote) { styles.push(tokenTypes.quote); // Add `quote-#` where the maximum for `#` is modeCfg.maxBlockquoteDepth if (!modeCfg.maxBlockquoteDepth || modeCfg.maxBlockquoteDepth >= state.quote) { styles.push(tokenTypes.quote + "-" + state.quote); } else { styles.push(tokenTypes.quote + "-" + modeCfg.maxBlockquoteDepth); } } if (state.list !== false) { var listMod = (state.listStack.length - 1) % 3; if (!listMod) { styles.push(tokenTypes.list1); } else if (listMod === 1) { styles.push(tokenTypes.list2); } else { styles.push(tokenTypes.list3); } } if (state.trailingSpaceNewLine) { styles.push("trailing-space-new-line"); } else if (state.trailingSpace) { styles.push("trailing-space-" + (state.trailingSpace % 2 ? "a" : "b")); } return styles.length ? styles.join(' ') : null; } function handleText(stream, state) { if (stream.match(textRE, true)) { return getType(state); } return undefined; } function inlineNormal(stream, state) { var style = state.text(stream, state); if (typeof style !== 'undefined') return style; if (state.list) { // List marker (*, +, -, 1., etc) state.list = null; return getType(state); } if (state.taskList) { var taskOpen = stream.match(taskListRE, true)[1] !== "x"; if (taskOpen) state.taskOpen = true; else state.taskClosed = true; if (modeCfg.highlightFormatting) state.formatting = "task"; state.taskList = false; return getType(state); } state.taskOpen = false; state.taskClosed = false; if (state.header && stream.match(/^#+$/, true)) { if (modeCfg.highlightFormatting) state.formatting = "header"; return getType(state); } // Get sol() value now, before character is consumed var sol = stream.sol(); var ch = stream.next(); // Matches link titles present on next line if (state.linkTitle) { state.linkTitle = false; var matchCh = ch; if (ch === '(') { matchCh = ')'; } matchCh = (matchCh+'').replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1"); var regex = '^\\s*(?:[^' + matchCh + '\\\\]+|\\\\\\\\|\\\\.)' + matchCh; if (stream.match(new RegExp(regex), true)) { return tokenTypes.linkHref; } } // If this block is changed, it may need to be updated in GFM mode if (ch === '`') { var previousFormatting = state.formatting; if (modeCfg.highlightFormatting) state.formatting = "code"; stream.eatWhile('`'); var count = stream.current().length if (state.code == 0) { state.code = count return getType(state) } else if (count == state.code) { // Must be exact var t = getType(state) state.code = 0 return t } else { state.formatting = previousFormatting return getType(state) } } else if (state.code) { return getType(state); } if (ch === '\\') { stream.next(); if (modeCfg.highlightFormatting) { var type = getType(state); var formattingEscape = tokenTypes.formatting + "-escape"; return type ? type + " " + formattingEscape : formattingEscape; } } if (ch === '!' && stream.match(/\[[^\]]*\] ?(?:\(|\[)/, false)) { state.imageMarker = true; state.image = true; if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === '[' && state.imageMarker) { state.imageMarker = false; state.imageAltText = true if (modeCfg.highlightFormatting) state.formatting = "image"; return getType(state); } if (ch === ']' && state.imageAltText) { if (modeCfg.highlightFormatting) state.formatting = "image"; var type = getType(state); state.imageAltText = false; state.image = false; state.inline = state.f = linkHref; return type; } if (ch === '[' && stream.match(/[^\]]*\](\(.*\)| ?\[.*?\])/, false) && !state.image) { state.linkText = true; if (modeCfg.highlightFormatting) state.formatting = "link"; return getType(state); } if (ch === ']' && state.linkText && stream.match(/\(.*?\)| ?\[.*?\]/, false)) { if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); state.linkText = false; state.inline = state.f = linkHref; return type; } if (ch === '<' && stream.match(/^(https?|ftps?):\/\/(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } if (ch === '<' && stream.match(/^[^> \\]+@(?:[^\\>]|\\.)+>/, false)) { state.f = state.inline = linkInline; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkEmail; } if (ch === '<' && stream.match(/^(!--|\w)/, false)) { var end = stream.string.indexOf(">", stream.pos); if (end != -1) { var atts = stream.string.substring(stream.start, end); if (/markdown\s*=\s*('|"){0,1}1('|"){0,1}/.test(atts)) state.md_inside = true; } stream.backUp(1); state.htmlState = CodeMirror.startState(htmlMode); return switchBlock(stream, state, htmlBlock); } if (ch === '<' && stream.match(/^\/\w*?>/)) { state.md_inside = false; return "tag"; } var ignoreUnderscore = false; if (!modeCfg.underscoresBreakWords) { if (ch === '_' && stream.peek() !== '_' && stream.match(/(\w)/, false)) { var prevPos = stream.pos - 2; if (prevPos >= 0) { var prevCh = stream.string.charAt(prevPos); if (prevCh !== '_' && prevCh.match(/(\w)/, false)) { ignoreUnderscore = true; } } } } if (ch === '*' || (ch === '_' && !ignoreUnderscore)) { if (sol && stream.peek() === ' ') { // Do nothing, surrounded by newline and space } else if (state.strong === ch && stream.eat(ch)) { // Remove STRONG if (modeCfg.highlightFormatting) state.formatting = "strong"; var t = getType(state); state.strong = false; return t; } else if (!state.strong && stream.eat(ch)) { // Add STRONG state.strong = ch; if (modeCfg.highlightFormatting) state.formatting = "strong"; return getType(state); } else if (state.em === ch) { // Remove EM if (modeCfg.highlightFormatting) state.formatting = "em"; var t = getType(state); state.em = false; return t; } else if (!state.em) { // Add EM state.em = ch; if (modeCfg.highlightFormatting) state.formatting = "em"; return getType(state); } } else if (ch === ' ') { if (stream.eat('*') || stream.eat('_')) { // Probably surrounded by spaces if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(1); } } } if (modeCfg.strikethrough) { if (ch === '~' && stream.eatWhile(ch)) { if (state.strikethrough) {// Remove strikethrough if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; var t = getType(state); state.strikethrough = false; return t; } else if (stream.match(/^[^\s]/, false)) {// Add strikethrough state.strikethrough = true; if (modeCfg.highlightFormatting) state.formatting = "strikethrough"; return getType(state); } } else if (ch === ' ') { if (stream.match(/^~~/, true)) { // Probably surrounded by space if (stream.peek() === ' ') { // Surrounded by spaces, ignore return getType(state); } else { // Not surrounded by spaces, back up pointer stream.backUp(2); } } } } if (ch === ' ') { if (stream.match(/ +$/, false)) { state.trailingSpace++; } else if (state.trailingSpace) { state.trailingSpaceNewLine = true; } } return getType(state); } function linkInline(stream, state) { var ch = stream.next(); if (ch === ">") { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link"; var type = getType(state); if (type){ type += " "; } else { type = ""; } return type + tokenTypes.linkInline; } stream.match(/^[^>]+/, true); return tokenTypes.linkInline; } function linkHref(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } var ch = stream.next(); if (ch === '(' || ch === '[') { state.f = state.inline = getLinkHrefInside(ch === "(" ? ")" : "]", 0); if (modeCfg.highlightFormatting) state.formatting = "link-string"; state.linkHref = true; return getType(state); } return 'error'; } var linkRE = { ")": /^(?:[^\\\(\)]|\\.|\((?:[^\\\(\)]|\\.)*\))*?(?=\))/, "]": /^(?:[^\\\[\]]|\\.|\[(?:[^\\\[\\]]|\\.)*\])*?(?=\])/ } function getLinkHrefInside(endChar) { return function(stream, state) { var ch = stream.next(); if (ch === endChar) { state.f = state.inline = inlineNormal; if (modeCfg.highlightFormatting) state.formatting = "link-string"; var returnState = getType(state); state.linkHref = false; return returnState; } stream.match(linkRE[endChar]) state.linkHref = true; return getType(state); }; } function footnoteLink(stream, state) { if (stream.match(/^([^\]\\]|\\.)*\]:/, false)) { state.f = footnoteLinkInside; stream.next(); // Consume [ if (modeCfg.highlightFormatting) state.formatting = "link"; state.linkText = true; return getType(state); } return switchInline(stream, state, inlineNormal); } function footnoteLinkInside(stream, state) { if (stream.match(/^\]:/, true)) { state.f = state.inline = footnoteUrl; if (modeCfg.highlightFormatting) state.formatting = "link"; var returnType = getType(state); state.linkText = false; return returnType; } stream.match(/^([^\]\\]|\\.)+/, true); return tokenTypes.linkText; } function footnoteUrl(stream, state) { // Check if space, and return NULL if so (to avoid marking the space) if(stream.eatSpace()){ return null; } // Match URL stream.match(/^[^\s]+/, true); // Check for link title if (stream.peek() === undefined) { // End of line, set flag to check next line state.linkTitle = true; } else { // More content on line, check if link title stream.match(/^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?/, true); } state.f = state.inline = inlineNormal; return tokenTypes.linkHref + " url"; } var mode = { startState: function() { return { f: blockNormal, prevLine: null, thisLine: null, block: blockNormal, htmlState: null, indentation: 0, inline: inlineNormal, text: handleText, formatting: false, linkText: false, linkHref: false, linkTitle: false, code: 0, em: false, strong: false, header: 0, hr: false, taskList: false, list: false, listStack: [], quote: 0, trailingSpace: 0, trailingSpaceNewLine: false, strikethrough: false, fencedChars: null }; }, copyState: function(s) { return { f: s.f, prevLine: s.prevLine, thisLine: s.thisLine, block: s.block, htmlState: s.htmlState && CodeMirror.copyState(htmlMode, s.htmlState), indentation: s.indentation, localMode: s.localMode, localState: s.localMode ? CodeMirror.copyState(s.localMode, s.localState) : null, inline: s.inline, text: s.text, formatting: false, linkTitle: s.linkTitle, code: s.code, em: s.em, strong: s.strong, strikethrough: s.strikethrough, header: s.header, hr: s.hr, taskList: s.taskList, list: s.list, listStack: s.listStack.slice(0), quote: s.quote, indentedCode: s.indentedCode, trailingSpace: s.trailingSpace, trailingSpaceNewLine: s.trailingSpaceNewLine, md_inside: s.md_inside, fencedChars: s.fencedChars }; }, token: function(stream, state) { // Reset state.formatting state.formatting = false; if (stream != state.thisLine) { var forceBlankLine = state.header || state.hr; // Reset state.header and state.hr state.header = 0; state.hr = false; if (stream.match(/^\s*$/, true) || forceBlankLine) { blankLine(state); if (!forceBlankLine) return null state.prevLine = null } state.prevLine = state.thisLine state.thisLine = stream // Reset state.taskList state.taskList = false; // Reset state.trailingSpace state.trailingSpace = 0; state.trailingSpaceNewLine = false; state.f = state.block; var indentation = stream.match(/^\s*/, true)[0].replace(/\t/g, ' ').length; state.indentationDiff = Math.min(indentation - state.indentation, 4); state.indentation = state.indentation + state.indentationDiff; if (indentation > 0) return null; } return state.f(stream, state); }, innerMode: function(state) { if (state.block == htmlBlock) return {state: state.htmlState, mode: htmlMode}; if (state.localState) return {state: state.localState, mode: state.localMode}; return {state: state, mode: mode}; }, blankLine: blankLine, getType: getType, fold: "markdown" }; return mode; }, "xml"); CodeMirror.defineMIME("text/x-markdown", "markdown"); });
leungwensen/d2recharts
dist/lib/codemirror-5.18.2/mode/markdown/markdown.js
JavaScript
mit
26,589
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var ActionSettingsInputHdmi = React.createClass({ displayName: 'ActionSettingsInputHdmi', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M18 7V4c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v3H5v6l3 6v3h8v-3l3-6V7h-1zM8 4h8v3h-2V5h-1v2h-2V5h-1v2H8V4z' }) ); } }); module.exports = ActionSettingsInputHdmi;
jotamaggi/react-calendar-app
node_modules/react-material-icons/icons/action/settings-input-hdmi.js
JavaScript
mit
498
/* Copyright (c) 2003-2011, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ /** * @file Horizontal Page Break */ // Register a plugin named "pagebreak". CKEDITOR.plugins.add( 'pagebreak', { init : function( editor ) { // Register the command. editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd ); // Register the toolbar button. editor.ui.addButton( 'PageBreak', { label : editor.lang.pagebreak, command : 'pagebreak' }); var cssStyles = [ '{' , 'background: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ') no-repeat center center;' , 'clear: both;' , 'width:100%; _width:99.9%;' , 'border-top: #999999 1px dotted;' , 'border-bottom: #999999 1px dotted;' , 'padding:0;' , 'height: 5px;' , 'cursor: default;' , '}' ].join( '' ).replace(/;/g, ' !important;' ); // Increase specificity to override other styles, e.g. block outline. // Add the style that renders our placeholder. editor.addCss( 'div.cke_pagebreak' + cssStyles ); // Opera needs help to select the page-break. CKEDITOR.env.opera && editor.on( 'contentDom', function() { editor.document.on( 'click', function( evt ) { var target = evt.data.getTarget(); if ( target.is( 'div' ) && target.hasClass( 'cke_pagebreak') ) editor.getSelection().selectElement( target ); }); }); }, afterInit : function( editor ) { var label = editor.lang.pagebreakAlt; // Register a filter to displaying placeholders after mode change. var dataProcessor = editor.dataProcessor, dataFilter = dataProcessor && dataProcessor.dataFilter, htmlFilter = dataProcessor && dataProcessor.htmlFilter; if ( htmlFilter ) { htmlFilter.addRules( { attributes : { 'class' : function( value, element ) { var className = value.replace( 'cke_pagebreak', '' ); if ( className != value ) { var span = CKEDITOR.htmlParser.fragment.fromHtml( '<span style="display: none;">&nbsp;</span>' ); element.children.length = 0; element.add( span ); var attrs = element.attributes; delete attrs[ 'aria-label' ]; delete attrs.contenteditable; delete attrs.title; } return className; } } }, 5 ); } if ( dataFilter ) { dataFilter.addRules( { elements : { div : function( element ) { var attributes = element.attributes, style = attributes && attributes.style, child = style && element.children.length == 1 && element.children[ 0 ], childStyle = child && ( child.name == 'span' ) && child.attributes.style; if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) ) { attributes.contenteditable = "false"; attributes[ 'class' ] = "cke_pagebreak"; attributes[ 'data-cke-display-name' ] = "pagebreak"; attributes[ 'aria-label' ] = label; attributes[ 'title' ] = label; element.children.length = 0; } } } }); } }, requires : [ 'fakeobjects' ] }); CKEDITOR.plugins.pagebreakCmd = { exec : function( editor ) { var label = editor.lang.pagebreakAlt; // Create read-only element that represents a print break. var pagebreak = CKEDITOR.dom.element.createFromHtml( '<div style="' + 'page-break-after: always;"' + 'contenteditable="false" ' + 'title="'+ label + '" ' + 'aria-label="'+ label + '" ' + 'data-cke-display-name="pagebreak" ' + 'class="cke_pagebreak">' + '</div>', editor.document ); var ranges = editor.getSelection().getRanges( true ); editor.fire( 'saveSnapshot' ); for ( var range, i = ranges.length - 1 ; i >= 0; i-- ) { range = ranges[ i ]; if ( i < ranges.length -1 ) pagebreak = pagebreak.clone( true ); range.splitBlock( 'p' ); range.insertNode( pagebreak ); if ( i == ranges.length - 1 ) { var next = pagebreak.getNext(); range.moveToPosition( pagebreak, CKEDITOR.POSITION_AFTER_END ); // If there's nothing or a non-editable block followed by, establish a new paragraph // to make sure cursor is not trapped. if ( !next || next.type == CKEDITOR.NODE_ELEMENT && !next.isEditable() ) range.fixBlock( true, editor.config.enterMode == CKEDITOR.ENTER_DIV ? 'div' : 'p' ); range.select(); } } editor.fire( 'saveSnapshot' ); } };
evansd-archive/kohana-module--ckeditor
vendor/ckeditor/_source/plugins/pagebreak/plugin.js
JavaScript
mit
4,671
/*! * ===================================================== * dmui v0.1.0 (http://www.91holy.com) * ===================================================== */ /*! * dmui JavaScript Library v0.1.0 * https://dmui.com/ * Copyright dmui Foundation and other contributors * Released under the MIT license * https://github.com/desangel/dmui/license * * Date: 2016-05-12T06:59Z */ ( function( global, factory ) { if ( typeof module === "object" && typeof module.exports === "object" ) { // For CommonJS and CommonJS-like environments where a proper `window` // is present, execute the factory and get dmui. // For environments that do not have a `window` with a `document` // (such as Node.js), expose a factory as module.exports. // This accentuates the need for the creation of a real `window`. // e.g. var dmui = require("jquery")(window); // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { if ( !w.document ) { throw new Error( "dmui requires a window with a document" ); } return factory( w ); }; } else { factory( global ); } // Pass this if window is not defined yet }( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { // Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 // throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode // arguments.callee.caller (trac-13335). But as of dmui 3.0 (2016), strict mode should be common // enough that all such attempts are guarded in a try block. "use strict"; (function(){ "use strict"; window.URL = window.URL||window.webkitURL; }()); var util = (function(){ "use strict"; var class2type = {}; var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; var util = { isFunction: isFunction, isArray: Array.isArray || isArray, isWindow: isWindow, isNumeric: isNumeric, isEmptyObject: isEmptyObject, isPlainObject: isPlainObject, type: type, extend: extend }; function isFunction( obj ) { return type(obj) === "function"; } function isArray( obj ) { return type(obj) === "array"; } function isWindow( obj ) { return obj != null && obj === obj.window; } function isNumeric( obj ) { // parseFloat NaNs numeric-cast false positives (null|true|false|"") // ...but misinterprets leading-number strings, particularly hex literals ("0x...") // subtraction forces infinities to NaN // adding 1 corrects loss of precision from parseFloat (#15100) return !isArray( obj ) && (obj - parseFloat( obj ) + 1) >= 0; } function isEmptyObject( obj ) { var name; for ( name in obj ) { return false; } return true; } function isPlainObject( obj ) { var key; // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || type(obj) !== "object" || obj.nodeType || isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !hasOwn.call(obj, "constructor") && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Support: IE<9 // Handle iteration over inherited properties before own properties. //if ( support.ownLast ) { // for ( key in obj ) { // return hasOwn.call( obj, key ); // } //} // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. for ( key in obj ) {} return key === undefined || hasOwn.call( obj, key ); } function type( obj ) { if ( obj == null ) { return obj + ""; } return typeof obj === "object" || typeof obj === "function" ? class2type[ toString.call(obj) ] || "object" : typeof obj; } function extend(){ var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; // skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !isFunction(target)) { target = {}; } // extend itself if only one argument is passed if ( i === length ) { target = {}; //this i--; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // do not copy prototype function if ( !options.hasOwnProperty(name)){ continue; } // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( name!== 'parent' && deep && copy && !isPlainObject(copy) && typeof copy.clone === "function" ){ //remove parent for no dead loop //clone is for classType object target[ name ] = copy.clone(); if(target[ name ] ===undefined){ target[ name ] = copy; } } else if ( deep && copy && ( isPlainObject(copy) || (copyIsArray = isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && isArray(src) ? src : []; } else { clone = src && isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; } return util; }()); /* global xyz */ util.classExtend = (function(){ "use strict"; //inheritance function classExtend(ChildClass, ParentClass){ var initializing = false, fnTest = /xyz/.test(function() { xyz; }) ? /\b_super\b/ : /.*/; var _super = ParentClass.prototype; var prop = ChildClass.prototype; var prototype = typeof Object.create === "function" ? Object.create(ParentClass.prototype):new ParentClass(); for (var name in prop) { // Check if we're overwriting an existing function prototype[name] = typeof prop[name] === "function" && typeof _super[name] === "function" && fnTest.test(prop[name]) ? createCallSuperFunction(name, prop[name]) : prop[name]; } initializing = true; ChildClass.prototype = prototype; ChildClass.prototype.constructor = ChildClass; function createCallSuperFunction(name, fn){ return function() { var tmp = this._super; // Add a new ._super() method that is the same method // but on the super-class this._super = _super[name]; // The method only need to be bound temporarily, so we // remove it when we're done executing var ret = fn.apply(this, arguments); this._super = tmp; return ret; }; } } return classExtend; }()); var document = window.document; util.extend( util, (function(){ "use strict"; var code = { htmlEncode: htmlEncode, htmlDecode: htmlDecode }; function htmlEncode(value){ var temp = document.createElement('div'); (temp.textContent!=null)?(temp.textContent=value) : (temp.innerText=value); var result = temp.html.innerHTML; temp = null; return result; } function htmlDecode(value){ var temp = document.createElement('div'); temp.innerHTML = value; var result = temp.innerText || temp.textContent; temp = null; return result; } return code; }()) ); util.extend(util, (function(){ "use strict"; //ECMA SCRIPT 5 var object = { defineProperty: defineProperty, defineProperties: defineProperties }; function defineProperty(obj, name, prop){ if(typeof Object.defineProperty ==='function'){ Object.defineProperty(obj, name, prop); } else{ obj[name] = prop['value']; } } function defineProperties(obj, props){ if(typeof Object.defineProperties ==='function'){ Object.defineProperties(obj, props); } else{ for(var i in props){ var prop = props[i]; obj[i] = prop['value']; } } } return object; }()) ); util.browser = (function(){ "use strict"; var navigator = window.navigator; var browser = { versions: (function(){ var u = navigator.userAgent, app = navigator.appVersion; var vendor = navigator.vendor; return { u: u, app: app, vendor: vendor, windows: u.indexOf('Windows') > -1, //windows trident: u.indexOf('Trident') > -1, //IE内核 presto: u.indexOf('Presto') > -1, //opera内核 webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核 gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1,//火狐内核 chrome: u.indexOf('Chrome') > -1 ,//chrome内核 mobile: !!u.match(/AppleWebKit.*Mobile.*/), //是否为移动终端 ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端 android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器 iPhone: u.indexOf('iPhone') > -1 , //是否为iPhone或者QQHD浏览器 iPad: u.indexOf('iPad') > -1, //是否iPad webApp: u.indexOf('Safari') === -1, //是否web应该程序,没有头部与底部 weixin: u.indexOf('MicroMessenger') > -1, //是否微信 (2015-01-22新增) weibo: u.indexOf('Weibo') > -1, //是否微博 qq: u.match(/\sQQ/i) === " qq" //是否QQ }; })(), language:(navigator.browserLanguage || navigator.language || navigator.userLanguage).toLowerCase() }; return browser; }()); util.collection = (function(){ "use strict"; var collection = { is: is }; function is(arr, element){ for(var i = 0; i<arr.length; i++){ if(typeof element === 'function'){ if(element(i, arr[i])){return true;} }else{ if(arr[i]===element){return true;} } } return false; } return collection; }()); util.cookie = (function(){ "use strict"; var cookie = { addCookie: addCookie, deleteCookie: deleteCookie, getCookie: getCookie, getDocumentCookie: getDocumentCookie }; function addCookie(name, value, attr){ var str = ""; if(attr){ for(var prop in attr){ str+=";"+prop+"="+attr[prop]; } } document.cookie = name + "=" + window.escape(value) + str; } function deleteCookie(name){ var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = getCookie(name); if (cval != null){ document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString(); } } function getCookie(name){ var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)")); if (arr != null){ return (arr[2]); } return null; } function getDocumentCookie(){ return document.cookie; } return cookie; }()); util.date = (function(){ "use strict"; var getDateHelper = function(){ return { date : getDate(), duration : getDurationHelper(), dateDiff : dateDiff, dateDiffResult : dateDiffResult, dateDiffResultFull : dateDiffResultFull, dateToStr : dateToStr, datetimeToStr : datetimeToStr, getOffsetDate : getOffsetDate, paramToDate : paramToDate, strToDate : strToDate, timeToStr : timeToStr, durationToStr : durationToStr, durationToObj : durationToObj, typeToStr : typeToStr, weekdayToStr : weekdayToStr, zhDateToStr : zhDateToStr, zhDatetimeToStr : zhDatetimeToStr, fillZero : fillZero }; function getDate(){ return { monthFirstDay : monthFirstDay, monthLastDay : monthLastDay }; function monthFirstDay(date){ return paramToDate(date.getFullYear(), date.getMonth()); } function monthLastDay(date){ var result = monthFirstDay(date); result = getOffsetDate('month', result, 1); result = getOffsetDate('date', result, -1); return result; } } function getDurationHelper() { return { today : today, yestoday : yestoday, date: day, currentWeek : currentWeek, lastWeek : lastWeek, currentMonth : currentMonth, currentYear : currentYear, calendarMonth : calendarMonth, month : month, year : year }; function today() { return getDurationStr('date', new Date()); } function yestoday() { return getDurationStr('date', getOffsetDate('date', new Date(), -1)); } function day(date){ return getDurationStr('date', date); } function currentWeek(){ return getDurationStr('day', new Date()); } function lastWeek(){ return getDurationStr('day', getOffsetDate('date', new Date(), -7)); } function currentMonth(){ return getDurationStr('month', new Date()); } function currentYear(){ return getDurationStr('year', new Date()); } function calendarMonth(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth()+1; return getDurationStr('calendarMonth', paramToDate(year, month-1)); } function month(year, month){ var now = new Date(); year = year || now.getFullYear(); month = month || now.getMonth()+1; return getDurationStr('month', paramToDate(year, month-1)); } function year(year){ return getDurationStr('year', paramToDate(year)); } } function getDurationStr(type, startTime) { var result = getDuration(type, startTime); return { startTime : datetimeToStr(result['startTime']), endTime : datetimeToStr(result['endTime']) }; } function getDuration(type, startTime) { var year, month, date, hour, minute, second; var day; var startTimeDate, endTimeDate; switch (type) { case 'calendarMonth': year = startTime.getFullYear(); month = startTime.getMonth(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate('month', startTimeDate, 1); var startTimeWeekDay = startTimeDate.getDay(); var endTimeWeekDay = endTimeDate.getDay(); startTimeDate = getOffsetDate('date', startTimeDate, - startTimeWeekDay%7); endTimeDate = getOffsetDate('date', endTimeDate, (7-endTimeWeekDay)%7); break; case 'year': year = startTime.getFullYear(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'month': year = startTime.getFullYear(); month = startTime.getMonth(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'date': year = startTime.getFullYear(); month = startTime.getMonth(); date = startTime.getDate(); startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate(type, startTimeDate, 1); break; case 'day': year = startTime.getFullYear(); month = startTime.getMonth(); date = startTime.getDate(); day = startTime.getDay(); date = date - (day+6)%7; startTimeDate = paramToDate(year, month, date, hour, minute, second); endTimeDate = getOffsetDate('date', startTimeDate, 7); break; } return { startTime : startTimeDate, endTime : endTimeDate }; } function dateDiff(type, date1, date2){ var result = 0; switch (type) { case 'year': result = Math.floor(((date1.getFullYear() - date2.getFullYear())*12+ date1.getMonth() - date2.getMonth())/12);break; case 'month': result = (date1.getFullYear() - date2.getFullYear())*12 + date1.getMonth() - date2.getMonth() + (((date1.getDate()-date2.getDate())>=0?1:-1) + (date1>=date2?-1: 1))/2;break; case 'date': result = Math.floor(date1.getTime()/(1000*60*60*24))-Math.floor(date2.getTime()/(1000*60*60*24)); break; case 'hour': result = Math.floor(date1.getTime()/(1000*60*60))-Math.floor(date2.getTime()/(1000*60*60)); break; case 'minute': result = Math.floor(date1.getTime()/(1000*60))-Math.floor(date2.getTime()/(1000*60)); break; case 'second': result = Math.floor(date1.getTime()/(1000))-Math.floor(date2.getTime()/(1000)); break; default: result = (date1.getTime()-date2.getTime()); } return result; } function dateDiffResult(date1, date2){ var offset, type; type = 'year'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'month'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'date'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'hour'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'minute'; offset = dateDiff(type, date1, date2); if(offset!==0)return {offset: offset, type: type}; type = 'second'; offset = dateDiff(type, date1, date2); return {offset: offset, type: type}; } function dateDiffResultFull(type, date1, date2){ var result = {}; var delta = date1.getTime()-date2.getTime(); var rest = delta; switch(type){ case 'year': result['year'] = dateDiff('year', date1, date2); break; case 'date': result['date'] = Math.floor(rest / (1000*60*60*24) ); rest = rest % (1000*60*60*24); result['hour'] = Math.floor(rest / (1000*60*60) ); rest = rest % (1000*60*60); result['minute'] = Math.floor(rest / (1000*60) ); rest = rest % (1000*60); result['second'] = Math.floor(rest / (1000) ); rest = rest % (1000); break; } return result; } function getOffsetDate(type, date, offset) { var year = date.getFullYear(); var month = date.getMonth(); var day = date.getDate(); var hour = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); switch (type) { case 'year':year+=offset;break; case 'month':month+=offset;break; case 'date':day+=offset;break; case 'hour':hour+=offset;break; case 'minute':minute+=offset;break; case 'second':second+=offset;break; } return paramToDate(year, month, day, hour, minute, second); } function fillZero(input, num) { var result = '' + input; for (var i = 0; i < (num - result.length); i++) { result = '0' + result; } return result; } function datetimeToStr(date, fmt) { if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyy-MM-dd hh:mm:ss'; var year = date.getFullYear(); var month = fillZero(date.getMonth() + 1, 2); var dateString = fillZero(date.getDate(), 2); var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var second = fillZero(date.getSeconds(), 2); return fmt.replace('yyyy',year).replace('MM',month).replace('dd', dateString).replace('hh',hour).replace('mm',minute).replace('ss', second); } function dateToStr(date, fmt) { if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyy-MM-dd'; var year = date.getFullYear(); var month = fillZero(date.getMonth() + 1, 2); var dateString = fillZero(date.getDate(), 2); return fmt.replace('yyyy',year).replace('MM',month).replace('dd', dateString); } function timeToStr(date, fmt){ if(typeof date==='string')date = strToDate(date); fmt = fmt||'hh:mm:ss'; var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var second = fillZero(date.getSeconds(), 2); return fmt.replace('hh',hour).replace('mm',minute).replace('ss', second); } function durationToStr(millisecond, fmt, fillType){ fmt = fmt||'hh:mm:ss.ms'; fillType = fillType||'hh'; var obj = durationToObj(millisecond); var hour = fillZero(obj['hour'] ,2); var minute = fillZero(obj['minute'], 2); var second = fillZero(obj['second'], 2); if(fillType==='hh'||fillType==='mm'&&obj['hour']===0){ fmt = fmt.replace('hh:', ''); if(fillType==='mm'&&obj['minute']===0){ fmt = fmt.replace('mm:', ''); } } return fmt.replace('hh', hour).replace('mm', minute).replace('ss', second).replace('ms', obj['millisecond']); } function durationToObj(millisecond){ var result = {}; var rest = millisecond; result['hour'] = Math.floor(rest / (1000*60*60) ); rest = rest % (1000*60*60); result['minute'] = Math.floor(rest / (1000*60) ); rest = rest % (1000*60); result['second'] = Math.floor(rest / (1000) ); rest = rest % (1000); result['millisecond'] = rest; return result; } function zhDateToStr(date, fmt){ if(typeof date==='string')date = strToDate(date); fmt = fmt||'yyyyMMdd'; var year = date.getFullYear(); var month = date.getMonth() + 1; var dateString = date.getDate(); return fmt.replace('yyyy',year+'年').replace('MM',month+'月').replace('dd', dateString+'日'); } function zhDatetimeToStr(date){ var now = new Date(); var year = date.getFullYear(); var month = date.getMonth() + 1; var dateString = date.getDate(); var hour = fillZero(date.getHours() ,2); var minute = fillZero(date.getMinutes(), 2); var result = ''; if(now.getFullYear()===year&&now.getMonth()+1===month){ if(now.getDate()-dateString===0){ }else if(now.getDate()-dateString===1){ result += '昨天'; }else if(now.getDate()-dateString===2){ result += '前天'; }else{ result += zhDateToStr(date); } if(now.getDate()-dateString!==0)result += ' '; } result += hour+':'+minute; return result; } // 微信客户端不支持new Date("2015-07-04 12:00:00") function strToDate(dateTimeStr) { if(!dateTimeStr)return null; var date = new Date(0); var dateTimeArray = dateTimeStr.split(' '); var dateStr = dateTimeArray[0]; var dateArray = dateStr.split('-'); date.setFullYear(parseInt(dateArray[0], 0)); date.setMonth(parseInt(dateArray[1], 0) - 1); date.setDate(parseInt(dateArray[2], 0)); if (dateTimeArray.length > 1) { var timeStr = dateTimeArray[1]; var timeArray = timeStr.split(':'); date.setHours(parseInt(timeArray[0], 0)); date.setMinutes(parseInt(timeArray[1], 0)); date.setSeconds(parseInt(timeArray[2], 0)); } return date; } function paramToDate(year, month, date, hour, minute, second) { month =month || 0; date = date!==undefined? date : 1; hour = hour || 0; minute = minute || 0; second = second || 0; var result = new Date(0); result.setFullYear(year); result.setMonth(month); result.setDate(date); result.setHours(hour); result.setMinutes(minute); result.setSeconds(second); return result; } function weekdayToStr(weekday){ var result = ''; switch(weekday){ case 0:result='日';break; case 1:result='一';break; case 2:result='二';break; case 3:result='三';break; case 4:result='四';break; case 5:result='五';break; case 6:result='六';break; } return result; } function typeToStr(type){ var result = ''; switch(type){ case 'year':result='年';break; case 'month':result='月';break; case 'day': case 'date':result='天';break; case 'hour':result='小时';break; case 'minute':result='分钟';break; case 'second':result='秒';break; } return result; } }; return getDateHelper(); }()); util.path = (function(){ "use strict"; function findCurrentPath(){ return document.currentScript&&document.currentScript.src||(function(){ //for IE10+ Safari Opera9 var a = {}, stack; try{ a.b(); }catch(e){ stack = e.stack || e.sourceURL || e.stacktrace; } var rExtractUri = /(?:http|https|file):\/\/.*?\/.+?.js/, absPath = rExtractUri.exec(stack); return absPath[0] || ''; })()||(function(){ // IE5.5 - 9 var scripts = document.scripts; var isLt8 = ('' + document.querySelector).indexOf('[native code]') === -1; for (var i = scripts.length - 1, script; script = scripts[i--];){ if (script.readyState === 'interative'){ return isLt8 ? script.getAttribute('src', 4) : script.src; } } })(); } return { findCurrentPath: findCurrentPath }; }()); var version = "0.1.0"; var dmui = function(){ this.init(); }; dmui.fn = dmui.prototype = { version: version, constructor: dmui, init: function(){ window.console.log(util); } }; var // Map over dmui in case of overwrite _dmui = window.dmui; dmui.noConflict = function( deep ) { if ( deep && window.dmui === dmui ) { window.dmui = _dmui; } return dmui; }; // Expose dmui and $ identifiers, even in AMD // and CommonJS for browser emulators (#13566) if ( !noGlobal ) { window.dmui = dmui; } return dmui; } ) );
desangel/dmui
example/js/dmui.js
JavaScript
mit
24,049
import { sortSurveyElements } from '../index'; describe('sortSurveyElements', () => { it('sorts survey elements by weight', () => { const inputSurvey = { title: 'Sample Survey', sections: [ { id: 1, title: 'Later Section', weight: 1 }, { id: 2, title: 'Earlier Section', weight: 0, questions: [ { id: 4, description: 'Q3', weight: 2 }, { id: 5, description: 'Q1', weight: 0 }, { id: 1, description: 'Q2', weight: 1, options: [ { option: 'Choice 2', weight: 1 }, { option: 'Choice 1', weight: 0 }, ], }, ], }, ], }; const outputSurvey = { title: 'Sample Survey', sections: [ { id: 2, title: 'Earlier Section', weight: 0, questions: [ { id: 5, description: 'Q1', weight: 0 }, { id: 1, description: 'Q2', weight: 1, options: [ { option: 'Choice 1', weight: 0 }, { option: 'Choice 2', weight: 1 }, ], }, { id: 4, description: 'Q3', weight: 2 }, ], }, { id: 1, title: 'Later Section', weight: 1 }, ], }; expect(sortSurveyElements(inputSurvey)).toEqual(outputSurvey); }); });
cysjonathan/coursemology2
client/app/bundles/course/survey/utils/__test__/index.test.js
JavaScript
mit
1,481
const should = require('should'); const sinon = require('sinon'); const configUtils = require('../../../utils/configUtils'); // Stuff we are testing const img_url = require('../../../../core/frontend/helpers/img_url'); const logging = require('@tryghost/logging'); describe('{{img_url}} helper', function () { let logWarnStub; beforeEach(function () { logWarnStub = sinon.stub(logging, 'warn'); }); afterEach(function () { sinon.restore(); }); describe('without sub-directory', function () { before(function () { configUtils.set({url: 'http://localhost:65535/'}); }); after(function () { configUtils.restore(); }); it('should output relative url of image', function () { const rendered = img_url('/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output relative url of image if the input is absolute', function () { const rendered = img_url('http://localhost:65535/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should output absolute url of image if the option is present ', function () { const rendered = img_url('/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/content/images/image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should NOT output absolute url of image if the option is "false" ', function () { const rendered = img_url('/content/images/image-relative-url.png', {hash: {absolute: 'false'}}); should.exist(rendered); rendered.should.equal('/content/images/image-relative-url.png'); }); it('should output author url', function () { const rendered = img_url('/content/images/author-image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/content/images/author-image-relative-url.png'); logWarnStub.called.should.be.false(); }); it('should have no output if the image attribute is not provided (with warning)', function () { const rendered = img_url({hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to undefined (with warning)', function () { const rendered = img_url(undefined, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.true(); }); it('should have no output if the image attribute evaluates to null (no waring)', function () { const rendered = img_url(null, {hash: {absolute: 'true'}}); should.not.exist(rendered); logWarnStub.calledOnce.should.be.false(); }); }); describe('with sub-directory', function () { before(function () { configUtils.set({url: 'http://localhost:65535/blog'}); }); after(function () { configUtils.restore(); }); it('should output relative url of image', function () { const rendered = img_url('/blog/content/images/image-relative-url.png', {}); should.exist(rendered); rendered.should.equal('/blog/content/images/image-relative-url.png'); }); it('should output absolute url of image if the option is present ', function () { const rendered = img_url('/blog/content/images/image-relative-url.png', {hash: {absolute: 'true'}}); should.exist(rendered); rendered.should.equal('http://localhost:65535/blog/content/images/image-relative-url.png'); }); it('should not change output for an external url', function () { const rendered = img_url('http://example.com/picture.jpg', {}); should.exist(rendered); rendered.should.equal('http://example.com/picture.jpg'); }); }); describe('image_sizes', function () { before(function () { configUtils.set({url: 'http://localhost:65535/'}); }); after(function () { configUtils.restore(); }); it('should output correct url for absolute paths which are internal', function () { const rendered = img_url('http://localhost:65535/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); it('should output the correct url for protocol relative urls', function () { const rendered = img_url('//website.com/whatever/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('//website.com/whatever/my-coole-img.jpg'); }); it('should output the correct url for relative paths', function () { const rendered = img_url('/content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('/content/images/size/w400/my-coole-img.jpg'); }); it('should output the correct url for relative paths without leading slash', function () { const rendered = img_url('content/images/my-coole-img.jpg', { hash: { size: 'medium' }, data: { config: { image_sizes: { medium: { width: 400 } } } } }); should.exist(rendered); rendered.should.equal('content/images/size/w400/my-coole-img.jpg'); }); }); });
ErisDS/Ghost
test/unit/frontend/helpers/img_url.test.js
JavaScript
mit
7,360
import { findPort, killApp, nextBuild, nextStart, renderViaHTTP, File, waitFor, } from 'next-test-utils' import webdriver from 'next-webdriver' import { join } from 'path' const appDir = join(__dirname, '../') let appPort let app let browser let html const indexPage = new File(join(appDir, 'pages/static-img.js')) const runTests = () => { it('Should allow an image with a static src to omit height and width', async () => { expect(await browser.elementById('basic-static')).toBeTruthy() expect(await browser.elementById('blur-png')).toBeTruthy() expect(await browser.elementById('blur-webp')).toBeTruthy() expect(await browser.elementById('blur-avif')).toBeTruthy() expect(await browser.elementById('blur-jpg')).toBeTruthy() expect(await browser.elementById('static-svg')).toBeTruthy() expect(await browser.elementById('static-gif')).toBeTruthy() expect(await browser.elementById('static-bmp')).toBeTruthy() expect(await browser.elementById('static-ico')).toBeTruthy() expect(await browser.elementById('static-unoptimized')).toBeTruthy() }) it('Should use immutable cache-control header for static import', async () => { await browser.eval( `document.getElementById("basic-static").scrollIntoView()` ) await waitFor(1000) const url = await browser.eval( `document.getElementById("basic-static").src` ) const res = await fetch(url) expect(res.headers.get('cache-control')).toBe( 'public, max-age=315360000, immutable' ) }) it('Should use immutable cache-control header even when unoptimized', async () => { await browser.eval( `document.getElementById("static-unoptimized").scrollIntoView()` ) await waitFor(1000) const url = await browser.eval( `document.getElementById("static-unoptimized").src` ) const res = await fetch(url) expect(res.headers.get('cache-control')).toBe( 'public, max-age=31536000, immutable' ) }) it('Should automatically provide an image height and width', async () => { expect(html).toContain('width:400px;height:300px') }) it('Should allow provided width and height to override intrinsic', async () => { expect(html).toContain('width:200px;height:200px') expect(html).not.toContain('width:400px;height:400px') }) it('Should add a blur placeholder to statically imported jpg', async () => { expect(html).toContain( `style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;filter:blur(20px);background-size:cover;background-image:url(&quot;data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoKCgoKCgsMDAsPEA4QDxYUExMUFiIYGhgaGCIzICUgICUgMy03LCksNy1RQDg4QFFeT0pPXnFlZXGPiI+7u/sBCgoKCgoKCwwMCw8QDhAPFhQTExQWIhgaGBoYIjMgJSAgJSAzLTcsKSw3LVFAODhAUV5PSk9ecWVlcY+Ij7u7+//CABEIAAYACAMBIgACEQEDEQH/xAAnAAEBAAAAAAAAAAAAAAAAAAAABwEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEAMQAAAAmgP/xAAcEAACAQUBAAAAAAAAAAAAAAASFBMAAQMFERX/2gAIAQEAAT8AZ1HjrKZX55JysIc4Ff/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQIBAT8Af//EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAIAQMBAT8Af//Z&quot;);background-position:0% 0%"` ) }) it('Should add a blur placeholder to statically imported png', async () => { expect(html).toContain( `style="position:absolute;top:0;left:0;bottom:0;right:0;box-sizing:border-box;padding:0;border:none;margin:auto;display:block;width:0;height:0;min-width:100%;max-width:100%;min-height:100%;max-height:100%;filter:blur(20px);background-size:cover;background-image:url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAAAAADhZOFXAAAAOklEQVR42iWGsQkAIBDE0iuIdiLOJjiGIzjiL/Meb4okiNYIlLjK3hJMzCQG1/0qmXXOUkjAV+m9wAMe3QiV6Ne8VgAAAABJRU5ErkJggg==&quot;);background-position:0% 0%"` ) }) } describe('Build Error Tests', () => { it('should throw build error when import statement is used with missing file', async () => { await indexPage.replace( '../public/foo/test-rect.jpg', '../public/foo/test-rect-broken.jpg' ) const { stderr } = await nextBuild(appDir, undefined, { stderr: true }) await indexPage.restore() expect(stderr).toContain( "Module not found: Can't resolve '../public/foo/test-rect-broken.jpg" ) // should contain the importing module expect(stderr).toContain('./pages/static-img.js') // should contain a import trace expect(stderr).not.toContain('Import trace for requested module') }) }) describe('Static Image Component Tests', () => { beforeAll(async () => { await nextBuild(appDir) appPort = await findPort() app = await nextStart(appDir, appPort) html = await renderViaHTTP(appPort, '/static-img') browser = await webdriver(appPort, '/static-img') }) afterAll(() => { killApp(app) }) runTests() })
zeit/next.js
test/integration/image-component/default/test/static.test.js
JavaScript
mit
4,891
const DrawCard = require('../../drawcard.js'); class AeronDamphair extends DrawCard { setupCardAbilities() { this.reaction({ when: { onCardSaved: event => event.card.getType() === 'character' }, handler: context => { let card = context.event.card; if(card.kneeled) { card.controller.standCard(card); this.game.addMessage('{0} uses {1} to stand {2}', this.controller, this, card); } else { card.controller.kneelCard(card); this.game.addMessage('{0} uses {1} to kneel {2}', this.controller, this, card); } } }); } } AeronDamphair.code = '04071'; module.exports = AeronDamphair;
cryogen/gameteki
server/game/cards/04.4-TIMC/AeronDamphair.js
JavaScript
mit
813
function foo() { throw <Bar />; } function foo() { throw <Bar>baz</Bar>; } function foo() { throw <Bar baz={baz} />; } function foo() { throw <Bar baz={baz}>foo</Bar>; } function foo() { throw <></>; } function foo() { throw <>foo</>; }
rattrayalex/prettier
tests/format/js/throw_statement/jsx.js
JavaScript
mit
254
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // This is a very simple test, and could be made more robust. // All we do is check for the presence of "http://" or "https://" // at the start of the string. var description = 'Relative src URLs can break (i.e. if recipients are outside the company network) and make your content unavailable to view.'; exports.default = function (props) { if (props.hasOwnProperty('src')) { if (!/^https?:\/\//.test(props['src'])) { return new Error(description); } } };
oysterbooks/oy
lib/rules/SrcAbsoluteURLRule.js
JavaScript
mit
555
var assert = require('assert'); var R = require('..'); describe('join', function() { it("concatenates a list's elements to a string, with an seperator string between elements", function() { var list = [1, 2, 3, 4]; assert.strictEqual(R.join('~', list), '1~2~3~4'); }); });
raine/ramda
test/join.js
JavaScript
mit
300
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var prefix = 'fas'; var iconName = 'intersection'; var width = 384; var height = 512; var ligatures = []; var unicode = 'f668'; var svgPathData = 'M166.74 33.62C69.96 46.04 0 133.11 0 230.68V464c0 8.84 7.16 16 16 16h64c8.84 0 16-7.16 16-16V224c0-59.2 53.85-106.04 115.13-94.14 45.58 8.85 76.87 51.5 76.87 97.93V464c0 8.84 7.16 16 16 16h64c8.84 0 16-7.16 16-16V224c0-114.18-100.17-205.4-217.26-190.38z'; exports.definition = { prefix: prefix, iconName: iconName, icon: [ width, height, ligatures, unicode, svgPathData ]}; exports.faIntersection = exports.definition; exports.prefix = prefix; exports.iconName = iconName; exports.width = width; exports.height = height; exports.ligatures = ligatures; exports.unicode = unicode; exports.svgPathData = svgPathData;
haraldnagel/greatreadingadventure
src/GRA.Web/wwwroot/lib/font-awesome/advanced-options/use-with-node-js/free-solid-svg-icons/faIntersection.js
JavaScript
mit
867
/* * Moonshine - a Lua virtual machine. * * Email: moonshine@gamesys.co.uk * http://moonshinejs.org * * Copyright (c) 2013-2015 Gamesys Limited. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @fileOverview File class. * @author <a href="mailto:paul.cuthbertson@gamesys.co.uk">Paul Cuthbertson</a> */ 'use strict'; var shine = shine || {}; /** * Represents a Luac data file. * @constructor * @extends shine.EventEmitter * @param {String} url Url of the distilled JSON file. */ shine.File = function (url, data) { this.url = url; this.data = data; }; /** * Dump memory associated with file. */ shine.File.prototype.dispose = function () { delete this.url; delete this.data; };
gamesys/moonshine
vm/src/File.js
JavaScript
mit
1,769
// ---------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // ---------------------------------------------------------------------------- var promises = require('../utilities/promises'), log = require('../logger'); module.exports = function (tables) { log.warn('The memory data provider is deprecated and will be removed from future versions. Use the sqlite provider instead.'); tables = tables || {}; return function (table) { return { read: function (query) { // need to evaluate query against each item before returning return promises.resolved(values(table)); }, update: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, insert: function (item) { items(table)[item.id] = item; return promises.resolved(item); }, delete: function (id, version) { delete items(table)[id]; return promises.resolved(id); }, undelete: function (id) { // unsupported return promises.resolved({ id: id }); }, truncate: function () { tables[table.name] = {}; return promises.resolved(); }, initialize: function () { return promises.resolved(); } } function items(table) { var name = table.name.toLowerCase(); if(!tables[name]) tables[name] = {}; return tables[name]; } function values(table) { var tableItems = items(table); return Object.keys(tableItems).map(function (id) { return tableItems[id]; }); } }; };
shrishrirang/azure-mobile-apps-node
src/data/memory.js
JavaScript
mit
1,959
/*globals EmberDev */ import Ember from "ember-metal/core"; import {get} from "ember-metal/property_get"; import {set} from "ember-metal/property_set"; import {forEach} from "ember-metal/array"; import run from "ember-metal/run_loop"; import Application from "ember-application/system/application"; import {DefaultResolver} from "ember-application/system/resolver"; import Router from "ember-routing/system/router"; import {View} from "ember-views/views/view"; import {Controller} from "ember-runtime/controllers/controller"; import NoneLocation from "ember-routing/location/none_location"; import EmberHandlebars from "ember-handlebars"; import EmberObject from "ember-runtime/system/object"; import {outletHelper} from "ember-routing/helpers/outlet"; import jQuery from "ember-views/system/jquery"; var trim = jQuery.trim; var view, app, application, originalLookup, originalDebug; module("Ember.Application", { setup: function() { originalLookup = Ember.lookup; originalDebug = Ember.debug; jQuery("#qunit-fixture").html("<div id='one'><div id='one-child'>HI</div></div><div id='two'>HI</div>"); run(function() { application = Application.create({ rootElement: '#one', router: null }); }); }, teardown: function() { jQuery("#qunit-fixture").empty(); Ember.debug = originalDebug; Ember.lookup = originalLookup; if (application) { run(application, 'destroy'); } if (app) { run(app, 'destroy'); } } }); test("you can make a new application in a non-overlapping element", function() { run(function() { app = Application.create({ rootElement: '#two', router: null }); }); run(app, 'destroy'); ok(true, "should not raise"); }); test("you cannot make a new application that is a parent of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#qunit-fixture' }); }); }); }); test("you cannot make a new application that is a descendent of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#one-child' }); }); }); }); test("you cannot make a new application that is a duplicate of an existing application", function() { expectAssertion(function() { run(function() { Application.create({ rootElement: '#one' }); }); }); }); test("you cannot make two default applications without a rootElement error", function() { expectAssertion(function() { run(function() { Application.create({ router: false }); }); }); }); test("acts like a namespace", function() { var lookup = Ember.lookup = {}, app; run(function() { app = lookup.TestApp = Application.create({ rootElement: '#two', router: false }); }); Ember.BOOTED = false; app.Foo = EmberObject.extend(); equal(app.Foo.toString(), "TestApp.Foo", "Classes pick up their parent namespace"); }); module("Ember.Application initialization", { teardown: function() { if (app) { run(app, 'destroy'); } Ember.TEMPLATES = {}; } }); test('initialized application go to initial route', function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.register('template:application', EmberHandlebars.compile("{{outlet}}") ); Ember.TEMPLATES.index = EmberHandlebars.compile( "<h1>Hi from index</h1>" ); }); equal(jQuery('#qunit-fixture h1').text(), "Hi from index"); }); test("initialize application via initialize call", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.ApplicationView = View.extend({ template: function() { return "<h1>Hello!</h1>"; } }); }); // This is not a public way to access the container; we just // need to make some assertions about the created router var router = app.__container__.lookup('router:main'); equal(router instanceof Router, true, "Router was set from initialize call"); equal(router.location instanceof NoneLocation, true, "Location was set from location implementation name"); }); test("initialize application with stateManager via initialize call from Router class", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); app.register('template:application', function() { return "<h1>Hello!</h1>"; }); }); var router = app.__container__.lookup('router:main'); equal(router instanceof Router, true, "Router was set from initialize call"); equal(jQuery("#qunit-fixture h1").text(), "Hello!"); }); test("ApplicationView is inserted into the page", function() { run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.ApplicationView = View.extend({ render: function(buffer) { buffer.push("<h1>Hello!</h1>"); } }); app.ApplicationController = Controller.extend(); app.Router.reopen({ location: 'none' }); }); equal(jQuery("#qunit-fixture h1").text(), "Hello!"); }); test("Minimal Application initialized with just an application template", function() { jQuery('#qunit-fixture').html('<script type="text/x-handlebars">Hello World</script>'); run(function () { app = Application.create({ rootElement: '#qunit-fixture' }); }); equal(trim(jQuery('#qunit-fixture').text()), 'Hello World'); }); test('enable log of libraries with an ENV var', function() { if (EmberDev && EmberDev.runningProdBuild){ ok(true, 'Logging does not occur in production builds'); return; } var debug = Ember.debug; var messages = []; Ember.LOG_VERSION = true; Ember.debug = function(message) { messages.push(message); }; Ember.libraries.register("my-lib", "2.0.0a"); run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); }); equal(messages[1], "Ember : " + Ember.VERSION); equal(messages[2], "Handlebars : " + EmberHandlebars.VERSION); equal(messages[3], "jQuery : " + jQuery().jquery); equal(messages[4], "my-lib : " + "2.0.0a"); Ember.libraries.deRegister("my-lib"); Ember.LOG_VERSION = false; Ember.debug = debug; }); test('disable log version of libraries with an ENV var', function() { var logged = false; Ember.LOG_VERSION = false; Ember.debug = function(message) { logged = true; }; jQuery("#qunit-fixture").empty(); run(function() { app = Application.create({ rootElement: '#qunit-fixture' }); app.Router.reopen({ location: 'none' }); }); ok(!logged, 'library version logging skipped'); }); test("can resolve custom router", function(){ var CustomRouter = Router.extend(); var CustomResolver = DefaultResolver.extend({ resolveOther: function(parsedName){ if (parsedName.type === "router") { return CustomRouter; } else { return this._super(parsedName); } } }); app = run(function(){ return Application.create({ Resolver: CustomResolver }); }); ok(app.__container__.lookup('router:main') instanceof CustomRouter, 'application resolved the correct router'); });
g13013/ember.js
packages_es6/ember-application/tests/system/application_test.js
JavaScript
mit
7,427
parent.jQuery(window).load(function() { parent.jQuery('div.container select', document).change(function () { change(); }); parent.jQuery('div.container input', document).keyup(function () { change(); }); }); function change() { fsi=parseInt(parent.jQuery('#fontsize', document).val(),10); lh=parseInt(parent.jQuery('#lineheight', document).val(),10); if (lh==0) lh=Math.round(font_size[fsi][2] * 1.2); parent.jQuery('div.preview_text', document).html('<p style="font-size:' + font_size[fsi][2] + 'px; line-height:' + lh + 'px; font-family:' + parent.jQuery('#fontfamily', document).val() + '">' + demo_text + '</p>'); parent.jQuery('div.preview_text_no_css', document).html('<font size="' + font_size[fsi][1] + '" face="' + parent.jQuery('#fontfamily', document).val() + '">' + demo_text + '</font>'); } function select_font() { ff = parent.jQuery('#fontfamily', document).val(); fsi=parseInt(parent.jQuery('#fontsize', document).val(),10); fs=font_size[fsi][1]; ss=font_size[fsi][2]; lh=parseInt(parent.jQuery('#lineheight', document).val(),10); parent.CallBackFont(ff, fs, ss, lh); }
joasssko/tironib
wp-content/plugins/knews/wysiwyg/fontpicker/scripts.js
JavaScript
gpl-2.0
1,150
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const Cogl = imports.gi.Cogl; const GLib = imports.gi.GLib; const Gio = imports.gi.Gio; const Gtk = imports.gi.Gtk; const Meta = imports.gi.Meta; const Pango = imports.gi.Pango; const St = imports.gi.St; const Shell = imports.gi.Shell; const Signals = imports.signals; const Lang = imports.lang; const Mainloop = imports.mainloop; const System = imports.system; const History = imports.misc.history; const ExtensionSystem = imports.ui.extensionSystem; const ExtensionUtils = imports.misc.extensionUtils; const ShellEntry = imports.ui.shellEntry; const Tweener = imports.ui.tweener; const Main = imports.ui.main; const JsParse = imports.misc.jsParse; const CHEVRON = '>>> '; /* Imports...feel free to add here as needed */ var commandHeader = 'const Clutter = imports.gi.Clutter; ' + 'const GLib = imports.gi.GLib; ' + 'const GObject = imports.gi.GObject; ' + 'const Gio = imports.gi.Gio; ' + 'const Gtk = imports.gi.Gtk; ' + 'const Mainloop = imports.mainloop; ' + 'const Meta = imports.gi.Meta; ' + 'const Shell = imports.gi.Shell; ' + 'const Tp = imports.gi.TelepathyGLib; ' + 'const Main = imports.ui.main; ' + 'const Lang = imports.lang; ' + 'const Tweener = imports.ui.tweener; ' + /* Utility functions...we should probably be able to use these * in the shell core code too. */ 'const stage = global.stage; ' + /* Special lookingGlass functions */ 'const inspect = Lang.bind(Main.lookingGlass, Main.lookingGlass.inspect); ' + 'const it = Main.lookingGlass.getIt(); ' + 'const r = Lang.bind(Main.lookingGlass, Main.lookingGlass.getResult); '; const HISTORY_KEY = 'looking-glass-history'; // Time between tabs for them to count as a double-tab event const AUTO_COMPLETE_DOUBLE_TAB_DELAY = 500; const AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION = 0.2; const AUTO_COMPLETE_GLOBAL_KEYWORDS = _getAutoCompleteGlobalKeywords(); function _getAutoCompleteGlobalKeywords() { const keywords = ['true', 'false', 'null', 'new']; // Don't add the private properties of window (i.e., ones starting with '_') const windowProperties = Object.getOwnPropertyNames(window).filter(function(a){ return a.charAt(0) != '_' }); const headerProperties = JsParse.getDeclaredConstants(commandHeader); return keywords.concat(windowProperties).concat(headerProperties); } const AutoComplete = new Lang.Class({ Name: 'AutoComplete', _init: function(entry) { this._entry = entry; this._entry.connect('key-press-event', Lang.bind(this, this._entryKeyPressEvent)); this._lastTabTime = global.get_current_time(); }, _processCompletionRequest: function(event) { if (event.completions.length == 0) { return; } // Unique match = go ahead and complete; multiple matches + single tab = complete the common starting string; // multiple matches + double tab = emit a suggest event with all possible options if (event.completions.length == 1) { this.additionalCompletionText(event.completions[0], event.attrHead); this.emit('completion', { completion: event.completions[0], type: 'whole-word' }); } else if (event.completions.length > 1 && event.tabType === 'single') { let commonPrefix = JsParse.getCommonPrefix(event.completions); if (commonPrefix.length > 0) { this.additionalCompletionText(commonPrefix, event.attrHead); this.emit('completion', { completion: commonPrefix, type: 'prefix' }); this.emit('suggest', { completions: event.completions}); } } else if (event.completions.length > 1 && event.tabType === 'double') { this.emit('suggest', { completions: event.completions}); } }, _entryKeyPressEvent: function(actor, event) { let cursorPos = this._entry.clutter_text.get_cursor_position(); let text = this._entry.get_text(); if (cursorPos != -1) { text = text.slice(0, cursorPos); } if (event.get_key_symbol() == Clutter.Tab) { let [completions, attrHead] = JsParse.getCompletions(text, commandHeader, AUTO_COMPLETE_GLOBAL_KEYWORDS); let currTime = global.get_current_time(); if ((currTime - this._lastTabTime) < AUTO_COMPLETE_DOUBLE_TAB_DELAY) { this._processCompletionRequest({ tabType: 'double', completions: completions, attrHead: attrHead }); } else { this._processCompletionRequest({ tabType: 'single', completions: completions, attrHead: attrHead }); } this._lastTabTime = currTime; } return Clutter.EVENT_PROPAGATE; }, // Insert characters of text not already included in head at cursor position. i.e., if text="abc" and head="a", // the string "bc" will be appended to this._entry additionalCompletionText: function(text, head) { let additionalCompletionText = text.slice(head.length); let cursorPos = this._entry.clutter_text.get_cursor_position(); this._entry.clutter_text.insert_text(additionalCompletionText, cursorPos); } }); Signals.addSignalMethods(AutoComplete.prototype); const Notebook = new Lang.Class({ Name: 'Notebook', _init: function() { this.actor = new St.BoxLayout({ vertical: true }); this.tabControls = new St.BoxLayout({ style_class: 'labels' }); this._selectedIndex = -1; this._tabs = []; }, appendPage: function(name, child) { let labelBox = new St.BoxLayout({ style_class: 'notebook-tab', reactive: true, track_hover: true }); let label = new St.Button({ label: name }); label.connect('clicked', Lang.bind(this, function () { this.selectChild(child); return true; })); labelBox.add(label, { expand: true }); this.tabControls.add(labelBox); let scrollview = new St.ScrollView({ x_fill: true, y_fill: true }); scrollview.get_hscroll_bar().hide(); scrollview.add_actor(child); let tabData = { child: child, labelBox: labelBox, label: label, scrollView: scrollview, _scrollToBottom: false }; this._tabs.push(tabData); scrollview.hide(); this.actor.add(scrollview, { expand: true }); let vAdjust = scrollview.vscroll.adjustment; vAdjust.connect('changed', Lang.bind(this, function () { this._onAdjustScopeChanged(tabData); })); vAdjust.connect('notify::value', Lang.bind(this, function() { this._onAdjustValueChanged(tabData); })); if (this._selectedIndex == -1) this.selectIndex(0); }, _unselect: function() { if (this._selectedIndex < 0) return; let tabData = this._tabs[this._selectedIndex]; tabData.labelBox.remove_style_pseudo_class('selected'); tabData.scrollView.hide(); this._selectedIndex = -1; }, selectIndex: function(index) { if (index == this._selectedIndex) return; if (index < 0) { this._unselect(); this.emit('selection', null); return; } // Focus the new tab before unmapping the old one let tabData = this._tabs[index]; if (!tabData.scrollView.navigate_focus(null, Gtk.DirectionType.TAB_FORWARD, false)) this.actor.grab_key_focus(); this._unselect(); tabData.labelBox.add_style_pseudo_class('selected'); tabData.scrollView.show(); this._selectedIndex = index; this.emit('selection', tabData.child); }, selectChild: function(child) { if (child == null) this.selectIndex(-1); else { for (let i = 0; i < this._tabs.length; i++) { let tabData = this._tabs[i]; if (tabData.child == child) { this.selectIndex(i); return; } } } }, scrollToBottom: function(index) { let tabData = this._tabs[index]; tabData._scrollToBottom = true; }, _onAdjustValueChanged: function (tabData) { let vAdjust = tabData.scrollView.vscroll.adjustment; if (vAdjust.value < (vAdjust.upper - vAdjust.lower - 0.5)) tabData._scrolltoBottom = false; }, _onAdjustScopeChanged: function (tabData) { if (!tabData._scrollToBottom) return; let vAdjust = tabData.scrollView.vscroll.adjustment; vAdjust.value = vAdjust.upper - vAdjust.page_size; }, nextTab: function() { let nextIndex = this._selectedIndex; if (nextIndex < this._tabs.length - 1) { ++nextIndex; } this.selectIndex(nextIndex); }, prevTab: function() { let prevIndex = this._selectedIndex; if (prevIndex > 0) { --prevIndex; } this.selectIndex(prevIndex); } }); Signals.addSignalMethods(Notebook.prototype); function objectToString(o) { if (typeof(o) == typeof(objectToString)) { // special case this since the default is way, way too verbose return '<js function>'; } else { return '' + o; } } const ObjLink = new Lang.Class({ Name: 'ObjLink', _init: function(lookingGlass, o, title) { let text; if (title) text = title; else text = objectToString(o); text = GLib.markup_escape_text(text, -1); this._obj = o; this.actor = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: text }); this.actor.get_child().single_line_mode = true; this.actor.connect('clicked', Lang.bind(this, this._onClicked)); this._lookingGlass = lookingGlass; }, _onClicked: function (link) { this._lookingGlass.inspectObject(this._obj, this.actor); } }); const Result = new Lang.Class({ Name: 'Result', _init: function(lookingGlass, command, o, index) { this.index = index; this.o = o; this.actor = new St.BoxLayout({ vertical: true }); this._lookingGlass = lookingGlass; let cmdTxt = new St.Label({ text: command }); cmdTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END; this.actor.add(cmdTxt); let box = new St.BoxLayout({}); this.actor.add(box); let resultTxt = new St.Label({ text: 'r(' + index + ') = ' }); resultTxt.clutter_text.ellipsize = Pango.EllipsizeMode.END; box.add(resultTxt); let objLink = new ObjLink(this._lookingGlass, o); box.add(objLink.actor); } }); const WindowList = new Lang.Class({ Name: 'WindowList', _init: function(lookingGlass) { this.actor = new St.BoxLayout({ name: 'Windows', vertical: true, style: 'spacing: 8px' }); let tracker = Shell.WindowTracker.get_default(); this._updateId = Main.initializeDeferredWork(this.actor, Lang.bind(this, this._updateWindowList)); global.display.connect('window-created', Lang.bind(this, this._updateWindowList)); tracker.connect('tracked-windows-changed', Lang.bind(this, this._updateWindowList)); this._lookingGlass = lookingGlass; }, _updateWindowList: function() { this.actor.destroy_all_children(); let windows = global.get_window_actors(); let tracker = Shell.WindowTracker.get_default(); for (let i = 0; i < windows.length; i++) { let metaWindow = windows[i].metaWindow; // Avoid multiple connections if (!metaWindow._lookingGlassManaged) { metaWindow.connect('unmanaged', Lang.bind(this, this._updateWindowList)); metaWindow._lookingGlassManaged = true; } let box = new St.BoxLayout({ vertical: true }); this.actor.add(box); let windowLink = new ObjLink(this._lookingGlass, metaWindow, metaWindow.title); box.add(windowLink.actor, { x_align: St.Align.START, x_fill: false }); let propsBox = new St.BoxLayout({ vertical: true, style: 'padding-left: 6px;' }); box.add(propsBox); propsBox.add(new St.Label({ text: 'wmclass: ' + metaWindow.get_wm_class() })); let app = tracker.get_window_app(metaWindow); if (app != null && !app.is_window_backed()) { let icon = app.create_icon_texture(22); let propBox = new St.BoxLayout({ style: 'spacing: 6px; ' }); propsBox.add(propBox); propBox.add(new St.Label({ text: 'app: ' }), { y_fill: false }); let appLink = new ObjLink(this._lookingGlass, app, app.get_id()); propBox.add(appLink.actor, { y_fill: false }); propBox.add(icon, { y_fill: false }); } else { propsBox.add(new St.Label({ text: '<untracked>' })); } } } }); Signals.addSignalMethods(WindowList.prototype); const ObjInspector = new Lang.Class({ Name: 'ObjInspector', _init: function(lookingGlass) { this._obj = null; this._previousObj = null; this._parentList = []; this.actor = new St.ScrollView({ pivot_point: new Clutter.Point({ x: 0.5, y: 0.5 }), x_fill: true, y_fill: true }); this.actor.get_hscroll_bar().hide(); this._container = new St.BoxLayout({ name: 'LookingGlassPropertyInspector', style_class: 'lg-dialog', vertical: true }); this.actor.add_actor(this._container); this._lookingGlass = lookingGlass; }, selectObject: function(obj, skipPrevious) { if (!skipPrevious) this._previousObj = this._obj; else this._previousObj = null; this._obj = obj; this._container.destroy_all_children(); let hbox = new St.BoxLayout({ style_class: 'lg-obj-inspector-title' }); this._container.add_actor(hbox); let label = new St.Label({ text: 'Inspecting: %s: %s'.format(typeof(obj), objectToString(obj)) }); label.single_line_mode = true; hbox.add(label, { expand: true, y_fill: false }); let button = new St.Button({ label: 'Insert', style_class: 'lg-obj-inspector-button' }); button.connect('clicked', Lang.bind(this, this._onInsert)); hbox.add(button); if (this._previousObj != null) { button = new St.Button({ label: 'Back', style_class: 'lg-obj-inspector-button' }); button.connect('clicked', Lang.bind(this, this._onBack)); hbox.add(button); } button = new St.Button({ style_class: 'window-close' }); button.connect('clicked', Lang.bind(this, this.close)); hbox.add(button); if (typeof(obj) == typeof({})) { let properties = []; for (let propName in obj) { properties.push(propName); } properties.sort(); for (let i = 0; i < properties.length; i++) { let propName = properties[i]; let valueStr; let link; try { let prop = obj[propName]; link = new ObjLink(this._lookingGlass, prop).actor; } catch (e) { link = new St.Label({ text: '<error>' }); } let hbox = new St.BoxLayout(); let propText = propName + ': ' + valueStr; hbox.add(new St.Label({ text: propName + ': ' })); hbox.add(link); this._container.add_actor(hbox); } } }, open: function(sourceActor) { if (this._open) return; this._previousObj = null; this._open = true; this.actor.show(); if (sourceActor) { this.actor.set_scale(0, 0); Tweener.addTween(this.actor, { scale_x: 1, scale_y: 1, transition: 'easeOutQuad', time: 0.2 }); } else { this.actor.set_scale(1, 1); } }, close: function() { if (!this._open) return; this._open = false; this.actor.hide(); this._previousObj = null; this._obj = null; }, _onInsert: function() { let obj = this._obj; this.close(); this._lookingGlass.insertObject(obj); }, _onBack: function() { this.selectObject(this._previousObj, true); } }); const RedBorderEffect = new Lang.Class({ Name: 'RedBorderEffect', Extends: Clutter.Effect, vfunc_paint: function() { let actor = this.get_actor(); actor.continue_paint(); let color = new Cogl.Color(); color.init_from_4ub(0xff, 0, 0, 0xc4); Cogl.set_source_color(color); let geom = actor.get_allocation_geometry(); let width = 2; // clockwise order Cogl.rectangle(0, 0, geom.width, width); Cogl.rectangle(geom.width - width, width, geom.width, geom.height); Cogl.rectangle(0, geom.height, geom.width - width, geom.height - width); Cogl.rectangle(0, geom.height - width, width, width); }, }); const Inspector = new Lang.Class({ Name: 'Inspector', _init: function(lookingGlass) { let container = new Shell.GenericContainer({ width: 0, height: 0 }); container.connect('allocate', Lang.bind(this, this._allocate)); Main.uiGroup.add_actor(container); let eventHandler = new St.BoxLayout({ name: 'LookingGlassDialog', vertical: false, reactive: true }); this._eventHandler = eventHandler; container.add_actor(eventHandler); this._displayText = new St.Label(); eventHandler.add(this._displayText, { expand: true }); eventHandler.connect('key-press-event', Lang.bind(this, this._onKeyPressEvent)); eventHandler.connect('button-press-event', Lang.bind(this, this._onButtonPressEvent)); eventHandler.connect('scroll-event', Lang.bind(this, this._onScrollEvent)); eventHandler.connect('motion-event', Lang.bind(this, this._onMotionEvent)); Clutter.grab_pointer(eventHandler); Clutter.grab_keyboard(eventHandler); // this._target is the actor currently shown by the inspector. // this._pointerTarget is the actor directly under the pointer. // Normally these are the same, but if you use the scroll wheel // to drill down, they'll diverge until you either scroll back // out, or move the pointer outside of _pointerTarget. this._target = null; this._pointerTarget = null; this._lookingGlass = lookingGlass; }, _allocate: function(actor, box, flags) { if (!this._eventHandler) return; let primary = Main.layoutManager.primaryMonitor; let [minWidth, minHeight, natWidth, natHeight] = this._eventHandler.get_preferred_size(); let childBox = new Clutter.ActorBox(); childBox.x1 = primary.x + Math.floor((primary.width - natWidth) / 2); childBox.x2 = childBox.x1 + natWidth; childBox.y1 = primary.y + Math.floor((primary.height - natHeight) / 2); childBox.y2 = childBox.y1 + natHeight; this._eventHandler.allocate(childBox, flags); }, _close: function() { Clutter.ungrab_pointer(); Clutter.ungrab_keyboard(); this._eventHandler.destroy(); this._eventHandler = null; this.emit('closed'); }, _onKeyPressEvent: function (actor, event) { if (event.get_key_symbol() == Clutter.Escape) this._close(); return Clutter.EVENT_STOP; }, _onButtonPressEvent: function (actor, event) { if (this._target) { let [stageX, stageY] = event.get_coords(); this.emit('target', this._target, stageX, stageY); } this._close(); return Clutter.EVENT_STOP; }, _onScrollEvent: function (actor, event) { switch (event.get_scroll_direction()) { case Clutter.ScrollDirection.UP: // select parent let parent = this._target.get_parent(); if (parent != null) { this._target = parent; this._update(event); } break; case Clutter.ScrollDirection.DOWN: // select child if (this._target != this._pointerTarget) { let child = this._pointerTarget; while (child) { let parent = child.get_parent(); if (parent == this._target) break; child = parent; } if (child) { this._target = child; this._update(event); } } break; default: break; } return Clutter.EVENT_STOP; }, _onMotionEvent: function (actor, event) { this._update(event); return Clutter.EVENT_STOP; }, _update: function(event) { let [stageX, stageY] = event.get_coords(); let target = global.stage.get_actor_at_pos(Clutter.PickMode.ALL, stageX, stageY); if (target != this._pointerTarget) this._target = target; this._pointerTarget = target; let position = '[inspect x: ' + stageX + ' y: ' + stageY + ']'; this._displayText.text = ''; this._displayText.text = position + ' ' + this._target; this._lookingGlass.setBorderPaintTarget(this._target); } }); Signals.addSignalMethods(Inspector.prototype); const Extensions = new Lang.Class({ Name: 'Extensions', _init: function(lookingGlass) { this._lookingGlass = lookingGlass; this.actor = new St.BoxLayout({ vertical: true, name: 'lookingGlassExtensions' }); this._noExtensions = new St.Label({ style_class: 'lg-extensions-none', text: _("No extensions installed") }); this._numExtensions = 0; this._extensionsList = new St.BoxLayout({ vertical: true, style_class: 'lg-extensions-list' }); this._extensionsList.add(this._noExtensions); this.actor.add(this._extensionsList); for (let uuid in ExtensionUtils.extensions) this._loadExtension(null, uuid); ExtensionSystem.connect('extension-loaded', Lang.bind(this, this._loadExtension)); }, _loadExtension: function(o, uuid) { let extension = ExtensionUtils.extensions[uuid]; // There can be cases where we create dummy extension metadata // that's not really a proper extension. Don't bother with these. if (!extension.metadata.name) return; let extensionDisplay = this._createExtensionDisplay(extension); if (this._numExtensions == 0) this._extensionsList.remove_actor(this._noExtensions); this._numExtensions ++; this._extensionsList.add(extensionDisplay); }, _onViewSource: function (actor) { let extension = actor._extension; let uri = extension.dir.get_uri(); Gio.app_info_launch_default_for_uri(uri, global.create_app_launch_context(0, -1)); this._lookingGlass.close(); }, _onWebPage: function (actor) { let extension = actor._extension; Gio.app_info_launch_default_for_uri(extension.metadata.url, global.create_app_launch_context(0, -1)); this._lookingGlass.close(); }, _onViewErrors: function (actor) { let extension = actor._extension; let shouldShow = !actor._isShowing; if (shouldShow) { let errors = extension.errors; let errorDisplay = new St.BoxLayout({ vertical: true }); if (errors && errors.length) { for (let i = 0; i < errors.length; i ++) errorDisplay.add(new St.Label({ text: errors[i] })); } else { /* Translators: argument is an extension UUID. */ let message = _("%s has not emitted any errors.").format(extension.uuid); errorDisplay.add(new St.Label({ text: message })); } actor._errorDisplay = errorDisplay; actor._parentBox.add(errorDisplay); actor.label = _("Hide Errors"); } else { actor._errorDisplay.destroy(); actor._errorDisplay = null; actor.label = _("Show Errors"); } actor._isShowing = shouldShow; }, _stateToString: function(extensionState) { switch (extensionState) { case ExtensionSystem.ExtensionState.ENABLED: return _("Enabled"); case ExtensionSystem.ExtensionState.DISABLED: case ExtensionSystem.ExtensionState.INITIALIZED: return _("Disabled"); case ExtensionSystem.ExtensionState.ERROR: return _("Error"); case ExtensionSystem.ExtensionState.OUT_OF_DATE: return _("Out of date"); case ExtensionSystem.ExtensionState.DOWNLOADING: return _("Downloading"); } return 'Unknown'; // Not translated, shouldn't appear }, _createExtensionDisplay: function(extension) { let box = new St.BoxLayout({ style_class: 'lg-extension', vertical: true }); let name = new St.Label({ style_class: 'lg-extension-name', text: extension.metadata.name }); box.add(name, { expand: true }); let description = new St.Label({ style_class: 'lg-extension-description', text: extension.metadata.description || 'No description' }); box.add(description, { expand: true }); let metaBox = new St.BoxLayout({ style_class: 'lg-extension-meta' }); box.add(metaBox); let stateString = this._stateToString(extension.state); let state = new St.Label({ style_class: 'lg-extension-state', text: this._stateToString(extension.state) }); metaBox.add(state); let viewsource = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("View Source") }); viewsource._extension = extension; viewsource.connect('clicked', Lang.bind(this, this._onViewSource)); metaBox.add(viewsource); if (extension.metadata.url) { let webpage = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("Web Page") }); webpage._extension = extension; webpage.connect('clicked', Lang.bind(this, this._onWebPage)); metaBox.add(webpage); } let viewerrors = new St.Button({ reactive: true, track_hover: true, style_class: 'shell-link', label: _("Show Errors") }); viewerrors._extension = extension; viewerrors._parentBox = box; viewerrors._isShowing = false; viewerrors.connect('clicked', Lang.bind(this, this._onViewErrors)); metaBox.add(viewerrors); return box; } }); const LookingGlass = new Lang.Class({ Name: 'LookingGlass', _init : function() { this._borderPaintTarget = null; this._redBorderEffect = new RedBorderEffect(); this._open = false; this._offset = 0; this._results = []; // Sort of magic, but...eh. this._maxItems = 150; this.actor = new St.BoxLayout({ name: 'LookingGlassDialog', style_class: 'lg-dialog', vertical: true, visible: false, reactive: true }); this.actor.connect('key-press-event', Lang.bind(this, this._globalKeyPressEvent)); this._interfaceSettings = new Gio.Settings({ schema_id: 'org.gnome.desktop.interface' }); this._interfaceSettings.connect('changed::monospace-font-name', Lang.bind(this, this._updateFont)); this._updateFont(); // We want it to appear to slide out from underneath the panel Main.uiGroup.add_actor(this.actor); Main.uiGroup.set_child_below_sibling(this.actor, Main.layoutManager.panelBox); Main.layoutManager.panelBox.connect('allocation-changed', Lang.bind(this, this._queueResize)); Main.layoutManager.keyboardBox.connect('allocation-changed', Lang.bind(this, this._queueResize)); this._objInspector = new ObjInspector(this); Main.uiGroup.add_actor(this._objInspector.actor); this._objInspector.actor.hide(); let toolbar = new St.BoxLayout({ name: 'Toolbar' }); this.actor.add_actor(toolbar); let inspectIcon = new St.Icon({ icon_name: 'gtk-color-picker', icon_size: 24 }); toolbar.add_actor(inspectIcon); inspectIcon.reactive = true; inspectIcon.connect('button-press-event', Lang.bind(this, function () { let inspector = new Inspector(this); inspector.connect('target', Lang.bind(this, function(i, target, stageX, stageY) { this._pushResult('inspect(' + Math.round(stageX) + ', ' + Math.round(stageY) + ')', target); })); inspector.connect('closed', Lang.bind(this, function() { this.actor.show(); global.stage.set_key_focus(this._entry); })); this.actor.hide(); return Clutter.EVENT_STOP; })); let gcIcon = new St.Icon({ icon_name: 'gnome-fs-trash-full', icon_size: 24 }); toolbar.add_actor(gcIcon); gcIcon.reactive = true; gcIcon.connect('button-press-event', Lang.bind(this, function () { gcIcon.icon_name = 'gnome-fs-trash-empty'; System.gc(); this._timeoutId = Mainloop.timeout_add(500, Lang.bind(this, function () { gcIcon.icon_name = 'gnome-fs-trash-full'; this._timeoutId = 0; return GLib.SOURCE_REMOVE; })); GLib.Source.set_name_by_id(this._timeoutId, '[gnome-shell] gcIcon.icon_name = \'gnome-fs-trash-full\''); return Clutter.EVENT_PROPAGATE; })); let notebook = new Notebook(); this._notebook = notebook; this.actor.add(notebook.actor, { expand: true }); let emptyBox = new St.Bin(); toolbar.add(emptyBox, { expand: true }); toolbar.add_actor(notebook.tabControls); this._evalBox = new St.BoxLayout({ name: 'EvalBox', vertical: true }); notebook.appendPage('Evaluator', this._evalBox); this._resultsArea = new St.BoxLayout({ name: 'ResultsArea', vertical: true }); this._evalBox.add(this._resultsArea, { expand: true }); this._entryArea = new St.BoxLayout({ name: 'EntryArea' }); this._evalBox.add_actor(this._entryArea); let label = new St.Label({ text: CHEVRON }); this._entryArea.add(label); this._entry = new St.Entry({ can_focus: true }); ShellEntry.addContextMenu(this._entry); this._entryArea.add(this._entry, { expand: true }); this._windowList = new WindowList(this); notebook.appendPage('Windows', this._windowList.actor); this._extensions = new Extensions(this); notebook.appendPage('Extensions', this._extensions.actor); this._entry.clutter_text.connect('activate', Lang.bind(this, function (o, e) { // Hide any completions we are currently showing this._hideCompletions(); let text = o.get_text(); // Ensure we don't get newlines in the command; the history file is // newline-separated. text = text.replace('\n', ' '); // Strip leading and trailing whitespace text = text.replace(/^\s+/g, '').replace(/\s+$/g, ''); if (text == '') return true; this._evaluate(text); return true; })); this._history = new History.HistoryManager({ gsettingsKey: HISTORY_KEY, entry: this._entry.clutter_text }); this._autoComplete = new AutoComplete(this._entry); this._autoComplete.connect('suggest', Lang.bind(this, function(a,e) { this._showCompletions(e.completions); })); // If a completion is completed unambiguously, the currently-displayed completion // suggestions become irrelevant. this._autoComplete.connect('completion', Lang.bind(this, function(a,e) { if (e.type == 'whole-word') this._hideCompletions(); })); this._resize(); }, _updateFont: function() { let fontName = this._interfaceSettings.get_string('monospace-font-name'); let fontDesc = Pango.FontDescription.from_string(fontName); // We ignore everything but size and style; you'd be crazy to set your system-wide // monospace font to be bold/oblique/etc. Could easily be added here. this.actor.style = 'font-size: ' + fontDesc.get_size() / 1024. + (fontDesc.get_size_is_absolute() ? 'px' : 'pt') + ';' + 'font-family: "' + fontDesc.get_family() + '";'; }, setBorderPaintTarget: function(obj) { if (this._borderPaintTarget != null) this._borderPaintTarget.remove_effect(this._redBorderEffect); this._borderPaintTarget = obj; if (this._borderPaintTarget != null) this._borderPaintTarget.add_effect(this._redBorderEffect); }, _pushResult: function(command, obj) { let index = this._results.length + this._offset; let result = new Result(this, CHEVRON + command, obj, index); this._results.push(result); this._resultsArea.add(result.actor); if (obj instanceof Clutter.Actor) this.setBorderPaintTarget(obj); let children = this._resultsArea.get_children(); if (children.length > this._maxItems) { this._results.shift(); children[0].destroy(); this._offset++; } this._it = obj; // Scroll to bottom this._notebook.scrollToBottom(0); }, _showCompletions: function(completions) { if (!this._completionActor) { this._completionActor = new St.Label({ name: 'LookingGlassAutoCompletionText', style_class: 'lg-completions-text' }); this._completionActor.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; this._completionActor.clutter_text.line_wrap = true; this._evalBox.insert_child_below(this._completionActor, this._entryArea); } this._completionActor.set_text(completions.join(', ')); // Setting the height to -1 allows us to get its actual preferred height rather than // whatever was last given in set_height by Tweener. this._completionActor.set_height(-1); let [minHeight, naturalHeight] = this._completionActor.get_preferred_height(this._resultsArea.get_width()); // Don't reanimate if we are already visible if (this._completionActor.visible) { this._completionActor.height = naturalHeight; } else { this._completionActor.show(); Tweener.removeTweens(this._completionActor); Tweener.addTween(this._completionActor, { time: AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / St.get_slow_down_factor(), transition: 'easeOutQuad', height: naturalHeight, opacity: 255 }); } }, _hideCompletions: function() { if (this._completionActor) { Tweener.removeTweens(this._completionActor); Tweener.addTween(this._completionActor, { time: AUTO_COMPLETE_SHOW_COMPLETION_ANIMATION_DURATION / St.get_slow_down_factor(), transition: 'easeOutQuad', height: 0, opacity: 0, onComplete: Lang.bind(this, function () { this._completionActor.hide(); }) }); } }, _evaluate : function(command) { this._history.addItem(command); let fullCmd = commandHeader + command; let resultObj; try { resultObj = eval(fullCmd); } catch (e) { resultObj = '<exception ' + e + '>'; } this._pushResult(command, resultObj); this._entry.text = ''; }, inspect: function(x, y) { return global.stage.get_actor_at_pos(Clutter.PickMode.REACTIVE, x, y); }, getIt: function () { return this._it; }, getResult: function(idx) { return this._results[idx - this._offset].o; }, toggle: function() { if (this._open) this.close(); else this.open(); }, _queueResize: function() { Meta.later_add(Meta.LaterType.BEFORE_REDRAW, Lang.bind(this, function () { this._resize(); })); }, _resize: function() { let primary = Main.layoutManager.primaryMonitor; let myWidth = primary.width * 0.7; let availableHeight = primary.height - Main.layoutManager.keyboardBox.height; let myHeight = Math.min(primary.height * 0.7, availableHeight * 0.9); this.actor.x = primary.x + (primary.width - myWidth) / 2; this._hiddenY = primary.y + Main.layoutManager.panelBox.height - myHeight - 4; // -4 to hide the top corners this._targetY = this._hiddenY + myHeight; this.actor.y = this._hiddenY; this.actor.width = myWidth; this.actor.height = myHeight; this._objInspector.actor.set_size(Math.floor(myWidth * 0.8), Math.floor(myHeight * 0.8)); this._objInspector.actor.set_position(this.actor.x + Math.floor(myWidth * 0.1), this._targetY + Math.floor(myHeight * 0.1)); }, insertObject: function(obj) { this._pushResult('<insert>', obj); }, inspectObject: function(obj, sourceActor) { this._objInspector.open(sourceActor); this._objInspector.selectObject(obj); }, // Handle key events which are relevant for all tabs of the LookingGlass _globalKeyPressEvent : function(actor, event) { let symbol = event.get_key_symbol(); let modifierState = event.get_state(); if (symbol == Clutter.Escape) { if (this._objInspector.actor.visible) { this._objInspector.close(); } else { this.close(); } return Clutter.EVENT_STOP; } // Ctrl+PgUp and Ctrl+PgDown switches tabs in the notebook view if (modifierState & Clutter.ModifierType.CONTROL_MASK) { if (symbol == Clutter.KEY_Page_Up) { this._notebook.prevTab(); } else if (symbol == Clutter.KEY_Page_Down) { this._notebook.nextTab(); } } return Clutter.EVENT_PROPAGATE; }, open : function() { if (this._open) return; if (!Main.pushModal(this._entry, { keybindingMode: Shell.KeyBindingMode.LOOKING_GLASS })) return; this._notebook.selectIndex(0); this.actor.show(); this._open = true; this._history.lastItem(); Tweener.removeTweens(this.actor); // We inverse compensate for the slow-down so you can change the factor // through LookingGlass without long waits. Tweener.addTween(this.actor, { time: 0.5 / St.get_slow_down_factor(), transition: 'easeOutQuad', y: this._targetY }); }, close : function() { if (!this._open) return; this._objInspector.actor.hide(); this._open = false; Tweener.removeTweens(this.actor); this.setBorderPaintTarget(null); Main.popModal(this._entry); Tweener.addTween(this.actor, { time: Math.min(0.5 / St.get_slow_down_factor(), 0.5), transition: 'easeOutQuad', y: this._hiddenY, onComplete: Lang.bind(this, function () { this.actor.hide(); }) }); } }); Signals.addSignalMethods(LookingGlass.prototype);
Devyani-Divs/gnome-shell
js/ui/lookingGlass.js
JavaScript
gpl-2.0
43,481
//>>built define("dojox/wire/ml/RestHandler",["dijit","dojo","dojox","dojo/require!dojox/wire/_base,dojox/wire/ml/util"],function(_1,_2,_3){ _2.provide("dojox.wire.ml.RestHandler"); _2.require("dojox.wire._base"); _2.require("dojox.wire.ml.util"); _2.declare("dojox.wire.ml.RestHandler",null,{contentType:"text/plain",handleAs:"text",bind:function(_4,_5,_6,_7){ _4=_4.toUpperCase(); var _8=this; var _9={url:this._getUrl(_4,_5,_7),contentType:this.contentType,handleAs:this.handleAs,headers:this.headers,preventCache:this.preventCache}; var d=null; if(_4=="POST"){ _9.postData=this._getContent(_4,_5); d=_2.rawXhrPost(_9); }else{ if(_4=="PUT"){ _9.putData=this._getContent(_4,_5); d=_2.rawXhrPut(_9); }else{ if(_4=="DELETE"){ d=_2.xhrDelete(_9); }else{ d=_2.xhrGet(_9); } } } d.addCallbacks(function(_a){ _6.callback(_8._getResult(_a)); },function(_b){ _6.errback(_b); }); },_getUrl:function(_c,_d,_e){ var _f; if(_c=="GET"||_c=="DELETE"){ if(_d.length>0){ _f=_d[0]; } }else{ if(_d.length>1){ _f=_d[1]; } } if(_f){ var _10=""; for(var _11 in _f){ var _12=_f[_11]; if(_12){ _12=encodeURIComponent(_12); var _13="{"+_11+"}"; var _14=_e.indexOf(_13); if(_14>=0){ _e=_e.substring(0,_14)+_12+_e.substring(_14+_13.length); }else{ if(_10){ _10+="&"; } _10+=(_11+"="+_12); } } } if(_10){ _e+="?"+_10; } } return _e; },_getContent:function(_15,_16){ if(_15=="POST"||_15=="PUT"){ return (_16?_16[0]:null); }else{ return null; } },_getResult:function(_17){ return _17; }}); });
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/wire/ml/RestHandler.js
JavaScript
gpl-2.0
1,541
define( "dojox/calendar/nls/fr/buttons", { previousButton: "◄", nextButton: "►", todayButton: "Aujourd'hui", dayButton: "Jour", weekButton: "Semaine", fourDaysButton: "4 jours", monthButton: "Mois" } );
hariomkumarmth/champaranexpress
wp-content/plugins/dojo/dojox/calendar/nls/fr/buttons.js.uncompressed.js
JavaScript
gpl-2.0
224
function setupFilterForm() { // make filter form expandable $('#filter-panel .card-header').on('click', function() { $('#filter-panel .card-body').toggle(200); if($('#filter-panel').hasClass('filter-panel-bottom')) { $('html,body').animate({ scrollTop: $(document).height() }); } }); $('#filter-panel .help_popover').on('click', function(event) { event.stopPropagation(); }); $('#filter-form').on('submit', function(event) { if($('#filter-form').serialize() !== window.location.search.substring(1)) { // show progress indication $('#filter-form').hide(); $('#filter-panel .card-body').append('<span id="filter-progress"><i class="fa fa-cog fa-spin fa-2x fa-fw"></i> <span>Applying filter…</span></span>'); } }); } function parseFilterArguments(paramHandler) { var varPairs = window.location.search.substring(1).split('&'); var filterLabels = []; for (var j = 0; j < varPairs.length; ++j) { var pair = varPairs[j].split('='); if(pair.length > 1) { var key = decodeURIComponent(pair[0].replace(/\+/g, '%20')); var val = decodeURIComponent(pair[1].replace(/\+/g, '%20')); if(val.length < 1) { continue; } var filterLabel = paramHandler(key, val); if(filterLabel) { filterLabels.push(filterLabel); } else { var input = $('<input/>'); input.attr('value', val); input.attr('name', key); input.attr('hidden', true); $('#filter-form').append(input); } } } if(filterLabels.length > 0) { $('#filter-panel .card-header').find('span').text('current: ' + filterLabels.join(', ')); } return filterLabels; }
mudler/openQA
assets/javascripts/filter_form.js
JavaScript
gpl-2.0
1,918
// $Id$ function CRMLookupCallBack() { ZCForm.triggerExternalOnUser(ExternalFieldName); } function SDPODLookupCallBack() { ZCForm.triggerExternalOnUser(ExternalFieldName); } function gDocImportFile(fileName, gDocId) { var importEl = $("#gFormName"); if($(importEl).attr("importOpen") == 'true') { $("[name=GDOC_ID]").val(gDocId); $("#gFormName").html(fileName); closeDialog(); $(importEl).attr("importOpen", false); } else { ZCForm.googleDocAttachEvent(fileName, gDocId); } } function closeGDocDialog() { var importEl = $("#gFormName"); if($(importEl).attr("importOpen") == 'true') { closeDialog(); $(importEl).attr("importOpen", false); } else { ZCForm.closeDocsAttachTemplate(); } } function selectedDocDetails(docDetails, docName) { ZCForm.cloudDocAttachEvent(docDetails, docName); closeCloudPicDialog(); } function closeCloudPicDialog() { $("#zc-gadgets_cloudpicker_div").remove(); $("[isAttachOpen=true]:first").removeAttr("isAttachOpen"); } isViewBeta = false; var ZCForm = new function() { this.formArr = []; this.showFormVar = "true"; this.custParams = ""; this.onUserInputElem = new Array(); this.editorRef = new Array(); this.isEmbeddedForm = "false"; this.isPermaForm = "false"; this.inZohoCreator = true; this.zcFormAttributes = new Array(); this.zcFormAttributes['formParentDiv'] = true; this.zcFormAttributes['customCalendar'] = false; this.zcFormAttributes['browseralert'] = false; this.zcFormAttributes['ajaxreload'] = true; this.zcFormAttributes['fieldContainer'] = "tr"; this.zcFormAttributes['eleErrTemplate'] = "<tr tag='eleErr'><td width='100%' height='100%' valign='top' colspan='insertColSpan' class='zc-form-errormsg' > insertMessage </td></tr>"; this.isSubFormFileSubmit = false; this.focusElement = ""; this.formLabelWidth = "auto"; //No I18N this.isRecursiveCall = false; this.addToFormArr = function(formParamsMap, formLinkName) { formParamsMap = formParamsMap.substring(1, formParamsMap.length-1); formParamsMap = ZCUtil.getParamsAsMap(formParamsMap, ",", "="); isViewBeta = ZCUtil.getFromMap(formParamsMap, "isViewBeta") == "true";//No I18N this.formLabelWidth = ZCUtil.getFromMap(formParamsMap, "formLabelWidth");//No I18N this.formArr[formLinkName] = formParamsMap; if(isViewBeta) { ZCApp.dialogAbove = "<div class=\"zc-dialog-heading zc-dialog-noheading\" elname=\"zc-dialogheader\"><h1 elname=\"zc_dialog_header\">&nbsp;</h1></div><div class=\"zc-dialogdiv zc-noappearance\">"; } } this.addNextUrlToFormArr = function(zcNextUrl, formLinkName) { if(zcNextUrl && zcNextUrl != "") { var formParamsMap = ZCForm.formArr[formLinkName]; formParamsMap["zc_NextUrl"] = new Array(); var val = formParamsMap["zc_NextUrl"]; val[val.length] = zcNextUrl; ZCForm.formArr[formLinkName] = formParamsMap; } } this.callFormOnLoad = function(formActionMap, formID, formLinkName, formAccessType) { ZCForm.showFormVar = "true"; var invokeOnLoad = false; if(formActionMap.length > 4) { formActionMap = formActionMap.substring(1, formActionMap.length-1); formActionMap = ZCUtil.getParamsAsMap(formActionMap, ",", "="); try { invokeOnLoad = (formAccessType == ZCConstants.FORM_LOOKUP_ADD_FORM || formAccessType == ZCConstants.FORM_ALONE || formAccessType == ZCConstants.VIEW_ADD_FORM)?ZCUtil.getFromMap(formActionMap, ZCConstants.FORM_EVENT_ON_LOAD):false; invokeOnLoad = (formAccessType == ZCConstants.VIEW_EDIT_FORM)?ZCUtil.getFromMap(formActionMap, ZCConstants.EDIT_FORM_EVENT_ON_LOAD):invokeOnLoad; } catch(e) { } if(invokeOnLoad) doActionOnLoad(formID, ZCForm.getForm(formLinkName, formAccessType)[0]); else ZCForm.enableForm(formLinkName, formAccessType); } else { ZCForm.enableForm(formLinkName, formAccessType); } } this.enableForm = function(formLinkName, formAccessType,subFormLabelName) { var frm = ZCForm.getForm(formLinkName, formAccessType,subFormLabelName); if($(frm).attr("formType") == "SubForm" || !this.zcFormAttributes['formParentDiv']) { $(frm).css("visibility", "visible"); return false; } ZCUtil.getParent(frm, "div").css("visibility", "visible"); //$(frm).find(":input[type!=hidden]:eq(0)").focus(); if(ZCApp.inZC) ZCForm.setFocus(frm); this.handleScreenResize(frm); } this.handleScreenResize = function(formCont) { if(isViewBeta) { var zcFieldsTable = formCont.find('table[elName=zc-fieldsTable]');//No I18N if(ZCForm.formLabelWidth == 'auto') { //No I18N zcFieldsTable.each(function() { //No I18N var maxWidth = 0; var tdList = $(this).find("tbody tr td[class=zc-labelheader]"); //No I18N tdList.find('label').each(function() { //No I18N var wi = $(this).outerWidth(); if(wi>maxWidth) maxWidth = wi; }); tdList.css("width", (maxWidth+10) + "px"); //No I18N }); } var totalWidth = 0; zcFieldsTable.each(function() { //No I18N totalWidth = totalWidth + $(this).width(); }); var inpElSpan = formCont.find('table[elName=zc-submitTable]').find("span[elName=zc-formsubmitspan]");//No I18N var padding = (totalWidth - inpElSpan.width())/2; inpElSpan.css("padding-left", (padding>0)?padding:0);//No I18N } } this.setFocus = function(frm) { var firstElement = ZCForm.getFirstVisibleElement(frm); if(firstElement) { var x = window.scrollX, y = window.scrollY; $(firstElement).focus(); window.scrollTo(x, y); } } this.getFirstVisibleElement = function(frm) { var element; $(frm).find("table[elname=zc-fieldsTable]").find("tr").each(function() { var style = $(this).css("display"); var parentStyle = $(this).parents("tr").css("display"); if(style != "none" && parentStyle != "none") { element = $(this).find(":input[type!=hidden]:eq(0)"); if($(element).attr("name")!=null) return false; } }); return element; } this.getNextLookupPage = function(respTxt, paramsMap, argsMap) { var compName = ZCUtil.getFromMap(argsMap, "compName"); var El = $("div[zcSearchDDFieldName="+compName+"]:first"); $(El).html(respTxt); ZCForm.regCustomLookUpEvents(El); } this.regCustomLookUpEvents = function(El) { $(El).find("[elName=zcSearchDDListing] tr").click(function() { ZCForm.selectExternalModule(this); }); $(El).find("[elName=zcSearchDDListing] tr").mouseover(function() { $(this).removeClass().addClass("custom_dropdown_menu_selected"); }); $(El).find("[elName=zcSearchDDListing] tr").mouseleave(function() { $(this).removeClass("custom_dropdown_menu_selected"); }); $(El).find("[elName=zc-zcDDPaginationEl]").click(function(event) { ZCApp.hideAndStopPropogation(event); var parEl = $(this).parents("div[elName=zcDDPagination]:first"); var formID = $(parEl).attr("zcFormID"); var formCompID = $(parEl).attr("zcFormCompId"); var reqPage = $(this).attr("showList"); var startIndex = $(parEl).find("[startIndex]").attr("startIndex"); var endIndex = $(parEl).find("[startIndex]").attr("endIndex"); var compName = $(parEl).attr("zcsearchddfieldname"); var urlParams = "formID="+formID+"&formCompID="+formCompID+"&startIndex="+startIndex+"&endIndex="+endIndex+"&reqPage="+reqPage+"&compName=" + compName; var args = "compName=" + compName; ZCUtil.sendRequest("/live/common/jsp/form/fields/getnextpagelist.jsp", urlParams, "html", "ZCForm.getNextLookupPage", ZCUtil.getParamsAsMap(args), i18n.pleasewait); //No I18N }); $(El).find("[elName=zcDropDownSelVal],[elName=zcDropDownImg]").click(function(event) { var isVisible = $(this).parents("[elName=zc-fieldtd]:first").find("[elName=zcDDPagination]:first").is(":visible"); ZCApp.hideAndStopPropogation(event); $("[elName=zcDDPagination]").hide(); if(!isVisible) { $(this).parents("[elName=zc-fieldtd]:first").find("[elName=zcDDPagination]:first").show(); } else { $(this).parents("[elName=zc-fieldtd]:first").find("[elName=zcDDPagination]:first").hide(); } }); } this.selectExternalModule = function(thisObj) { var El = $(thisObj).parents("[elName=zc-fieldtd]:first"); $(El).find(":input[type=text]").val($(thisObj).attr("elValue")); $(El).find("div[elName=zcDropDownSelVal]").html($(thisObj).attr("elDispVal")); $(El).find("div[elName=zcDDPagination]").hide(); var mainForm = $(El).parents('form'); var mainFormLinkName = $(mainForm).attr("name"); var formParamsMap = ZCForm.formArr[mainFormLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap,"formAccessType");//No I18N var formID = ZCUtil.getFromMap(formParamsMap,"formID"); var formElem = ZCForm.getForm(mainFormLinkName, formAccessType); ZCForm.invokeOnChange($(El).find(":input[type=text]"), mainForm, formAccessType); } this.setFieldValsFromURL = function(formLinkName, formAccessType) { var loc = location.href; if(formLinkName == ZCApp.currZCComp) { var params = loc.substr(loc.lastIndexOf("/")+1); var hashIdx = params.indexOf("#"); var qstIdx = params.indexOf("?"); if(hashIdx != -1 && qstIdx != -1) { if(hashIdx == 0 && qstIdx != -1) { params = params.substr(qstIdx+1) } else { params = params.substring(0, hashIdx) + "&" + params.substr(qstIdx+1); } } var paramsMap = ZCUtil.getParamsAsMap(params); $.each(paramsMap, function(paramName, paramValue) { if(paramName.indexOf(".do?") != -1) { paramName = paramName.substring(paramName.indexOf(".do?")+4); } if(paramName.indexOf("?") != -1) { paramName = paramName.substring(paramName.indexOf("?")+1); } if(paramName != "sharedBy" && paramName != "appLinkName") { for(var i = 0; i < paramValue.length;i++) { paramValue[i]=decodeURIComponent(paramValue[i]); } var el = ZCForm.getField(formLinkName, paramName, formAccessType); var elType = el.attr("type"); // No I18N if(elType != "searchLookupSingle" && elType != "searchLookupMulti") { ZCForm.setFieldValue(formLinkName, paramName, formAccessType, paramValue); } } }); } } this.showHideField = function(toShow, formLinkName, fieldName, formAccessType) { var trID = formLinkName+"-"+fieldName+"-"+formAccessType; var eltr = $("#"+trID); if(eltr.length == 0) { var el = ZCForm.getField(formLinkName, fieldName, formAccessType); if(ZCUtil.isNull(el)) { el = $(ZCForm.getForm(formLinkName, formAccessType)).find("div[name=parentOf-"+fieldName + "],span[name=parentOf-"+fieldName + "]"); } if(ZCUtil.isNull(el)) { el = $(ZCForm.getForm(formLinkName, formAccessType)).find("td[elName="+fieldName+"_label]"); } eltr = ZCUtil.getParent(el, "tr"); // specifically put for zohosites bcoz their form field construction based on li in ul instead of tr in table if(eltr == undefined) { eltr = ZCUtil.getParent(el, "li"); } // var eltable = ZCUtil.getParent(eltr, "table"); // var colCount = eltable.attr("colCount"); } if($(el).is(':button') || $(el).is(':submit') || $(el).is(':reset')) { eltr = el; } if(eltr != undefined) { eltr.css("display", toShow?"":"none"); } //Custom event triggered to reposition the disable div - Rich Text Field } this.enDisableField = function(disable, formLinkName, fieldName, formAccessType) { var el = ZCForm.getField(formLinkName, fieldName, formAccessType); var type = el.attr("type"); var elToLoop = (type == "image" || type == "url")?el.find(":input"):el; if (type == "image" && formAccessType == "3") { el.find("a[enable=enable]").each(function(index, elem) { (disable) ? $(elem).css("visibility", "hidden"): $(elem).css("visibility", "visible"); }); } $.each(elToLoop, function(index, elem) { $(elem).attr("disabled", disable); }); if(type == "radio" || type == "checkbox" || type == "select-one" || type == "select-multiple") { var par = (type=="radio"||type=="checkbox")?ZCUtil.getParent(el).parent():ZCUtil.getParent(el); var spanToLoop = par.find("span"); $.each(spanToLoop, function(index, elem){ if($(elem).attr("elname") == "zc-show-parent"){ if(disable) $(elem).css("visibility", "hidden"); else $(elem).css("visibility", "visible"); } } ); } var modtype=$("#"+fieldName).attr("modtype"); if((modtype!==undefined) && (modtype===ZCConstants.ZOHO_CRM_USERS)) { $("#"+fieldName).attr("disabled", disable); } if(el.attr("fieldtype") == ZCConstants.FILE_UPLOAD) { var fieldid=el.attr("formCompID"); //No internationalization $("a[id=zc-toggleupload-"+fieldid+"]").css("visibility", disable?"hidden":"visible"); //No internationalization } if(el.attr("fieldtype") == ZCConstants.RICH_TEXT_AREA && !ZCApp.isMobileSite) { var textareaname = el.attr("formcompid"); var freezdivid = "freezdiv_" + textareaname; var _editordiv = $("div[textareaname=" + textareaname + "]"); var divID = _editordiv.attr("id");//No I18N var _RTEditor = ZCForm.editorRef[divID]; //console.log(divID); try{ if(_RTEditor){ if(_RTEditor.mode == "plaintext"){ $(_RTEditor._textarea).attr("disabled" , disable); }else{ var _iframe = _RTEditor.iframe; var desMod = disable?"off":"on"; if(!($.browser.msie)) _RTEditor.doc.designMode = desMod; else { var ieMod = disable?"false":"true"; _RTEditor.doc.body.contentEditable=ieMod; //test } } } } catch(e4){} if( _editordiv.find("#"+freezdivid)[0] ){ var _freezdiv = _editordiv.find("#"+freezdivid); var _map = { "zIndex":disable?50:-50 }; ZE_Init.tabKeyHandling=true; _freezdiv.css(_map); }else if(disable){ var _newdiv = document.createElement("div"); _newdiv.className = "freezeLayer"; _newdiv.id = freezdivid; var _map = { "left":"0", "top":"0", "height":"100%", "width":"100%", "zIndex":50, "background":"#AAAAAA", "border":"1px solid #AAAAAA" }; $(_newdiv).css(_map); _editordiv[0].appendChild(_newdiv); } } /*if(el.attr("fieldtype") == ZCConstants.RICH_TEXT_AREA && !ZCApp.isMobileSite) { var textareaname = el.attr("formcompid"); var freezdivid = "freezdiv_" + textareaname; var freezdivbody = "bodydiv_" + freezdivid; var _editordiv = $("div[textareaname=" + textareaname + "]"); var divID = _editordiv.attr("id");//No I18N var _RTEditor = ZCForm.editorRef[divID]; //console.log(divID); try{ if(_RTEditor && _RTEditor.doc) { if(_RTEditor.mode == "plaintext") { $(_RTEditor._textarea).attr("disabled" , disable); } else { //var _iframe = _RTEditor.iframe; var toolbardiv = _editordiv.find('div[class="ze_toolbarbg"]'); if(toolbardiv) { if(disable){ toolbardiv.hide(); }else{ toolbardiv.show(); } //var if1 = _editordiv.find('iframe'); //var yy = if1[0]; //yy.contentDocument.bgColor = disable ? '#AAAAAA' : '#FFFFFF'; _RTEditor.iframe.contentDocument.bgColor = disable ? '#AAAAAA' : '#FFFFFF'; if(!($.browser.msie)) { _RTEditor.doc.designMode = disable?"off":"on"; } else { var ieMod = disable?"false":"true"; _RTEditor.doc.body.contentEditable=ieMod; //test $(_RTEditor.doc.body).keydown(function(event){ event.cancelBubble = true; event.returnValue = false; } ); } } else { setTimeout( function() { ZCForm.enDisableField(disable, formLinkName, fieldName, formAccessType); }, 100); } } }else{ setTimeout( function(){ ZCForm.enDisableField(disable, formLinkName, fieldName, formAccessType); }, 100); } } catch(e4) { console.log(fieldName); console.log(e4); } }*/ if((el.attr("type") == "radio") || (el.attr("type") == "checkbox" && el.attr("fieldtype") != 9)) { var optTbl = docid("opt-table-"+el.attr("formCompID")); el = $(optTbl); if(disable) ZCUtil.getParent(el).attr("status","disable"); else ZCUtil.getParent(el).attr("status","enable"); } else if(el.attr("delugeType") == "TIMESTAMP") { if(disable) ZCUtil.getParent(el).find("a").css("visibility", "hidden"); else ZCUtil.getParent(el).find("a").css("visibility", "visible"); } else if(el.attr("subType") == "file") { var ele = ZCForm.getFileUploadField(formLinkName, fieldName, formAccessType); (ele).attr("disabled", disable); } else if(el.attr("disptype") == "popup") { var divEl = $(el).parents("[elname=zc-fieldtd]:first").find("[elname=zcDisableDiv]"); if(disable) { $(divEl).show(); } else { $(divEl).hide(); } } else if(type == "searchLookupSingle" || type == "searchLookupMulti") { if(disable) { $(el).parent("div:first").find("div[elName=srchDivEl]").css("display","none"); // No I18N $(el).css("background-color","#ebebe4"); $(el).unbind(); } else { $(el).css("background-color",""); $(el).click(function(event) { searchFactory.setVariables(this,false); searchFactory.triggerClickEvent(event); }); } } else if(type == "picklist") { if(disable) { $(el).css("background-color","#ebebe4"); } else { $(el).css("background-color",""); } } } //Two new functions - To Show/Hide Subform's Add and Delete buttons this.hideShowAddEntry = function(toHide, formLinkName, fieldName, formAccessType) { var subform = $('body').find('div[name='+fieldName+']'); var addbutton1 = subform.find('div[id='+fieldName+'_addNewLine]'); var addbutton2 = subform.find('table').find('tr[elname='+fieldName+'_norecordrow]').find('span[class=add_value_link]'); if(toHide) { $(addbutton1).hide(); $(addbutton2).hide(); } else { $(addbutton1).show(); $(addbutton2).show(); } } this.hideShowDeleteEntry = function(toHide, formLinkName, fieldName, formAccessType) { $('body').find('div[name='+fieldName+']').find('table').find('tr[elname=dataRow]').each(function() { if(toHide) { $(this).first().find('a').hide(); //Hide Delete Buttons } else { $(this).first().find('a').show(); // Shows Delete buttons } }); } this.addButtonStatus = function(fieldName) { var subform = $('body').find('div[name='+fieldName+']'); var addbutton1 = subform.find('div[id='+fieldName+'_addNewLine]'); return $(addbutton1).is(':visible'); } this.deleteButtonStatus = function(fieldName) { return $('body').find('div[name='+fieldName+']').find('table').find('tr[elname=dataRow]:last').first().find('a').is(':visible'); } this.clearField = function(formLinkName, fieldName, formAccessType)//issue fix { var el = ZCForm.getField(formLinkName, fieldName, formAccessType); var optTbl; var inputEl; if(el.attr("type") == "radio"||el.attr("type") == "checkbox") { inputEl = $(el); // Input Ele optTbl = docid("opt-table-"+el.attr("formCompID")); // Table Ele el = $(optTbl).parent(); // Span Ele } if($(el).attr("disptype") == "popup") { var defVal = "-Select-"; $(el).val(defVal); var parEl = $(el).parents("[elname=zc-fieldtd]:first"); var selEl = $(parEl).find("[elname=zcDDPagination]"); $(parEl).find("[elname=zcDropDownSelVal]:first").html(defVal); $(selEl).find("tr").each(function(){ if($(this).attr("elValue") != defVal) { $(this).remove(); } }); ZCForm.invokeOnChange($(el).find(":input[type=text]"), mainForm, formAccessType); } else if($(el).attr("type") == "searchLookupSingle" || $(el).attr("type") == "searchLookupMulti") { $(el).data('immutable',true); searchFactory.clearCache(fieldName); $(el).find("li").remove(); $(el).parent("div:first").find("div[elName=srchValDiv]").find("table").attr("issaturated","true"); // No I18N $(el).parent("div:first").find("div[elName=srchValDiv]").find("table").find("tr[value!=-Select-]").remove(); if($(el).attr("type") == "searchLookupSingle") { var valhtml = searchFactory.formatValueToShow($(el).parent("div:first").find("table").find("tr[value=-Select-]"), $(el).attr("name"), $(el).attr("type"),$(el).width()); $(el).append(valhtml); } else { $(el).find("span[elName=selectEl]").show(); } } else { if(el.attr("type") == "radio" || el.attr("type") == "checkbox") { $(optTbl).empty(); } else { el.empty(); } } return el[0]; } this.setFieldValue = function(formLinkName, fieldName, formAccessType, fieldValue, subFormLabelName, isFromSubForm, rowNo, combinedValue, onChangeFlag) { onChangeFlag = onChangeFlag == undefined ? true:onChangeFlag; var el ; if(isFromSubForm) { if(rowNo != -1) el = $(ZCForm.getForm(formLinkName, formAccessType)).find(":input[rowLabelName='"+fieldName+"_"+rowNo+"'], div[elName=srchDiv][labelName='"+fieldName+"'][subformrow='"+rowNo+"']"); } else { el = ZCForm.getField(formLinkName, fieldName, formAccessType,subFormLabelName); } var elType = el.attr("type"); var elToLoop = (elType == "image" || elType == "url")?el.find(":input"):el; if(!newGenerateJsCodeEnabled && fieldValue.constructor.toString().indexOf("Array") == -1) { fieldValue = fieldValue.replace(new RegExp(ZCConstants.REPLACE_DQ_CHAR,'g'),"\""); } var combinedValueList = new Array(); if(combinedValue != undefined) { if(combinedValue.constructor.toString().indexOf("Array") == -1) { combinedValueList.push(combinedValue); } else { combinedValueList = combinedValue; } } var paramsMap = ZCForm.formArr[formLinkName]; var formID = ZCUtil.getFromMap(paramsMap, "formID"); // No I18N if(!ZCForm.isAddToParentLookup && elType == "searchLookupMulti") { $(el).find("li").remove(); } if(elType == "searchLookupSingle" || (elType == "searchLookupMulti" && typeof(fieldValue) == "string")) { if(elType == "searchLookupSingle" && fieldValue == "") { fieldValue = "-Select-"; // No I18N } var tmpFieldValue = ""; if(typeof(fieldValue) == "object") { tmpFieldValue = fieldValue[0].replace("'",""); } else { tmpFieldValue = fieldValue.replace("'",""); } if($(el).find("li[selValue='"+tmpFieldValue+"']").length == 0) { var trEl = $(el).parent("div").find("div[elName=srchValDiv]").find("table").find("tr[value='"+tmpFieldValue+"']"); var inputname = !ZCUtil.isNull(isFromSubForm) ? $(el).attr("name") : fieldName; var valHtml = searchFactory.formatValueToShow(trEl, inputname, elType,$(el).width(),fieldValue, combinedValueList[0]); $(el).find("span[elName=selectEl]").hide(); $(el).find("li").remove(); $(el).append(valHtml); } var onChangeExists = $(el).attr("onChangeExists"); // No I18N var formCompId = $(el).attr("formCompId"); // No I18N if(onChangeFlag && onChangeExists == "true" && formAccessType != ZCConstants.VIEW_BULK_EDIT_FORM) { ZCForm.showHideCog(el, "visible"); // No I18N onChangeScript(ZCForm.getForm(formLinkName, formAccessType),formID, formCompId,formAccessType,true); } } else if(elType == "searchLookupMulti" && typeof(fieldValue) == "object") { var inputname = !ZCUtil.isNull(isFromSubForm) ? $(el).attr("name") : fieldName; for(var i = 0; i < fieldValue.length; i++) { var tmpFieldValue = fieldValue[i].replace("'",""); if($(el).find("li[selValue='"+tmpFieldValue+"']").length == 0) { var trEl = $(el).parent("div").find("div[elName=srchValDiv]").find("table").find("tr[value='"+tmpFieldValue+"']"); var valHtml = searchFactory.formatValueToShow(trEl, inputname, elType, $(el).width(),fieldValue[i], combinedValueList[i]); $(el).find("span[elName=selectEl]").hide(); $(el).append(valHtml); } } var onChangeExists = $(el).attr("onChangeExists"); // No I18N var formCompId = $(el).attr("formCompId"); // No I18N if(onChangeExists == "true" && formAccessType != ZCConstants.VIEW_BULK_EDIT_FORM) { ZCForm.showHideCog(el, "visible"); // No I18N onChangeScript(ZCForm.getForm(formLinkName, formAccessType),formID, formCompId,formAccessType,true); } } var chck = false; var radioOther = true; var picklistOther =true; $.each(elToLoop, function(index, elem) { if((elType == "radio" || elType == "checkbox") && !ZCForm.isAddToParentLookup) { $(elem).removeAttr("checked"); } if(elType == "radio" && $(elem).val() == fieldValue) { $(elem).prop("checked", "checked"); radioOther = false; } else if(elType == "checkbox") { if(el.attr("delugetype") == "BOOLEAN")//if(fieldValue.constructor.toString().indexOf("Array") == -1) { if(fieldValue == "true") { $(elem).prop("checked", "checked"); } else { $(elem).removeAttr("checked"); } } else { for(var i = 0;i < fieldValue.length;i++) { if($(elem).val() == fieldValue[i]) { chck = true; $(elem).prop("checked","checked"); } } if (!chck && fieldValue.length == 1 && fieldValue[0].indexOf(",") > 0) { var tmpFieldValue = fieldValue[0].split(","); for(var i = 0;i < tmpFieldValue.length;i++) { if($(elem).val() == tmpFieldValue[i] || $(elem).val() == tmpFieldValue[i].trim()) { $(elem).prop("checked","checked"); } } } } } else if(elType == "plaintext") { fieldValue = fieldValue ? fieldValue.toString() : ''; $(elem).html(fieldValue); } else if(elType == "hidden" || elType == "text"|| elType == "picklist" || elType == "select-one" || elType == "textarea" || elType == "number" || elType == "email") { if(fieldValue == "" && (elType == "picklist" || elType == "select-one")) { $(elem).val("-Select-"); picklistOther = false; } else if($(elem).attr("fieldtype") == ZCConstants.RICH_TEXT_AREA && elType == "textarea") { var textareaname = $(elem).attr("name"); var richtextdiv = $("div[nameoftextarea='" + textareaname + "']"); //No I18N var divID = $(richtextdiv).attr("id");//No I18N if (divID != "" && ZCForm.editorRef[divID] != null) //No I18N { ZCForm.editorRef[divID].setContent(fieldValue); } } else { $(elem).val(fieldValue); } if($(elem).attr("disptype") == "popup") { var parEl = $(elem).parents("[elname=zc-fieldtd]:first"); var selEl = $(parEl).find("[elname=zcDDPagination] tr[elvalue='"+ fieldValue +"']"); if(selEl != null) { $(parEl).find("[elname=zcDropDownSelVal]:first").html(fieldValue); } } try{ if(elType == "picklist" || elType == "select-one"){ if(typeof(fieldValue) == "object") { var temp = fieldValue[0].replace("'",""); if($(elem).find("option[value='"+temp+"']").length != 0) { picklistOther = false; } } else { var elToLoop = $(el).children(); $.each(elToLoop, function() { if($(this).val() == fieldValue) { picklistOther = false; return false; } }); } } } catch(e){} } else if(elType == "select-multiple" || elType == "multiselect") { if(!ZCForm.isAddToParentLookup) { $(el.find("option")).removeAttr("selected"); } for(var i = 0; i < fieldValue.length; i++) { var mulEle = $(el.find("option[value='"+fieldValue[i]+"']"));//No I18N if (mulEle.length > 0) { chck = true; mulEle.prop("selected","selected");//No I18N } } if (!chck && fieldValue.length == 1 && fieldValue[0].indexOf(",") > 0) { var tmpFieldValue = fieldValue[0].split(","); for(var i = 0;i < tmpFieldValue.length;i++) { var mulEle = $(el.find("option[value='" + tmpFieldValue[i] + "']"));//No I18N if (mulEle.length > 0) { mulEle.prop("selected","selected");//No I18N } else { $(el.find("option[value='" + tmpFieldValue[i].trim() + "']")).prop("selected","selected");//No I18N } } } } else if(elType == "image" || elType == "url") { if(newGenerateJsCodeEnabled){ fieldValue = fieldValue ? fieldValue : '' ; } fieldValue = fieldValue.toString(); var valArr = ZCUtil.getAttrsAsArr(fieldValue,elType); setImageUrlValue(formLinkName, fieldName, valArr, formAccessType) } }); /** * Handled for other option by script */ if(elType == "radio") { if(radioOther && fieldValue!='') { $.each(elToLoop, function(index, elem) { if($(elem).val() == "-otherVal-") { $(elem).prop("checked", "checked"); $(elem).closest('table').siblings('div').find('input').val(fieldValue); $(elem).closest('table').siblings('div').show() } }); } else { $.each(elToLoop, function(index, elem) { $(elem).closest('table').siblings('div').hide(); $(elem).closest('table').siblings('div').find('input').val(""); }); } } if(elType == "picklist" || elType == "select-one") { if(picklistOther) { $.each(elToLoop, function(index, elem) { if($(elem).find("option[value='-otherVal-']").length == 1) { $(elem).val("-otherVal-"); } else { $(elem).val("-Select-"); } $(elem).siblings('div').find('input').val(fieldValue); $(elem).siblings('div').show(); }); } else { $.each(elToLoop, function(index, elem) { $(elem).siblings('div').hide(); $(elem).siblings('div').find('input').val(""); }); } } return el[0]; } this.setSubFormValue = function(formLinkName, fieldName, formAccessType, fieldValue, disType, combinedValue){ if(disType == ZCConstants.SUB_FORM_GRID){ return ZCForm.setFieldValue(formLinkName, fieldName, formAccessType, fieldValue, null, false, null , combinedValue, false); } else{ //console.log("Client side action supported only for GridType : " + fieldName + "_____" + fieldValue); } } this.doActionOnInit = function(formLinkName,formCompID,formAccessType) { var frm = ZCForm.getForm(formLinkName, formAccessType); onInitScript(frm, $(frm).find(":input[name=formid]").val(), formCompID, formAccessType); } this.selectDeselect= function(formLinkName, fieldName, formAccessType, fieldValue, selectBool, combinedValue) { var el = ZCForm.getField(formLinkName, fieldName, formAccessType); var elType = el.attr("type"); if((elType == "radio" || elType == "picklist" || elType == "select-one" || el.attr("disptype") == "popup") && selectBool) { el = ZCForm.setFieldValue(formLinkName, fieldName, formAccessType, fieldValue, null, false, null, combinedValue); } else if(elType == "multiselect" || elType == "select-multiple" || elType == "checkbox") { var onChange = false; var elToLoop = (elType == "checkbox")?el:$(el).children(); var lastEl = null; $.each(elToLoop, function(){ var preValue = (elType == "checkbox")?$(this).prop("checked"):$(this).prop("selected"); if(fieldValue.constructor.toString().indexOf("Array") == -1) { fieldValue = fieldValue.replace(new RegExp(ZCConstants.REPLACE_DQ_CHAR,'g'),"\"");//No I18N fieldValue = fieldValue.replace(new RegExp(ZCConstants.REPLACE_NL_CHAR,'g'),"\n"); //No I18N if($(this).val() == fieldValue) (elType == "checkbox")?$(this).prop("checked",selectBool):$(this).prop("selected",selectBool); } else { if(jQuery.inArray(($(this).val()),fieldValue)!= -1) (elType == "checkbox")?$(this).prop("checked",selectBool):$(this).prop("selected",selectBool); } var postValue = (elType == "checkbox")?$(this).prop("checked"):$(this).prop("selected"); if(preValue != postValue) { onChange = true; } lastEl = (elType == "checkbox")?$(this):$(el); }); if(onChange) { if(lastEl != null) { fireOnChange(lastEl); } } } else if(!selectBool) { if(elType == "radio") { $(el).removeAttr("checked"); } else if(elType == "picklist" || elType == "select-one") { $(el).val(selectBool); } } var combinedValueList = new Array(); if(combinedValue != undefined) { if(combinedValue.constructor.toString().indexOf("Array") == -1) { combinedValueList.push(combinedValue); } else { combinedValueList = combinedValue; } } if(elType == "searchLookupSingle" || (elType == "searchLookupMulti" && typeof(fieldValue) == "string")) { if(selectBool) { if($(el).find("li[selValue='"+fieldValue+"']").length == 0) { var trEl = $(el).parent("div").find("div[elName=srchValDiv]").find("table").find("tr[value='"+fieldValue+"']"); var valHtml = searchFactory.formatValueToShow(trEl, fieldName, elType,$(el).width(), fieldValue, combinedValueList[0]); $(el).find("span[elName=selectEl]").hide(); if(el.attr("fieldType") == ZCConstants.SINGLE_SELECT) { $(el).find("li").remove(); } $(el).append(valHtml); } } else { $(el).find("li[selValue='"+fieldValue+"']").remove(); } if($(el).find("li").length == 0) { if(elType == "searchLookupSingle") { var valhtml = searchFactory.formatValueToShow($(el).parent("div:first").find("table").find("tr[value=-Select-]"), $(el).attr("name"), elType,$(el).width()); $(el).append(valhtml); } $(el).find("span[elName=selectEl]").show(); } } else if(elType == "searchLookupMulti" && typeof(fieldValue) == "object") { if(selectBool) { for(var i = 0; i < fieldValue.length; i++) { if($(el).find("li[selValue='"+fieldValue[i]+"']").length == 0) { var trEl = $(el).parent("div").find("div[elName=srchValDiv]").find("table").find("tr[value='"+fieldValue[i]+"']"); var valHtml = searchFactory.formatValueToShow(trEl, fieldName, elType, $(el).width(),fieldValue[i], combinedValueList[i]); $(el).find("span[elName=selectEl]").hide(); $(el).append(valHtml); } } } else { for(var i = 0; i < fieldValue.length; i++) { $(el).find("li[selValue='"+fieldValue[i]+"']").remove(); } } if($(el).find("li").length == 0) { $(el).find("span[elName=selectEl]").show(); } } } this.selectDeselectAll = function(formLinkName, fieldName, formAccessType, selectBool) { var el = ZCForm.getField(formLinkName, fieldName, formAccessType); var elType = el.attr("type"); if(elType == "multiselect" || elType == "select-multiple") { if(selectBool) { $(el).find("option:not(selected)").prop("selected",true); // No I18N } else { $(el).find("option:selected").prop("selected",false); } } else if(elType == "checkbox") { $(el).prop("checked",selectBool); } else if(el.attr("disptype") == "popup") { ZCForm.setFieldValue(formLinkName, fieldName, formAccessType, "-Select-"); } else if(elType == "searchLookupMulti") { if(selectBool) { $(el).find("li").remove(); var tableRows = $(el).parent("div:first").find("div[elName=srchDivEl]").find("table").find("tr"); for(var i = 0 ; i < tableRows.length ; i++) { var trEl = tableRows[i]; var valHtml = searchFactory.formatValueToShow(trEl, fieldName, elType,$(el).width()); $(el).find("span[elName=selectEl]").hide(); $(el).append(valHtml); } } else { $(el).find("li").remove(); $(el).find("span[elName=selectEl]").show(); } } } this.useNewGetFieldApi = false; this.getField = function(formLinkName, fieldName, formAccessType,subFormLabelName) { if(ZCForm.useNewGetFieldApi) { return ZCForm.getZCField(formLinkName, fieldName, formAccessType,subFormLabelName); } var fiedEl = $(ZCForm.getForm(formLinkName, formAccessType,subFormLabelName)).find(":input[name='"+fieldName+"'], span[name='"+fieldName+"'], div[name='"+fieldName+"'], table[name='"+fieldName+"'], div[elName=srchDiv][labelName='"+fieldName+"'],div[elName=subformComposite][compositeName='"+fieldName+"']"); if($(fiedEl).attr("type") == "searchLookupSingle" || $(fiedEl).attr("type") == "searchLookupMulti") { fiedEl = $(fiedEl).eq(0); } return fiedEl; } this.getZCField = function(formLinkName, fieldName, formAccessType,subFormLabelName) { var form = ZCForm.getForm(formLinkName, formAccessType,subFormLabelName); /* var fiedEl = $(form).find(":input[name='"+fieldName+"'], span[name='"+fieldName+"'], div[name='"+fieldName+"'], table[name='"+fieldName+"'], div[elName=srchDiv][labelName='"+fieldName+"'],div[elName=subformComposite][compositeName='"+fieldName+"']");*/ var fiedEl = new Array(); var t = form[0].elements[fieldName]; if(t !== undefined) { if(t instanceof NodeList) { fiedEl = Array.prototype.slice.call(t); } else { fiedEl.push(t); } t = $(form).find('div[elName=srchDiv][labelName='+fieldName+']')[0]; if(t !== undefined) { fiedEl = new Array(); fiedEl.push(t); } return $(fiedEl); } t = t === undefined ? $(form).find('span[name='+fieldName+']')[0] : t; t = t === undefined ? $(form).find('div[name='+fieldName+']')[0] : t; t = t === undefined ? $(form).find('table[name='+fieldName+']')[0] : t; t = t === undefined ? $(form).find('div[elName=subformComposite][compositeName='+fieldName+']')[0] : t; if(t !== undefined) { fiedEl.push(t); return $(fiedEl); } return $(fiedEl); } this.getFileUploadField = function(formLinkName, fieldName, formAccessType) { return $(ZCForm.getForm(formLinkName, formAccessType)).find(":input[labelname='"+fieldName+"'],span[name='"+fieldName+"'],div[name='"+fieldName+"'], table[name='"+fieldName+"']"); } this.getFormCont = function(formLinkName, formAccessType,subFormLabelName) { if(ZCUtil.isNull(formAccessType)) formAccessType = ZCConstants.FORM_ALONE; if(ZCUtil.isNull(subFormLabelName)) return $("#"+formLinkName+"_"+formAccessType); else return $("#"+subFormLabelName+"_"+formLinkName+"_"+formAccessType); } this.getForm = function(formLinkName, formAccessType, subFormLabelName) { if(!this.zcFormAttributes['formParentDiv']) { return $("form[elName="+formLinkName+"]"); } else { var formCont = ZCForm.getFormCont(formLinkName, formAccessType,subFormLabelName); if($(formCont).attr("formType") == "Form") return $(formCont).find("form[elName="+formLinkName+"]"); else return formCont; } } this.selectCustomDDValue = function(formName, fieldName, fieldValue, recType, envalue) { var elem = document.getElementById(formName+":"+fieldName+"_"+recType+"_comp"); var parEl = $(elem).parents("[elname=zc-fieldtd]:first"); var selEl = $(parEl).find("[elname=zcDDPagination] tr[elvalue='"+ fieldValue +"']"); if(selEl != null) { $(parEl).find("[elname=zcDropDownSelVal]:first").html(fieldValue); } } this.hideFormMenus = function(formCont) { if($(formCont)[0]) { ZCUtil.hideMenu($(formCont)[0], $(formCont).find("div[elName=zc-formOptionsDIV]")[0]); $(formCont).find("div[elName=zc-moreactionsel]").find("a:first").removeClass("zc-viewheader-menus-moreicon");//No I18N } } this.regCommonFormEvents = function(formLinkName, formAccessType,subFormLabelName) { var formCont = ZCForm.getFormCont(formLinkName, formAccessType,subFormLabelName); var frm = ZCForm.getForm(formLinkName, formAccessType,subFormLabelName); var moreAct = $(formCont).find("div[elName=zc-moreactionsel]"); $(moreAct).click(function(event) { $(moreAct).find("a:first").addClass("zc-viewheader-menus-moreicon"); var showEl = $(formCont).find("div[elName=zc-formOptionsDIV]")[0]; ZCUtil.showDropDownMenu(this, showEl); $(showEl).css("top",$(showEl).position().top -1); ZCApp.hideAndStopPropogation(event); //event.stopPropagation(); }); var exFile_fileupload={}; $(formCont).find("a[elName=zc-toggleupload]").click(function() { var enable = $(this).attr("enable"); var fileupname = $(this).attr("fileupname"); ZCUtil.getParent(this)[0].style.display = "none"; var fieldtd = ZCUtil.getParent(this, "td"); if(exFile_fileupload[fileupname] == undefined || exFile_fileupload[fileupname] == "") { exFile_fileupload[fileupname] = $(fieldtd).find("input[subtype=file]").prop("value"); $(fieldtd).find("input[subtype=file]").attr("value",""); } else { $(fieldtd).find("input[subtype=file]").attr("value",exFile_fileupload[fileupname]); exFile_fileupload[fileupname] = ""; } var fileEl = $(fieldtd).find(":input[name=uploadFile]"); $(fileEl).attr("changed", (enable == "enable")?"changed":null); $(fieldtd).find("span[elName=zc-"+enable+"upload],div[elName=zc-"+enable+"upload]")[0].style.display = ""; }); //Signature field handling $(formCont).find("div[eleName=signature-field], div[eleName=signature-field-subform]").each(function() { var signatureFieldObj = this; var recordsequence = $(signatureFieldObj).attr("recordsequence"); recordsequence = recordsequence !== undefined ? recordsequence : "1"; //Subform handling //No I18N if(recordsequence !== "0") { var signature = $(signatureFieldObj).find("div[eleName=signature]"); $(signatureFieldObj).find("span[eleName=signatureClear]").click(function() { $(signature).jSignature("reset"); }); $(signature).jSignature({'decor-color': 'transparent', 'height':'100', 'width':'300'}); $(signature).addClass("signature-div"); //No I18N var signatureEle = $(this).find("div[divName=signatureEle]"); if($(signatureEle).attr("isHide") === "true") { $(signatureEle).hide(); } $(signatureFieldObj).find("a[eleName=zc-togglesignature]").click(function() { $(signatureFieldObj).find("div[elName=editEle-signature]").hide(); var signatureEle = $(signatureFieldObj).find("div[divName=signatureEle]"); $(signatureEle).show(); $(signatureEle).find("div[eleName=signature]").attr("update","true"); }); $(signatureFieldObj).find("a[elName=zc-togglesignature-restore]").click(function() { $(signatureFieldObj).find("div[elName=editEle-signature]").show(); var signatureEle = $(signatureFieldObj).find("div[divName=signatureEle]"); $(signatureEle).hide(); $(signatureEle).find("div[eleName=signature]").attr("update","false"); }); } }); var exFile_image={}; $(formCont).find("a[elName=zc-toggleimage]").click(function() { var enable = $(this).attr("enable"); var imgname = $(this).attr("imgname"); ZCUtil.getParent(this)[0].style.display = "none"; var fieldtd = ZCUtil.getParent(this, "table"); // No I18N var imgfile = ""; if(exFile_image[imgname] == undefined || exFile_image[imgname] == "") { exFile_image[imgname] = $(fieldtd).find("input[subtype=image]").prop("value"); $(fieldtd).find("input[subtype=image]").attr("value",""); } else { $(fieldtd).find("input[subtype=image]").attr("value",exFile_image[imgname]); imgfile = exFile_image[imgname]; exFile_image[imgname] = ""; } var zcimagetype = ($(fieldtd).find("input[subname=zcimagetype]").attr("value") == undefined) ? "input[subname=zcimagetype-"+imgname+"]" : "input[subname=zcimagetype]"; if(enable == "enable") { $(fieldtd).find("tr[imagelocal=browselocal]").show() $(fieldtd).find("input[subtype=image]").attr("imagevalue",""); $(fieldtd).find(zcimagetype).attr("value","2"); } else { $(fieldtd).find("tr[imagelocal=browselocal]").hide() $(fieldtd).find("input[subtype=image]").attr("imagevalue",imgfile); $(fieldtd).find(zcimagetype).attr("value","1"); } if($(fieldtd).find("input[name=displayLinkImage]")[0] && enable == "enable") { $(fieldtd).find("input[subname=zcimagetype]").attr("value","2"); } if($(fieldtd).find("input[name=displayLinkImage]")[0] && enable == "disable") { $(fieldtd).find("input[subname=zcimagetype]").attr("value","1"); } var fileEl = $(fieldtd).find(":input[name=uploadFile]"); $(fileEl).attr("changed", (enable == "enable")?"changed":null); // No I18N $(fieldtd).find("span[elName=zc-"+enable+"upload],div[elName=zc-"+enable+"upload]")[0].style.display = ""; }); $(formCont).find("tr[elName=zc-showFormDialog],a[elName=zc-showFormDialog]").click(function() { var dialogKey = $(this).attr("dialogHTMLKey"); if(ZCApp.htmlArr[formLinkName+"-"+dialogKey] == null) { var dialogDiv = $(formCont).find("div[elName='"+$(this).attr("dialogElName")+"']"); ZCApp.htmlArr[formLinkName+"-"+dialogKey] = $(dialogDiv).html(); $(dialogDiv).remove(); } var props = ""; if(dialogKey == 'embedDialogHtml') { props = ",position=absolute,left=300"; } ZCUtil.showInDialog(ZCApp.htmlArr[formLinkName+"-"+dialogKey], "closeButton=no, modal=yes" + props); if($(this).attr("dialogElName")=="zc-embed-dialog" || $(this).attr("dialogElName")=="zc-perma-dialog") { ZCForm.custParams = ""; var embediv = $("div[elName=zc-embed-dialog-div]"); ZCApp.toggleLoginPrompt(formCont, embediv, formLinkName); ZCApp.setEmbedLink(formCont, embediv); var embedUrl = $(embediv).attr("embedurl"); var beforeht = embedUrl.substring(0, embedUrl.indexOf("height='")+8); var afterht = embedUrl.substr(embedUrl.indexOf("px")+2); embedUrl = beforeht + ($(formCont).find("table").attr("clientHeight")+200) + "px" + afterht; $(embediv).attr("embedurl", embedUrl) //$(embediv).find('textarea[elName="zc-embed-ta"]').val(embedUrl+"'></iframe>"); if($(this).attr("selectEl")=="zc-perma") { ZCForm.toggleEmbedTag($(embediv).find('td[comElName="zc-embed-crit-td"]')[1], 'zc-javascript-code'); } } }); if(!this.zcFormAttributes['customCalendar']) { $(frm).find(":input[fieldType="+ZCConstants.DATE+"], :input[fieldType="+ZCConstants.DATE_TIME+"]").each(function() { var elID = $(this).attr("id"); var buttonID = "dateButtonEl_"+elID.substr(elID.indexOf("_")+1); var shTime = ($(this).attr("fieldType") == ZCConstants.DATE_TIME)?true:false; var format = shTime?ZCApp.dateFormat + " " + ZCConstants.TIME_FORMAT:ZCApp.dateFormat; var weekWork = $(this).attr("workweek"); //ZCForm.setUpCalendar(elID, elID, format, shTime); ZCForm.setUpCalendar(elID, buttonID, format, shTime, weekWork); }); } } this.setEmbedLinks = function(embediv, formLinkName, embedParams) { embedParams = ZCUtil.isNull(embedParams)?"":embedParams; var embedurl = $(embediv).attr("embedurl"); var privUrl = $(embediv).attr("privateLink"); if(ZCUtil.isNull(privUrl)) { privUrl = ""; $(embediv).find("div[elName='zc-embedInfoDivDisable']").hide(); $(embediv).find("div[elName='zc-embedInfoDivEnable']").show(); } else { privUrl = privUrl + "/"; $(embediv).find("div[elName='zc-embedInfoDivEnable']").hide(); $(embediv).find("div[elName='zc-embedInfoDivDisable']").show(); } $(embediv).find('textarea[elName="zc-embedSnippet"]').val(embedurl+privUrl+embedParams+"'></iframe>"); } this.showSubForm = function(el) { var url = "/showSubForm.do"; //No I18N var formElem = $(el).parents('td[elname = subformtd]:first').find('div[elname = subformdiv]'); var zc_LblWidth = $(el).attr("lblwidth"); if(zc_LblWidth != null) zc_LblWidth = zc_LblWidth.replace("%","_"); var parentFormName = $(formElem).attr("parentFormName"); var formLinkName = $(formElem).attr("subFormLinkName"); var subFormAppLinkName = $(formElem).attr("subFormAppLinkName"); var dispType = $(formElem).attr("dispType"); var labelName = $(formElem).attr("name"); var formAccessType = $(formElem).attr("formAccessType"); var formCompID = $(formElem).attr("formcompid"); var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + subFormAppLinkName + "&formLinkName=" + formLinkName+ "&isSubform=" + true+ "&compType=" + ZCConstants.FORM+ "&formAccessType=" + formAccessType+"&labelName=" + labelName ; //No I18 var argsMap = ZCUtil.getParamsAsMap("appLinkName="+subFormAppLinkName+"&formLinkName="+formLinkName+"&dispType="+dispType+ "&parentFormName=" + parentFormName+ "&labelName=" + labelName + "&formCompID=" + formCompID); //No I18N ZCUtil.sendRequest(url,params,null,"ZCForm.loadSubForm",argsMap); //No I18N } this.cancelSubForm = function(el) { var url = "/showSubForm.do"; //No I18N var formCont = $(el).parents('div[elname = subFormContainer]:first'); var formLinkName = $(formCont).attr("name"); var labelName = $(formCont).attr("labelName"); var formElem = $('div[name = '+labelName+']'); $(formCont).remove(); $(formElem).attr("edit",""); var subFormLink = $(formElem).parents('td[elname = subformtd]:first').find('a[elname=subFormLink]'); var eventOnClick = "ZCForm.showSubForm(this);"; //No I18N $(subFormLink).attr("onClick",eventOnClick); if($(formElem).attr("dispType") == ZCConstants.SUB_FORM_POPUP || $(formCont).attr("isEditRecord") == "true") closeDialog(); var valTab = $(formElem).find('table[elname = subform_values]'); if(parseInt($(valTab).attr("recCount")) == 0) $(formElem).find('div[elname=no_records_div]').css("display","block"); else $(formElem).find('div[elname=no_records_div]').css("display","none"); } this.loadSubForm = function(responseText, paramsMap, argsMap) { var dispType = ZCUtil.getFromMap(argsMap, "dispType"); //No I18N var isSubformRecEdit = ZCUtil.getFromMap(argsMap, "isSubformRecEdit"); //No I18N if(dispType == ZCConstants.SUB_FORM_POPUP || isSubformRecEdit == "true") { ZCForm.loadSubFormInDialog(responseText, paramsMap, argsMap); return; } var formLinkName = ZCUtil.getFromMap(argsMap, "formLinkName"); //No I18N var parentFormName = ZCUtil.getFromMap(argsMap, "parentFormName"); //No I18N var parentFormParamsMap = ZCForm.formArr[parentFormName]; var parentFormAccessType = ZCUtil.getFromMap(parentFormParamsMap, "formAccessType"); //No I18N var formAccessType = ZCUtil.getFromMap(paramsMap, "formAccessType"); //No I18N var labelName = ZCUtil.getFromMap(argsMap, "labelName");//No I18N var compDIV = ZCForm.getField(parentFormName, labelName, parentFormAccessType); $(compDIV).find('div[elname=staticSubFormHolder]').html(responseText); ZCUtil.evalJS($(compDIV).find("script").html()); var link = $(compDIV).parents('td[elname = subformtd]:first').find('a[elname=subFormLink]'); $(link).attr('onClick',''); $(compDIV).find('div[elname=no_records_div]').css("display","none"); } this.loadSubFormInDialog = function(responseText, paramsMap, argsMap) { ZCUtil.setInMap(argsMap, "include", "true"); //No I18N ZCApp.loadZCCompInDialog(responseText, paramsMap, argsMap); var formLinkName = ZCUtil.getFromMap(argsMap, "formLinkName"); //No I18N var formAccessType = ZCUtil.getFromMap(paramsMap, "formAccessType"); //No I18N var formCont = ZCForm.getForm(formLinkName,formAccessType); var formElem = $('div[subFormLinkName = '+formLinkName+']'); } this.triggerSubFormSubmit = function(el) { var formCont = $(el).parents('div[elname = subFormContainer]:first'); var fileElArr = $(formCont).find(":input[type=file]"); if(fileElArr.length > 0 ) { ZCForm.uploadFilesAndSubmit(formCont,fileElArr,el,true); return false; } else { ZCForm.submitSubForm(el); } } this.submitSubForm = function(el) { var formCont = $(el).parents('div[elname = subFormContainer]:first'); var formLinkName = $(formCont).attr("name"); var labelName = $(formCont).attr("labelName"); var formElem = $('div[name = '+labelName+']'); var subFormAppLinkName = $(formElem).attr("subFormAppLinkName"); var parentFormName = $(formElem).attr("parentFormName"); var isNewTypeSubform =$(formElem).attr("isNewTypeSubform"); var subFormType = $(formElem).attr("disptype"); if(subFormType == ZCConstants.SUB_FORM_POPUP) { ZCForm.isSubFormFileSubmit = false; } var formParamsMap = ZCForm.formArr[formLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap,"formAccessType"); //No I18N ZCForm.updateRichTextContent(); var params = "appLinkName="+subFormAppLinkName+"&formLinkName=" +formLinkName+"&formAccessType="+formAccessType+"&"; //No I18N if(ZCUtil.isNull(ZCUtil.getFromMap(formParamsMap,"onuserinput"))) { ZCUtil.removeFromMap(formParamsMap, "showfield"); //No I18N ZCUtil.removeFromMap(formParamsMap, "autosubmit"); //No I18N params+= ZCUtil.getFieldsAsParams(formCont, ":input[type!=reset][type!=submit][type!=button][type!=file]"); //No I18N ZCUtil.sendRequest("/validateSubForm.do", params, "json", "ZCForm.handleSubFormResponse", ZCUtil.getParamsAsMap("formLinkName="+formLinkName+"&formAccessType="+formAccessType+"&parentFormName="+parentFormName+"&labelName="+labelName), i18n.pleasewait); //No I18N return false; } else { ZCUtil.removeFromMap(formParamsMap, "showfield"); //No I18N ZCUtil.setInMap(formParamsMap, "autosubmit", "true"); //No I18N ZCForm.clearErrors(formCont); return false; } } this.handleSubFormResponse = function(responseText, paramsMap, argsMap) { var labelName = ZCUtil.getFromMap(argsMap, "labelName"); //No I18N var parentFormName = ZCUtil.getFromMap(argsMap, "parentFormName"); //No I18N var formLinkName = ZCUtil.getFromMap(paramsMap, "formLinkName"); //No I18N var formParamsMap = ZCForm.formArr[formLinkName]; var formAccessType = ZCUtil.getFromMap(argsMap, "formAccessType"); var subFormLabelName = ZCUtil.getFromMap(argsMap, "labelName"); var formCont = ZCForm.getForm(formLinkName,formAccessType,subFormLabelName); var formID = ZCUtil.getFromMap(formParamsMap,"formID"); //No I18N var responseArr = ZCForm.getMsgFromResponse(responseText, formID); var fieldsArr = ZCForm.getFieldsArrFromResponse(responseText, formID); var succMsg = responseArr["succMsg"]; var errMsg = responseArr["errMsg"]; var fieldErrObj = responseArr["fieldErrObj"]; var infoMsg = (ZCApp.sharedBy == ZCApp.loginUser || ZCApp.loginUser == ZCApp.appOwner)?responseArr["infoMsg"]:""; //No I18N var errorMsg = responseArr["errorMsg"]; ZCForm.defreezeButton(formCont); ZCForm.clearErrors(formCont); var alertMsg = responseArr["alertMsg"]; if(!ZCUtil.isNull(succMsg)) { if(relodCurrentForm == "true") { ZCForm.CreateSFTable(formLinkName,fieldsArr,parentFormName,labelName,formAccessType); var btn = $(formCont).find('input[name = reset]'); if(formAccessType == ZCConstants.VIEW_EDIT_FORM) btn = $(formCont).find('input[name = cancel]'); var formElem = $("#"+subFormLabelName+"_"+formLinkName); var dispType = $(formElem).attr("dispType"); if(dispType == ZCConstants.SUB_FORM_POPUP || $(formCont).attr("isEditRecord") == "true") { $('div[elname = no_records_div]').css("display","none"); closeDialog(); } else { //ZCForm.resetSubForm(btn); ZCForm.cancelSubForm(btn); } } relodCurrentForm = "true"; } else { ZCApp.showFadingMsg(i18n.invalidmsg, 0, 5000); ZCForm.resetCaptcha(formElem); ZCForm.showErrors(formLinkName, formAccessType, null, null, fieldErrObj,subFormLabelName); if(!ZCUtil.isNull(infoMsg)|| !ZCUtil.isNull(errorMsg)) ZCForm.showInfo(infoMsg, succMsg, formLinkName, formAccessType, errorMsg); } } this.CreateSFTable = function(formLinkName,fieldsArr,parentFormName,subFormLabelName,formAccessType) { var parentFormParamsMap = ZCForm.formArr[parentFormName]; var parentFormAccessType = ZCUtil.getFromMap(parentFormParamsMap,"formAccessType"); //No I18N var subFormCont = ZCForm.getForm(formLinkName,formAccessType); var compDIV = $('div[id = '+subFormLabelName+"_"+formLinkName+']'); var valTab = $(compDIV).find('table[elname=subform_values]'); var i = 0; var valRow = $(valTab).find('tr')[1]; var recCount =parseInt($(valTab).attr('recCount')); var nextRecordSequence = parseInt($(compDIV).attr('nextRecordSequence'))+1; var tempValRow = $(valRow).clone(); $(valRow).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"record::status","added",true)); $(valTab).attr('recCount',recCount+1); $(compDIV).attr('nextRecordSequence',nextRecordSequence); if($(valRow).css("display") == "none") $(valRow).css("display",""); for(i=1;i<fieldsArr.length;i++) { if(fieldsArr[i] == null) continue; var url = ""; var link = ""; var title =""; var imgSrc = ""; var imgTitle =""; var imgLink = ""; var imgAltText = ""; var valueToShow = ""; var chkVal = false; var fieldsArrMap = ZCUtil.getParamsAsMap(fieldsArr[i]); var value = ZCUtil.getFromMap(fieldsArrMap,"value"); //No I18N var labelName = ZCUtil.getFromMap(fieldsArrMap,"labelName"); //No I18N var dispName = ZCUtil.getFromMap(fieldsArrMap,"fieldName"); //No I18N var type = ZCUtil.getFromMap(fieldsArrMap,"paramType"); var fcType = ZCUtil.getFromMap(fieldsArrMap,"fcType");//No I18N if(fcType != ZCConstants.PLAIN_TEXT && fcType != ZCConstants.SCRIPT) { if($(valTab).attr('labelAdded') != "true") { var labRow = $(valTab).find('tr:first'); var labCol = $(labRow).find('td:last'); var tempLabCol = $(labCol).clone(); $(labCol).attr("elname","labelCol"); $(labCol).css("display",""); $(labCol).attr("type",type); $(labCol).attr("label",labelName); $(labCol).attr("fcType",fcType); $(labCol).text(dispName); $(labRow).append(tempLabCol); } var valCol = $(valRow).find('td:last'); var tempValCol = $(valCol).clone(); if(fcType == ZCConstants.URL) { url = ZCUtil.getFromMap(fieldsArrMap,"zcurl-"+labelName); link = ZCUtil.getFromMap(fieldsArrMap,"zclnkname-"+labelName); title = ZCUtil.getFromMap(fieldsArrMap,"zctitle-"+labelName); if(!ZCUtil.isNull(url)) { value = "URL : "+url; $(valCol).attr("urlvalue",url); } if(!ZCUtil.isNull(link)) { value = value+"<br>Link : "+link; $(valCol).attr("linkvalue",link); } if(!ZCUtil.isNull(title)) { value = value+"<br>Title : "+title; $(valCol).attr("titlevalue",title); } } if(fcType == ZCConstants.IMAGE) { imgSrc = ZCUtil.getFromMap(fieldsArrMap,"zcsource-"+labelName); imgLink = ZCUtil.getFromMap(fieldsArrMap,"zcfieldlink-"+labelName); imgTitle = ZCUtil.getFromMap(fieldsArrMap,"zctitle-"+labelName); imgAltText = ZCUtil.getFromMap(fieldsArrMap,"zcalttext-"+labelName); if(!ZCUtil.isNull(imgSrc)) { value = "Source : "+imgSrc; $(valCol).attr("imgSrc",imgSrc); } if(!ZCUtil.isNull(imgAltText)) { value = value+"<br>Alt Text : "+imgAltText; $(valCol).attr("imgAltText",imgAltText); } if(!ZCUtil.isNull(imgLink)) { value = value+"<br>Link : "+imgLink; $(valCol).attr("imgLink",imgLink); } if(!ZCUtil.isNull(imgTitle)) { value = value+"<br>Title : "+imgTitle; $(valCol).attr("imgTitle",imgTitle); } } else if(fcType == ZCConstants.FILE_UPLOAD) { if(value!="") { valueToShow = value.substring(value.indexOf('_')+1); } } else if(fcType == ZCConstants.CHECK_BOX) { if(value!="") { chkVal = true; valueToShow = "true"; } else { chkVal = false; valueToShow = "false"; } } $(valCol).attr("elname","valueCol"); $(valCol).attr("label",labelName); $(valCol).attr("type",type); $(valCol).attr("fcType",fcType); $(valCol).css("display",""); if((value == "" || value == null || value == "-Select-")&&(fcType != ZCConstants.CHECK_BOX) ) { $(valCol).html("&nbsp;"); } else { if(fcType == ZCConstants.FILE_UPLOAD || fcType == ZCConstants.CHECK_BOX) $(valCol).html(valueToShow); else $(valCol).html(value); } if(fcType == ZCConstants.URL) { if(!ZCUtil.isNull(url)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zcurl-"+labelName,url,true)); } if(!ZCUtil.isNull(link)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zclnkname-"+labelName,link,true)); } if(!ZCUtil.isNull(title)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zctitle-"+labelName,title,true)); } } else if(fcType == ZCConstants.IMAGE) { if(!ZCUtil.isNull(imgSrc)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zcsource-"+labelName,imgSrc,true)); } if(!ZCUtil.isNull(imgLink)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zcfieldlink-"+labelName,imgLink,true)); } if(!ZCUtil.isNull(imgAltText)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zcalttext-"+labelName,imgAltText,true)); } if(!ZCUtil.isNull(imgTitle)) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,"zctitle-"+labelName,imgTitle,true)); } } else if(fcType == ZCConstants.MULTI_SELECT) { var options = value.split(","); for(var opt=0;opt<options.length;opt++) { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,labelName,options[opt],false)); } } else { $(valCol).append(ZCForm.createHiddenInputElement(subFormLabelName,nextRecordSequence,labelName,value,true)); } $(valCol).attr("value",value); $(valRow).append(tempValCol); } } if($(valTab).attr('labelAdded') != "true") $(valTab).attr("labelAdded","true"); $(valRow).attr("status","added"); $(valRow).attr("isTemp","false"); $(tempValRow).css("display","none"); if($(compDIV).attr("edit") == "true") { var rowInd = $(compDIV).attr("rowInd");$(compDIV).attr("edit",""); var editRow = $(valTab).find('tr')[rowInd]; var status = $(editRow).attr("status"); $(editRow).html($(valRow).html()); $(editRow).attr("status",status); $(valRow).remove();$(valTab).attr('recCount',recCount); } $(valTab).find('tr:first').after(tempValRow); if($(valTab).css("display") == "none"); $(valTab).css("display",""); ZCForm.applyClass(valTab); } this.createHiddenInputElement = function(subFormLabelName,nextRecordSequence,labelName,value,isSingleValued) { var paramType = ""; if(isSingleValued) { paramType = "SV"; } else { paramType = "MV"; } var inputelem = document.createElement('input'); $(inputelem).attr('type','hidden'); $(inputelem).attr('value',value) var inputelName = "SF("+subFormLabelName+").FD(t::row_"+nextRecordSequence+")."+paramType+"("+labelName+")"; return $(inputelem).attr('name',inputelName); } this.applyClass = function(valTab) { $.each($(valTab).find('tr[status!=deleted]'),function(i,e){ if(i != 0 && (i%2)==0) $(e).attr("class","zc-subform-viewrow zc-row-1"); else if(i != 0 && (i%2)!=0) $(e).attr("class","zc-subform-viewrow zc-row-2"); }); } this.EditSubFormRecord = function(col,formLinkName,parentFormName,labelName, subFormAppLinkName) { var url = "/showSubForm.do"; //No I18N var parentFormParamsMap = ZCForm.formArr[parentFormName]; var parentFormAccessType = ZCUtil.getFromMap(parentFormParamsMap, "formAccessType"); //No I18N var formElem = ZCForm.getField(parentFormName, labelName, parentFormAccessType); var formCompID = $(formElem).attr("formcompid"); var formParamsMap = ZCForm.formArr[formLinkName]; var formAccessType = $(formElem).attr("formAccessType"); //No I18N var formContainer = ZCForm.getForm(formLinkName,formAccessType); $(formContainer).remove(); var subFormLink = $(formElem).parents('td[elname = subformtd]:first').find('a[elname=subFormLink]'); var eventOnClick = "ZCForm.showSubForm(this);"; //No I18N $(subFormLink).attr("onClick",eventOnClick); var rowIndex = $(col).parents('table:first').find('tr').index($(col).parents('tr:first')); $(formElem).attr("edit","true"); $(formElem).attr("rowInd",rowIndex); //ZCForm.DeleteSubFormRecord(col); var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + subFormAppLinkName + "&formLinkName=" + formLinkName + "&parentFormName=" + parentFormName+ "&labelName=" + labelName + "&compType=" + ZCConstants.FORM+ "&formCompID=" + formCompID+ "&formAccessType=" + ZCConstants.VIEW_EDIT_FORM +"&edit=true&rowIndex="+rowIndex+"&isSubform="+true+"&isSubformRecEdit="+true; //No I18N $(col).parents('tr:first').find('td[elname=valueCol]').each(function(){ var label = $(this).attr("label"); var val = $(this).attr("value"); if($(this).attr("fctype") == ZCConstants.CHECK_BOX) { if(val != "") val = "true"; else val = "false"; } if($(this).attr("fctype") == ZCConstants.MULTI_SELECT) { var valArr = val.split(","); for(var i=0; i<valArr.length;i++) { params+="&"+label +"=" + valArr[i]; } } else if($(this).attr("fctype") == ZCConstants.URL) { if(!ZCUtil.isNull($(this).attr("urlvalue"))) { params+="&zcurl-"+label +"=" + $(this).attr("urlvalue"); } if(!ZCUtil.isNull($(this).attr("linkvalue"))) { params+="&zclnkname-"+label +"=" + $(this).attr("linkvalue"); } if(!ZCUtil.isNull($(this).attr("titlevalue"))) { params+="&zctitle-"+label +"=" + $(this).attr("titlevalue"); } } else if($(this).attr("fctype") == ZCConstants.IMAGE) { if(!ZCUtil.isNull($(this).attr("imgSrc"))) { params+="&zcsource-"+label +"=" + $(this).attr("imgSrc"); } if(!ZCUtil.isNull($(this).attr("imgLink"))) { params+="&zcfieldlink-"+label +"=" + $(this).attr("imgLink"); } if(!ZCUtil.isNull($(this).attr("imgTitle"))) { params+="&zctitle-"+label +"=" + $(this).attr("imgTitle"); } if(!ZCUtil.isNull($(this).attr("imgAltText"))) { params+="&zcalttext-"+label +"=" + $(this).attr("imgAltText"); } params+="&zcimagetype-"+label +"=" + $(this).attr("zcimagetype"); //No I18N } else { params+="&"+label +"=" + val; } }); var argsMap = ZCUtil.getParamsAsMap("appLinkName="+subFormAppLinkName+"&formLinkName="+formLinkName+"&dispType="+ZCConstants.SUB_FORM_POPUP+ "&parentFormName=" + parentFormName+ "&labelName=" + labelName + "&formCompID=" + formCompID+"&edit=true"+"&rowIndex="+rowIndex); //No I18N ZCUtil.sendRequest(url,params,null,"ZCForm.loadSubForm",argsMap); //No I18N } this.DeleteSubFormRecord = function(col) { var parentRow = $(col).parents('tr:first'); var valTab = $(parentRow).parents('table[elname = subform_values]'); $(valTab).attr("recCount",parseInt($(valTab).attr("recCount")) - 1) if(parseInt($(valTab).attr("recCount")) == 0) { $(valTab).css("display","none"); if($(valTab).parents('div[elname=subformdiv]').find('div[elname=subFormContainer]').css("visibility") != "visible") $(valTab).parents('div[elname=subformdiv]').find('div[elname=no_records_div]').css("display","block"); //No I18N } var status = $(parentRow).attr("status"); if(status == "added") { $(parentRow).remove(); } else { $(parentRow).css("display","none"); $(parentRow).attr("status","deleted"); $(parentRow).find("input[elName=record_status]").attr("value","deleted"); } ZCForm.applyClass(valTab); } this.resetSubForm = function(el) { var url = "/showSubForm.do"; //No I18N var formCont = $(el).parents('div[elname = subFormContainer]:first'); var formLinkName = $(formCont).attr("name"); var labelName = $(formCont).attr("labelName"); var formElem = $('div[name = '+labelName+']'); var parentFormName = $(formElem).attr("parentFormName"); var subFormAppLinkName = $(formElem).attr("subFormAppLinkName"); var labelName = $(formElem).attr("name"); var formParamsMap = ZCForm.formArr[formLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap, "formAccessType"); //No I18N var subFormLabelName = ZCUtil.getFromMap(formParamsMap, "subFormLabelName"); var formContainer = $("#"+subFormLabelName+"_"+formLinkName+"_"+formAccessType); $(formElem).find('div[elname=staticSubFormHolder]').css("visibility","hidden"); $(formContainer).remove(); var subFormLink = $(formElem).parents('td[elname = subformtd]:first').find('a[elname=subFormLink]'); var zc_LblWidth = $(subFormLink).attr("lblwidth"); if(zc_LblWidth != null) zc_LblWidth = zc_LblWidth.replace("%","_"); var dispType = $(formElem).attr("dispType"); var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + subFormAppLinkName + "&formLinkName=" + formLinkName+ "&isSubform=" + true+ "&compType=" + ZCConstants.FORM+ "&formAccessType=" + formAccessType+"&labelName="+subFormLabelName; //No I18 var argsMap = ZCUtil.getParamsAsMap("appLinkName="+subFormAppLinkName+"&formLinkName="+formLinkName+"&dispType="+dispType+ "&parentFormName=" + parentFormName+ "&labelName=" + labelName); //No I18N if(dispType == ZCConstants.SUB_FORM_POPUP || $(formCont).attr("isEditRecord") == "true") { closeDialog(); if($(formCont).attr("isEditRecord") == "true") { params+="&isSubformRecEdit="+true; ZCUtil.setInMap(argsMap,"isSubformRecEdit","true"); } } ZCUtil.sendRequest(url,params,null,"ZCForm.loadSubForm",argsMap); } this.setPermaLinks = function(permadiv, formLinkName) { var privUrl = $(permadiv).attr("privateLink"); if(!ZCUtil.isNull(privUrl)) { $("div[elName='zc-permaLinkDiv']").find("div[elName='zc-embedInfoDivEnable']").hide(); $("div[elName='zc-permaLinkDiv']").find("div[elName='zc-embedInfoDivDisable']").show(); } else { privUrl = ""; $("div[elName='zc-permaLinkDiv']").find("div[elName='zc-embedInfoDivDisable']").hide(); $("div[elName='zc-permaLinkDiv']").find("div[elName='zc-embedInfoDivEnable']").show(); } $(permadiv).find("textarea[elName=zc-textareaPermaDialog]").val($(permadiv).attr("serverprefix") + "/" + ZCApp.sharedByDisp + "/" + ZCApp.appLinkName + "/form-perma/" + formLinkName + "/" + privUrl);//No I18N } this.regBulkEditFormEvents = function(formLinkName, formAccessType) { var formCont = ZCForm.getFormCont(formLinkName, formAccessType); var frm = ZCForm.getForm(formLinkName, formAccessType); var lblNameArr = []; var notSelArr = []; $(formCont).find(":input[fieldtype = "+ZCConstants.INLINE_SINGLE_SELECT+"]").change( function() //No I18N { showOthersOption(this); } ); $.each($(formCont).find("select[elName=zc-formFieldSelectEl]").find("option[value!=-1]"),function(index, elem) { var isBidirectOtherSideSingle = $(elem).attr("isBidirectOtherSideSingle"); if(isBidirectOtherSideSingle == "true") { //notSelArr[notSelArr.length] = $(elem).val(); $(elem).remove(); } }); $(formCont).find("select[elName=zc-formFieldSelectEl]").change(function() { var fieldName = $(this).val(); lblNameArr[lblNameArr.length] = fieldName; ZCForm.showHideField(true, formLinkName, fieldName, formAccessType); $(this)[0].options[0].innerHTML = i18n.selectcolumn; $(this)[0].options[$(this)[0].selectedIndex] = null; /* if(isViewBeta) { ZCApp.correctDialog(); }*/ }); $(formCont).find("a[elName=zc-hideFormFieldEl]").click(function() { var fieldName = $(this).attr("labelName"); ZCUtil.removeFromArray(lblNameArr, fieldName); ZCForm.showHideField(false, formLinkName, fieldName, formAccessType); ZCForm.getFormCont(formLinkName, formAccessType).find("select[elName=zc-formFieldSelectEl]").append($("<option value="+$(this).attr("labelName")+">"+$(this).attr("displayName")+"</option>")); }); $.each($(frm).find(":input[tagfor=formComp],div[tagfor=formComp],span[tagfor=formComp],div[elName=srchDiv]"), function(index, inputEl) { ZCUtil.getParent(inputEl, "tr").attr("style", "display:none");//No I18N }); $(frm).find(":input[type=submit]").click(function(formElem) { ZCForm.updateRichTextContent(); return ZCForm.bulkEditRecords(formLinkName, formAccessType, lblNameArr); }); $(frm).find("span[elname=zc-show-parent]").click(function() { ZCForm.showLookupForm(this); }); ZCForm.regCustomLookUpEvents(frm); ZCForm.showRichTextEditor(frm); /* Lookup Search Reg-Event Starts */ var paramsMap = ZCForm.formArr[formLinkName]; var formID = ZCUtil.getFromMap(paramsMap, "formID"); searchFactory.regLookupSearchEvents(frm,formID,formAccessType); /* Lookup Search Reg-Event Ends */ } this.adjustWidth = function(formLinkName) { var formCont = ZCForm.getFormCont(formLinkName, ZCConstants.FORM_ALONE); var fUrl = $(formCont).attr("formURL"); var zcFormTable = formCont.find('table[elName=zc-formTable]'); if(fUrl.indexOf('/showPermaForm.do') != -1 || fUrl.indexOf('/liveFormHeader.do') != -1 ) { zcFormTable.css('width', '100%'); } } this.isAddToParentLookup = false; this.childFormName = new Array(); this.childAppName = new Array(); this.childLabelName = new Array(); this.lookupCount = 1; this.findArrayLocation = function(array, ele) { var size = array.length; for(var location=0; location<size; location++) { if(array[location] == ele) { return location; } } return '-1'; } this.setLookupCount = function(formLinkName) { var location = ZCForm.findArrayLocation(ZCForm.childFormName, formLinkName); if(location != -1) { ZCForm.childFormName = ZCForm.childFormName.slice(0,location); ZCForm.childAppName = ZCForm.childAppName.slice(0,location); ZCForm.childLabelName = ZCForm.childLabelName.slice(0,location); ZCForm.lookupCount = location+1; } } this.showLookupForm = function(el) { var isFromSubForm = ($(el).attr("isFromSubForm") == 'true') ? true : false; var parentFormName = ""; if(isFromSubForm) { parentFormName = $(el).attr("parentFormName"); } var formLinkName = $(el).attr("formLinkName"); var viewLinkName = $(el).attr("viewLinkName"); var appLinkName = $(el).attr("appLinkName"); var labelName = $(el).attr("labelName"); var formAccessType = $(el).attr("formAccessType"); var rowNo = $(el).attr("rowNo"); rowNo = ZCUtil.isNull(rowNo) ? -1 : rowNo; var isNewTypeSubform = $(el).attr("isNewTypeSubform"); var childSubformField = $(el).attr("childSubformField"); ZCForm.setLookupCount(formLinkName); ZCForm.childFormName[ZCForm.lookupCount-1] = formLinkName; ZCForm.childAppName[ZCForm.lookupCount-1] = appLinkName; ZCForm.childLabelName[ZCForm.lookupCount-1] = labelName; var childParams = ""; var length = ZCForm.childAppName.length; for(var i=1; i <= length; i++) { childParams = childParams + "&zc_childformname_" + i + "=" + ZCForm.childFormName[i-1] + "&zc_childappname_" + i + "=" + ZCForm.childAppName[i-1] + "&zc_childlabelname_" + i + "=" + ZCForm.childLabelName[i-1];//No I18N } var refFormCompName = $(el).attr("refFormCompName"); var refFormID = $(el).attr("formID"); var formCompID = $(el).attr("formCompID"); var dispType = $(el).attr("dispType"); var privateLink = $(el).parents("[elName="+formLinkName+"]").find(":input[name=privatelink]").val(); var url = "/getRefFormDetails.do";//No I18N var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + appLinkName + "&refFormID="+refFormID + "&formLinkName=" + formLinkName + "&formAccessType=" + ZCConstants.FORM_LOOKUP_ADD_FORM + "&privateLink="+privateLink + "&zc_lookupCount=" + ZCForm.lookupCount + childParams;//No I18N if(viewLinkName !== '') { params = params + "&viewLinkName=" + viewLinkName; } if(isNewTypeSubform !== '') { params = params + "&isNewTypeSubform=" + isNewTypeSubform; } ZCForm.lookupCount++; ZCUtil.sendRequest(url,params,"json","ZCForm.loadLookupForm",ZCUtil.getParamsAsMap("refFormCompName="+refFormCompName+"&lookupFormCompID="+formCompID+"&formAccessType="+formAccessType+"&formLinkName="+formLinkName+"&labelName="+labelName+"&refFormID="+refFormID+"&privateLink="+privateLink+"&isFromSubForm="+isFromSubForm+"&rowNo="+rowNo+"&parentFormName="+parentFormName+"&isNewTypeSubform="+isNewTypeSubform+"&childSubformField="+childSubformField));//No I18N } this.loadLookupForm = function(respText, paramsMap, argsMap) { var isFromSubForm = ZCUtil.getFromMap(argsMap, "isFromSubForm");//No I18N var refFormCompName = ZCUtil.getFromMap(argsMap, "refFormCompName");//No I18N var subFormLinkName = ""; var subFormAppName = ""; var childFormLinkName = ""; if(isFromSubForm == "false") { childFormLinkName = ZCUtil.getFromMap(argsMap, "formLinkName");//No I18N } else { subFormLinkName = ZCUtil.getFromMap(paramsMap, "formLinkName");//No I18N subFormAppName = ZCUtil.getFromMap(paramsMap, "appLinkName");//No I18N childFormLinkName = ZCUtil.getFromMap(argsMap, "parentFormName");//No I18N } var childFieldLabelName = ZCUtil.getFromMap(argsMap, "labelName");//No I18N var childFormAccessType = ZCUtil.getFromMap(argsMap, "formAccessType");//No I18N var childFormPrivateLink = ZCUtil.getFromMap(argsMap, "privateLink");//No I18N var formid = ZCUtil.getFromMap(argsMap, "refFormID");//No I18N var respArr = ZCUtil.parseJSONResponse(respText); var refFormLinkName = respArr["refFormLinkName"]; var refAppLinkName = respArr["refAppLinkName"]; var isFromSubForm = ZCUtil.getFromMap(argsMap, "isFromSubForm"); var rowNo = ZCUtil.getFromMap(argsMap, "rowNo"); var isNewTypeSubform = ZCUtil.getFromMap(argsMap, "isNewTypeSubform");//No I18N var childSubformField = ZCUtil.getFromMap(argsMap, "childSubformField");//No I18N var childParams = ""; var length = ZCForm.childAppName.length; var lastChildAppName = ZCForm.childAppName[length-1]; for(var i=1; i <= length; i++) { childParams = childParams + "&zc_childformname_" + i + "=" + ZCForm.childFormName[i-1] + "&zc_childappname_" + i + "=" + ZCForm.childAppName[i-1] + "&zc_childlabelname_" + i + "=" + ZCForm.childLabelName[i-1];//No I18N } if(!ZCUtil.isNull(refFormLinkName) && !ZCUtil.isNull(refAppLinkName)) { var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + refAppLinkName + "&compType=" + ZCConstants.FORM + "&formLinkName=" + refFormLinkName + "&formAccessType=" + ZCConstants.FORM_LOOKUP_ADD_FORM + "&lookupFieldName=" + refFormCompName+"&childFormLinkName="+childFormLinkName+"&childFieldLabelName="+childFieldLabelName+"&childFormAccessType="+childFormAccessType+"&childAppLinkName="+lastChildAppName+"&childFormPrivateLink="+childFormPrivateLink+"&zc_lookupCount="+(ZCForm.lookupCount-1)+childParams+"&isFromSubForm="+isFromSubForm+"&rowNo="+rowNo+"&subFormLinkName="+subFormLinkName+"&subFormAppName="+subFormAppName+"&isNewTypeSubform="+isNewTypeSubform+"&childSubformField="+childSubformField;//No I18N if(isViewBeta) { params = params + "&isNewAppearance=true";//No I18N } var viewLinkName = ZCUtil.getFromMap(paramsMap, "viewLinkName");//No I18N if(!ZCUtil.isNull(viewLinkName)) { params = params + "&viewLinkName=" + viewLinkName;//No I18N } ZCUtil.sendRequest(ZCApp.compProps["actionURL-"+ZCConstants.FORM], params, "html", "ZCApp.loadZCCompInDialog", ZCUtil.getParamsAsMap("include=false&formAccessType=" + ZCConstants.FORM_LOOKUP_ADD_FORM), i18n.pleasewait);//No I18N } } this.regFormEvents = function(formLinkName, formAccessType,subFormLabelName) { ZCForm.regCommonFormEvents(formLinkName, formAccessType,subFormLabelName); var formCont = ZCForm.getFormCont(formLinkName, formAccessType,subFormLabelName); var frm = ZCForm.getForm(formLinkName, formAccessType,subFormLabelName); if(formAccessType == ZCConstants.VIEW_BULK_EDIT_FORM) { ZCForm.regBulkEditFormEvents(formLinkName, formAccessType); } else { $(frm).find("span[elname=zc-show-parent]").click(function() { ZCForm.showLookupForm(this); }); $(frm).find(":input[type=radio], :input[type=checkbox]").click(function() { var divElem = $(this).parents('div[elname=subformdiv]')[0]; if(divElem) { ZCForm.invokeOnChange(this, frm, formAccessType, $(divElem).attr('formcompid')); } else { ZCForm.invokeOnChange(this, frm, formAccessType); } }); $(frm).find(":input[type!=hidden][type!=reset][type!=submit][type!=button][type!=radio][type!=checkbox]").keyup(function(e){ var el = this; if(!ZCUtil.isValueKeyPressed(e)) { return false; } if(window.RuleEvents !== undefined && window.RuleEvents[$(frm).attr('name')] !== undefined && window.RuleEvents[$(frm).attr('name')][$(el).attr('name')] !== undefined) { window.RuleEvents[$(frm).attr('name')][$(el).attr('name')](); } }); $(frm).find(":input[type!=hidden][type!=reset][type!=submit][type!=button][type!=radio][type!=checkbox]").change(function() { if($(this).attr("type") == "file") { $(this).attr("changed", "changed"); } var divElem = $(this).parents('div[elname=subformdiv]')[0]; if(divElem) { ZCForm.invokeOnChange(this, frm, formAccessType, $(divElem).attr('formcompid')); } else { ZCForm.invokeOnChange(this, frm, formAccessType); } }); $(frm).submit(function(formElem) { ZCForm.updateRichTextContent(); if(ZCForm.doSubmit(frm)) { ZCForm.freezeButton(frm); if($(frm).attr("formType") == ZCConstants.FORM_TYPE_OUTZC) { return ZCForm.handleButtonOnClick(frm, formAccessType, $(frm).find(":input[type=submit]")); } else { if(!ZCForm.isSubFormFileSubmit) { return ZCForm.triggerSubmit(frm); } ZCForm.isSubFormFileSubmit = false; //reseting the flag; } } else { return false; } }); $(frm).find(":input[type=reset]").click(function(formElem) { ZCForm.resetForm(formLinkName, formAccessType); }); $(frm).find(":input[comElName=zc-extformbutton][type!=submit][type!=reset]").click(function(formElem) { if(ZCForm.doSubmit(frm)) { ZCForm.freezeButton(frm); return ZCForm.handleButtonOnClick(frm, formAccessType, this); } }); $(frm).find(":input[elName=zc-cancelformbutton]").click(function(formElem) { var viewLinkName = $(frm).find(":input[name=viewLinkName]").val(); closeDialog(); /* * Navigation URL Issue fix :: While canceling the form Edit popup the brower url should be set to prevURL */ if(ZCApp.currURL.indexOf('zc_LoadIn=dialog') !=-1){ window.location.href = ZCApp.prevURL; ZCApp.loadPage = "false"; //No I18N } var viewParamsMap = ZCView.viewArr[viewLinkName]; if(ZCUtil.getFromMap(viewParamsMap, "viewType") == ZCConstants.VIEW_CALENDAR && ZCView.currRecSumry) { ZCUtil.showInDialog(ZCView.currRecSumry, "closeButton=no, closeOnBodyClick=yes, modal=yes"); } }); /* Lookup Search Reg-Event Starts */ var paramsMap = ZCForm.formArr[formLinkName]; var formID = ZCUtil.getFromMap(paramsMap, "formID"); //No I18N searchFactory.regLookupSearchEvents(frm,formID,formAccessType); /* Lookup Search Reg-Event Ends */ ZCForm.regCustomLookUpEvents(frm); ZCForm.showRichTextEditor(frm); $(frm).find("div[elName=subformdiv]").each(function(index,subformEl) { var defRows = $(subformEl).attr("defRows"); var currentRows = $(subformEl).find("tr[elName=dataRow][reclinkid!='t::row']").length; for(var i=0;i<defRows - currentRows;i++) { ZCForm.createNewSubFormRow($(subformEl).find("a[elName=subFormLink]"), false); } }); } if(this.isEmbeddedForm == "true" || this.isPermaForm == "true" || formAccessType == ZCConstants.VIEW_ADD_FORM || formAccessType == ZCConstants.VIEW_EDIT_FORM || formAccessType == ZCConstants.FORM_LOOKUP_ADD_FORM || formAccessType == ZCConstants.FORM_ALONE) { //No I18N var formElem = ZCForm.getForm(formLinkName, formAccessType); formElem.find("td[elName=zc-formTableFix]").width("1px"); //No I18N this.handleScreenResize(formElem); } } this.applyDefaultStylesToComponents = function(formLinkName, styleJson, formAccessType) { var styleJson = JSON.parse(styleJson); for(fieldName in styleJson) { for(attr in styleJson[fieldName]) { switch(attr) { case 'disabled': ZCForm.enDisableField(styleJson[fieldName][attr], formLinkName, fieldName, formAccessType); break; case 'display': ZCForm.showHideField(styleJson[fieldName][attr] === 'block', formLinkName, fieldName, formAccessType); break; } } } } this.showRichTextEditor = function(frm) { var randNum = Math.floor(Math.random() * 10000000); var richtext_div = $(frm).find("div[elName=zc-richtextarea]").get();//No I18N for (i=0; i<richtext_div.length; i++) { randNum = randNum+1; divID = randNum + ""; $(richtext_div[i]).attr("id",divID); var divHeight = $(richtext_div[i]).attr("zc-editor-height"); divHeight = divHeight.substring(0, divHeight.length-2); var textAreaName = $(richtext_div[i]).attr("nameoftextarea"); var textAreaElem = $(frm).find("textarea[name = '"+textAreaName+"']");//No I18N var rteContent = $(textAreaElem).val(); var toolsJson = $(textAreaElem).attr("zc-rtetToolsJson");//No I18N toolsJson = (ZCUtil.isNull(toolsJson) ? "" : JSON.parse(toolsJson));//No I18N var fontSizeJson = $(textAreaElem).attr("zc-rtetFontJson");//No I18N fontSizeJson = (ZCUtil.isNull(fontSizeJson) ? "" : JSON.parse(fontSizeJson));//No I18N var fontFamilyJson = $(textAreaElem).attr("zc-rtetFontFamilyJson"); //No I18n fontFamilyJson = (ZCUtil.isNull(fontFamilyJson) ? "" : JSON.parse(fontFamilyJson));//No I18N var initObj = {id : divID, content : rteContent, editorheight : divHeight, toolbar : toolsJson, fontsize : fontSizeJson, fontfamily : fontFamilyJson}; ZCForm.createRichTextEditor(divID,initObj); } } this.createRichTextEditor = function(divID, initObj) { try { this.editorRef[divID] = ZE.create(initObj); return true; } catch(e) { setTimeout(function(){ ZCForm.createRichTextEditor(divID,initObj);},1000); } } this.updateRichTextContent = function() { var richtext_div = $("div[elName=zc-richtextarea]").get();//No I18N for (i=0; i<richtext_div.length; i++) { divID = $(richtext_div[i]).attr("Id"); var nameoftextarea = $(richtext_div[i]).attr("nameoftextarea"); var content = this.editorRef[divID].getContent(); var multiTextName = $("textarea[name='"+nameoftextarea+"']");//No I18N $(multiTextName).val(content); } } this.doSubmit = function(frm) { //var submitBtn = $(frm).find(":input[type=submit],[type=button]"); //IE 8 - Permission Denied Issue //var freezeTime = submitBtn.attr("freezeTime"); var freezeTime = $(frm).attr("freezeTime"); if(!ZCUtil.isNull(freezeTime) && ((new Date() - new Date(freezeTime)) < 5000)) { return false; } //submitBtn.removeAttr("freezeTime"); $(frm).removeAttr("freezeTime"); return true; } this.freezeButton = function(frm) { //$(frm).find(":input[type=submit],[type=button]").attr("freezeTime", new Date()); //IE 8 - Permission Denied Issue $(frm).attr("freezeTime", new Date()); } this.defreezeButton = function(frm) { //$(frm).find(":input[type=submit],[type=button]").removeAttr("freezeTime"); //IE 8 - Permission Denied Issue $(frm).removeAttr("freezeTime"); } this.invokeOnChange = function(el, frm, formAccessType, frmCmpID) { if(window.RuleEvents !== undefined && window.RuleEvents[$(frm).attr('name')] !== undefined && window.RuleEvents[$(frm).attr('name')][$(el).attr('name')] !== undefined) { window.RuleEvents[$(frm).attr('name')][$(el).attr('name')](); } var formCompObj = $(el); var fieldtype =formCompObj.attr("fieldtype"); //No I18N if(fieldtype == 29)//to support others option { showOthersOption(formCompObj); //No I18N } if($(el).attr("onChangeExists")) { ZCForm.showHideCog(el, "visible"); /*if($(frm).attr("formType") == "SubForm") { var id = $(frm).attr("id"); var formLinkName = $(frm).attr("name"); var paramsMap = ZCForm.formArr[formLinkName]; var formID = ZCUtil.getFromMap(paramsMap, "formID"); //No I18N onChangeScript(frm, formID, $(el).attr("formCompID"), formAccessType); } else*/ if(frmCmpID){ var name = $(el).attr("name"); if($(el).attr("type") == "file") { name = $(el).siblings('input[type=hidden]').attr("name"); } onChangeSubFormScript(frm, $(frm).find(":input[name=formid]").val(), frmCmpID, $(el).attr("formCompID"), name, formAccessType); } else{ onChangeScript(frm, $(frm).find(":input[name=formid]").val(), $(el).attr("formCompID"), formAccessType); } } if($(el).attr("isFormulaExist")== "true") { ZCForm.showHideCog(el, "visible");//No internationalization if(frmCmpID) { executeFormulaforSubForm(frm, $(frm).find(":input[name=formid]").val(), frmCmpID, $(el).attr("formCompID"), $(el).attr("name"), formAccessType); } else { executeFormula(frm, $(frm).find(":input[name=formid]").val(), $(el).attr("formCompID")); } } } this.invokeGridRowAction = function(el, frm, rowID, actionType, formAccessType){ if( (actionType==="onaddrow" && el.attr('onaddrowexist')) || (actionType==="ondeleterow" && el.attr('ondeleterowexist')) ){ var labelName = "SF(" + $(el).attr("name") + ").FD(" + rowID + ").SV(ID)"; ZCForm.showHideCog(el.find("a[labelname='"+ labelName +"']"), "visible", true); subFormRowAction(frm, $(frm).find(":input[name=formid]").val(), $(el).attr("formCompID"), $(el).attr("name"), rowID, actionType, formAccessType); return true; } } this.handleButtonOnClick = function(formElem, formAccessType, buttonEl) { ZCForm.updateRichTextContent(); if($(buttonEl).attr("eventType")) { var formLinkName = $(formElem).find(":input[name=formLinkName]").val(); var formParamsMap = ZCForm.formArr[formLinkName]; if(ZCUtil.isNull(ZCUtil.getFromMap(formParamsMap,"onuserinput"))) { ZCUtil.removeFromMap(formParamsMap, "fieldchange"); //No I18N ZCUtil.removeFromMap(formParamsMap, "autosubmit"); //No I18N ZCUtil.removeFromMap(formParamsMap, "buttonelem"); //No I18N submitExtForm(formElem, formAccessType, $(buttonEl).attr("buttonID"), $(buttonEl).attr("eventType")); } else { ZCUtil.removeFromMap(formParamsMap, "fieldchange"); //No I18N ZCUtil.setInMap(formParamsMap, "autosubmit", "true"); //No I18N ZCUtil.setInMap(formParamsMap, "buttonelem", buttonEl); //No I18N ZCForm.clearErrors(formElem); } } return false; } this.bulkEditRecords = function(formLinkName, formAccessType, lblNameArr) { var formElem = ZCForm.getForm(formLinkName, formAccessType); var viewLinkName = $(formElem).find(":input[name=viewLinkName]").val(); var viewParamsMap = ZCView.viewArr[viewLinkName]; var recLength = ZCUtil.getFromMap(viewParamsMap, "updateIdList").split(",").length-1; var paramsArr = new Array(); paramsArr[0] = recLength; var bulkEditMsg= replaceParams(i18n.bulkEditMsg, paramsArr); // if(confirm(bulkEditMsg)) // { if(lblNameArr == "" || lblNameArr == undefined || lblNameArr == null) { ZCView.showAlertPopUp(i18n['zc.viewlive.selectatleastonefield']); return false; } ZCView.showConfirmPopUp(bulkEditMsg, function(){ var params = "addviewid="+ZCUtil.getFromMap(viewParamsMap, "viewID")+"&tableName="+ZCUtil.getFromMap(viewParamsMap, "tableName")+"&formid="+ZCUtil.getFromMap(viewParamsMap, "viewFormID")+"&updateIdList="+ZCUtil.getFromMap(viewParamsMap, "updateIdList")+"&privateLink="+ZCUtil.getFromMap(viewParamsMap, "privateLink"); params = params + "&dateFormat=" + $(formElem).find(":input[name=dateFormat]").val()+ "&timeZone=" + $(formElem).find(":input[name=timeZone]").val()+"&viewLinkName="+viewLinkName; var othersObj = $(formElem).find(":input[name*=othersVal]"); //No I18N $.each(othersObj,function(index ,obj) { params=params+"&"+obj.name+"="+obj.value; //No I18N } ); $.each(lblNameArr, function(index, fieldName) { var tempParam = ""; var fieldEl = $(formElem).find(":input[name="+fieldName+"],div[name="+fieldName+"]"); var fieldType = fieldEl.attr("type"); if(fieldType == "url" || fieldType == "image" || fieldType == "radio" || (fieldType == "checkbox" && $(formElem).find("span[name=parentOf-"+fieldName+"]")[0])) { if(fieldType == "checkbox" || fieldType == "radio") { fieldEl = $(formElem).find("span[name=parentOf-"+fieldName+"],div[name=parentOf-"+fieldName+"]"); } $.each($(fieldEl).find(":input"), function(index, tag) { if((fieldType == "radio" && $(tag).attr("type") === "text") || ($(tag).attr("type") == "radio" && !$(tag).prop("checked")) || (fieldType == "checkbox" && !$(tag).prop("checked"))){ return }; tempParam = tempParam+"&"+$(tag).attr("name")+"="+encodeURIComponent($(tag).val()); }); } else if(fieldType == "checkbox" && $(fieldEl).prop("checked")) // DECISION CHECK { tempParam = "&"+fieldName+"="+$(fieldEl).prop("checked"); } else if(fieldType == "searchLookupSingle" || fieldType == "searchLookupMulti") { $.each($(fieldEl).find("input"), function(index, el) { tempParam = tempParam+"&"+fieldName+"="+encodeURIComponent($(el).val()); }); } else if(fieldType === "composite") { $.each($(fieldEl).find(':input'),function(el,index){ tempParam = tempParam +"&"+ $(this).attr('name')+"="+$(this).val(); }); tempParam = tempParam +"&CF("+$(fieldEl).attr('name')+").SV(status)=edit"; } else { if(fieldType == "select-multiple" || fieldType == "multiselect") { var vals = ZCUtil.getFieldValue(fieldEl); if(!ZCUtil.isNull(vals)) { $.each(vals, function(idx, val) { if(!ZCUtil.isNull(val)) tempParam = tempParam + "&"+ fieldName + "=" + encodeURIComponent(val); }); } } else if(fieldEl.attr("fieldtype") == 25) { var extFieldEl = $(formElem).find(":input[name="+fieldName+"_ID],div[name="+fieldName+"_ID]"); tempParam = tempParam + "&"+ fieldName+"="+encodeURIComponent(ZCUtil.getFieldValue(fieldEl)); tempParam = tempParam + "&"+ fieldName+"_ID="+encodeURIComponent(ZCUtil.getFieldValue(extFieldEl)); //No I18N lblNameArr[lblNameArr.length] = fieldName+"_ID"; } else if($(fieldEl).length > 1) { $.each(fieldEl,function(index, el){ tempParam = tempParam+"&"+$(el).attr("name")+"="+encodeURIComponent($(el).val()); }); } else { tempParam = tempParam + "&"+ fieldName+"="+encodeURIComponent(ZCUtil.getFieldValue(fieldEl)); } } params = params + tempParam; }); var linkedView = ZCUtil.getFromMap(viewParamsMap, "linkedView"); if(!ZCUtil.isNull(linkedView)) { params = params + "&linkedView="+linkedView; } params = params + "&" + ZCUtil.getParamsFromArray(lblNameArr, "SelLabel"); var newCodeBse = ZCUtil.getFromMap(viewParamsMap,"newCodeBaseEnabled"); var bulkeditUrl = (newCodeBse != "" && newCodeBse == "true") ? "/editbulkrecordNew.do" : "/editbulkrecord.do"; ZCUtil.sendRequest(bulkeditUrl , params, "json", "ZCForm.handleBulkEditResponse", ZCUtil.getParamsAsMap("viewLinkName="+viewLinkName+"&formLinkName="+formLinkName+"&formAccessType="+formAccessType+"&fid="+ZCUtil.getFromMap(viewParamsMap, "viewFormID")), i18n.pleasewait); //No I18N return false; }); /* else { return false; }*/ return false; } this.windowScrollTop; this.offsetTop; this.getParamsFromIfrme = function() { var message = document.location.hash; if (message.length > 1) { message = message.substr(1); var parameters = ZCForm.parseIframeParameters(message); if((parameters["windowScrollTop"] != null) && (parameters["offsetTop"] != null)) { ZCForm.windowScrollTop = parameters["windowScrollTop"]; ZCForm.offsetTop = parameters["offsetTop"]; } } } this.parseIframeParameters = function(message) { var dictionary = new Array(); var pairs = message.split(/&/); for (var keyValuePairIndex in pairs) { var nameVal = pairs[keyValuePairIndex].split(/=/); dictionary[nameVal[0]] = nameVal[1]; } return dictionary; } this.triggerSubmit = function(formElem) { ZCApp.setLoadingMsg($("#zc-loading"), i18n.pleasewait + " ..."); ZCApp.showLoading("zc-loading");//No I18N var elem = $("#zc-loading"); var loadingElem = elem.find('[loading=true]'); if(loadingElem.length == 0) loadingElem = elem.find('[loading=false]'); loadingElem.attr('loading', "true"); ZCForm.clearErrors(formElem); var fileElArr = $(formElem).find(":input[type=file]"); if(fileElArr.length > 0) { return ZCForm.uploadFilesAndSubmit(formElem, fileElArr); } else { return ZCForm.submitForm(formElem); } } this.resetForm = function(formLinkName, formAccessType) { var formParamsMap = ZCForm.formArr[formLinkName]; if(ZCUtil.getFromMap(formParamsMap, "zc_LoadIn") == "dialog") { ZCApp.reloadZCComp(formLinkName); } else { if(formAccessType == ZCConstants.VIEW_ADD_FORM) { closeDialog(); var viewLinkName = ZCUtil.getFromMap(formParamsMap, "viewLinkName"); var jsonObject = ZCUtil.getFromMap(formParamsMap, "dateJsonObject"); // No I18N if(!ZCUtil.isNull(jsonObject)) { jsonObject = jsonObject.replace(new RegExp('#zc_comma#','g'),","); jsonObject = jsonObject.replace(new RegExp('&#034,','g'),"\""); } ZCView.showAddForm(ZCView.getViewCont(viewLinkName).find("a[elName=zc-showAddFormEl]"), viewLinkName, jsonObject); } else if(formAccessType == ZCConstants.FORM_LOOKUP_ADD_FORM) { var frm = ZCForm.getForm(formLinkName, formAccessType); var el = $(frm).find(":input[type=reset]"); var refFormCompName = $(frm).find(':input[name=lookupFieldName]').val();//No I18N var childFormLinkName = $(frm).find(':input[name=childFormLinkName]').val();//No I18N var childFieldLabelName = $(frm).find(':input[name=childFieldLabelName]').val();//No I18N var childFormAccessType = $(frm).find(':input[name=childFormAccessType]').val();//No I18N var childFormPrivateLink = $(frm).find(':input[name=childFormPrivateLink]').val(); //No I18N var childAppLinkName = $(frm).find(':input[name=childAppLinkName]').val();//No I18N var isFromSubForm = ($(frm).find(':input[name=isFromSubForm]').val() == 'true') ? true : false; var appLinkName = $(frm).find(':input[name=appLinkName]').val(); var childParams = ""; var length = ZCForm.childAppName.length; for(var i=1; i <= length; i++) { childParams = childParams + "&zc_childformname_" + i + "=" + ZCForm.childFormName[i-1] + "&zc_childappname_" + i + "=" + ZCForm.childAppName[i-1] + "&zc_childlabelname_" + i + "=" + ZCForm.childLabelName[i-1];//No I18N } var params = "sharedBy=" + ZCApp.sharedByDisp + "&appLinkName=" + appLinkName + "&compType=" + ZCConstants.FORM + "&formLinkName=" + formLinkName + "&formAccessType=" + ZCConstants.FORM_LOOKUP_ADD_FORM + "&lookupFieldName=" + refFormCompName+"&childFormLinkName="+childFormLinkName+"&childFieldLabelName="+childFieldLabelName+"&childFormAccessType="+childFormAccessType+"&childAppLinkName="+childAppLinkName+"&childFormPrivateLink="+childFormPrivateLink+"&zc_lookupCount=" + ZCForm.lookupCount + childParams+"&isFromSubForm="+isFromSubForm;//No I18N ZCUtil.sendRequest(ZCApp.compProps["actionURL-"+ZCConstants.FORM], params, "html", "ZCApp.loadZCCompInDialog", ZCUtil.getParamsAsMap("include = false & closedialog = true & formAccessType =" + ZCConstants.FORM_LOOKUP_ADD_FORM), i18n.pleasewait);//No I18N } else { if(ZCUtil.getFromMap(formParamsMap, "client") == "changed") { ZCUtil.setInMap(formParamsMap, "client", "reset"); ZCForm.showForm(formLinkName, formAccessType); var frm = ZCForm.getForm(formLinkName,formAccessType); } //clear RichTextArea Content var _iframe = document.getElementsByTagName("iframe"); var _length = _iframe.length; for(var i = 0;i < _length;i++) { if(_iframe[i].className === "ze_area") { _iframe[i].contentWindow.document.body.innerHTML = ""; } } /*var editorRefObj = this.editorRef; $(frm).find("div[elName=zc-richtextarea]").each(function(){ var divID = $(this).attr("Id"); editorRefObj[divID].setContent(''); });waiting for the fix from writer team */ var formCont = ZCForm.getForm(formLinkName, formAccessType); $(formCont).find("input[type=file]").each(function(){ ZCForm.removeUploadedFile($(this)); }); $(formCont).find("div[elName=zcDropDownSelVal]").each(function(){ $(this).attr("elValue", "-Select-"); $(this).html("-Select-"); }); $(formCont).find("div[elName=srchDiv]").each(function(){ $(this).find("li").remove(); if($(this).attr("type") == "searchLookupSingle") { var valhtml = searchFactory.formatValueToShow($(this).parent("div:first").find("table").find("tr[value=-Select-]"), $(this).attr("name"), $(this).attr("type"),$(this).width()); $(this).append(valhtml); } else { $(this).find("span[elName=selectEl]").show(); } }); //Delete SubForm Tables.... $(frm).find('table[elname=subform_values]').each(function(){ $(this).find('tr').each(function(i,r){ if(i<=1){ $(r).find('td[elname!=delCol][elname!=editCol][elname!=template]').each(function(){ $(this).remove(); }); } else $(r).remove(); }); $(this).css("display","none"); $(this).attr("labelAdded",""); $(this).attr("reccount","0"); }); return false; } } } this.clearEmptyFiles = function(formElem, fileNamesMap) { fileNamesMap = fileNamesMap.substring(1, fileNamesMap.length-1); fileNamesMap = ZCUtil.getParamsAsMap(fileNamesMap, ",", "="); $(formElem).find(":input[type=file][changed='changed']").each(function() { var fieldName = $(this).attr("labelName"); //No I18N var fileVal =ZCUtil.getFromMap(fileNamesMap, fieldName); if(ZCUtil.isNull(fileVal)) { $(formElem).find("input[subType=file][name="+fieldName+"]").each(function() { $(this).attr("value",""); //No I18N }); } }); } this.submitForm = function(formElem) { var formLinkName = $(formElem).find(":input[name=formLinkName]").val(); var formAccessType = $(formElem).find(":input[name=recType]").val(); var focussed = document.activeElement; var formCont = $(focussed).parents('div[class=zc-formcontainer]:first'); //Signature field handling var signatureElArr = $(formElem).find("div[eleName=signature]"); $.each(signatureElArr, function(index, el) { var isEdit = $(el).attr("isEdit"); var value = "add"; var update = "true"; if(isEdit === "true") { value = "update"; update = $(el).attr("update"); update = update === undefined ? true : update; } if(update === "true") { var base30Arrdata = $(el).jSignature('getData','base30'); if(base30Arrdata != undefined) { var dataLength = base30Arrdata[1].length; if(dataLength > 0) { var data = $(el).jSignature('getData', "image"); var srcValue = value + "," + data[1]; var parentDiv = $(el).parent(); $(parentDiv).find("textarea[elename=signatureText]").val(srcValue); } else if(isEdit) { var parentDiv = $(el).parent(); $(parentDiv).find("textarea[elename=signatureText]").val(""); } } } }); if($(formCont).attr("formType") == "SubForm") { var subFormLinkName = $(formCont).attr("name"); var subFormLabelName = $(formCont).parents('div[elname=subformdiv]').attr("name"); ZCForm.submitSubForm(subFormLinkName,formLinkName,subFormLabelName); return false; } var formParamsMap = ZCForm.formArr[formLinkName]; if(ZCUtil.isNull(ZCUtil.getFromMap(formParamsMap,"onuserinput"))) { ZCUtil.removeFromMap(formParamsMap, "fieldchange"); //No I18N ZCUtil.removeFromMap(formParamsMap, "autosubmit"); //No I18N $(formElem).find("div[elName=zc-fileuploadtemplate]").html(""); var params = ZCUtil.getFieldsAsParams(formElem, ":input[type!=reset][type!=submit][type!=button][type!=file]",formLinkName,formAccessType); //No I18N var linkedView = ZCUtil.getFromMap(formParamsMap, "linkedView"); if(!ZCUtil.isNull(linkedView)) { params += "&linkedView="+linkedView; } params += "&hasSubForm="+ZCUtil.getFromMap(formParamsMap,"hasSubForm"); //No I18N params += "&formBasedOperation="+ZCUtil.getFromMap(formParamsMap, "formBasedOperation"); ZCUtil.sendRequest($(formElem).attr("action"), params, "json", "ZCForm.handleResponse", ZCUtil.getParamsAsMap("formLinkName="+formLinkName+"&formAccessType="+formAccessType), i18n.pleasewait); //No I18N return false; } else { ZCUtil.removeFromMap(formParamsMap, "fieldchange"); //No I18N ZCUtil.setInMap(formParamsMap, "autosubmit", "true"); //No I18N ZCForm.clearErrors(formElem); return false; } } this.uploadFilesAndSubmit = function(formElem, fileUploadArr,el,isSubForm) { var submitFile = ""; var filediv = ZCUtil.getParent(formElem, "div").find("div[elName=zc-fileuploadtemplate]:first"); var fileform = filediv.find("form")[0]; //sharedbyDisp and applinkname will come from the zohosites if(ZCApp.sharedByDisp != undefined) { fileform.sharedBy.value = ZCApp.sharedByDisp; } if(ZCApp.appLinkName != undefined) { fileform.appLinkName.value = ZCApp.appLinkName; } //fileform.formAccessType.value = $(formElem).find(":input[name=recType]").val(); //fileform.formLinkName.value = $(formElem).find(":input[name=formLinkName]").val(); var imageElArr = $(formElem).find(":input[subType=image]"); $.each(imageElArr, function(index, el) { var imgval = $(el).prop("value"); var orgval = $(el).attr("imagevalue"); if(imgval == "" && orgval != "" && orgval != null) { $(el).val(orgval); } }); $.each(fileUploadArr, function(index, el) { var changed = $(el).attr("changed"); if(changed && changed == "changed") { submitFile = "submit"; if($(el).attr("zc-Attached-Type") == "browse") { $(el).after($(el).clone()[0]); $(el).attr("name", $(el).attr("labelName")); $(fileform).append(el); } else if($(el).attr("zc-Attached-Type") == "cloud") { var arrEl = document.createElement('input'); $(arrEl).attr("type", "hidden"); $(arrEl).attr("name", "cloudDocAttachments"); $(arrEl).attr("value", $(el).attr("labelName")); $(fileform).append(arrEl); var inputEl = document.createElement('input'); $(inputEl).attr("type", "hidden"); $(inputEl).attr("name", $(el).attr("labelName")); $(inputEl).attr("value", $(el).attr("zc-DocId")); $(fileform).append(inputEl); } else if($(el).attr("zc-Attached-Type") == "google") { var arrEl = document.createElement('input'); $(arrEl).attr("type", "hidden"); $(arrEl).attr("name", "gDocAttachments"); $(arrEl).attr("value", $(el).attr("labelName")); $(fileform).append(arrEl); var inputEl = document.createElement('input'); $(inputEl).attr("type", "hidden"); $(inputEl).attr("name", $(el).attr("labelName")); $(inputEl).attr("value", $(el).attr("zc-DocId")); $(fileform).append(inputEl); } else if($(el).attr("zc-Attached-Type") == "zoho") { var arrEl = document.createElement('input'); $(arrEl).attr("type", "hidden"); $(arrEl).attr("name", "zDocAttachments"); $(arrEl).attr("value", $(el).attr("labelName")); $(fileform).append(arrEl); var inputEl = document.createElement('input'); $(inputEl).attr("type", "hidden"); $(inputEl).attr("name", $(el).attr("labelName")); $(inputEl).attr("value", $(el).attr("zc-DocId")); $(fileform).append(inputEl); } } }); if(submitFile == "submit") { if(isSubForm == true) { ZCForm.isSubFormFileSubmit = true; } else { ZCForm.isSubFormFileSubmit = false; } $(fileform).submit(); } else if(isSubForm != true) { return ZCForm.submitForm(formElem); } else { return ZCForm.submitSubForm(el); } return false; } this.clearimagevalue = function(thisObj, showDiv) { var tableEl = $(thisObj).parents("[elName=zc-fieldtd]:first"); var sourcevalue = $(tableEl).find("input[name="+showDiv+"]").val(); $(tableEl).find("input[name="+showDiv+"]").attr("imagevalue",sourcevalue); var subsourcevalue = $(tableEl).find("input[subname="+showDiv+"]").val(); $(tableEl).find("input[subname="+showDiv+"]").attr("imagevalue",subsourcevalue); } this.clearUploadForm = function(origform) { var filediv = ZCUtil.getParent(origform, "div").find("div[elName=zc-fileuploadtemplate]"); var fileform = filediv.find("form"); $(fileform).find(":input").remove("[type=file]"); } this.revertUpload = function(origform) { var filediv = ZCUtil.getParent(origform, "div").find("div[elName=zc-fileuploadtemplate]"); var fileform = filediv.find("form"); $.each($(origform).find(":input[type=file]"), function(index, elem) { $(elem).attr("name", "uploadFile"); }); $.each((fileform).find("input[name=gDocAttachments]"), function(index, elem) { var fieldName = $(fileform).find("input[name=gDocAttachments]").prop("value"); $(fileform).find("input[name=gDocAttachments]").remove(); $(fileform).find("input[name=" + fieldName +"]").remove(); }); $.each((fileform).find("input[name=zDocAttachments]"), function(index, elem) { var fieldName = $(fileform).find("input[name=zDocAttachments]").prop("value"); $(fileform).find("input[name=zDocAttachments]").remove(); $(fileform).find("input[name=" + fieldName +"]").remove(); }); /* $.each($(fileform).find(":input[type=file]"), function(index, elem) { var name = $(elem).attr("name"); var textel = $(origform).find(":input[name="+name+"]"); ZCUtil.getParent(textel).find(":input").remove("[type=file]"); $(elem).attr("name", "uploadFile") $(textel).after($(elem)[0]); });*/ ZCForm.clearUploadForm(origform); ZCApp.hideLoading("zc-loading"); } this.setUpCalendar = function(inputElID, buttonElID, format, showTime, weekWork) { var workDays = new Array(); if(weekWork != undefined && weekWork != "") { workDays = weekWork.split(","); } Calendar.setup( { inputField : inputElID, ifFormat : format, showsTime : showTime, button : buttonElID, onUpdate : ZCForm.triggerOnChange /*dateStatusFunc : function(dateObj) { if(workDays.length > 0 && !isValueExist(workDays, dateObj.getDay())) { return true; } return false; }*/ }); } this.triggerOnChange = function(cal) { var el = cal.params.inputField; $(el).change(); } this.checkAndAppend = function(formElem, elName, value, elem) { var envalueElem = $(formElem).find(":input[name="+elName+"]") if(envalueElem.get(0)) { envalueElem.attr("value", value); } else { $(ZCUtil.createElem("input", "type=hidden,name="+elName+",value="+value, "")).insertAfter($(elem)); } return formElem; } this.getFieldsArrFromResponse = function(responseText, formID) { var fieldsArr =new Array(); if(typeof(responseText) == "object") { for(var eachResText in responseText) { var objEle = responseText[eachResText]; if(typeof(objEle) == "object") { for(var eachObjEle in objEle) { var insideObj = objEle[eachObjEle]; if(typeof(insideObj) == "object") { var key = ""; var val = ""; for(var eachInsideObj in insideObj) { var el = insideObj[eachInsideObj]; if(eachInsideObj == "seq") {key=el;} val=val + eachInsideObj + "=" +el+"&"; } if(key!="") fieldsArr[key] = val; //ieldsArr[key]); } } } } } return fieldsArr; } this.getMsgFromResponse = function(responseText, formID) { var responseArr = []; if(typeof(responseText) == "object") { for(var eachResText in responseText) { var objEle = responseText[eachResText]; if(typeof(objEle) == "object") { for(var eachObjEle in objEle) { var insideObj = objEle[eachObjEle]; if(eachObjEle==("success"+formID)) { responseArr["succMsg"] = insideObj; } else if(eachObjEle==("errors"+formID) && typeof(insideObj) == "object") { responseArr["fieldErrObj"] = insideObj; } else if(eachObjEle==("errors"+formID)) { responseArr["errors"] = insideObj; } else if(eachObjEle==("errorList"+formID) && typeof(insideObj) == "object") { responseArr["errorList"] = insideObj; } else if(eachObjEle==("successList"+formID) && typeof(insideObj) == "object") { responseArr["successList"] = insideObj; } else if(eachObjEle==("successes"+formID)) { responseArr["fieldSuccObj"] = insideObj; } else if(eachObjEle==("recordDetails"+formID)) { responseArr["recordDetails"] = insideObj; } else if(eachObjEle==("msg"+formID)) { responseArr["errMsg"] = insideObj; } else if(eachObjEle==("info"+formID)) { responseArr["infoMsg"] = insideObj; } else if(eachObjEle==("alert"+formID)) { responseArr["alertMsg"] = insideObj; } else if(eachObjEle==("successMsgDuration"+formID)) { responseArr["successMsgDuration"] = insideObj; } else if(eachObjEle==("captcha"+formID)) { responseArr["captchaTxt"] = insideObj; } else if(eachObjEle==("generatedjs"+formID)) { responseArr["generatedjs"] = insideObj; } else if(eachObjEle==("errorMsg"+formID)) { responseArr["errorMsg"] = insideObj; } else if(eachObjEle==("status"+formID)) { responseArr["statusMsg"] = insideObj; } else if(eachObjEle==("dummyForm")) { responseArr["dummyForm"] = insideObj; } else if(eachObjEle==("execType")) { responseArr["execType"] = insideObj; } else if(eachObjEle==("successmsg")) { responseArr["successmsg"] = insideObj; } else if(eachObjEle==("lookupFieldValue"+formID)) { responseArr["lookupFieldValue"] = insideObj; } else if(eachObjEle==("childFormAccessType"+formID)) { responseArr["childFormAccessType"] = insideObj; } else if(eachObjEle==("childFieldLabelName"+formID)) { responseArr["childFieldLabelName"] = insideObj; } else if(eachObjEle==("childFormLinkName"+formID)) { responseArr["childFormLinkName"] = insideObj; } else if(eachObjEle==("isFromSubForm"+formID)) { responseArr["isFromSubForm"] = insideObj; } else if(eachObjEle==("compType"+formID)) { responseArr.compType = insideObj; } else if(eachObjEle==("childSubformField"+formID)) { responseArr.childSubformField = insideObj; } else if(eachObjEle==("rowNo"+formID)) { responseArr["rowNo"] = insideObj; } else if(eachObjEle==("recLinkID"+formID)) { responseArr["recLinkID"] = insideObj; } else if(eachObjEle==("paymentConfigId"+formID)) { responseArr["paymentConfigId"] = insideObj; } else if(eachObjEle==("combinedValue"+formID)) { responseArr["combinedValue"] = insideObj; } else if(eachObjEle == ("paidUserFieldError"+formID)) { responseArr["paidUserFieldError"] = insideObj; } else if(eachObjEle === ("nexturl_rule"+formID)) { responseArr.nexturl_rule = insideObj; } } } } } return responseArr; } this.handleBulkEditResponse = function(responseText, paramsMap, argsMap) { var viewLinkName = ZCUtil.getFromMap(argsMap, "viewLinkName"); var formLinkName = ZCUtil.getFromMap(argsMap, "formLinkName"); var formAccessType = ZCUtil.getFromMap(argsMap, "formAccessType"); var viewParamsMap = ZCView.viewArr[viewLinkName]; var formElem = ZCForm.getForm(formLinkName, formAccessType); var formID = $(formElem).find(":input[name=formid]").val(); var responseArr = ZCForm.getMsgFromResponse(responseText, formID); var succMsg = responseArr["succMsg"]; var errMsg = responseArr["errMsg"]; var fieldErrObj = responseArr["fieldErrObj"]; ZCForm.clearErrors(formElem); if(ZCUtil.isNull(succMsg)) { ZCForm.showErrors(formLinkName, formAccessType, "", "", fieldErrObj); } else { closeDialog(); ZCUtil.removeFromMap(viewParamsMap, "bulkEditParams"); ZCView.showView(viewParamsMap, succMsg); } } this.resetCaptcha = function(formElem) { var formID = $(formElem).find(":input[name=formid]").val(); $(formElem).find(":input[name=captcha]").val(""); var captchaUrl = "/getcaptcha.do?time="+new Date()+"&formid="+formID;//No I18N if(ZCApp.contextPath != "") { captchaUrl = ZCApp.contextPath + captchaUrl; } $(formElem).find("img[elName='zc-captcha']").attr("src", captchaUrl); } this.handleResponse = function(responseText, paramsMap, argsMap) { var formLinkName = ZCUtil.getFromMap(paramsMap, "formLinkName"); var formParamsMap = ZCForm.formArr[formLinkName]; var zcNextUrl = ZCUtil.getFromMap(formParamsMap, "zc_NextUrl"); var zcnewPage = ZCUtil.getFromMap(formParamsMap,"zc_newPage"); var zc_EditType = ZCUtil.getFromMap(formParamsMap, "zc_EditType"); //No I18N var formBasedOperation = ZCUtil.getFromMap(paramsMap, "formBasedOperation"); var formAccessType = ZCUtil.getFromMap(paramsMap, "recType"); var formElem = ZCForm.getForm(formLinkName, formAccessType); var formID = $(formElem).find(":input[name=formid]").val(); var responseArr = ZCForm.getMsgFromResponse(responseText, formID); var succMsg = responseArr["succMsg"]; var succMsgDuration = responseArr["successMsgDuration"]; var errMsg = responseArr["errMsg"]; var paidUserFieldError = responseArr["paidUserFieldError"]; var fieldErrObj = responseArr["fieldErrObj"]; var combinedValue = responseArr["combinedValue"]; var lookupFieldValue = responseArr["lookupFieldValue"]; var compType = responseArr.compType; var childFormLinkName = responseArr["childFormLinkName"]; var childFieldLabelName = responseArr["childFieldLabelName"]; var childFormAccessType = responseArr["childFormAccessType"]; var isFromSubForm = (responseArr["isFromSubForm"] == 'true') ? true : false; var rowNo = responseArr["rowNo"] ; var childSubformField = responseArr.childSubformField; var infoMsg = (ZCApp.sharedBy == ZCApp.loginUser || ZCApp.loginUser == ZCApp.appOwner)?responseArr["infoMsg"]:""; var errorMsg = responseArr["errorMsg"]; ZCForm.defreezeButton(formElem); ZCForm.clearErrors(formElem); var alertMsg = responseArr["alertMsg"]; var captchaTxt = responseArr["captchaTxt"]; var generatedjs = responseArr["generatedjs"]; var nexturl_rule = responseArr.nexturl_rule; //Harishankar - payment feature actions var paymentConfigId = responseArr["paymentConfigId"]; var recLinkID = responseArr["recLinkID"]; if(!ZCUtil.isNull(succMsg)) { if(formAccessType == ZCConstants.FORM_LOOKUP_ADD_FORM) { relodCurrentForm = "false"; closeDialog(); var subFormRecordCmpName = "SF(" + childSubformField + ").FD(t::row_" + rowNo + ")." + ( ZCConstants.MULTI_SELECT == compType ? "MV(" : "SV(" ) + childFieldLabelName + ")"; //No I18N var frmCmpElem = $(ZCForm.getForm(childFormLinkName, childFormAccessType)).find("[name='"+subFormRecordCmpName+"']"); addValue(childFormLinkName, childFieldLabelName, frmCmpElem, lookupFieldValue, childFormAccessType, combinedValue,isFromSubForm);//No I18N setValue(childFormLinkName, childFieldLabelName, new makeList(lookupFieldValue), childFormAccessType,isFromSubForm,rowNo, combinedValue); } if(!ZCUtil.isNull(generatedjs) && ZCUtil.isNull(paymentConfigId)) { if( relodCurrentForm != "falseRS") { ZCApp.showFadingMsg(succMsg, 0,5000); } if(formAccessType != ZCConstants.FORM_LOOKUP_ADD_FORM){ evaluateJs(generatedjs, formAccessType); } } if(!ZCUtil.isNull(nexturl_rule)) { window.location = nexturl_rule; } if(formAccessType == ZCConstants.VIEW_EDIT_FORM && formBasedOperation && formBasedOperation == "true") { relodCurrentForm = "false"; closeDialog(); ZCAppSearch.loadLayoutData(formLinkName, 'current'); } else if(formAccessType == ZCConstants.VIEW_EDIT_FORM && (zcnewPage == "true" || zc_EditType != "default")) { var urlParams = ZCUtil.getURLParams(); var reloadPrevURL = false; if(urlParams) { var urlArr = urlParams.split("&"); for(var i=0; i< urlArr.length; i++) { var attr = (urlArr[i]).split("="); if(attr[0] == "zc_LoadIn" && attr[1] == "dialog" ) { reloadPrevURL = true; break; } } } if(!ZCUtil.isNull(zcNextUrl)) { ZCApp.showFadingMsg(succMsg, 0, succMsgDuration||2500); if(layerCount>1) { closeDialog(); } zcNextUrl = ZCForm.correctURL(zcNextUrl); ZCUtil.setURLInLocationBar(zcNextUrl); } else if(relodCurrentForm == "true") { if(layerCount>1) { ZCApp.showFadingMsg(succMsg, 0, succMsgDuration||2500); closeDialog(); ZCUtil.setURLInLocationBar(reloadPrevURL?ZCApp.prevURL:ZCApp.currURL); if(!reloadPrevURL){ ZCApp.reloadSameURL(ZCApp.currURL); } } else { var f = document.createElement('form'); f.method="post";//No I18N f.action=encodeURI("/appcreator/jsp/successpage.jsp"); var sucElement = document.createElement("input"); sucElement.name = "success"; sucElement.type="hidden"; sucElement.value=succMsg; f.appendChild(sucElement); document.body.appendChild(f); relodCurrentForm = "true"; //No I18N f.submit(); } } } else if(relodCurrentForm == "true") { if(!this.zcFormAttributes['ajaxreload']) { var windowlocation = location.href; if(windowlocation.indexOf("?") == -1) { windowlocation = windowlocation + "?zc_success=true"; // No I18N } else { windowlocation = windowlocation + "&zc_success=true"; // No I18N } location.href = windowlocation; } if(!ZCUtil.isNull(paymentConfigId)) { var formParamsMap = ZCForm.formArr[formLinkName]; ZCUtil.setInMap(formParamsMap, "processPayment", true); ZCUtil.setInMap(formParamsMap, "recLinkID", recLinkID); ZCUtil.setInMap(formParamsMap, "paymentConfigId", paymentConfigId); var formCont = ZCForm.getFormCont(formLinkName, formAccessType); var fUrl = $(formCont).attr("formURL"); if(fUrl.indexOf('/showPermaForm.do') != -1) { ZCUtil.setInMap(formParamsMap, "perma", "true"); } if(!ZCUtil.isNull(zcNextUrl)) { var zcPmtNextUrl = ZCForm.correctURL(zcNextUrl); zcNextUrl=""; ZCUtil.setInMap(formParamsMap, "zc_NextUrl", zcNextUrl); ZCUtil.setInMap(formParamsMap, "zc_PmtNextUrl", zcPmtNextUrl); } ZCForm.formArr[formLinkName]=formParamsMap; ZCForm.reloadFormView(formLinkName, formAccessType, paramsMap, infoMsg, errorMsg, succMsg); } else { ZCForm.reloadFormView(formLinkName, formAccessType, paramsMap, infoMsg, errorMsg, succMsg, succMsgDuration); } } else if(!ZCUtil.isNull(ZCForm.callbackFunc)) { relodCurrentForm = "true"; ZCForm.callbackFunc(formLinkName, formAccessType, paramsMap, infoMsg, errorMsg, succMsg, succMsgDuration); } else if(relodCurrentForm == "falseRS") //For edit action in record summary live view { closeDialog(); ZCApp.showFadingMsg(succMsg, 0, relodCurrentForm == "falseRS"?1000:5000); var viewLinkName = ZCUtil.getFromMap(paramsMap, "viewLinkName"); ZCView.refreshRecordSummaryView(viewLinkName); relodCurrentForm = "true"; } // When a callback function is assigned (actually used in Zoho Sites) the callback function itself will take care of resetting the relodCurrentForm value if(ZCUtil.isNull(ZCForm.callbackFunc)) { relodCurrentForm = "true"; } } else { var options = "position=absmiddle, closeParent=false";//No I18N var headerMsg = i18n.headererrormsg; if(alertMsg == "" || alertMsg == undefined) { alertMsg = i18n.invalidmsg; } if(!this.zcFormAttributes['browseralert']) { if(paidUserFieldError == undefined) { headerMsg = i18n.headererrormsg; if(typeof(alertMsg) == "object") { alertMsg = alertMsg[0]; for(var msgtype in alertMsg) { var eachAlertMsg = alertMsg[msgtype]; eachAlertMsg = eachAlertMsg.replace(new RegExp('\n','g'),"<br>"); eachAlertMsg = eachAlertMsg.replace(new RegExp('#zc_amp#','g'),"&"); ZCApp.showErrorDialog(headerMsg, eachAlertMsg, options); } } else { ZCApp.showErrorDialog(headerMsg, alertMsg, options); } } else { if(ZCApp.isAdmin == "true") { ZCApp.showUpgradeDialog(paidUserFieldError); } else { ZCApp.showErrorDialog(headerMsg, paidUserFieldError, options); } } } else { if(typeof(alertMsg) == "object") { alertMsg = alertMsg[0]; for(var msgtype in alertMsg) { var eachAlertMsg = alertMsg[msgtype]; eachAlertMsg = eachAlertMsg.replace(new RegExp('\n','g'),"<br>"); eachAlertMsg = eachAlertMsg.replace(new RegExp('#zc_amp#','g'),"&"); alert(eachAlertMsg); } } else { alert(alertMsg); } } ZCForm.resetCaptcha(formElem); if(paidUserFieldError == undefined) { ZCForm.showErrors(formLinkName, formAccessType, errMsg, null, fieldErrObj); if(!ZCUtil.isNull(infoMsg) || !ZCUtil.isNull(errorMsg)) ZCForm.showInfo(infoMsg, succMsg, formLinkName, formAccessType, errorMsg); } } } this.reloadFormView = function(formLinkName, formAccessType, paramsMap, infoMsg, errorMsg, succMsg, succMsgDuration) { var formParamsMap = ZCForm.formArr[formLinkName]; var zc_EditType = ZCUtil.getFromMap(formParamsMap, "zc_EditType"); var processPayment = ZCUtil.getFromMap(formParamsMap, "processPayment"); if(formAccessType == ZCConstants.VIEW_ADD_FORM || formAccessType == ZCConstants.VIEW_EDIT_FORM) { if(formAccessType == ZCConstants.VIEW_EDIT_FORM && zc_EditType != "default") { ZCApp.showFadingMsg(succMsg, 0, 5000); } else { closeDialog(); var viewParamsMap = ZCView.viewArr[ZCUtil.getFromMap(paramsMap, "viewLinkName")]; if(ZCUtil.getFromMap(viewParamsMap, "viewType") == ZCConstants.VIEW_CALENDAR) { if(formAccessType == ZCConstants.VIEW_EDIT_FORM) { var viewObject = ZCView.zc_calendar.fullCalendar('getView'); // No I18N var viewType = ZCView.calDisplayType(viewObject.name); ZCUtil.setInMap(viewParamsMap, "calViewType", viewType); // No I18N } else if(formAccessType == ZCConstants.VIEW_ADD_FORM) { var jsonStr = ZCUtil.getFromMap(formParamsMap, "dateJsonObject"); // No I18N if(!ZCUtil.isNull(jsonStr)) { jsonStr = jsonStr.replace(new RegExp('#zc_comma#','g'),","); jsonStr = jsonStr.replace(new RegExp('&#034,','g'),"\""); ZCUtil.setInMap(viewParamsMap, "dateJsonObject", jsonStr); // No I18N } } } ZCView.showView(viewParamsMap, succMsg, infoMsg, succMsgDuration, errorMsg); } } else if(!ZCUtil.isNull(processPayment) && processPayment==true) { ZCUtil.removeFromMap(formParamsMap, "client"); var params = ZCUtil.getParamsFromMap(formParamsMap); var args = "compLinkName="+formLinkName+"&formAccessType="+formAccessType+"&succMsg="+succMsg+"&compName=Form&compType="+ZCConstants.FORM; var infoMsgStr = ZCForm.convertInfoMsgObjToString(infoMsg); var paramsMap = ZCUtil.getParamsAsMap(args); paramsMap["infoMsg"]=new Array() paramsMap["infoMsg"][0] = infoMsgStr; paramsMap["errorMsg"]=new Array(); paramsMap["errorMsg"][0] = errorMsg; var isInIFrame = (window.top!=window.self) ? true : false; if(isInIFrame) { //Harishankar - Due to cross domain permission denial, href of current window is taken instead of top window //params = params + "&zc_pmtRetUrl=" + encodeURIComponent(window.top.location.href); params = params + "&zc_pmtRetUrl=" + encodeURIComponent(window.location.href); } else { params = params + "&zc_pmtRetUrl=" + encodeURIComponent(window.location.href); } if(window.location.href.indexOf("/form-perma/")!= -1 || window.location.href.indexOf("/view-perma/")!= -1) { params = params + "&isPermaPage=true"; } if(window.location.href.indexOf("/form-embed/")!= -1 || window.location.href.indexOf("/view-embed/")!= -1) { params = params + "&isPermaPage=true"; } ZCUtil.sendRequest("/formpaymentprocess.do", params, "html", "ZCForm.loadForm", paramsMap,i18n.loadingmsg,false); } else { ZCForm.showForm(formLinkName, formAccessType, infoMsg, errorMsg, succMsg, succMsgDuration); } } this.getInfoMsgHtml = function(actInfoMsg, errorMsg) { infoMsg = actInfoMsg; if(typeof(infoMsg) == "object") { infoMsg = ZCForm.convertInfoMsgObjToString(infoMsg); actInfoMsg = infoMsg; } if(infoMsg != "" && infoMsg != undefined) { infoMsg = infoMsg.replace(new RegExp('\r\n','g'), "<br>"); infoMsg = infoMsg.replace(new RegExp('\n','g'), "<br>"); infoMsg = infoMsg.replace(/\\n|\\r/g,"<br />"); infoMsg = infoMsg.replace(/\\t/g," "); infoMsg = infoMsg.replace(/\\\\/g,"@@@BSD@@@"); infoMsg = infoMsg.replace(/\\/g,""); infoMsg = infoMsg.replace(/@@@BSD@@@/g,"\\\\"); try { infoMsg = JSON.parse(infoMsg); // jshint ignore:line } catch (e) {} if (typeof(infoMsg) == "object") { //infoMsg comes as a json string assumption so we convert that to object and form an html var infoMsgHtml = "<table style='width:100%;' elname='errortable' border='0' cellpadding='0' cellspacing='0'><tbody>"; var userInfoMsgObj = ""; var infoHeaderMsgObj = ""; for(var wfType in infoMsg) { var infoMsgMap = infoMsg[wfType]; if(infoMsgMap["HeaderMsg"] != undefined) { userInfoMsgObj = infoMsgMap["UserMsgs"]; infoHeaderMsgObj = infoMsgMap["HeaderMsg"]; infoMsgHtml += "<tr><td valign='middle' class='zoho-black-small-text'><strong>"+infoHeaderMsgObj+"</strong></td></tr>"; if(userInfoMsgObj != "") { infoMsgHtml += "<tr><td valign='middle' class='zoho-black-small-text'>"; for(var msgtype in userInfoMsgObj) { var eachInfoMsg = userInfoMsgObj[msgtype]; eachInfoMsg = eachInfoMsg.replace(new RegExp(ZCConstants.REPLACE_DQ_CHAR,'g'),"\""); infoMsgHtml += eachInfoMsg+"<br><br>"; } infoMsgHtml += "</td></tr>"; } } } if(errorMsg != "" && errorMsg != undefined) { infoMsgHtml += "<tr><td valign='middle' class='zoho-black-small-text'>" + errorMsg + "</td></tr>"; } infoMsgHtml += "</tbody></table>"; return infoMsgHtml; } } if(errorMsg != "" && errorMsg != undefined) { return errorMsg; } return actInfoMsg; } this.showInfo = function(infoMsg, succMsg, formLinkName, formAccessType, errorMsg) { var infoMsgHtml = ZCForm.getInfoMsgHtml(infoMsg, errorMsg); if (infoMsgHtml == "") return; var linkStr = (!ZCUtil.isNull(succMsg))?i18n.viewlogdetails:i18n.viewerrordetails; //No I18N var formElem = ZCForm.getForm(formLinkName, formAccessType); if(succMsg && succMsg != "" && formAccessType != ZCConstants.FORM_ALONE) { ZCUtil.showInDialog(ZCApp.dialogAbove+infoMsgHtml+ZCApp.dialogBelow, "closeButton=no"); ZCUtil.removeInfoHdr(); } else { var errLogTR = $(formElem).find("tr[elName='zc-errorLogAlert']"); $(errLogTR).find("a[elName=errorLogAnc]").html(linkStr); $(errLogTR).show(); $(errLogTR).children().children().unbind("click"); $(errLogTR).children().children().click(function() { if(formAccessType != ZCConstants.FORM_ALONE || formAccessType == ZCConstants.VIEW_ADD_FORM || formAccessType == ZCConstants.VIEW_EDIT_FORM) { var ftable = $(formElem).find("table[elname='zc-formTable']"); if(ftable.length == 0) { ftable = $(formElem).find("table[elname='zc-form2Table']"); } if($(formElem).find("tr[elName=zc-infoMsgTag]")[0]) { var hCorr = 12; $(formElem).find("tr").remove("[elName=zc-infoMsgTag]"); if(!isViewBeta) { var hei = ftable.height(); hei = hei + $('#_DIALOG_CONTENT').find("div[elname='zc-dialogheader']").height(); $('#_DIALOG_CONTENT').height(hei + 12); var widnow = ftable.width(); $('#_DIALOG_CONTENT').find("div[elname='zc-dialogheader']").width(widnow - 8); } } else { var colValue = formElem.attr('colValue'); var cspan = 2; if(colValue == '2') cspan = 3; var infoMsgTag = "<tr tag='eleErr'elName='zc-infoMsgTag'><td class='zc-form-errormsg' width='100%' height='100%' valign='top' text-align='left' colspan='" + cspan + "'> "+infoMsgHtml+"</td></tr>"; $(infoMsgTag).insertBefore(ZCUtil.getParent($(formElem).find(":input[elName='zc-submitformbutton']"), "tr")); var freezeLayerHeight = $('#FreezeLayer_1').height(); var dialogLayerHeight = $('#_DIALOG_LAYER_1').height(); var dialogLayerTop = $('#_DIALOG_LAYER_1').position().top; var totalHeight = dialogLayerHeight + dialogLayerTop; if(totalHeight > freezeLayerHeight) { $('#FreezeLayer_1').height(totalHeight); } $('#_DIALOG_CONTENT').height('auto'); $('#_DIALOG_CONTENT').find("div[elname='zc-dialogheader']").width('auto'); } } else { ZCUtil.showInDialog(ZCApp.dialogAbove+infoMsgHtml+ZCApp.dialogBelow, "closeButton=yes, width=500px"); ZCUtil.removeInfoHdr(); var widnow = $('#_DIALOG_CONTENT').find("table[elname='errortable']").width(); if(widnow < 500) { widnow = 490; } $('#_DIALOG_CONTENT').find("div[elname='zc-dialogheader']").width(widnow); } }); } } this.clearErrors = function(formEl) { $(formEl).find("tr[tag=eleErr], div[tag=eleErr]").remove(); $(formEl).find("tr[elName=zc-errorLogAlert], div[elName=zc-errorLogAlert]").hide(); } this.showErrors = function(formLinkName, formAccessType, errMsg, alertMsg, fieldErrObj,subFormLabelName) { var formElem = ZCForm.getForm(formLinkName, formAccessType); var formFooterElem = $(formElem).find("tr[elName=zc-errorLogAlert], div[elName=zc-errorLogAlert]"); var colValue = formElem.attr('colValue'); var cspan = 2; if(colValue == '2') cspan = 3; var eleErrTemplate = this.zcFormAttributes['eleErrTemplate']; eleErrTemplate = eleErrTemplate.replace("insertColSpan", cspan); if(!ZCUtil.isNull(alertMsg)) { $(eleErrTemplate.replace("insertMessage", alertMsg)).insertBefore(formFooterElem); } if(!ZCUtil.isNull(errMsg)) { $(eleErrTemplate.replace("insertMessage", errMsg)).insertBefore(formFooterElem); } if(typeof(fieldErrObj) == "object") { for(var eachInsideObj in fieldErrObj) { var eachElem = fieldErrObj[eachInsideObj]; if(typeof(eachElem) == "object") { for(var eachElemName in eachElem) { var errorElem = eachElem[eachElemName]; var fieldEl = ZCForm.getField(formLinkName, eachElemName , formAccessType,subFormLabelName); ZCForm.showFieldErr(fieldEl, errorElem, subFormLabelName); if(this.focusElement == "") { this.focusElement = fieldEl; } } } } } } this.showFieldErr = function(fieldEl, errMsg, subFormLabelName) { //Harishankar - calculate the number of columns in existing rows of the table and set that as the column span for the new row if($(fieldEl)[0]) { if($(fieldEl).attr("type") == "radio" || ($(fieldEl).attr("type") == "checkbox" && $(fieldEl).attr("fieldtype") != 9)) { var optTbl = docid("opt-table-"+$(fieldEl).attr("formCompID")); fieldEl = $(ZCUtil.getParent(optTbl, "span")); } var fieldRow = $(ZCUtil.getParent(fieldEl, "tr")); var noOfCols = fieldRow.children("td").size();//No I18N if(ZCUtil.isNull(subFormLabelName)) { noOfCols = noOfCols + 1; } var errorTag = this.zcFormAttributes['eleErrTemplate']; errorTag = errorTag.replace("insertColSpan", noOfCols); errorTag = errorTag.replace("insertMessage", errMsg); errorTag = errorTag.replace("height='100%'", "height='25px'"); $(errorTag).insertAfter(ZCUtil.getParent(fieldEl, this.zcFormAttributes['fieldContainer'])); } } this.showHideCog = function(field, visibleStr, isRowAction) { if(this.inZohoCreator){ if(isRowAction){ $("#zc-rowaction-image").css("visibility", visibleStr);//No I18N }else{ ZCUtil.getParent(field, "td[elName=zc-fieldtd],div[elName=zc-fieldtd]").find("img[elName=zc-onchange-image]").css("visibility", visibleStr);//No I18N } } else { //show the revolving image } } this.correctURL = function(zcNextUrl) { if(zcNextUrl.indexOf("ht" + "tp:") == 0) { var slashIdx = zcNextUrl.indexOf("/"); var scheme = zcNextUrl.substr(0, slashIdx); if(zcNextUrl.charAt(slashIdx+1) != "/") { zcNextUrl = scheme + "//" + zcNextUrl.substr(slashIdx+1); } } return zcNextUrl; } this.showForm = function(formLinkName, formAccessType, infoMsg, errorMsg, succMsg, succMsgDuration) { var formParamsMap = ZCForm.formArr[formLinkName]; var zcNextUrl = ZCUtil.getFromMap(formParamsMap, "zc_NextUrl"); var zcSuccMsg = ZCUtil.getFromMap(formParamsMap, "zc_SuccMsg"); var zcOpenUrlIn = ZCUtil.getFromMap(formParamsMap, "zc_OpenUrlIn"); var zcLoadIn = ZCUtil.getFromMap(formParamsMap, "zc_LoadIn"); var clientAction = ZCUtil.getFromMap(formParamsMap, "client"); ZCUtil.setInMap(formParamsMap, "zc-mobile", ZCApp.isMobileSite);//No I18N succMsg = ZCUtil.isNull(zcSuccMsg)?succMsg:zcSuccMsg; if(!ZCUtil.isNull(succMsg) && succMsg != 'zc_success' && clientAction != "reset") { if(!ZCUtil.isNull(succMsgDuration)) { succMsgDuration = succMsgDuration*1000; ZCApp.showFadingMsg(succMsg, 0, succMsgDuration); } else { ZCApp.showFadingMsg(succMsg, 0, 2000); } } if(!ZCUtil.isNull(zcNextUrl) && clientAction != "reset") { closeDialog(); zcNextUrl = ZCForm.correctURL(zcNextUrl); if(zcLoadIn == "dialog" && zcNextUrl.indexOf("#Script:") != 0) { ZCApp.reloadZCComp(ZCUtil.getLinkName(zcNextUrl), ZCUtil.getParams(zcNextUrl)); return false; } else { var timeout = (zcNextUrl.indexOf("#") == 0)?0:5000; ZCUtil.setURLInLocationBar(zcNextUrl, zcOpenUrlIn, timeout); } } else { var formCont = ZCForm.getFormCont(formLinkName, formAccessType); ZCUtil.removeFromMap(formParamsMap, "client"); var params = ZCUtil.getParamsFromMap(formParamsMap); var args = "compLinkName="+formLinkName+"&formAccessType="+formAccessType+"&succMsg="+succMsg+"&compName=Form&compType="+ZCConstants.FORM; var infoMsgStr = ZCForm.convertInfoMsgObjToString(infoMsg); var paramsMap = ZCUtil.getParamsAsMap(args); paramsMap["infoMsg"]=new Array() paramsMap["infoMsg"][0] = infoMsgStr; paramsMap["errorMsg"]=new Array(); paramsMap["errorMsg"][0] = errorMsg; ZCUtil.sendRequest($(formCont).attr("formURL"), params, "html", "ZCForm.loadForm", paramsMap, i18n.loadingform); } } this.convertInfoMsgObjToString = function(infoMsg) { var infoMsgStr = ""; var i = 0; if(infoMsg != "" && infoMsg != undefined) { for(var wfType in infoMsg) { if(wfType.length>0) { i++; if (i != 1) { infoMsgStr += ","; } infoMsgStr += "\""+wfType+"\":"; var userInfoMsg = "{\"UserMsgs\":["; var infoHeaderMsg = ""; var infoMsgMap = infoMsg[wfType]; if(infoMsgMap["HeaderMsg"] != undefined) { var userInfoMsgObj = infoMsgMap["UserMsgs"]; var userInfoMsgStrList = ""; for(var msgtype in userInfoMsgObj) { if(msgtype > 0) { userInfoMsgStrList += ","; } var eachInfoMsg = userInfoMsgObj[msgtype]; eachInfoMsg = eachInfoMsg.replace(new RegExp('"','g'),ZCConstants.REPLACE_DQ_CHAR); userInfoMsgStrList += "\""+eachInfoMsg+"\""; } userInfoMsg += userInfoMsgStrList; infoHeaderMsg += ",\"HeaderMsg\":\""; infoHeaderMsg += infoMsgMap["HeaderMsg"]+"\"}"; } userInfoMsg += "]"; infoMsgStr += userInfoMsg + infoHeaderMsg; } } if(infoMsgStr.length > 1) { infoMsgStr = "{" + infoMsgStr + "}"; } while(infoMsgStr.indexOf("#zc_amp#")!= -1) { infoMsgStr=infoMsgStr.replace("#zc_amp#","&"); } } return infoMsgStr; } this.loadForm = function(respTxt, paramsMap, argsMap) { var infoMsg = ZCUtil.getFromMap(argsMap, "infoMsg"); var errorMsg = ZCUtil.getFromMap(argsMap, "errorMsg"); var succMsg = ZCUtil.getFromMap(argsMap, "succMsg"); var formLinkName = ZCUtil.getFromMap(argsMap, "compLinkName"); var formAccessType = ZCUtil.getFromMap(argsMap, "formAccessType"); ZCApp.loadZCComponent(respTxt, paramsMap, argsMap); if(!ZCUtil.isNull(infoMsg)|| !ZCUtil.isNull(errorMsg)) ZCForm.showInfo(infoMsg, succMsg, formLinkName, formAccessType, errorMsg); } this.changeImpMode = function(inputElem,elname) { var divElem =$("#zc-import-dialog"); if($(inputElem).val() == "pastedata") { $(divElem).find("div[elName=impDataFileSec]").hide(); $(divElem).find("div[elName=impPasteDataSec]").show(); $(divElem).find("div[elName=fileExtension]").show(); $(divElem).find("input[elName=headerRow]").prop("checked",false); } if($(inputElem).val() == "importfile") { $(divElem).find("div[elName=impPasteDataSec]").hide(); $(divElem).find("div[elName=impDataFileSec]").show(); $(divElem).find("div[elName=fileExtension]").hide(); $(divElem).find("input[elName=headerRow]").prop("checked","checked"); } } this.importData = function(formElem, formId) { if($(formElem).find("textarea[name=pData]").val() == '' && $(formElem).find("input[elName=writeDataRadio]").is(":checked")) { alert(i18n.pastedata); return false; } ZCUtil.sendRequest("/isFormBusy.do", "fid="+formId, "text", "ZCForm.submitImportForm", ZCUtil.setInMap(new Object(), "formElem", formElem), i18n.importing); //No I18N } this.submitImportForm = function(responseText, paramsMap, argsMap) { if(responseText == "true") { alertFormLiveBusy(); return false; } var formElem = $("#zc-import-dialog").find("form[elName=zc-import-form]"); $(formElem)[0].submit; } this.handleImportResp = function(respTxt, paramsMap, argsMap) { var responseArr = ZCForm.getMsgFromResponse(respTxt,""); var statusMsg = responseArr["statusMsg"]; if(statusMsg == "success") { closeDialog(); var viewLinkName = ZCUtil.getFromMap(paramsMap, "viewLinkName"); if(!ZCUtil.isNull(viewLinkName)) { ZCView.showView(ZCView.viewArr[viewLinkName], i18n.successmsg); } else { ZCApp.showFadingMsg(i18n.successmsg, 0, 2000); } } else { var errorMsg = responseArr["errorMsg"]; var errInfo = responseArr["info"]; if(!ZCUtil.isNull(errorMsg)) { alert(errorMsg); }else if(!ZCUtil.isNull(errInfo)) { alert(errInfo); }else { alert(i18n.dataerror); } } } this.updateEmbedField = function(el, formLinkName) { var param = $(el).val().trim(); if(paramValue!="") { if($(el).attr("elName").indexOf("Clr") != -1 && param.indexOf("#") == -1) { var colors = new Array("aqua","black","blue","fuchsia","gray","green","lime","maroon","navy","olive","purple","red","silver","teal","white","yellow"); if("rgb" != (param.substr(0,3).toLowerCase()) && colors.indexOf(param.toLowerCase()) == -1) { param = "#" + param; } } if($(el).attr("elName").indexOf("Height") != -1 || $(el).attr("elName").indexOf("Width") != -1){ if(param.indexOf("px") == -1 && param.indexOf("%") == -1){ param = param + "px"; //No I18N } } var paramValue = param.replace("#", "_"); paramValue = paramValue.replace("%", "_"); if(ZCForm.custParams.indexOf($(el).attr("elName"))!=-1) { ZCForm.removeParam(el); } ZCForm.custParams = ZCForm.custParams + ZCForm.checkForAnd(ZCForm.custParams) + $(el).attr("elName") + "=" + paramValue; if($(el).attr("elName").indexOf('Clr') != -1) { $(el).css("background-color", param); } } else { if(ZCForm.custParams.indexOf($(el).attr("elName"))!=-1) { ZCForm.removeParam(el); } } ZCApp.resetEmbedParams(formLinkName); } this.removeParam = function(el) { var elemIndex = ZCForm.custParams.indexOf($(el).attr("elName")); var initial = ZCForm.custParams.substring(0, elemIndex); var temp = ZCForm.custParams.substring(elemIndex); var last = ""; if(temp.indexOf("&")!=-1) { last = temp.substring(temp.indexOf("&")+1 , temp.length); } else { initial = initial.substring(0,initial.lastIndexOf("&")); } ZCForm.custParams = initial + last; } this.getEmbedParams = function(formLinkName) { var embediv = $('div[elName="zc-embed-dialog-div"]'); var successmsg = $(embediv).find("input[elName=zc-successmsg]").val(); var nexturl = $(embediv).find("input[elName=zc-nexturl]").val(); nexturl = ((nexturl.substring(0, 3)).indexOf("www") != -1)?"ht" + "tp:" + "//"+nexturl:nexturl; var openinparent = $(embediv).find("input[elName=zc-openinparent]").is(":checked"); var embedParams = ($(embediv).find("input[elName=zc-hidehdr]").is(":checked"))?"zc_Header=false":""; embedParams = ZCUtil.isNull(successmsg)?embedParams:embedParams+ ZCForm.checkForAnd(embedParams) +"zc_SuccMsg=" + successmsg; embedParams = ZCUtil.isNull(nexturl)?embedParams:embedParams+ ZCForm.checkForAnd(embedParams) +"zc_NextUrl="+nexturl; embedParams = ZCUtil.isNull(nexturl)?embedParams:(openinparent == true)?embedParams+"&zc_OpenUrlIn=parent":embedParams; if(ZCForm.custParams!=""&&embedParams!="") { embedParams = ZCForm.custParams + "&" + embedParams; } else { embedParams = ZCForm.custParams + embedParams; } return embedParams; } this.checkForAnd = function(checkVar) { var andifneed = checkVar!=""?"&":""; return andifneed; } this.showCustomize = function(el) { var embediv = $('div[elName="zc-embed-dialog-div"]'); $(embediv).find("td[comElName=zc-embed-left-td]").attr("class", "zc-dialog-viewtypes-normal"); $(embediv).find("table[comElName=zc-embed-table]").hide(); $(el).attr("class", "zc-dialog-viewtypes-selected"); var typestr = $(el).attr("elName"); $(embediv).find("table[elName="+typestr+ "]").show(); } this.alertFormLiveBusy = function() { alert(i18n.formulacalc); } this.toggleEmbedTag = function(el, selTab) { var tabTr = ZCUtil.getParent(el).find('td[comElName="zc-embed-crit-td"]'); for(var i = 0; i<tabTr.length; i++) { $(tabTr[i]).attr("class", "zc-dialog-viewtypes-normal-tab"); } $(el).attr("class", "zc-dialog-viewtypes-selected-tab"); var tabTable = ZCUtil.getParent(el,"td").find('[comElName="zc-embed-crit-table"]');//No I18N for(var i = 0; i<tabTable.length; i++) { if(selTab.match($(tabTable[i]).attr("elName"))) { $(tabTable[i]).show(); } else { $(tabTable[i]).hide(); } } } this.toggleEmbedProps = function(el) { var tableElem = ZCUtil.getParent(el).find('table[elName="zc-embed-props-table"]'); var imgElem = $(el).find('img')[0]; if(tableElem[0].style.display=="none") { $(imgElem).attr("src", $(imgElem).attr("src").replace("show","hide")); $(tableElem[0]).show(); }else { $(imgElem).attr("src", $(imgElem).attr("src").replace("hide","show")); $(tableElem[0]).hide(); } } this.showImportDialog = function(formLinkName) { params = ""; if(isViewBeta) { params = "&isViewBeta=true";//No I18N } ZCUtil.sendRequest("/showImportDialog.do", "formLinkName="+formLinkName + params, "html", "ZCForm.loadImportDialog", "", i18n.pleasewait); //No I18N } this.loadImportDialog = function(respTxt, paramsMap) { closeDialog(); ZCUtil.showDialog(respTxt, "false", "modal=yes, width=800px"); //No I18N //ZCUtil.showInDialog(respTxt, "closeButton=no, modal=yes, width=800px"); //No I18N } this.showImportError = function(zcErrMsg) { if(!ZCUtil.isNull(zcErrMsg)) { var alertMsg = i18n.importerror; if(zcErrMsg == "NOFILE") { alertMsg = i18n.nofiletoimport; } else { if(zcErrMsg == "EMPTYFILE") { alertMsg = i18n.emptyfiletoimport; } else if(zcErrMsg == "FILETOOLARGE") { alertMsg = i18n.largefiletoimport + "\n" + i18n.uploadmore; //No I18N } } alert(alertMsg); } } this.setImportMode = function(impModeEl) { var matchColsDiv = $("#ZC_IMPORTDATA_DIV").find("div[elName=UPDATE_ADD_DIV]"); if($(impModeEl).val() == "UPDATE_ADD") { matchColsDiv.show(); } else { matchColsDiv.hide(); matchColsDiv.find(":input[type=checkbox]").prop("checked", false); //No I18N } } this.toggleDataLoc = function(radioEl) { var radioVal = $(radioEl).val(); var impDataDiv = $("#ZC_IMPORTDATA_DIV"); if(radioVal == "PASTED_DATA") { impDataDiv.find("div[elName=WEBCLIENT_DIV]").show(); impDataDiv.find("div[elName=PASTED_DATA_DIV]").show(); impDataDiv.find("div[elName=LOCAL_DRIVE_DIV]").hide(); impDataDiv.find("div[elName=MIGRATION_DIV]").hide(); impDataDiv.find("div[elName=CLOUD_PICKER_DIV]").hide(); impDataDiv.find("div[elName=GOOGLE_DOCS_DIV]").hide(); } else if(radioVal == "CLOUD_PICKER") { impDataDiv.find("div[elName=WEBCLIENT_DIV]").show(); impDataDiv.find("div[elName=PASTED_DATA_DIV]").hide(); impDataDiv.find("div[elName=LOCAL_DRIVE_DIV]").hide(); impDataDiv.find("div[elName=CLOUD_PICKER_DIV]").show(); impDataDiv.find("div[elName=GOOGLE_DOCS_DIV]").hide(); impDataDiv.find("div[elName=MIGRATION_DIV]").hide(); } else if(radioVal == "GOOGLE_DOCS") { impDataDiv.find("div[elName=WEBCLIENT_DIV]").show(); impDataDiv.find("div[elName=PASTED_DATA_DIV]").hide(); impDataDiv.find("div[elName=LOCAL_DRIVE_DIV]").hide(); impDataDiv.find("div[elName=CLOUD_PICKER_DIV]").hide(); impDataDiv.find("div[elName=GOOGLE_DOCS_DIV]").show(); impDataDiv.find("div[elName=MIGRATION_DIV]").hide(); } else if(radioVal == "LOCAL_DRIVE") { impDataDiv.find("div[elName=WEBCLIENT_DIV]").show(); impDataDiv.find("div[elName=PASTED_DATA_DIV]").hide(); impDataDiv.find("div[elName=LOCAL_DRIVE_DIV]").show(); impDataDiv.find("div[elName=MIGRATION_DIV]").hide(); impDataDiv.find("div[elName=CLOUD_PICKER_DIV]").hide(); impDataDiv.find("div[elName=GOOGLE_DOCS_DIV]").hide(); } else if(radioVal == "MIGRATION") { impDataDiv.find("div[elName=PASTED_DATA_DIV]").hide(); impDataDiv.find("div[elName=LOCAL_DRIVE_DIV]").hide(); impDataDiv.find("div[elName=WEBCLIENT_DIV]").hide(); impDataDiv.find("div[elName=MIGRATION_DIV]").show(); impDataDiv.find("div[elName=CLOUD_PICKER_DIV]").hide(); impDataDiv.find("div[elName=GOOGLE_DOCS_DIV]").hide(); } } this.toggleScriptDiv = function() { var skipScriptDiv = $("#ZC_IMPORTDATA_DIV").find("div[elName=SKIP_SCRIPT_DIV]"); if($(skipScriptDiv).css("display") == "none") { $(skipScriptDiv).show(); } else { $(skipScriptDiv).hide(); } } this.continueImport = function(formElem) { var goAhead = ZCForm.checkInputs(formElem); if(goAhead) { ZCApp.showLoading("zc-loading"); //No I18N } return goAhead; } this.checkInputs = function(formElem) { if($(formElem).find(":input[name=IMPORT_MODE]").val() == "UPDATE_ADD") { var noCol = true; $.each($(formElem).find("div[elName=UPDATE_ADD_DIV]").find(":input[name=UPDATE_ADD_COLS]"), function(idx, elem) { if($(elem).is(":checked")) { noCol = false; } }); if(ZCUtil.isTrue(noCol)) { alert(i18n.nofldtomatch); return false; } } if($(formElem).find(":input[elName=PASTED_DATA_RADIO]").is(":checked")) { if($(formElem).find(":input[name=PASTED_DATA]").val() == "") { alert(i18n.plzpastedata); return false; } } if($(formElem).find(":input[elName=GOOGLE_DOCS_RADIO]").is(":checked")) { if($(formElem).find(":input[name=GDOC_ID]").val() == "") { alert(i18n.nofiletoimport); return false; } } return true; } this.toggleFirstRow = function(radioEl) { var previewDiv = $("#ZC_IMPORTDATA_DIV").find("div[elName=ZCIMPORT_PREVIEW_DIV]"); var hdrDataTR = $(previewDiv).find("tr[elName=ZCIMPORT_HDRDATA_TR]"); var hasHdrTR = $(previewDiv).find("tr[elName=ZCIMPORT_HASHDR_TR]"); var noHdrTR = $(previewDiv).find("tr[elName=ZCIMPORT_NOHDR_TR]"); if(ZCUtil.isTrue($(radioEl).val())) { $(hdrDataTR).hide(); $(noHdrTR).hide(); $(hasHdrTR).show(); } else { $(hdrDataTR).show(); $(hasHdrTR).hide(); $(noHdrTR).show(); } } this.toggleCSVSettings = function() { var importDiv = $("#ZC_IMPORTDATA_DIV"); var csvSettingsDiv = $(importDiv).find("div[elName=ZCIMPORT_CSVSETTINGS_DIV]"); var refPrevMsgDiv = $(importDiv).find("div[elName=ZCIMPORT_PREVIEW_REFRESH_DIV]"); if(ZCUtil.isHidden(csvSettingsDiv)) { $(csvSettingsDiv).show(); } else { $(csvSettingsDiv).hide(); } } this.refreshPreview = function(formLinkName, fileName) { var importDiv = $("#ZC_IMPORTDATA_DIV"); var csvSettingsDiv = $(importDiv).find("div[elName=ZCIMPORT_CSVSETTINGS_DIV]"); var urlParams = "ZCACTION=PARSEFILE&formLinkName="+formLinkName+"&FILENAME="+fileName; //No I18N urlParams += "&DELIMETER=" + $(csvSettingsDiv).find(":input[name=DELIMETER]").val(); //No I18N urlParams += "&HASFIELDNAMES="+$(importDiv).find(":input[elName=HASFIELDNAMES_RADIO]").is(":checked"); //No I18N urlParams += "&TEXT_QUALIFIER="+$(csvSettingsDiv).find(":input[name=TEXT_QUALIFIER]").val(); //No I18N urlParams += "&isViewBeta="+$(csvSettingsDiv).find(":input[name=isViewBeta]").val(); //No I18N var skipTopRows = $(csvSettingsDiv).find(":input[name=SKIP_TOP_ROWS]").val(); //No I18N if(!ZCUtil.isNull(skipTopRows)) { urlParams += "&SKIP_TOP_ROWS="+skipTopRows; //No I18N } var commentChar = $(csvSettingsDiv).find(":input[name=COMMENT_CHAR]").val(); //No I18N if(!ZCUtil.isNull(commentChar)) { urlParams += "&COMMENT_CHAR="+commentChar; //No I18N } ZCUtil.sendRequest("/importFormData.do", urlParams, "html", "ZCForm.reloadPreview", "", i18n.pleasewait); //No I18N } this.reloadPreview = function(respTxt) { $("#ZC_IMPORTDATA_DIV").find("div[elName=ZCIMPORT_PREVIEW_DIV]").html(respTxt); //No I18N } this.fieldOnChange = function(selectEl) { var previewDiv = $("#ZC_IMPORTDATA_DIV").find("div[elName=ZCIMPORT_PREVIEW_DIV]"); //No I18N var colIndex = $(selectEl).attr("colIndex"); var currFCLabelName = $(selectEl).val(); var noHdrTRElem = $(previewDiv).find("tr[elName=ZCIMPORT_NOHDR_TR]"); var hasHdrTRElem = $(previewDiv).find("tr[elName=ZCIMPORT_HASHDR_TR]"); if(currFCLabelName == -1) { $(hasHdrTRElem).find(":checkbox:eq("+colIndex+")").prop("checked", false); //No I18N $(noHdrTRElem).find(":checkbox:eq("+colIndex+")").prop("checked", false); //No I18N } else { $.each($(previewDiv).find("select"), function(colIDX, currSelectEl) { if(currFCLabelName == $(currSelectEl).val()) { var isChecked = (colIDX == colIndex); if(!ZCUtil.isTrue(isChecked)) { $(currSelectEl).val(-1); } $(hasHdrTRElem).find(":checkbox:eq("+colIDX+")").prop("checked", isChecked); //No I18N $(noHdrTRElem).find(":checkbox:eq("+colIDX+")").prop("checked", isChecked); //No I18N } }); } } this.checkColumn = function(checkBoxElem) { if(!ZCUtil.isTrue($(checkBoxElem).is(":checked"))) { $("#ZC_IMPORTDATA_DIV").find("div[elName=ZCIMPORT_PREVIEW_DIV]").find("select:eq("+$(checkBoxElem).attr("colIndex")+")").val(-1); //No I18N } } this.importFormData = function(formLinkName, importParamsJSON) { var importDiv = $("#ZC_IMPORTDATA_DIV"); //No I18N var previewDiv = $(importDiv).find("div[elName=ZCIMPORT_PREVIEW_DIV]"); //No I18N var labelTR = $(previewDiv).find("tr[elName=ZCIMPORT_LABEL_TR]"); //No I18N var hasFldNames = $(importDiv).find(":input[elName=HASFIELDNAMES_RADIO]").is(":checked"); //No I18N var headerTR = hasFldNames?$(previewDiv).find("tr[elName=ZCIMPORT_HASHDR_TR]"):$(previewDiv).find("tr[elName=ZCIMPORT_NOHDR_TR]"); //No I18N var importParams = "ZCACTION=IMPORT"; //No I18N importParams += "&formLinkName="+formLinkName; //No I18N importParams += "&HASFIELDNAMES="+hasFldNames; //No I18N importParams += "&DELIMETER="+$(importDiv).find(":input[name=DELIMETER]").val(); //No I18N importParams += "&TEXT_QUALIFIER="+$(importDiv).find(":input[name=TEXT_QUALIFIER]").val(); //No I18N importParams += "&SKIP_TOP_ROWS="+$(importDiv).find(":input[name=SKIP_TOP_ROWS]").val(); //No I18N importParams += "&ONIMPORTERROR="+$(importDiv).find(":input[name=ONIMPORTERROR]").val(); //No I18N importParams += "&isViewBeta="+$(importDiv).find(":input[name=isViewBeta]").val(); //No I18N var dateFormat = $(importDiv).find(":input[name=DATE_FORMAT]").val(); //No I18N if(!ZCUtil.isNull(dateFormat)) { importParams += "&DATE_FORMAT="+dateFormat; //No I18N } var commentChar = $(importDiv).find(":input[name=COMMENT_CHAR]").val(); //No I18N if(!ZCUtil.isNull(commentChar)) { importParams += "&DATE_FORMAT="+commentChar; //No I18N } var importSettings = ZCUtil.evalJSONObject(importParamsJSON); if(!ZCUtil.isNull(importSettings.FILENAME)) { var passFile = importSettings.FILENAME; var filename = $(importDiv).find("select[name=SHEET_NAME]").val(); if(filename != undefined) { passFile = filename; } importParams += "&FILENAME=" + encodeURIComponent(passFile); //No I18N } var datetype = $(importDiv).find("select[name=DATE_TYPE]").val(); if(!ZCUtil.isNull(datetype)) { importParams += "&DATE_TYPE=" + datetype; //No I18N } if(!ZCUtil.isNull(importSettings.IMPORT_MODE)) { importParams += "&IMPORT_MODE=" + importSettings.IMPORT_MODE; //No I18N } if(!ZCUtil.isNull(importSettings.SKIP_ONUPDATE)) { importParams += "&SKIP_ONUPDATE=" + importSettings.SKIP_ONUPDATE; //No I18N } if(!ZCUtil.isNull(importSettings.SKIP_ONSUBMIT)) { importParams += "&SKIP_ONSUBMIT=" + importSettings.SKIP_ONSUBMIT; //No I18N } if(!ZCUtil.isNull(importSettings.SKIP_ONCOMMIT)) { importParams += "&SKIP_ONCOMMIT=" + importSettings.SKIP_ONCOMMIT; //No I18N } if(!ZCUtil.isNull(importSettings.IMPORTSUBFORMDATA)) { importParams += "&IMPORTSUBFORMDATA=" + importSettings.IMPORTSUBFORMDATA; //No I18N } if(!ZCUtil.isNull(importSettings.MATCHING_COLUMNS)) { var matchColsArr = ZCUtil.evalJSONArray(importSettings.MATCHING_COLUMNS); for(var colCount = 0; colCount < matchColsArr.length; colCount++) { importParams += "&MATCHING_COLUMNS=" + matchColsArr[colCount]; } } var hasColsToImport = false; importParams += "&IMPORTCOLUMNS=<COLUMNS>" //No I18N $.each($(headerTR).find(":input[type=checkbox]"), function(idx, hdrElem) { var delugeName = $(labelTR).find(":input:eq("+idx+")").val(); var toImport = (ZCUtil.isTrue($(hdrElem).is(":checked")) && (delugeName != -1)); if(ZCUtil.isTrue(toImport)) { hasColsToImport = true; } importParams += "<COLUMN INDEX=\"" + (idx+1) + "\" DELUGENAME=\"" + delugeName + "\" IMPORT=\"" + toImport + "\" />"; //No I18N }); importParams += "</COLUMNS>"; //No I18N if(hasColsToImport) { ZCUtil.sendRequest("/importFormData.do", importParams, "html", "ZCForm.loadImportDialog", "", i18n.importingmsg); //No I18N } else { alert(i18n.selcols4imp); } } this.showHideImportError = function(clickEl) { var errorTR = ZCUtil.getParent(clickEl, "table").find("tr[elName=ZCERRORDETAILS]"); // No I18N if(ZCUtil.isTrue($(clickEl).attr("showError"))) { $(errorTR).show(); $(clickEl).attr("showError", false); $(clickEl).html(i18n.hideimperrors); } else { $(errorTR).hide(); $(clickEl).attr("showError", true); $(clickEl).html(i18n.showimperrors); } } this.closeImportDialog = function() { closeDialog(); if(ZCUtil.getFromMap(ZCApp.compNameVsTypeMap, ZCApp.currZCComp) == ZCConstants.VIEW) { ZCView.showView(ZCView.viewArr[ZCApp.currZCComp]); } } //Included by Harishankar for Grid-view type subform //Gets invoked when the Add link is clicked for adding a new row this.createNewSubFormRow = function(el, isRowActionNeeded){ var mainForm = $(el).parents('form'); var mainFormLinkName = $(mainForm).attr("name"); var formParamsMap = ZCForm.formArr[mainFormLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap,"formAccessType");//No I18N var formElem = $(el).parents('td[elname = subformtd]:first').find('div[elname = subformdiv]'); var maxRows = $(formElem).attr("maxRows"); if(maxRows == 0) { ZCApp.showErrorDialog(i18n.headererrormsg,i18n.cannoraddsubformrowmsg); return; } var subFormLabelName = $(formElem).attr("name"); $(formElem).find("tr[elName="+subFormLabelName+"_norecordrow]").css('display','none'); //$("#"+subFormLabelName+"_addNewLine").css('display',''); var name = $(formElem).attr("name"); var formCompID = $(formElem).attr("formcompid"); var nextRecordSequence = ZCUtil.isNull($(formElem).attr("nextRecordSequence"))?0:$(formElem).attr("nextRecordSequence"); var newSequence = parseInt(nextRecordSequence) + 1; var formTable = $(formElem).find("table[elName='zc-subFormTable']"); var className = $(formElem).find("tr[id='" + name + "_t::row']").attr("class"); var dataRows = $(formElem).find("tr[elName=dataRow]"); $.each($(dataRows),function(index,rowEl){ $(rowEl).find("td").css("border-bottom",""); }); var newRow = $(formElem).find("tr[id='" + name + "_t::row']").clone(); $(newRow).attr("id",name + "-" + nextRecordSequence); $(newRow).show(); $(newRow).find("td").css("border-bottom","none"); $(formElem).attr("nextRecordSequence",newSequence); $(formTable).children("tbody").append(newRow); $(newRow).attr("reclinkid",""); $(newRow).find(":input[id*='0'],:checkbox[id*='0'],:radio[id*='0'],:hidden[id*='0'],div[id*='0'],span[id*='0'],a[id*='0'],label[id*='0']").each( function(){ $(this).attr("id",$(this).attr("id").replace("row_0","row_"+nextRecordSequence)); } ); $(newRow).find(":input[name*='0'],:checkbox[name*='0'],:radio[name*='0'],:hidden[name*='0'],div[name*='0'],span[name*='0'],a[name*='0'],label[name*='0']").each( function(){ $(this).attr("name",$(this).attr("name").replace("row_0","row_"+nextRecordSequence)); } ); $(newRow).find("label[for*='0']").each( function(){ $(this).attr("for",$(this).attr("for").replace("_0","_"+nextRecordSequence)); } ); $(newRow).find("a[labelName*='0'],:file[labelName*='0']").each( function(){ $(this).attr("labelName",$(this).attr("labelName").replace("row_0","row_"+nextRecordSequence)); } ); $(newRow).find("span[rowNo*='0']").each( function(){ $(this).attr("rowNo",nextRecordSequence); } ); $(newRow).find(":input[rowLabelName*='0']").each( function(){ $(this).attr("rowLabelName",$(this).attr("rowLabelName").replace("_0","_"+nextRecordSequence)); } ); $(newRow).find("div[compositename*='0']").each( function(){ $(this).attr("compositename",$(this).attr("compositename").replace("_0","_"+nextRecordSequence)); } ); //Bind events to calendar and form elements in the new row $(newRow).find(":input[fieldType="+ZCConstants.DATE+"], :input[fieldType="+ZCConstants.DATE_TIME+"]").each(function() { var elID = $(this).attr("id"); var buttonID = "dateButtonEl_"+elID.substr(elID.indexOf("_")+1);// No I18N var shTime = ($(this).attr("fieldType") == ZCConstants.DATE_TIME)?true:false; var format = shTime?ZCApp.dateFormat + " " + ZCConstants.TIME_FORMAT:ZCApp.dateFormat; ZCForm.setUpCalendar(elID, buttonID, format, shTime); }); $(newRow).find(":input[type=radio], :input[type=checkbox]").click(function() { ZCForm.invokeOnChange(this, mainForm, formAccessType, formCompID); }); $(newRow).find(":input[type!=hidden][type!=reset][type!=submit][type!=button][type!=radio][type!=checkbox]").change(function() { if($(this).attr("type") == "file") { $(this).attr("changed", "changed"); } ZCForm.invokeOnChange(this, mainForm, formAccessType, formCompID); }); $(newRow).find("span[elname=zc-show-parent]").click(function() { ZCForm.showLookupForm(this); }); var randNum = Math.floor(Math.random() * 10000000); $(newRow).find("div[elName=zc-richtextarea]").each(function(index,elem){ $(this).attr("nameoftextarea",$(this).attr("nameoftextarea").replace("0",nextRecordSequence)); randNum = randNum+1; var defaultrow = $(formElem).find("tr[id='" + name + "_t::row']"); var disable = $(defaultrow).find("div[elname=zc-richtextarea]").attr("disablerichtext"); divID = randNum+""; $(elem).attr("id",divID); var divHeight = $(elem).attr("zc-editor-height"); divHeight = divHeight.substring(0, divHeight.length-2); var textAreaElem = $(elem).parents("td").find("textarea[formcompid="+$(elem).attr("textAreaName")+"]");//No I18N var rteContent = $(textAreaElem).val(); var toolsJson = $(textAreaElem).attr("zc-rtetToolsJson");//No I18N toolsJson = (ZCUtil.isNull(toolsJson) ? "" : JSON.parse(toolsJson));//No I18N var fontSizeJson = $(textAreaElem).attr("zc-rtetFontJson");//No I18N fontSizeJson = (ZCUtil.isNull(fontSizeJson) ? "" : JSON.parse(fontSizeJson));//No I18N var fontFamilyJson = $(textAreaElem).attr("zc-rtetFontFamilyJson"); //No I18n fontFamilyJson = (ZCUtil.isNull(fontFamilyJson) ? "" : JSON.parse(fontFamilyJson));//No I18N var initObj = {id : divID, content : rteContent, editorheight : divHeight, toolbar : toolsJson, fontsize : fontSizeJson, fontfamily : fontFamilyJson}; $(elem).html(""); ZCForm.createRichTextEditor(divID,initObj); if((disable=="true")) { var freezdivid = "freezdiv_" + $(this).attr("textareaname"); _editordiv = $("div[id=" + divID + "]"); var _RTEditor = ZCForm.editorRef[divID]; try { if(_RTEditor) { if(_RTEditor.mode == "plaintext") { $(_RTEditor._textarea).attr("disabled" , disable); } else { var _iframe = _RTEditor.iframe; var desMod = disable?"off":"on"; var ieMod = disable?"false":"true"; if(!($.browser.msie)) { setTimeout(function(){_RTEditor.doc.body.contentEditable=ieMod}, 100); _RTEditor.doc.designMode = desMod; } else { setTimeout(function(){_RTEditor.doc.body.contentEditable=ieMod}, 100); } } } } catch(e4){} var _newdiv = document.createElement("div"); _newdiv.className = "freezeLayer"; _newdiv.id = freezdivid; var _map = { "left":"0", "top":"0", "height":"100%", "width":"100%", "zIndex":50, "background":"#AAAAAA", "border":"1px solid #AAAAAA" }; $(_newdiv).css(_map); $(_editordiv).css("position","relative"); _editordiv[0].appendChild(_newdiv); } }); /* Lookup Search Reg-Event Starts */ $(newRow).find("div[elName=srchDiv]").each(function(){ $(this).attr("subFormRow",nextRecordSequence); }); var paramsMap = ZCForm.formArr[mainFormLinkName]; var formID = ZCUtil.getFromMap(paramsMap, "formID"); searchFactory.regLookupSearchEvents(newRow,formID,formAccessType,mainForm); $(newRow).find("div[elName=srchDiv]").each(function(i,element){ if($(element).attr("disable") == "true") { $(element).unbind(); } }); $(newRow).find("div[eleName=signature-field-subform]").each(function() { var signatureFieldObj = this; var signature = $(signatureFieldObj).find("div[eleName=signature]"); $(signatureFieldObj).find("span[eleName=signatureClear]").click(function() { $(signature).jSignature("reset"); }); $(signature).jSignature({'decor-color': 'transparent', 'height':'100', 'width':'300'}) $(signature).addClass("signature-div"); //No I18N var signatureEle = $(this).find("div[divName=signatureEle]"); if($(signatureEle).attr("isHide") === "true") { $(signatureEle).hide(); } }); /* Lookup Search Reg-Event Ends */ if(isRowActionNeeded) { ZCForm.invokeGridRowAction(formElem, mainForm, "t::row_" + nextRecordSequence, "onaddrow", formAccessType); } $(formElem).attr("maxRows",maxRows-1); if(!isViewBeta) { resizeDialog($(mainForm).parents("div[id=_DIALOG_CONTENT]:first")); //No I18N } } //Included by Harishankar for Grid-view type subform //Gets invoked when the delete link is clicked for deleting a row this.deleteSubFormRow = function(deleteLinkElement){ var parentTr = $(deleteLinkElement).parents('tr:first'); var mainForm = parentTr.parents('form'); var mainFormLinkName = $(mainForm).attr("name"); var formParamsMap = ZCForm.formArr[mainFormLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap,"formAccessType");//No I18N var recLinkId = parentTr.attr("reclinkid");// No I18N var formElem = parentTr.parents('div[elname = subformdiv]'); var maxRows = parseInt($(formElem).attr("maxRows")); var labelname = $(deleteLinkElement).attr('labelname'); var str1 = "SF(" + $(formElem).attr("name") +").FD("; var str2 = ").SV(ID)"; var rowID = labelname.split(str1)[1].split(str2)[0]; if(!ZCForm.invokeGridRowAction(formElem, mainForm, rowID, "ondeleterow", formAccessType)){ ZCForm.removeTR(mainForm, $(formElem).attr("name"), rowID); } $(formElem).attr("maxRows",maxRows+1); if(!isViewBeta) { resizeDialog($(mainForm).parents("div[id=_DIALOG_CONTENT]:first")); } } this.removeTR = function(mainForm, subfrmCmpName, rowID){ var formElem = mainForm.find('div[name='+ subfrmCmpName +']'); var labelName = "SF(" + subfrmCmpName +").FD(" + rowID + ").SV(ID)"; var deleteLinkElement = formElem.find("a[labelname='"+ labelName +"']"); var parentTr = $(deleteLinkElement).parents('tr:first'); var parentTable = $(parentTr).parents('table[elName=zc-subFormTable]'); var noOfTrs = $(parentTable).find("tr[elName=dataRow]").length; if(noOfTrs-1 == 1) { $(parentTable).find("tr[elName="+subfrmCmpName+"_norecordrow]").css('display',''); } var recLinkId = parentTr.attr("reclinkid");// No I18N /*if(recLinkId != null) { if(recLinkId.trim() != "") { $(parentTr).find(":input[elname=record_status]").attr("value","deleted"); $(parentTr).css("display","none"); } else { $(parentTr).remove(); } } else { $(parentTr).remove(); }*/ $(parentTr).remove(); } this.triggerExternalOnUser = function(exFldName) { try { if(exFldName == ExternalFieldName) { var ele = document.getElementById(exFldName); var onUserInput = ele.getAttribute("onChangeExists"); var isformula=ele.getAttribute("isFormulaExist"); var setdataatcell = ele.getAttribute("setdataatcell"); if(onUserInput == "true" || isformula=="true") { var formCompId = ele.getAttribute("formCompID"); var mainForm = $(ele).parents('form'); var mainFormLinkName = $(mainForm).attr("name"); var formParamsMap = ZCForm.formArr[mainFormLinkName]; var formAccessType = ZCUtil.getFromMap(formParamsMap,"formAccessType");//No I18N var formID = ZCUtil.getFromMap(formParamsMap,"formID"); var formElem = ZCForm.getForm(mainFormLinkName, formAccessType); if(onUserInput == "true") { onChangeScript(formElem,formID,formCompId); } if(isformula=="true") { executeFormula(formElem,formID,formCompId); } } else if(setdataatcell === "true") { ZCSheetView.updateZohoCrmVal(exFldName); } } ExternalFieldName = ''; } catch(e) { } } this.showhideFileUploadDiv = function(thisObj, showDiv) { var tableEl = $(thisObj).parents("[elName=zc-fieldtd]:first"); if($(tableEl).find(":input[type=file]").attr("isAttached") == "true") { alert(i18n.alreadyfileuploaded); return; } $(tableEl).find("[zc-type=fileUpload-Div]").hide(); $(tableEl).find("[zc-type=fileUpload-Div][elName="+ showDiv +"]").show(); var elName = $(thisObj).attr("name"); $(tableEl).find("[name="+ elName +"]").removeClass("selected"); $(tableEl).find("[name="+ elName +"]").removeClass("normal"); $(tableEl).find("[name="+ elName +"]").addClass("normal"); $(thisObj).removeClass("normal").addClass("selected"); } this.showhideImageDiv = function(thisObj, showDiv, labelName, type, isLocalImage) { var tableEl = $(thisObj).parents("[elName=zc-fieldtd]:first"); if ($(tableEl).find("[name=zcimagetype-"+labelName+"],[subname=zcimagetype-"+labelName+"]").attr("disabled") == true) { return; // Image field is disabled } $(tableEl).find("[zc-type=imageUpload-Div]").hide(); $(tableEl).find("[zc-type=imageUpload-Div][elName="+ showDiv +"]").show(); var elName = $(thisObj).attr("name"); $(tableEl).find("[name="+ elName +"]").removeClass("selected"); $(tableEl).find("[name="+ elName +"]").removeClass("normal"); $(tableEl).find("[name="+ elName +"]").addClass("normal"); $(thisObj).removeClass("normal").addClass("selected"); if(isLocalImage && type=='link') { $(tableEl).find("[name=zcsource-"+labelName+"]").val(''); $(tableEl).find("[subname=zcsource-"+labelName+"]").val(''); } if(isLocalImage && type=='local') { var iamgeval = $(tableEl).find("[name=zcsource-"+labelName+"]").attr('imagevalue'); $(tableEl).find("[name=zcsource-"+labelName+"]").val(iamgeval); var subiamgeval = $(tableEl).find("[subname=zcsource-"+labelName+"]").attr('imagevalue'); $(tableEl).find("[subname=zcsource-"+labelName+"]").val(subiamgeval); } if(type=='link') { $(tableEl).find("[name=zcimagetype-"+labelName+"]").val('1'); $(tableEl).find("[subname=zcimagetype-"+labelName+"]").val('1'); } else { $(tableEl).find("[name=zcimagetype-"+labelName+"]").val('2'); $(tableEl).find("[subname=zcimagetype-"+labelName+"]").val('2'); } } this.browseAttachEvent = function(thisObj) { $(thisObj).attr("zc-Attached-Type", "browse"); $(thisObj).attr("zc-DocId",""); $(thisObj).attr("isAttached","true"); $(thisObj).parents("[elName=zc-fieldtd]:first").find("[elName=zc-Browse-FileAttach]").show(); } this.googleDocAttachEvent = function(fileName, gDocId) { $("[isAttachOpen=true]:first").find("[elName=zc-GoogleDoc-FileName]").html(fileName); var El = $("[isAttachOpen=true]:first").find(":input[type=file]"); $(El).attr("zc-Attached-Type", "google"); $(El).attr("zc-DocId", gDocId); $(El).attr("isAttached","true"); $(El).attr("changed", "changed"); $(El).parent().html($(El).parent().html()); $("[isAttachOpen=true]:first").find("[elName=zc-GoogleDoc-Button]").hide(); $("[isAttachOpen=true]:first").find("[elName=zc-GoogleDoc-FileAttach]").show(); ZCForm.closeDocsAttachTemplate(); } this.isImport = false; this.cloudDocAttachEvent = function(docDetails, fileName) { if(this.isImport) { $("#cloudPickVal").val(docDetails); $("#cloudFileName").html(fileName); this.isImport = false; } else{ $("[isAttachOpen=true]:first").find("[elName=zc-CloudDoc-FileName]").html(fileName); var El = $("[isAttachOpen=true]:first").find(":input[type=file]"); $(El).attr("zc-Attached-Type", "cloud"); $(El).attr("zc-DocId", docDetails); $(El).attr("isAttached","true"); $(El).attr("changed", "changed"); $("[isAttachOpen=true]:first").find("[elName=zc-CloudDoc-Button]").hide(); $("[isAttachOpen=true]:first").find("[elName=zc-CloudDoc-FileAttach]").show(); } } this.openCloudPickerForImport = function(thisObj) { this.isImport= true; var docDiv = $("<div id=\"zc-gadgets_cloudpicker_div\"></div>"); docDiv.addClass("gadgets_cloudpicker_div"); docDiv.css("z-index", "99"); docDiv.append("<iframe class='gadgets_cloudpicker_iframe' style='' id='zc-file_attach_iframe' src='"+ clouddocurl +"'>") $("body").append(docDiv); } this.zohoDocAttachEvent = function(fileName, zDocId) { $("[isAttachOpen=true]:first").find("[elName=zc-ZohoDoc-FileName]").html(fileName); var El = $("[isAttachOpen=true]:first").find(":input[type=file]"); $(El).attr("zc-Attached-Type", "zoho"); $(El).attr("zc-DocId", zDocId); $(El).attr("isAttached","true"); $(El).attr("changed", "changed"); $(El).parent().html($(El).parent().html()); $("[isAttachOpen=true]:first").find("[elName=zc-ZohoDoc-Button]").hide(); $("[isAttachOpen=true]:first").find("[elName=zc-ZohoDoc-FileAttach]").show(); ZCForm.closeDocsAttachTemplate(); } this.openCloudAttachTemplate = function(thisObj) { $(thisObj).parents("[elName=zc-fieldtd]:first").attr("isattachopen", "true"); var docDiv = $("<div id=\"zc-gadgets_cloudpicker_div\"></div>"); docDiv.addClass("gadgets_cloudpicker_div"); var cloudService = $(thisObj).attr('cloudService'); var cloudPickUrl = fileCloudUrl.replace("=ZCCLOUD_OPT", "=" + cloudService); docDiv.append("<iframe class='gadgets_cloudpicker_iframe' style='' id='zc-file_attach_iframe' src='"+ cloudPickUrl +"'>") $("body").append(docDiv); } this.openDocsAttachTemplate = function(thisObj) { $(thisObj).parents("[elName=zc-fieldtd]:first").attr("isattachopen", "true"); var url = ''; if($(thisObj).attr("zc-Doc-Type") == "zoho") { url = zohodocurl; } else if($(thisObj).attr("zc-Doc-Type") == "google") { url = googledocurl; } ZCUtil.showDialog("<iframe class='file_attach_iframe' id='zc-file_attach_iframe' src='"+ url +"'>", "false", "modal=yes"); //No I18N $(".file_attach_iframe").parents(".dialog-border:first").removeClass("dialog-border"); } this.openImportGDocDialog = function() { $("#gFormName").attr("importOpen", true); ZCUtil.showDialog("<iframe class='file_attach_iframe' id='zc-file_attach_iframe' src='" + googlesheeturl + "'>", "false", "modal=yes"); //No I18N $(".file_attach_iframe").parents(".dialog-border:first").removeClass("dialog-border"); } this.closeDocsAttachTemplate = function() { $("[isAttachOpen=true]").attr("isAttachOpen", "false"); closeDialog(); } this.removeUploadedFile = function(thisObj) { var tableEl = $(thisObj).parents("[elName=zc-fieldtd]:first"); $(tableEl).find(":input[subtype=file]").attr("value",""); $(tableEl).find(":input[type=file]").attr("zc-Attached-Type","browse"); $(tableEl).find(":input[type=file]").attr("zc-DocId",""); $(tableEl).find(":input[type=file]").attr("isAttached","false"); $(tableEl).find(":input[type=file]").parent().html($(tableEl).find(":input[type=file]").parent().html()); $(tableEl).find("[elName=zc-GoogleDoc-FileName]").html(""); $(tableEl).find("[elName=zc-ZohoDoc-FileName]").html(""); $(tableEl).find("[elName=zc-GoogleDoc-Button]").show(); $(tableEl).find("[elName=zc-GoogleDoc-FileAttach]").hide(); $(tableEl).find("[elName=zc-ZohoDoc-Button]").show(); $(tableEl).find("[elName=zc-ZohoDoc-FileAttach]").hide(); $(tableEl).find("[elName=zc-Browse-FileAttach]").hide(); $(tableEl).find("[elName=zc-CloudDoc-Button]").show(); $(tableEl).find("[elName=zc-CloudDoc-FileAttach]").hide(); $(tableEl).find("[elName=zc-CloudDoc-FileName]").html(""); } }();
mohjaba/Health-Activity-Monitoring
1_code/www/Recommendation_files/form.js
JavaScript
gpl-2.0
185,459
(function ($) { /** * Drag and drop table rows with field manipulation. * * Using the drupal_add_tabledrag() function, any table with weights or parent * relationships may be made into draggable tables. Columns containing a field * may optionally be hidden, providing a better user experience. * * Created tableDrag instances may be modified with custom behaviors by * overriding the .onDrag, .onDrop, .row.onSwap, and .row.onIndent methods. * See blocks.js for an example of adding additional functionality to tableDrag. */ Drupal.behaviors.tableDrag = { attach: function (context, settings) { for (var base in settings.tableDrag) { $('#' + base, context).once('tabledrag', function () { // Create the new tableDrag instance. Save in the Drupal variable // to allow other scripts access to the object. Drupal.tableDrag[base] = new Drupal.tableDrag(this, settings.tableDrag[base]); }); } } }; /** * Constructor for the tableDrag object. Provides table and field manipulation. * * @param table * DOM object for the table to be made draggable. * @param tableSettings * Settings for the table added via drupal_add_dragtable(). */ Drupal.tableDrag = function (table, tableSettings) { var self = this; // Required object variables. this.table = table; this.tableSettings = tableSettings; this.dragObject = null; // Used to hold information about a current drag operation. this.rowObject = null; // Provides operations for row manipulation. this.oldRowElement = null; // Remember the previous element. this.oldY = 0; // Used to determine up or down direction from last mouse move. this.changed = false; // Whether anything in the entire table has changed. this.maxDepth = 0; // Maximum amount of allowed parenting. this.rtl = $(this.table).css('direction') == 'rtl' ? -1 : 1; // Direction of the table. // Configure the scroll settings. this.scrollSettings = { amount: 4, interval: 50, trigger: 70 }; this.scrollInterval = null; this.scrollY = 0; this.windowHeight = 0; // Check this table's settings to see if there are parent relationships in // this table. For efficiency, large sections of code can be skipped if we // don't need to track horizontal movement and indentations. this.indentEnabled = false; for (var group in tableSettings) { for (var n in tableSettings[group]) { if (tableSettings[group][n].relationship == 'parent') { this.indentEnabled = true; } if (tableSettings[group][n].limit > 0) { this.maxDepth = tableSettings[group][n].limit; } } } if (this.indentEnabled) { this.indentCount = 1; // Total width of indents, set in makeDraggable. // Find the width of indentations to measure mouse movements against. // Because the table doesn't need to start with any indentations, we // manually append 2 indentations in the first draggable row, measure // the offset, then remove. var indent = Drupal.theme('tableDragIndentation'); var testRow = $('<tr/>').addClass('draggable').appendTo(table); var testCell = $('<td/>').appendTo(testRow).prepend(indent).prepend(indent); this.indentAmount = $('.indentation', testCell).get(1).offsetLeft - $('.indentation', testCell).get(0).offsetLeft; testRow.remove(); } // Make each applicable row draggable. // Match immediate children of the parent element to allow nesting. $('> tr.draggable, > tbody > tr.draggable', table).each(function () { self.makeDraggable(this); }); // Add a link before the table for users to show or hide weight columns. $(table).before($('<a href="#" class="tabledrag-toggle-weight"></a>') .attr('title', Drupal.t('Re-order rows by numerical weight instead of dragging.')) .click(function () { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { self.hideColumns(); } else { self.showColumns(); } return false; }) .wrap('<div class="tabledrag-toggle-weight-wrapper"></div>') .parent() ); // Initialize the specified columns (for example, weight or parent columns) // to show or hide according to user preference. This aids accessibility // so that, e.g., screen reader users can choose to enter weight values and // manipulate form elements directly, rather than using drag-and-drop.. self.initColumns(); // Add mouse bindings to the document. The self variable is passed along // as event handlers do not have direct access to the tableDrag object. $(document).bind('mousemove', function (event) { return self.dragRow(event, self); }); $(document).bind('mouseup', function (event) { return self.dropRow(event, self); }); }; /** * Initialize columns containing form elements to be hidden by default, * according to the settings for this tableDrag instance. * * Identify and mark each cell with a CSS class so we can easily toggle * show/hide it. Finally, hide columns if user does not have a * 'Drupal.tableDrag.showWeight' cookie. */ Drupal.tableDrag.prototype.initColumns = function () { for (var group in this.tableSettings) { // Find the first field in this group. for (var d in this.tableSettings[group]) { var field = $('.' + this.tableSettings[group][d].target + ':first', this.table); if (field.length && this.tableSettings[group][d].hidden) { var hidden = this.tableSettings[group][d].hidden; var cell = field.closest('td'); break; } } // Mark the column containing this field so it can be hidden. if (hidden && cell[0]) { // Add 1 to our indexes. The nth-child selector is 1 based, not 0 based. // Match immediate children of the parent element to allow nesting. var columnIndex = $('> td', cell.parent()).index(cell.get(0)) + 1; $('> thead > tr, > tbody > tr, > tr', this.table).each(function () { // Get the columnIndex and adjust for any colspans in this row. var index = columnIndex; var cells = $(this).children(); cells.each(function (n) { if (n < index && this.colSpan && this.colSpan > 1) { index -= this.colSpan - 1; } }); if (index > 0) { cell = cells.filter(':nth-child(' + index + ')'); if (cell[0].colSpan && cell[0].colSpan > 1) { // If this cell has a colspan, mark it so we can reduce the colspan. cell.addClass('tabledrag-has-colspan'); } else { // Mark this cell so we can hide it. cell.addClass('tabledrag-hide'); } } }); } } // Now hide cells and reduce colspans unless cookie indicates previous choice. // Set a cookie if it is not already present. if ($.cookie('Drupal.tableDrag.showWeight') === null) { $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); this.hideColumns(); } // Check cookie value and show/hide weight columns accordingly. else { if ($.cookie('Drupal.tableDrag.showWeight') == 1) { this.showColumns(); } else { this.hideColumns(); } } }; /** * Hide the columns containing weight/parent form elements. * Undo showColumns(). */ Drupal.tableDrag.prototype.hideColumns = function () { // Hide weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', 'none'); // Show TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', ''); // Reduce the colspan of any effected multi-span columns. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan - 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Show row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 0, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'hide'); }; /** * Show the columns containing weight/parent form elements * Undo hideColumns(). */ Drupal.tableDrag.prototype.showColumns = function () { // Show weight/parent cells and headers. $('.tabledrag-hide', 'table.tabledrag-processed').css('display', ''); // Hide TableDrag handles. $('.tabledrag-handle', 'table.tabledrag-processed').css('display', 'none'); // Increase the colspan for any columns where it was previously reduced. $('.tabledrag-has-colspan', 'table.tabledrag-processed').each(function () { this.colSpan = this.colSpan + 1; }); // Change link text. $('.tabledrag-toggle-weight').text(Drupal.t('Hide row weights')); // Change cookie. $.cookie('Drupal.tableDrag.showWeight', 1, { path: Drupal.settings.basePath, // The cookie expires in one year. expires: 365 }); // Trigger an event to allow other scripts to react to this display change. $('table.tabledrag-processed').trigger('columnschange', 'show'); }; /** * Find the target used within a particular row and group. */ Drupal.tableDrag.prototype.rowSettings = function (group, row) { var field = $('.' + group, row); for (var delta in this.tableSettings[group]) { var targetClass = this.tableSettings[group][delta].target; if (field.is('.' + targetClass)) { // Return a copy of the row settings. var rowSettings = {}; for (var n in this.tableSettings[group][delta]) { rowSettings[n] = this.tableSettings[group][delta][n]; } return rowSettings; } } }; /** * Take an item and add event handlers to make it become draggable. */ Drupal.tableDrag.prototype.makeDraggable = function (item) { var self = this; // Create the handle. var handle = $('<a href="#" class="tabledrag-handle"><div class="handle">&nbsp;</div></a>').attr('title', Drupal.t('Drag to re-order')); // Insert the handle after indentations (if any). if ($('td:first .indentation:last', item).length) { $('td:first .indentation:last', item).after(handle); // Update the total width of indentation in this entire table. self.indentCount = Math.max($('.indentation', item).length, self.indentCount); } else { $('td:first', item).prepend(handle); } // Add hover action for the handle. handle.hover(function () { self.dragObject == null ? $(this).addClass('tabledrag-handle-hover') : null; }, function () { self.dragObject == null ? $(this).removeClass('tabledrag-handle-hover') : null; }); // Add the mousedown action for the handle. handle.mousedown(function (event) { // Create a new dragObject recording the event information. self.dragObject = {}; self.dragObject.initMouseOffset = self.getMouseOffset(item, event); self.dragObject.initMouseCoords = self.mouseCoords(event); if (self.indentEnabled) { self.dragObject.indentMousePos = self.dragObject.initMouseCoords; } // If there's a lingering row object from the keyboard, remove its focus. if (self.rowObject) { $('a.tabledrag-handle', self.rowObject.element).blur(); } // Create a new rowObject for manipulation of this row. self.rowObject = new self.row(item, 'mouse', self.indentEnabled, self.maxDepth, true); // Save the position of the table. self.table.topY = $(self.table).offset().top; self.table.bottomY = self.table.topY + self.table.offsetHeight; // Add classes to the handle and row. $(this).addClass('tabledrag-handle-hover'); $(item).addClass('drag'); // Set the document to use the move cursor during drag. $('body').addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'none'); } // Hack for Konqueror, prevent the blur handler from firing. // Konqueror always gives links focus, even after returning false on mousedown. self.safeBlur = false; // Call optional placeholder function. self.onDrag(); return false; }); // Prevent the anchor tag from jumping us to the top of the page. handle.click(function () { return false; }); // Similar to the hover event, add a class when the handle is focused. handle.focus(function () { $(this).addClass('tabledrag-handle-hover'); self.safeBlur = true; }); // Remove the handle class on blur and fire the same function as a mouseup. handle.blur(function (event) { $(this).removeClass('tabledrag-handle-hover'); if (self.rowObject && self.safeBlur) { self.dropRow(event, self); } }); // Add arrow-key support to the handle. handle.keydown(function (event) { // If a rowObject doesn't yet exist and this isn't the tab key. if (event.keyCode != 9 && !self.rowObject) { self.rowObject = new self.row(item, 'keyboard', self.indentEnabled, self.maxDepth, true); } var keyChange = false; switch (event.keyCode) { case 37: // Left arrow. case 63234: // Safari left arrow. keyChange = true; self.rowObject.indent(-1 * self.rtl); break; case 38: // Up arrow. case 63232: // Safari up arrow. var previousRow = $(self.rowObject.element).prev('tr').get(0); while (previousRow && $(previousRow).is(':hidden')) { previousRow = $(previousRow).prev('tr').get(0); } if (previousRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'up'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the previous top-level row. var groupHeight = 0; while (previousRow && $('.indentation', previousRow).length) { previousRow = $(previousRow).prev('tr').get(0); groupHeight += $(previousRow).is(':hidden') ? 0 : previousRow.offsetHeight; } if (previousRow) { self.rowObject.swap('before', previousRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, -groupHeight); } } else if (self.table.tBodies[0].rows[0] != previousRow || $(previousRow).is('.draggable')) { // Swap with the previous row (unless previous row is the first one // and undraggable). self.rowObject.swap('before', previousRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, -parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; case 39: // Right arrow. case 63235: // Safari right arrow. keyChange = true; self.rowObject.indent(1 * self.rtl); break; case 40: // Down arrow. case 63233: // Safari down arrow. var nextRow = $(self.rowObject.group).filter(':last').next('tr').get(0); while (nextRow && $(nextRow).is(':hidden')) { nextRow = $(nextRow).next('tr').get(0); } if (nextRow) { self.safeBlur = false; // Do not allow the onBlur cleanup. self.rowObject.direction = 'down'; keyChange = true; if ($(item).is('.tabledrag-root')) { // Swap with the next group (necessarily a top-level one). var groupHeight = 0; var nextGroup = new self.row(nextRow, 'keyboard', self.indentEnabled, self.maxDepth, false); if (nextGroup) { $(nextGroup.group).each(function () { groupHeight += $(this).is(':hidden') ? 0 : this.offsetHeight; }); var nextGroupRow = $(nextGroup.group).filter(':last').get(0); self.rowObject.swap('after', nextGroupRow); // No need to check for indentation, 0 is the only valid one. window.scrollBy(0, parseInt(groupHeight, 10)); } } else { // Swap with the next row. self.rowObject.swap('after', nextRow); self.rowObject.interval = null; self.rowObject.indent(0); window.scrollBy(0, parseInt(item.offsetHeight, 10)); } handle.get(0).focus(); // Regain focus after the DOM manipulation. } break; } if (self.rowObject && self.rowObject.changed == true) { $(item).addClass('drag'); if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } self.oldRowElement = item; self.restripeTable(); self.onDrag(); } // Returning false if we have an arrow key to prevent scrolling. if (keyChange) { return false; } }); // Compatibility addition, return false on keypress to prevent unwanted scrolling. // IE and Safari will suppress scrolling on keydown, but all other browsers // need to return false on keypress. http://www.quirksmode.org/js/keys.html handle.keypress(function (event) { switch (event.keyCode) { case 37: // Left arrow. case 38: // Up arrow. case 39: // Right arrow. case 40: // Down arrow. return false; } }); }; /** * Mousemove event handler, bound to document. */ Drupal.tableDrag.prototype.dragRow = function (event, self) { if (self.dragObject) { self.currentMouseCoords = self.mouseCoords(event); var y = self.currentMouseCoords.y - self.dragObject.initMouseOffset.y; var x = self.currentMouseCoords.x - self.dragObject.initMouseOffset.x; // Check for row swapping and vertical scrolling. if (y != self.oldY) { self.rowObject.direction = y > self.oldY ? 'down' : 'up'; self.oldY = y; // Update the old value. // Check if the window should be scrolled (and how fast). var scrollAmount = self.checkScroll(self.currentMouseCoords.y); // Stop any current scrolling. clearInterval(self.scrollInterval); // Continue scrolling if the mouse has moved in the scroll direction. if (scrollAmount > 0 && self.rowObject.direction == 'down' || scrollAmount < 0 && self.rowObject.direction == 'up') { self.setScroll(scrollAmount); } // If we have a valid target, perform the swap and restripe the table. var currentRow = self.findDropTargetRow(x, y); if (currentRow) { if (self.rowObject.direction == 'down') { self.rowObject.swap('after', currentRow, self); } else { self.rowObject.swap('before', currentRow, self); } self.restripeTable(); } } // Similar to row swapping, handle indentations. if (self.indentEnabled) { var xDiff = self.currentMouseCoords.x - self.dragObject.indentMousePos.x; // Set the number of indentations the mouse has been moved left or right. var indentDiff = Math.round(xDiff / self.indentAmount * self.rtl); // Indent the row with our estimated diff, which may be further // restricted according to the rows around this row. var indentChange = self.rowObject.indent(indentDiff); // Update table and mouse indentations. self.dragObject.indentMousePos.x += self.indentAmount * indentChange * self.rtl; self.indentCount = Math.max(self.indentCount, self.rowObject.indents); } return false; } }; /** * Mouseup event handler, bound to document. * Blur event handler, bound to drag handle for keyboard support. */ Drupal.tableDrag.prototype.dropRow = function (event, self) { // Drop row functionality shared between mouseup and blur events. if (self.rowObject != null) { var droppedRow = self.rowObject.element; // The row is already in the right place so we just release it. if (self.rowObject.changed == true) { // Update the fields in the dropped row. self.updateFields(droppedRow); // If a setting exists for affecting the entire group, update all the // fields in the entire dragged group. for (var group in self.tableSettings) { var rowSettings = self.rowSettings(group, droppedRow); if (rowSettings.relationship == 'group') { for (var n in self.rowObject.children) { self.updateField(self.rowObject.children[n], group); } } } self.rowObject.markChanged(); if (self.changed == false) { $(Drupal.theme('tableDragChangedWarning')).insertBefore(self.table).hide().fadeIn('slow'); self.changed = true; } } if (self.indentEnabled) { self.rowObject.removeIndentClasses(); } if (self.oldRowElement) { $(self.oldRowElement).removeClass('drag-previous'); } $(droppedRow).removeClass('drag').addClass('drag-previous'); self.oldRowElement = droppedRow; self.onDrop(); self.rowObject = null; } // Functionality specific only to mouseup event. if (self.dragObject != null) { $('.tabledrag-handle', droppedRow).removeClass('tabledrag-handle-hover'); self.dragObject = null; $('body').removeClass('drag'); clearInterval(self.scrollInterval); // Hack for IE6 that flickers uncontrollably if select lists are moved. if (navigator.userAgent.indexOf('MSIE 6.') != -1) { $('select', this.table).css('display', 'block'); } } }; /** * Get the mouse coordinates from the event (allowing for browser differences). */ Drupal.tableDrag.prototype.mouseCoords = function (event) { if (event.pageX || event.pageY) { return { x: event.pageX, y: event.pageY }; } return { x: event.clientX + document.body.scrollLeft - document.body.clientLeft, y: event.clientY + document.body.scrollTop - document.body.clientTop }; }; /** * Given a target element and a mouse event, get the mouse offset from that * element. To do this we need the element's position and the mouse position. */ Drupal.tableDrag.prototype.getMouseOffset = function (target, event) { var docPos = $(target).offset(); var mousePos = this.mouseCoords(event); return { x: mousePos.x - docPos.left, y: mousePos.y - docPos.top }; }; /** * Find the row the mouse is currently over. This row is then taken and swapped * with the one being dragged. * * @param x * The x coordinate of the mouse on the page (not the screen). * @param y * The y coordinate of the mouse on the page (not the screen). */ Drupal.tableDrag.prototype.findDropTargetRow = function (x, y) { var rows = $(this.table.tBodies[0].rows).not(':hidden'); for (var n = 0; n < rows.length; n++) { var row = rows[n]; var indentDiff = 0; var rowY = $(row).offset().top; // Because Safari does not report offsetHeight on table rows, but does on // table cells, grab the firstChild of the row and use that instead. // http://jacob.peargrove.com/blog/2006/technical/table-row-offsettop-bug-in-safari. if (row.offsetHeight == 0) { var rowHeight = parseInt(row.firstChild.offsetHeight, 10) / 2; } // Other browsers. else { var rowHeight = parseInt(row.offsetHeight, 10) / 2; } // Because we always insert before, we need to offset the height a bit. if ((y > (rowY - rowHeight)) && (y < (rowY + rowHeight))) { if (this.indentEnabled) { // Check that this row is not a child of the row being dragged. for (var n in this.rowObject.group) { if (this.rowObject.group[n] == row) { return null; } } } else { // Do not allow a row to be swapped with itself. if (row == this.rowObject.element) { return null; } } // Check that swapping with this row is allowed. if (!this.rowObject.isValidSwap(row)) { return null; } // We may have found the row the mouse just passed over, but it doesn't // take into account hidden rows. Skip backwards until we find a draggable // row. while ($(row).is(':hidden') && $(row).prev('tr').is(':hidden')) { row = $(row).prev('tr').get(0); } return row; } } return null; }; /** * After the row is dropped, update the table fields according to the settings * set for this table. * * @param changedRow * DOM object for the row that was just dropped. */ Drupal.tableDrag.prototype.updateFields = function (changedRow) { for (var group in this.tableSettings) { // Each group may have a different setting for relationship, so we find // the source rows for each separately. this.updateField(changedRow, group); } }; /** * After the row is dropped, update a single table field according to specific * settings. * * @param changedRow * DOM object for the row that was just dropped. * @param group * The settings group on which field updates will occur. */ Drupal.tableDrag.prototype.updateField = function (changedRow, group) { var rowSettings = this.rowSettings(group, changedRow); // Set the row as its own target. if (rowSettings.relationship == 'self' || rowSettings.relationship == 'group') { var sourceRow = changedRow; } // Siblings are easy, check previous and next rows. else if (rowSettings.relationship == 'sibling') { var previousRow = $(changedRow).prev('tr').get(0); var nextRow = $(changedRow).next('tr').get(0); var sourceRow = changedRow; if ($(previousRow).is('.draggable') && $('.' + group, previousRow).length) { if (this.indentEnabled) { if ($('.indentations', previousRow).length == $('.indentations', changedRow)) { sourceRow = previousRow; } } else { sourceRow = previousRow; } } else if ($(nextRow).is('.draggable') && $('.' + group, nextRow).length) { if (this.indentEnabled) { if ($('.indentations', nextRow).length == $('.indentations', changedRow)) { sourceRow = nextRow; } } else { sourceRow = nextRow; } } } // Parents, look up the tree until we find a field not in this group. // Go up as many parents as indentations in the changed row. else if (rowSettings.relationship == 'parent') { var previousRow = $(changedRow).prev('tr'); while (previousRow.length && $('.indentation', previousRow).length >= this.rowObject.indents) { previousRow = previousRow.prev('tr'); } // If we found a row. if (previousRow.length) { sourceRow = previousRow[0]; } // Otherwise we went all the way to the left of the table without finding // a parent, meaning this item has been placed at the root level. else { // Use the first row in the table as source, because it's guaranteed to // be at the root level. Find the first item, then compare this row // against it as a sibling. sourceRow = $(this.table).find('tr.draggable:first').get(0); if (sourceRow == this.rowObject.element) { sourceRow = $(this.rowObject.group[this.rowObject.group.length - 1]).next('tr.draggable').get(0); } var useSibling = true; } } // Because we may have moved the row from one category to another, // take a look at our sibling and borrow its sources and targets. this.copyDragClasses(sourceRow, changedRow, group); rowSettings = this.rowSettings(group, changedRow); // In the case that we're looking for a parent, but the row is at the top // of the tree, copy our sibling's values. if (useSibling) { rowSettings.relationship = 'sibling'; rowSettings.source = rowSettings.target; } var targetClass = '.' + rowSettings.target; var targetElement = $(targetClass, changedRow).get(0); // Check if a target element exists in this row. if (targetElement) { var sourceClass = '.' + rowSettings.source; var sourceElement = $(sourceClass, sourceRow).get(0); switch (rowSettings.action) { case 'depth': // Get the depth of the target row. targetElement.value = $('.indentation', $(sourceElement).closest('tr')).length; break; case 'match': // Update the value. targetElement.value = sourceElement.value; break; case 'order': var siblings = this.rowObject.findSiblings(rowSettings); if ($(targetElement).is('select')) { // Get a list of acceptable values. var values = []; $('option', targetElement).each(function () { values.push(this.value); }); var maxVal = values[values.length - 1]; // Populate the values in the siblings. $(targetClass, siblings).each(function () { // If there are more items than possible values, assign the maximum value to the row. if (values.length > 0) { this.value = values.shift(); } else { this.value = maxVal; } }); } else { // Assume a numeric input field. var weight = parseInt($(targetClass, siblings[0]).val(), 10) || 0; $(targetClass, siblings).each(function () { this.value = weight; weight++; }); } break; } } }; /** * Copy all special tableDrag classes from one row's form elements to a * different one, removing any special classes that the destination row * may have had. */ Drupal.tableDrag.prototype.copyDragClasses = function (sourceRow, targetRow, group) { var sourceElement = $('.' + group, sourceRow); var targetElement = $('.' + group, targetRow); if (sourceElement.length && targetElement.length) { targetElement[0].className = sourceElement[0].className; } }; Drupal.tableDrag.prototype.checkScroll = function (cursorY) { var de = document.documentElement; var b = document.body; var windowHeight = this.windowHeight = window.innerHeight || (de.clientHeight && de.clientWidth != 0 ? de.clientHeight : b.offsetHeight); var scrollY = this.scrollY = (document.all ? (!de.scrollTop ? b.scrollTop : de.scrollTop) : (window.pageYOffset ? window.pageYOffset : window.scrollY)); var trigger = this.scrollSettings.trigger; var delta = 0; // Return a scroll speed relative to the edge of the screen. if (cursorY - scrollY > windowHeight - trigger) { delta = trigger / (windowHeight + scrollY - cursorY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return delta * this.scrollSettings.amount; } else if (cursorY - scrollY < trigger) { delta = trigger / (cursorY - scrollY); delta = (delta > 0 && delta < trigger) ? delta : trigger; return -delta * this.scrollSettings.amount; } }; Drupal.tableDrag.prototype.setScroll = function (scrollAmount) { var self = this; this.scrollInterval = setInterval(function () { // Update the scroll values stored in the object. self.checkScroll(self.currentMouseCoords.y); var aboveTable = self.scrollY > self.table.topY; var belowTable = self.scrollY + self.windowHeight < self.table.bottomY; if (scrollAmount > 0 && belowTable || scrollAmount < 0 && aboveTable) { window.scrollBy(0, scrollAmount); } }, this.scrollSettings.interval); }; Drupal.tableDrag.prototype.restripeTable = function () { // :even and :odd are reversed because jQuery counts from 0 and // we count from 1, so we're out of sync. // Match immediate children of the parent element to allow nesting. $('> tbody > tr.draggable:visible, > tr.draggable:visible', this.table) .removeClass('odd even') .filter(':odd').addClass('even').end() .filter(':even').addClass('odd'); }; /** * Stub function. Allows a custom handler when a row begins dragging. */ Drupal.tableDrag.prototype.onDrag = function () { return null; }; /** * Stub function. Allows a custom handler when a row is dropped. */ Drupal.tableDrag.prototype.onDrop = function () { return null; }; /** * Constructor to make a new object to manipulate a table row. * * @param tableRow * The DOM element for the table row we will be manipulating. * @param method * The method in which this row is being moved. Either 'keyboard' or 'mouse'. * @param indentEnabled * Whether the containing table uses indentations. Used for optimizations. * @param maxDepth * The maximum amount of indentations this row may contain. * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row = function (tableRow, method, indentEnabled, maxDepth, addClasses) { this.element = tableRow; this.method = method; this.group = [tableRow]; this.groupDepth = $('.indentation', tableRow).length; this.changed = false; this.table = $(tableRow).closest('table').get(0); this.indentEnabled = indentEnabled; this.maxDepth = maxDepth; this.direction = ''; // Direction the row is being moved. if (this.indentEnabled) { this.indents = $('.indentation', tableRow).length; this.children = this.findChildren(addClasses); this.group = $.merge(this.group, this.children); // Find the depth of this entire group. for (var n = 0; n < this.group.length; n++) { this.groupDepth = Math.max($('.indentation', this.group[n]).length, this.groupDepth); } } }; /** * Find all children of rowObject by indentation. * * @param addClasses * Whether we want to add classes to this row to indicate child relationships. */ Drupal.tableDrag.prototype.row.prototype.findChildren = function (addClasses) { var parentIndentation = this.indents; var currentRow = $(this.element, this.table).next('tr.draggable'); var rows = []; var child = 0; while (currentRow.length) { var rowIndentation = $('.indentation', currentRow).length; // A greater indentation indicates this is a child. if (rowIndentation > parentIndentation) { child++; rows.push(currentRow[0]); if (addClasses) { $('.indentation', currentRow).each(function (indentNum) { if (child == 1 && (indentNum == parentIndentation)) { $(this).addClass('tree-child-first'); } if (indentNum == parentIndentation) { $(this).addClass('tree-child'); } else if (indentNum > parentIndentation) { $(this).addClass('tree-child-horizontal'); } }); } } else { break; } currentRow = currentRow.next('tr.draggable'); } if (addClasses && rows.length) { $('.indentation:nth-child(' + (parentIndentation + 1) + ')', rows[rows.length - 1]).addClass('tree-child-last'); } return rows; }; /** * Ensure that two rows are allowed to be swapped. * * @param row * DOM object for the row being considered for swapping. */ Drupal.tableDrag.prototype.row.prototype.isValidSwap = function (row) { if (this.indentEnabled) { var prevRow, nextRow; if (this.direction == 'down') { prevRow = row; nextRow = $(row).next('tr').get(0); } else { prevRow = $(row).prev('tr').get(0); nextRow = row; } this.interval = this.validIndentInterval(prevRow, nextRow); // We have an invalid swap if the valid indentations interval is empty. if (this.interval.min > this.interval.max) { return false; } } // Do not let an un-draggable first row have anything put before it. if (this.table.tBodies[0].rows[0] == row && $(row).is(':not(.draggable)')) { return false; } return true; }; /** * Perform the swap between two rows. * * @param position * Whether the swap will occur 'before' or 'after' the given row. * @param row * DOM element what will be swapped with the row group. */ Drupal.tableDrag.prototype.row.prototype.swap = function (position, row) { Drupal.detachBehaviors(this.group, Drupal.settings, 'move'); $(row)[position](this.group); Drupal.attachBehaviors(this.group, Drupal.settings); this.changed = true; this.onSwap(row); }; /** * Determine the valid indentations interval for the row at a given position * in the table. * * @param prevRow * DOM object for the row before the tested position * (or null for first position in the table). * @param nextRow * DOM object for the row after the tested position * (or null for last position in the table). */ Drupal.tableDrag.prototype.row.prototype.validIndentInterval = function (prevRow, nextRow) { var minIndent, maxIndent; // Minimum indentation: // Do not orphan the next row. minIndent = nextRow ? $('.indentation', nextRow).length : 0; // Maximum indentation: if (!prevRow || $(prevRow).is(':not(.draggable)') || $(this.element).is('.tabledrag-root')) { // Do not indent: // - the first row in the table, // - rows dragged below a non-draggable row, // - 'root' rows. maxIndent = 0; } else { // Do not go deeper than as a child of the previous row. maxIndent = $('.indentation', prevRow).length + ($(prevRow).is('.tabledrag-leaf') ? 0 : 1); // Limit by the maximum allowed depth for the table. if (this.maxDepth) { maxIndent = Math.min(maxIndent, this.maxDepth - (this.groupDepth - this.indents)); } } return { 'min': minIndent, 'max': maxIndent }; }; /** * Indent a row within the legal bounds of the table. * * @param indentDiff * The number of additional indentations proposed for the row (can be * positive or negative). This number will be adjusted to nearest valid * indentation level for the row. */ Drupal.tableDrag.prototype.row.prototype.indent = function (indentDiff) { // Determine the valid indentations interval if not available yet. if (!this.interval) { var prevRow = $(this.element).prev('tr').get(0); var nextRow = $(this.group).filter(':last').next('tr').get(0); this.interval = this.validIndentInterval(prevRow, nextRow); } // Adjust to the nearest valid indentation. var indent = this.indents + indentDiff; indent = Math.max(indent, this.interval.min); indent = Math.min(indent, this.interval.max); indentDiff = indent - this.indents; for (var n = 1; n <= Math.abs(indentDiff); n++) { // Add or remove indentations. if (indentDiff < 0) { $('.indentation:first', this.group).remove(); this.indents--; } else { $('td:first', this.group).prepend(Drupal.theme('tableDragIndentation')); this.indents++; } } if (indentDiff) { // Update indentation for this row. this.changed = true; this.groupDepth += indentDiff; this.onIndent(); } return indentDiff; }; /** * Find all siblings for a row, either according to its subgroup or indentation. * Note that the passed-in row is included in the list of siblings. * * @param settings * The field settings we're using to identify what constitutes a sibling. */ Drupal.tableDrag.prototype.row.prototype.findSiblings = function (rowSettings) { var siblings = []; var directions = ['prev', 'next']; var rowIndentation = this.indents; for (var d = 0; d < directions.length; d++) { var checkRow = $(this.element)[directions[d]](); while (checkRow.length) { // Check that the sibling contains a similar target field. if ($('.' + rowSettings.target, checkRow)) { // Either add immediately if this is a flat table, or check to ensure // that this row has the same level of indentation. if (this.indentEnabled) { var checkRowIndentation = $('.indentation', checkRow).length; } if (!(this.indentEnabled) || (checkRowIndentation == rowIndentation)) { siblings.push(checkRow[0]); } else if (checkRowIndentation < rowIndentation) { // No need to keep looking for siblings when we get to a parent. break; } } else { break; } checkRow = $(checkRow)[directions[d]](); } // Since siblings are added in reverse order for previous, reverse the // completed list of previous siblings. Add the current row and continue. if (directions[d] == 'prev') { siblings.reverse(); siblings.push(this.element); } } return siblings; }; /** * Remove indentation helper classes from the current row group. */ Drupal.tableDrag.prototype.row.prototype.removeIndentClasses = function () { for (var n in this.children) { $('.indentation', this.children[n]) .removeClass('tree-child') .removeClass('tree-child-first') .removeClass('tree-child-last') .removeClass('tree-child-horizontal'); } }; /** * Add an asterisk or other marker to the changed row. */ Drupal.tableDrag.prototype.row.prototype.markChanged = function () { var marker = Drupal.theme('tableDragChangedMarker'); var cell = $('td:first', this.element); if ($('span.tabledrag-changed', cell).length == 0) { cell.append(marker); } }; /** * Stub function. Allows a custom handler when a row is indented. */ Drupal.tableDrag.prototype.row.prototype.onIndent = function () { return null; }; /** * Stub function. Allows a custom handler when a row is swapped. */ Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) { return null; }; Drupal.theme.prototype.tableDragChangedMarker = function () { return '<span class="warning tabledrag-changed">*</span>'; }; Drupal.theme.prototype.tableDragIndentation = function () { return '<div class="indentation">&nbsp;</div>'; }; Drupal.theme.prototype.tableDragChangedWarning = function () { return '<div class="tabledrag-changed-warning messages warning">' + Drupal.theme('tableDragChangedMarker') + ' ' + Drupal.t('Changes made in this table will not be saved until the form is submitted.') + '</div>'; }; })(jQuery); ; Drupal.locale = { 'pluralFormula': function ($n) { return Number(($n!=1)); }, 'strings': {"":{"All":"Todo(s)","OK":"OK","all":"todo","none":"ninguno"}} };;
kenorb-contrib/eid
sites/default/files/js/js_trYML-tyi_lsxuEEYX3YJChhmBiEWLjQ6cxOAGnjOVU.js
JavaScript
gpl-2.0
42,157
/*jslint browser: true, white: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, newcap: true, immed: true, indent: 4, onevar: false */ /*global window, $, jQuery, _ */ STUDIP.register = { re_username : null, re_email: null, re_name: null, clearErrors: function (field) { jQuery('input[name=' + field + ']').parent().find('div').remove(); }, addError: function (field, error) { jQuery('input[name=' + field + ']').parent().append('<div class="error">' + error + '</div>'); jQuery('div[class=error]').show(); }, checkusername: function () { STUDIP.register.clearErrors('username'); var checked = true; if (jQuery('input[name=username]').val().length < 4) { STUDIP.register.addError('username', "Der Benutzername ist zu kurz, er sollte mindestens 4 Zeichen lang sein.".toLocaleString()); document.login.username.focus(); checked = false; } if (STUDIP.register.re_username.test(jQuery('input[name=username]').val()) === false) { STUDIP.register.addError('username', "Der Benutzername enthält unzulässige Zeichen, er darf keine Sonderzeichen oder Leerzeichen enthalten.".toLocaleString()); document.login.username.focus(); checked = false; } return checked; }, checkpassword: function () { STUDIP.register.clearErrors('password'); var checked = true; if (jQuery('input[name=password]').val().length < 4) { STUDIP.register.addError('password', "Das Passwort ist zu kurz, es sollte mindestens 4 Zeichen lang sein.".toLocaleString()); document.login.password.focus(); checked = false; } return checked; }, checkpassword2: function () { STUDIP.register.clearErrors('password2'); var checked = true; if (jQuery('input[name=password]').val() !== jQuery('input[name=password2]').val()) { STUDIP.register.addError('password2', "Das Passwort stimmt nicht mit dem Bestätigungspasswort überein!".toLocaleString()); document.login.password2.focus(); checked = false; } return checked; }, checkVorname: function () { STUDIP.register.clearErrors('Vorname'); var checked = true; if (STUDIP.register.re_name.test(jQuery('input[name=Vorname]').val()) === false) { STUDIP.register.addError('Vorname', "Bitte geben Sie Ihren tatsächlichen Vornamen an.".toLocaleString()); document.login.Vorname.focus(); checked = false; } return checked; }, checkNachname: function () { STUDIP.register.clearErrors('Nachname'); var checked = true; if (STUDIP.register.re_name.test(jQuery('input[name=Nachname]').val()) === false) { STUDIP.register.addError('Nachname', "Bitte geben Sie Ihren tatsächlichen Nachnamen an.".toLocaleString()); document.login.Nachname.focus(); checked = false; } return checked; }, checkEmail: function () { STUDIP.register.clearErrors('Email'); var Email = jQuery('input[name=Email]').val(); var checked = true; if ((STUDIP.register.re_email.test(Email)) === false || Email.length === 0) { STUDIP.register.addError('Email', "Die E-Mail-Adresse ist nicht korrekt!".toLocaleString()); document.login.Email.focus(); checked = false; } return checked; }, checkdata: function () { return this.checkusername() && this.checkpassword() && this.checkpassword2() && this.checkVorname() && this.checkNachname() && this.checkEmail(); } };
kurvenschubser/studip-hks
public/assets/javascripts/register.js
JavaScript
gpl-2.0
3,919
/* ========================================================= * params/all.js v0.0.1 * ========================================================= * Copyright 2012 Wpbakery * * Visual composer javascript functions to enable fields. * This script loads with settings form. * ========================================================= */ var wpb_change_tab_title, wpb_change_accordion_tab_title; !function($) { wpb_change_tab_title = function($element, field) { $('.tabs_controls a[href=#tab-' + $(field).val() +']').text($('.wpb-edit-form [name=title].wpb_vc_param_value').val()); }; wpb_change_accordion_tab_title = function($element, field) { var $section_title = $element.prev(); $section_title.find('a').text($(field).val()); }; function init_textarea_html($element) { /* Simple version without all this buttons from Wordpress tinyMCE.init({ mode : "textareas", theme: 'advanced', editor_selector: $element.attr('name') + '_tinymce' }); */ if($('#wp-link').parent().hasClass('wp-dialog')) $('#wp-link').wpdialog('destroy'); var qt, textfield_id = $element.attr("id"), $form_line = $element.closest('.edit_form_line'), $content_holder = $form_line.find('.vc_textarea_html_content'), content = $content_holder.val(); window.tinyMCEPreInit.mceInit[textfield_id] = _.extend({}, tinyMCEPreInit.mceInit['content']); if(_.isUndefined(tinyMCEPreInit.qtInit[textfield_id])) { window.tinyMCEPreInit.qtInit[textfield_id] = _.extend({}, tinyMCEPreInit.qtInit['replycontent'], {id: textfield_id}) } $element.val($content_holder.val()); qt = quicktags( window.tinyMCEPreInit.qtInit[textfield_id] ); QTags._buttonsInit(); window.switchEditors.go(textfield_id, 'tmce'); if(tinymce.majorVersion === "4") tinymce.execCommand( 'mceAddEditor', true, textfield_id ); /// window.tinyMCE.get(textfield_id).focus(); } function init_textarea_html_old($element) { var textfield_id = $element.attr("id"), $form_line = $element.closest('.edit_form_line'), $content_holder = $form_line.find('.vc_textarea_html_content'); $('#' + textfield_id +'-html').trigger('click'); $('.switch-tmce').trigger('click'); $form_line.find('.wp-switch-editor').removeAttr("onclick"); $('.switch-tmce').trigger('click'); $element.closest('.edit_form_line').find('.switch-tmce').click(function () { window.tinyMCE.execCommand("mceAddControl", true, textfield_id); window.switchEditors.go(textfield_id, 'tmce'); $element.closest('.edit_form_line').find('.wp-editor-wrap').removeClass('html-active').addClass('tmce-active'); var val = window.switchEditors.wpautop($(this).closest('.edit_form_line').find("textarea.visual_composer_tinymce").val()); $("textarea.visual_composer_tinymce").val(val); // Add tinymce window.tinyMCE.execCommand("mceAddControl", true, textfield_id); }); $element.closest('.edit_form_line').find('.switch-html').click(function () { $element.closest('.edit_form_line').find('.wp-editor-wrap').removeClass('tmce-active').addClass('html-active'); window.tinyMCE.execCommand("mceRemoveControl", true, textfield_id); }); $('#wpb_tinymce_content-html').trigger('click'); $('#wpb_tinymce_content-tmce').trigger('click'); // Fix hidden toolbar } // TODO: unsecure. Think about it Color.prototype.toString = function() { if(this._alpha < 1) { return this.toCSS('rgba', this._alpha).replace(/\s+/g, ''); } var hex = parseInt( this._color, 10 ).toString( 16 ); if ( this.error ) return ''; // maybe left pad it if ( hex.length < 6 ) { for (var i = 6 - hex.length - 1; i >= 0; i--) { hex = '0' + hex; } } return '#' + hex; }; $('.vc-color-control').each(function(){ var $control = $(this), value = $control.val().replace(/\s+/g, ''), alpha_val = 100, $alpha, $alpha_output; if(value.match(/rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/)) { alpha_val = parseFloat(value.match(/rgba\(\d+\,\d+\,\d+\,([^\)]+)\)/)[1])*100; } $control.wpColorPicker({ clear: function(event, ui) { $alpha.val(100); $alpha_output.val(100 + '%'); } }); $('<div class="vc-alpha-container">' + '<label>Alpha: <output class="rangevalue">' + alpha_val +'%</output></label>' + '<input type="range" min="1" max="100" value="' + alpha_val +'" name="alpha" class="vc-alpha-field">' + '</div>').appendTo($control.parents('.wp-picker-container:first').addClass('vc-color-picker').find('.iris-picker')); $alpha = $control.parents('.wp-picker-container:first').find('.vc-alpha-field'); $alpha_output = $control.parents('.wp-picker-container:first').find('.vc-alpha-container output') $alpha.bind('change keyup', function(){ var alpha_val = parseFloat($alpha.val()), iris = $control.data('a8cIris'), color_picker = $control.data('wpWpColorPicker'); $alpha_output.val($alpha.val() + '%'); iris._color._alpha = alpha_val/100.0; $control.val(iris._color.toString()); color_picker.toggler.css( { backgroundColor: $control.val() }); }).val(alpha_val).trigger('change'); }); var InitGalleries = function() { var that = this; // TODO: Backbone style for view binding $('.gallery_widget_attached_images_list', this.$view).unbind('click.removeImage').on('click.removeImage', 'a.icon-remove', function(e){ e.preventDefault(); var $block = $(this).closest('.edit_form_line'); $(this).parent().remove(); var img_ids = []; $block.find('.added img').each(function () { img_ids.push($(this).attr("rel")); }); $block.find('.gallery_widget_attached_images_ids').val(img_ids.join(',')).trigger('change'); }); $('.gallery_widget_attached_images_list').each(function (index) { var $img_ul = $(this); $img_ul.sortable({ forcePlaceholderSize:true, placeholder:"widgets-placeholder-gallery", cursor:"move", items:"li", update:function () { var img_ids = []; $(this).find('.added img').each(function () { img_ids.push($(this).attr("rel")); }); $img_ul.closest('.edit_form_line').find('.gallery' + '' + '_widget_attached_images_ids').val(img_ids.join(',')).trigger('change'); } }); }); }; new InitGalleries(); var template_options = { evaluate: /<#([\s\S]+?)#>/g, interpolate: /\{\{\{([\s\S]+?)\}\}\}/g, escape: /\{\{([^\}]+?)\}\}(?!\})/g }; /** * Loop param for shortcode with magic query posts constructor. * ==================================== */ vc.loop_partial = function(template_name, key, loop, settings) { var data = _.isObject(loop) && !_.isUndefined(loop[key]) ? loop[key] : ''; return _.template($('#_vcl-' + template_name).html(), {name: key, data: data, settings: settings}, template_options); }; vc.loop_field_not_hidden = function(key, loop) { return !(_.isObject(loop[key]) && _.isBoolean(loop[key].hidden) && loop[key].hidden === true); }; vc.is_locked = function(data) { return _.isObject(data) && _.isBoolean(data.locked) && data.locked === true; }; var Suggester = function(element, options) { this.el = element; this.$el = $(this.el); this.$el_wrap = ''; this.$block = ''; this.suggester = ''; this.selected_items = []; this.options = _.isObject(options) ? options : {}; _.defaults(this.options, { css_class: 'vc-suggester', limit: false, source: {}, predefined: [], locked: false, select_callback: function(label, data) {}, remove_callback: function(label, data) {}, update_callback: function(label, data) {}, check_locked_callback: function(el, data) {return false;} }); this.init(); }; Suggester.prototype = { constructor: Suggester, init: function() { _.bindAll(this, 'buildSource', 'itemSelected', 'labelClick', 'setFocus', 'resize'); var that = this; this.$el.wrap('<ul class="' + this.options.css_class +'"><li class="input"/></ul>'); this.$el_wrap = this.$el.parent(); this.$block = this.$el_wrap.closest('ul').append($('<li class="clear"/>')); this.$el.focus(this.resize).blur(function(){ $(this).parent().width(170); $(this).val(''); }); this.$block.click(this.setFocus); this.suggester = this.$el.data('suggest'); // Remove form here this.$el.autocomplete({ source: this.buildSource, select: this.itemSelected, minLength: 3, focus: function( event, ui ) {return false;} }).data( "ui-autocomplete" )._renderItem = function( ul, item ) { return $( '<li data-value="' + item.value + '">' ) .append( "<a>" + item.name + "</a>" ) .appendTo( ul ); }; this.$el.autocomplete( "widget" ).addClass('vc-ui-front') if(_.isArray(this.options.predefined)) { _.each(this.options.predefined, function(item){ this.create(item); }, this); } }, resize: function() { var position = this.$el_wrap.position(), block_position = this.$block.position(); this.$el_wrap.width(parseFloat(this.$block.width()) - (parseFloat(position.left) - parseFloat(block_position.left) + 4)); }, setFocus: function(e) { e.preventDefault(); var $target = $(e.target); if($target.hasClass(this.options.css_class)) { this.$el.trigger('focus'); } }, itemSelected: function(event, ui) { this.$el.blur(); this.create(ui.item); this.$el.focus(); return false; }, create: function(item) { var index = (this.selected_items.push(item) - 1), remove = this.options.check_locked_callback(this.$el, item) === true ? '' : ' <a class="remove">&times;</a>', $label, exclude_css = ''; if(_.isUndefined(this.selected_items[index].action)) this.selected_items[index].action = '+'; exclude_css = this.selected_items[index].action === '-' ? ' exclude' : ' include'; $label = $('<li class="vc-suggest-label' + exclude_css +'" data-index="' + index + '" data-value="' + item.value + '"><span class="label">' + item.name + '</span>' + remove + '</li>'); $label.insertBefore(this.$el_wrap); if(!_.isEmpty(remove)) $label.click(this.labelClick); this.options.select_callback($label, this.selected_items); }, labelClick: function(e) { e.preventDefault(); var $label = $(e.currentTarget), index = parseInt($label.data('index'), 10), $target = $(e.target); if($target.is('.remove')) { delete this.selected_items[index]; this.options.remove_callback($label, this.selected_items); $label.remove(); return false; } this.selected_items[index].action = this.selected_items[index].action === '+' ? '-' : '+'; if(this.selected_items[index].action == '+') { $label.removeClass('exclude').addClass('include'); } else { $label.removeClass('include').addClass('exclude'); } this.options.update_callback($label, this.selected_items); }, buildSource: function(request, response) { var exclude = _.map(this.selected_items, function(item) {return item.value;}).join(','); $.ajax({ type: 'POST', dataType: 'json', url: window.ajaxurl, data: { action: 'wpb_get_loop_suggestion', field: this.suggester, exclude: exclude, query: request.term } }).done(function(data) { response(data); }); } }; $.fn.suggester = function(option) { return this.each(function () { var $this = $(this), data = $this.data('suggester'), options = _.isObject(option) ? option : {}; if (!data) $this.data('suggester', (data = new Suggester(this, option))); if (typeof option == 'string') data[option](); }); }; var VcLoopEditorView = Backbone.View.extend({ className: 'loop_params_holder', events: { 'click input, select': 'save', 'change input, select': 'save', 'change :checkbox[data-input]': 'updateCheckbox' }, query_options: { }, return_array: {}, controller: '', initialize: function() { _.bindAll(this, 'save', 'updateSuggestion', 'suggestionLocked'); }, render: function(controller) { var that = this, template = _.template($( '#vcl-loop-frame' ).html(), this.model, _.extend({}, template_options, {variable: 'loop'})); this.controller = controller; this.$el.html(template); this.controller.$el.append(this.$el); _.each($('[data-suggest]'), function(object){ var $field = $(object), current_value = window.decodeURIComponent($('[data-suggest-prefill=' + $field.data('suggest') + ']').val()); $field.suggester({ predefined: $.parseJSON(current_value), select_callback: this.updateSuggestion, update_callback: this.updateSuggestion, remove_callback: this.updateSuggestion, check_locked_callback: this.suggestionLocked }); }, this); return this; }, show: function() { this.$el.slideDown(); }, save: function(e) { this.return_array = {}; _.each(this.model, function(value, key){ var value = this.getValue(key, value); if(_.isString(value) && !_.isEmpty(value)) this.return_array[key] = value; }, this); this.controller.setInputValue(this.return_array); }, getValue: function(key, default_value) { var value = $('[name=' + key + ']', this.$el).val(); return value; }, hide: function() { this.$el.slideUp(); }, toggle: function() { if(!this.$el.is(':animated')) this.$el.slideToggle(); }, updateCheckbox: function(e) { var $checkbox = $(e.currentTarget), input_name = $checkbox.data('input'), $input = $('[data-name=' + input_name + ']', this.$el), value = []; $('[data-input=' + input_name+']:checked').each(function(){ value.push($(this).val()); }); $input.val(value); this.save(); }, updateSuggestion: function($elem, data) { var value, $suggestion_block = $elem.closest('[data-block=suggestion]'); value = _.reduce(data, function(memo, label){ if(!_.isEmpty(label)) { return memo + (_.isEmpty(memo) ? '' : ',') + (label.action === '-' ? '-' : '') + label.value; } }, ''); $suggestion_block.find('[data-suggest-value]').val(value).trigger('change'); }, suggestionLocked: function($elem, data) { var value = data.value, field = $elem.closest('[data-block=suggestion]').find('[data-suggest-value]').data('suggest-value'); return this.controller.settings[field] && _.isBoolean(this.controller.settings[field].locked) && this.controller.settings[field].locked == true && _.isString(this.controller.settings[field].value) && _.indexOf(this.controller.settings[field].value.replace('-', '').split(/\,/), '' + value) >= 0; } }); var VcLoop = Backbone.View.extend({ events: { 'click .vc-loop-build': 'showEditor' }, initialize: function() { _.bindAll(this, 'createEditor'); this.$input = $('.wpb_vc_param_value', this.$el); this.$button = this.$el.find('.vc-loop-build'); this.data = this.$input.val(); this.settings = $.parseJSON(window.decodeURIComponent(this.$button.data('settings'))); }, render: function() { return this; }, showEditor: function(e) { e.preventDefault(); if(_.isObject(this.loop_editor_view)) { this.loop_editor_view.toggle(); return false; } $.ajax({ type:'POST', dataType: 'json', url: window.ajaxurl, data: { action:'wpb_get_loop_settings', value: this.data, settings: this.settings } }).done(this.createEditor); }, createEditor: function(data) { this.loop_editor_view = new VcLoopEditorView({model:!_.isEmpty(data) ? data : {}}); this.loop_editor_view.render(this).show(); }, setInputValue: function(value) { this.$input.val(_.map(value, function(value, key){ return key + ':' + value; }).join('|')); } }); var VcOptionsField = Backbone.View.extend({ events: { 'click .vc-options-edit': 'showEditor', 'click .vc-close-button': 'showEditor', 'click input, select': 'save', 'change input, select': 'save', 'keyup input': 'save' }, data: {}, fields: {}, initialize: function() { this.$button = this.$el.find('.vc-options-edit'); this.$form = this.$el.find('.vc-options-fields'); this.$input = this.$el.find('.wpb_vc_param_value'); this.settings = this.$form.data('settings'); this.parseData(); this.render(); }, render: function() { var html = ''; _.each(this.settings, function(field){ if(!_.isUndefined(this.data[field.name])) { field.value = this.data[field.name]; } else if(!_.isUndefined(field.value)) { field.value = field.value.toString().split(','); this.data[field.name] = field.value; } this.fields[field.name] = field; if($( '#vcl-options-field-' + field.type).is('script')) { html += _.template( $( '#vcl-options-field-' + field.type ).html(), $.extend({name: '', label: '', value: [], options: '', description: ''}, field), _.extend({}, template_options) ); } }, this); this.$form.html(html + this.$form.html()); return this; }, parseData: function() { _.each(this.$input.val().split("|"), function(data) { if(data.match(/\:/)) { var split = data.split(':'), name = split[0], value = split[1]; this.data[name] = _.map(value.split(','), function(v){ return window.decodeURIComponent(v); }); } }, this); }, saveData: function() { var data_string = _.map(this.data, function(value, key){ return key + ':' + _.map(value, function(v){ return window.encodeURIComponent(v);}).join(','); }).join('|'); this.$input.val(data_string); }, showEditor: function() { this.$form.slideToggle(); }, save: function(e) { var $field = $(e.currentTarget) if($field.is(':checkbox')) { var value = []; this.$el.find('input[name=' + $field.attr('name') + ']').each(function(){ if($(this).is(':checked')) { value.push($(this).val()); } }); this.data[$field.attr('name')] = value; } else { this.data[$field.attr('name')] = [$field.val()]; } this.saveData(); } }); $(function(){ $('.wpb_el_type_loop').each(function(){ new VcLoop({el: $(this)}); }); $('.wpb_el_type_options').each(function(){ new VcOptionsField({el: $(this)}); }); }); /** * VC_link power code. */ $('.vc-link-build').click(function(e){ e.preventDefault(); var $self = $(this), $block = $(this).closest('.vc-link'), $input = $block.find('.wpb_vc_param_value'), $url_label = $block.find('.url-label'), $title_label = $block.find('.title-label'), value_object = $input.data('json'), $link_submit = $('#wp-link-submit'), $vc_link_submit = $('<input type="submit" name="vc-link-submit" id="vc-link-submit" class="button-primary" value="Set Link">'), dialog; $link_submit.hide(); $("#vc-link-submit").remove(); $vc_link_submit.insertBefore($link_submit); if($.fn.wpdialog && $('#wp-link').length) { dialog = { $link: false, open: function() { this.$link = $('#wp-link').wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); }, close: function() { this.$link.wpdialog('close'); } }; } else { dialog = window.wpLink; } /* $dialog = $('#wp-link').wpdialog({ title: wpLinkL10n.title, width: 480, height: 'auto', modal: true, dialogClass: 'wp-dialog', zIndex: 300000 }); */ dialog.open(); window.wpLink.textarea = $self; if(_.isString(value_object.url)) $('#url-field').val(value_object.url); if(_.isString(value_object.title)) $('#link-title-field').val(value_object.title); $('#link-target-checkbox').prop('checked', !_.isEmpty(value_object.target) ? true : false); $vc_link_submit.unbind('click.vcLink').bind('click.vcLink', function(e){ e.preventDefault(); e.stopImmediatePropagation(); var options = {}, string = ''; options.url = $('#url-field').val(); options.title = $('#link-title-field').val(); options.target = $('#link-target-checkbox').is(':checked') ? ' _blank' : ''; string = _.map(options, function(value, key){ if(_.isString(value) && value.length > 0) { return key + ':' + encodeURIComponent(value); } }).join('|'); $input.val(string); $input.data('json', options); $url_label.html(options.url + options.target ); $title_label.html(options.title); // $dialog.wpdialog('close'); dialog.close(); $link_submit.show(); $vc_link_submit.unbind('click.vcLink'); $vc_link_submit.remove(); // remove vc_link hooks for wpLink $('#wp-link-cancel').unbind('click.vcLink'); window.wpLink.textarea = ''; $('#link-target-checkbox').attr('checked', false); return false; }); $('#wp-link-cancel').unbind('click.vcLink').bind('click.vcLink', function(e){ e.preventDefault(); $dialog.wpdialog('close'); // remove vc_link hooks for wpLink $vc_link_submit.unbind('click.vcLink'); $vc_link_submit.remove(); // remove vc_link hooks for wpLink $('#wp-link-cancel').unbind('click.vcLink'); window.wpLink.textarea = ''; }); }); var VcSortedList = function(element, settings) { this.el = element; this.$el = $(this.el); this.$data_field = this.$el.find('.wpb_vc_param_value'); this.$toolbar = this.$el.find('.vc-sorted-list-toolbar'); this.$current_control = this.$el.find('.vc-sorted-list-container'); _.defaults(this.options, {}); this.init(); }; VcSortedList.prototype = { constructor: VcSortedList, init: function() { var that = this; _.bindAll(this, 'controlEvent', 'save'); this.$toolbar.on('change', 'input', this.controlEvent); var selected_data = this.$data_field.val().split(','); for(var i in selected_data) { var control_settings = selected_data[i].split('|'), $control = control_settings.length ? this.$toolbar.find('[data-element=' + decodeURIComponent(control_settings[0]) + ']') : false; if($control !== false && $control.is('input')) { $control.prop('checked', true); this.createControl({ value: $control.val(), label: $control.parent().text(), sub: $control.data('subcontrol'), sub_value:_.map(control_settings.slice(1), function(item) {return window.decodeURIComponent(item)}) }); } } this.$current_control.sortable({ stop: this.save }).on('change', 'select', this.save); }, createControl: function(data) { var sub_control = '', selected_sub_value = _.isUndefined(data.sub_value) ? [] : data.sub_value; if(_.isArray(data.sub)) { _.each(data.sub, function(sub, index){ sub_control += ' <select>'; _.each(sub, function(item){ sub_control += '<option value="' + item[0] + '"' + (_.isString(selected_sub_value[index]) && selected_sub_value[index]===item[0] ? ' selected="true"' : '') + '>' + item[1] + '</option>'; }); sub_control += '</select>'; }, this); } this.$current_control.append('<li class="vc-control-' + data.value + '" data-name="' + data.value + '">' + data.label + sub_control + '</li>'); }, controlEvent: function(e) { var $control = $(e.currentTarget); if($control.is(':checked')) { this.createControl({ value: $control.val(), label: $control.parent().text(), sub: $control.data('subcontrol') }); } else { this.$current_control.find('.vc-control-' + $control.val()).remove(); } this.save(); }, save: function() { var value = _.map(this.$current_control.find('[data-name]'), function(element){ var return_string = encodeURIComponent($(element).data('name')); $(element).find('select').each(function(){ $sub_control = $(this); if($sub_control.is('select') && $sub_control.val() !== '') { return_string += '|' + encodeURIComponent($sub_control.val()); } }); return return_string; }).join(','); this.$data_field.val(value); } }; $.fn.VcSortedList = function(option) { return this.each(function () { var $this = $(this), data = $this.data('vc_sorted_list'), options = _.isObject(option) ? option : {}; if (!data) $this.data('vc_sorted_list', (data = new VcSortedList(this, option))); if (typeof option == 'string') data[option](); }); }; $('.vc-sorted-list').VcSortedList(); $('.wpb-edit-form .textarea_html').each(function(){ init_textarea_html($(this)); }); $('.wpb_vc_param_value.dropdown').change(function(){ var $this = $(this), $options = $this.find(':selected'), prev_option_class = $this.data('option'), option_class = $options.length ? $options.attr('class').replace(/\s/g, '_') : ''; prev_option_class != undefined && $this.removeClass(prev_option_class); option_class != undefined && $this.data('option', option_class) && $this.addClass(option_class); }); if($('#vc-edit-form-tabs').length) { $('.wpb-edit-form').addClass('vc-with-tabs'); $('#vc-edit-form-tabs').tabs(); } }(window.jQuery);
christaclark/jacksongorksi
wp-content/plugins/js_composer/assets/js/params/all.js
JavaScript
gpl-2.0
30,613
/* ======================================================================== \ | FORMA - The E-Learning Suite | | | | Copyright (c) 2013 (Forma) | | http://www.formalms.org | | License http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt | | | | from docebo 4.0.5 CE 2008-2012 (c) docebo | | License http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt | \ ======================================================================== */ var userid=0; var username=""; var pingTimer; var _TTim; var pathImage; var chat_windows=0; function setup_instmsg(passed_userid,passed_username,passed_path) { userid=passed_userid; username=passed_username; pathImage=passed_path; } function getLang() { var data="op=getLang"; var objAjax = YAHOO.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: getLangCompleted }); } function getLangCompleted(o) { try { _TTim = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} startPinging(); } function startPinging() { pingTimer=setInterval("ping()",15000); } function ping() { var id_receiver=userid; var name_receiver=username; var data="op=ping&id_receiver="+id_receiver+"&name_receiver="+name_receiver; var objAjax = YAHOO.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: pingResponse }); } function pingResponse(o) { try { chatMsgs = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} for (var i=0;i<chatMsgs.content.length;i++) { var wChat=chatMsgs.content[i].id_sender; if (wObjList[wChat]==null) { startChat(chatMsgs.content[i].id_sender,chatMsgs.content[i].name_sender); return true; } msg=unescape(chatMsgs.content[i].msg); msg=replaceEmoticon(msg); var chatBox=YAHOO.util.Dom.get(wChat+'_text'); chatBox.innerHTML = chatBox.innerHTML + "<span class=\"timestamp\"> (" + chatMsgs.content[i].timestamp + ")</span> <strong class=\"userB\">" + chatMsgs.content[i].name_sender + ":</strong> <span class=\"new\">" + msg + "</span><br />\n"; chatBox.scrollTop = chatBox.scrollHeight - chatBox.clientHeight; } displayUsersList(chatMsgs.list,false); } function displayUsersList(usersList,openwin) { YAHOO.util.Dom.get('user_online_n').firstChild.innerHTML=usersList.length; if(!openwin) return; var str='<div id="listContainer"><ul id="userList">'; for (var i=0;i<usersList.length;i++) { if (usersList[i].idSt!=userid) str+='<li><a href="javascript:;" onclick="startChat(\''+usersList[i].idSt+'\',\''+usersList[i].idUser+'\');" class="callOut"><span>'+usersList[i].userName+'</span></a></li>'; else str+='<li><span class="callOutDisabled"><span>'+usersList[i].userName+'</span></a></li>'; } str+='</ul></div>'; var w = new YAHOO.widget.SimpleDialog("wUsersList", { fixedcenter: true, visible: true, close: true, modal: false, constraintoviewport: true } ); w.setHeader(_TTim._WHOIS_ONLINE); w.setBody(str); w.render(document.body); } function openUsersList() { var data="op=getUsersList"; var objAjax = YAHOO.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: showUsersList }); } function showUsersList(o) { try { users = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} displayUsersList(users.list,true); } function startChat(id_sender,name_sender) { if (id_sender==userid) return 0; var wChat=id_sender; if (wObjList[wChat]==null) { clearInterval(pingTimer); pingTimer=setInterval("ping()",5000); chat_windows++; getChatContent(wChat,name_sender); } destroyWindow("wUsersList"); } function getChatContent(wChat,name_sender) { var id_receiver=userid; var name_receiver=username; var id_sender=wChat; var data="op=getContent"; data+="&wChat="+wChat; data+="&id_sender="+id_sender; data+="&id_receiver="+id_receiver; data+="&name_sender="+name_sender; data+="&name_receiver="+name_receiver; var objAjax = YAHOO.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: showChat }); } function showChat(o) { try { chatObj = YAHOO.lang.JSON.parse(o.responseText); } catch (e) {return;} var wChat=chatObj.wChat; var name_sender=chatObj.name_sender; var msg=""; str='<div class="chat">'; str+='<div id="'+wChat+'_text'+'" class="chatText">'; for (var i=0;i<chatObj.content.length;i++) { msg=unescape(chatObj.content[i].msg); msg=replaceEmoticon(msg); str+="<span class=\"timestamp\"> (" + chatObj.content[i].timestamp + ")</span> <strong class=\""+chatObj.content[i].userClass+"\">" + chatObj.content[i].userName + ":</strong> <span class=\""+chatObj.content[i].lineStatus+"\">" + msg + "</span><br />\n"; } str+='</div>'; str+='<input type="text" name="'+wChat+'_inputBox'+'" id="'+wChat+'_inputBox'+'" onkeypress="keyHandler(event,'+"'"+wChat+"'"+');" style="width:350px;" /> <button onclick="sendLine(\''+wChat+'\')">'+_TTim._SEND+'</button>'; str+="</div>"; str+='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="1" height="1" id="soundeffect" align=""> <param name="movie" value="./modules/instmsg/grilli.swf"> <param name="quality" value="high"> <parame name="bgcolor" value="#FFFFFF"> <embed src="./modules/instmsg/grilli.swf" quality="high" bgcolor="#FFFFFF" name="soundeffect" width="1" height="1" align="" type="application/x-shockwave-flash" pluginspace="http://www.macromedia.com/go/getflashplayer"></embed></object>'; Stamp = new Date(); var day = String(Stamp.getDate()); var month = String(Stamp.getMonth()+1); var year = String(Stamp.getFullYear()); day = (day.length > 1) ? day : "0"+day; month = (month.length > 1) ? month : "0"+month; var name=wChat; var title=_TTim._CHAT+": "+name_sender+" ("+ day + "/" + month + "/" + year+")"; var w = new YAHOO.widget.SimpleDialog("inst_"+name, { visible: true, close: true, modal: false, constraintoviewport: true } ); w.setHeader(title); w.setBody(str); w.render(document.body); var chatBox=YAHOO.util.Dom.get(wChat+'_text'); setTimeout("setScroll('"+wChat+"_text')",500); w.addListener('cancelEvent', updateTimers); w.addListener('destroyEvent', updateTimers); } function setScroll(chatDiv) { var chatBox=YAHOO.util.Dom.get(chatDiv); chatBox.scrollTop = chatBox.scrollHeight - chatBox.clientHeight; } function keyHandler( e, wChat ) { var asc = document.all ? event.keyCode : e.which; if(asc == 13) { sendLine(wChat); } return asc != 13; } function sendLine(wChat) { var sentText=String(YAHOO.util.Dom.get(wChat+'_inputBox').value); if (sentText.length < 1) return true; YAHOO.util.Dom.get(wChat+'_inputBox').value=""; Stamp = new Date(); var h = String(Stamp.getHours()); var m = String(Stamp.getMinutes()); var s = String(Stamp.getSeconds()); var day = String(Stamp.getDate()); var month = String(Stamp.getMonth()+1); var year = String(Stamp.getFullYear()); day = (day.length > 1) ? day : "0"+day; month = (month.length > 1) ? month : "0"+month; h = (h.length > 1) ? h : "0"+h; m = (m.length > 1) ? m : "0"+m; s = (s.length > 1) ? s : "0"+s; var msg=replaceEmoticon(sentText); var chatBox=YAHOO.util.Dom.get(wChat+'_text'); chatBox.innerHTML = chatBox.innerHTML + "<span class=\"timestamp\"> (" + h + ":" + m + ":" + s + ")</span> <strong class=\"userA\">" + username + ":</strong> <span class=\"new\">" + msg + "</span><br />\n"; chatBox.scrollTop = chatBox.scrollHeight - chatBox.clientHeight; var id_sender=userid; var id_receiver=wChat; var msg=new String(); msg=escape(sentText); var data="op=sendLine&wChat="+wChat+"&id_sender="+id_sender+"&id_receiver="+id_receiver+"&msg="+msg; var objAjax = YAHOO.util.Connect.asyncRequest('POST', 'ajax.server.php?mn=instmsg&'+data, { success: lineSent }); } function lineSent(o) { return true; } function updateTimers() { chat_windows--; if (chat_windows==0) { clearInterval(pingTimer); pingTimer=setInterval("ping()",15000); } } /* replacing emoticons with images */ function getChatEmoticon(name) { var ext="gif"; var res ="<img alt=\""+name+"\" title=\""+name+"\" src=\""; res+=pathImage+"emoticons/"+name+"."+ext+"\" />"; return res; } function replaceEmoticon(txt) { var res=txt; res=res.replace(/;[-]?\)/i, getChatEmoticon("wink_smile")); res=res.replace(/:[-]?\|/i, getChatEmoticon("whatchutalkingabout_smile")); res=res.replace(/:[-]?P/i, getChatEmoticon("tounge_smile")); res=res.replace(/o:[-]?\)/i, getChatEmoticon("angel_smile")); res=res.replace(/:[-]?\)/i, getChatEmoticon("regular_smile")); res=res.replace(/:[-]?\(/i, getChatEmoticon("sad_smile")); res=res.replace(/:?\'[-]?(\(|\[)/i, getChatEmoticon("cry_smile")); res=res.replace(/:[-]?o/i, getChatEmoticon("omg_smile")); res=res.replace(/8[-]?\)/i, getChatEmoticon("shades_smile")); res=res.replace(/:[-]?s/i, getChatEmoticon("confused_smile")); res=res.replace(/X[-]?\(/i, getChatEmoticon("devil_smile")); res=res.replace(/\=\(\(/i, getChatEmoticon("broken_heart")); res=res.replace(/:[-]?x/i, getChatEmoticon("heart")); res=res.replace(/:[-]?d/i, getChatEmoticon("teeth_smile")); res=res.replace(/\[OK\]/, getChatEmoticon("thumbs_up")); res=res.replace(/\[BAD\]/, getChatEmoticon("thumbs_down")); res=res.replace(/\[IDEA\]/, getChatEmoticon("lightbulb")); res=res.replace(/\[MAIL\]/, getChatEmoticon("envelope")); return res; } onunload = function() {clearInterval(pingTimer);} YAHOO.util.Event.addListener(window,"load", getLang); YAHOO.util.Event.addListener("open_users_list","click", openUsersList); YAHOO.util.Event.addListener(window,"unload", onunload);
formalms/formalms
html/appLms/modules/instmsg/instmsg.js
JavaScript
gpl-2.0
10,399
/*global _, _s, Backbone*/ define(function(require) { var Super = require('views/base'), B = require('bluebird'), THEAD = require('hbs!./table/thead.tpl'), TBODY = require('hbs!./table/tbody.tpl'), TD = require('hbs!./table/td.tpl'), TR = require('hbs!./table/tr.tpl'), Template = require('hbs!./table.tpl'); var View = Super.extend({}); View.Columns = Backbone.Collection.extend(); View.prototype.initialize = function(options) { //super(options) Super.prototype.initialize.call(this, options); this.columns = this.getColumns(); }; View.prototype.render = function() { var that = this; return B.resolve() .then(function() { that.$el.html(Template({ id: that.id })); that.mapControls(); that.renderHead(); that.renderBody(); var events = {}; events['click th.sortable'] = 'sortableColumnClickHandler'; that.delegateEvents(events); that.collection.on('sync add remove', that.renderBody.bind(that)); that.on('sort', that.sortHandler.bind(that)); }); }; View.prototype.sortableColumnClickHandler = function(event) { var that = this; var e = $(event.currentTarget); var field = e.data('id'); var column = that.columns.get(field); var direction = ''; that.columns.forEach(function(column) { if (column.id !== field) { column.set('direction', ''); } }); switch (column.get('direction')) { case 'asc': direction = 'desc'; break; case 'desc': direction = ''; break; default: direction = 'asc'; } column.set('direction', direction); that.trigger('sort'); }; View.prototype.sortHandler = function(event) { var that = this; that.renderHead(); }; View.prototype.renderHead = function() { var that = this; // console.log('renderHead()', that.columns.toJSON()); that.controls.thead.html(THEAD({ id: that.id, columns: that.columns.map(function(column, index) { return that.tranformColumn(column, index); }) })); }; View.prototype.getColumns = function() { return new View.Columns(); }; View.prototype.tranformColumn = function(column, index) { return _.extend(column.toJSON(), { sortIcon: (function() { if (column.get('sortable')) { if (column.get('direction') === 'asc') { if (column.get('type') === 'number') { return 'fa-sort-numeric-asc text-success'; } else { return 'fa-sort-alpha-asc text-success'; } } else if (column.get('direction') === 'desc') { if (column.get('type') === 'number') { return 'fa-sort-numeric-desc text-warning'; } else { return 'fa-sort-alpha-desc text-warning'; } } else { return 'fa-sort'; } } else { return ''; } })() }); }; View.prototype.renderBody = function() { var that = this; that.controls.tbody.html(TBODY({ id: that.id, rows: that.collection.map(function(model, index) { return that.tranformRow(model, index); }), columns: that.columns.toJSON() })); }; View.prototype.tranformRow = function(model, index) { var that = this; var DefaultRenderer = that.getDefaultRenderer(); var cells = that.columns.map(function(column, columnIndex) { var value = '&nbsp;'; var renderer = column.get('renderer') || DefaultRenderer; var td = column.get('td') || TD; if (typeof renderer === 'function') { try { value = renderer(model, column, index, columnIndex); } catch (e) { console.error(e); } } if (typeof td === 'function') { return td({ value: value, field: column.id, data: model.toJSON(), column: column.toJSON(), rowIndex: index, columnIndex: columnIndex, className: column.get('className') }); } }); return TR({ data: model.toJSON(), cells: cells.join('') }); }; View.prototype.getDefaultRenderer = function() { return function(model, column, rowIndex, columnIndex) { return model.get(column.id); }; }; View.prototype.getSortedColumn = function() { var that = this; return that.columns.find(function(column) { return column.get('direction') === 'asc' || column.get('direction') === 'desc'; }); }; return View; });
aduyng/visual-regression-tool
app/views/controls/table.js
JavaScript
gpl-2.0
5,666
// // namespace : HG.Statistics // info : - // HG.Statistics = HG.Statistics || {}; // HG.Statistics.ServiceCall = function (fn, opt1, opt2, callback) { $.ajax({ url: '/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/' + fn + '/' + opt1 + '/' + opt2, type: 'GET', dataType: 'text', success: function (data) { var value = eval(data); if (typeof value == 'undefined') { value = data; } else if (typeof value[0] != 'undefined' && typeof value[0].ResponseValue != 'undefined') { value = value[0].ResponseValue; } callback(value); } }); }; // // namespace : HG.Statistics.Global // info : - // HG.Statistics.Global = HG.Statistics.Global || {}; HG.Statistics.Global.GetWattsCounter = function (callback) { $.ajax({ url: '/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/Global.CounterTotal/Meter.Watts', type: 'GET', dataType: 'text', success: function (data) { var counter = eval(data)[0]; callback(counter.ResponseValue); } }); }; // // namespace : HG.Statistics.Database // info : - // HG.Statistics.Database = HG.Statistics.Database || {}; HG.Statistics.Database.Reset = function () { $.get('/' + HG.WebApp.Data.ServiceKey + '/' + HG.WebApp.Data.ServiceDomain + '/Statistics/Database.Reset/' + (new Date().getTime()), function (data) { }); };
Klagopsalmer/HomeGenie
BaseFiles/Common/html/js/api/homegenie.statistics.js
JavaScript
gpl-3.0
1,579
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2004-2008 1&1 Internet AG, Germany, http://www.1und1.de License: LGPL: http://www.gnu.org/licenses/lgpl.html EPL: http://www.eclipse.org/org/documents/epl-v10.php See the LICENSE file in the project's top-level directory for details. Authors: * Fabian Jakobs (fjakobs) ************************************************************************ */ qx.Class.define("qx.test.ui.virtual.Pane", { extend : qx.test.ui.LayoutTestCase, members : { setUp : function() { this.base(arguments); this.defaultWidth = 30; this.defaultHeight = 10; this.rowCount = 1000; this.colCount = 200; var pane = new qx.ui.virtual.core.Pane( this.rowCount, this.colCount, this.defaultHeight, this.defaultWidth ); this.getRoot().add(pane); this.pane = pane; }, tearDown : function() { this.pane.destroy(); this.base(arguments); this.flush(); }, assertUpdateArgs : function(rowIndex, colIndex, rowSizes, colSizes, args, msg) { this.assertEquals(rowIndex, args[0], msg); this.assertEquals(colIndex, args[1], msg); this.assertArrayEquals(rowSizes, args[2], msg); this.assertArrayEquals(colSizes, args[3], msg); }, assertScrollArgs : function(rowIndex, colIndex, rowSizes, colSizes, args, msg) { this.assertEquals(rowIndex, args[0], msg); this.assertEquals(colIndex, args[1], msg); this.assertArrayEquals(rowSizes, args[2], msg); this.assertArrayEquals(colSizes, args[3], msg); }, assertScroll : function(scrollTop, scrollLeft, pane, msg) { var layerContainer = this.pane._getChildren()[0]; this.assertEquals(-scrollTop, layerContainer.getBounds().top, msg); this.assertEquals(-scrollLeft, layerContainer.getBounds().left, msg); }, testConstructor : function() { this.assertNotUndefined(this.pane); }, testScrollProperties : function() { this.flush(); this.pane.setScrollY(30); this.assertEquals(30, this.pane.getScrollY()); this.pane.setScrollX(40); this.assertEquals(40, this.pane.getScrollX()); }, testGetScrollSize : function() { var size = this.pane.getScrollSize(); this.assertEquals(this.defaultWidth * this.colCount, size.width); this.assertEquals(this.defaultHeight * this.rowCount, size.height); var rowConfig = this.pane.getRowConfig(); rowConfig.setDefaultItemSize(50); rowConfig.setItemCount(123); rowConfig.setItemSize(10, 30); this.assertEquals(50 * 123 - 20, this.pane.getScrollSize().height); }, testLayerAdd : function() { var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.assertEquals(layer, this.pane.getLayers()[0]); }, testUpdateEvent : function() { var called = 0; var pane = new qx.ui.virtual.core.Pane(100, 20, 10, 50); pane.addListener("update", function() { called ++}, this); pane.set({ width: 300, height: 200 }); // no update after creation this.getRoot().add(pane); this.assertEquals(0, called, "Expect no update after creation"); // one update after appear this.flush(); this.assertEquals(1, called, "Expect one update after appear"); // one update after pane resize called = 0; pane.setWidth(400); this.flush(); this.assertEquals(1, called, "Expect one update after pane resize"); // one update after data resize called = 0; pane.getRowConfig().setItemCount(200); this.flush(); this.assertEquals(1, called, "Expect one update after data resize"); // one update after data and pane resize called = 0; pane.getRowConfig().setItemCount(300); pane.setWidth(500); this.flush(); this.assertEquals(2, called, "Expect two updates after data and pane resize"); pane.destroy(); }, testFullUpdate : function() { var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({ width: 100, height: 50 }); this.flush(); layer.calls = []; this.pane.fullUpdate(); this.flush(); this.assertEquals(2, layer.calls.length); this.assertEquals("fullUpdate", layer.calls[0][0]); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 0, this.pane); this.pane.setScrollY(4); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [10, 10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(4, 0, this.pane); this.pane.setScrollY(10); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(1, 0, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 0, this.pane); this.pane.setScrollY(16); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(1, 0, [10, 10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(6, 0, this.pane); this.pane.setScrollY(0); this.flush(); this.pane.setScrollX(4); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 4, this.pane); this.pane.setScrollX(30); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 1, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 0, this.pane); this.pane.setScrollX(36); layer.calls = []; this.pane.fullUpdate(); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 1, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 6, this.pane); }, testNoRows : function() { var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); layer.calls = []; this.pane.setWidth(100); this.pane.getColumnConfig().setDefaultItemSize(100); this.pane.getColumnConfig().setItemCount(1); this.pane.getRowConfig().setItemCount(0); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [], [100], args); this.assertScroll(0, 0, this.pane); // resize layer.calls = []; this.pane.setWidth(30); this.pane.getColumnConfig().setDefaultItemSize(30); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [], [30], args); this.assertScroll(0, 0, this.pane); }, testNoColumns : function() { var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); layer.calls = []; this.pane.setHeight(100); this.pane.getRowConfig().setDefaultItemSize(100); this.pane.getRowConfig().setItemCount(1); this.pane.getColumnConfig().setItemCount(0); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [100], [], args); this.assertScroll(0, 0, this.pane); // resize layer.calls = []; this.pane.setHeight(30); this.pane.getRowConfig().setDefaultItemSize(30); this.flush(); var args = layer.calls[0][1]; this.assertUpdateArgs(0, 0, [30], [], args); this.assertScroll(0, 0, this.pane); }, testPrefetchYAtTop : function() { var layerHeight = 400; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: 300, height: layerHeight}); this.flush(); // scroll top is 0 and prefetch above this.pane.prefetchY(100, 200, 0, 0); this.flush(); this.assertEquals(layerHeight, layer.getBounds().height); this.assertScroll(0, 0, this.pane); }, testPrefetchYLimitedAtTop : function() { var layerHeight = 400; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: 300, height: layerHeight}); this.flush(); // scroll top is 100 and prefetch above 200 this.pane.setScrollY(100); this.pane.prefetchY(100, 200, 0, 0); this.flush(); this.assertEquals(layerHeight+100, layer.getBounds().height); this.assertScroll(100, 0, this.pane); }, testPrefetchYAtBottom : function() { var layerHeight = 400; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: 300, height: layerHeight}); this.flush(); // scroll top to bottom and prefetch below 200 this.pane.setScrollY(this.pane.getScrollMaxY()); this.pane.prefetchY(0, 0, 100, 200); this.flush(); this.assertEquals(layerHeight, layer.getBounds().height); this.assertScroll(0, 0, this.pane); }, testPrefetchYLimitedAtBottom : function() { var layerHeight = 400; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: 300, height: layerHeight}); this.flush(); // scroll top to bottom and prefetch below 200 this.pane.setScrollY(this.pane.getScrollMaxY()-100); this.pane.prefetchY(0, 0, 100, 200); this.flush(); this.assertEquals(layerHeight+100, layer.getBounds().height); this.assertScroll(0, 0, this.pane); }, testPrefetchYInMiddle : function() { var layerHeight = 400; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: 300, height: layerHeight}); this.flush(); // scroll top is 500 and prefetch above 200 this.pane.setScrollY(500); this.pane.prefetchY(100, 200, 100, 200); this.flush(); this.assertEquals(layerHeight+400, layer.getBounds().height); this.assertScroll(200, 0, this.pane); // already prefetched 200 pixel above. Scrolling up 20px and prefetching // again should not change the layers this.pane.setScrollY(480); this.pane.prefetchY(100, 200, 100, 200); this.flush(); this.assertEquals(layerHeight+400, layer.getBounds().height); this.assertScroll(180, 0, this.pane); // scroll more than minAbove up. Prefetching should update the layers this.pane.setScrollY(390); this.pane.prefetchY(100, 200, 100, 200); this.flush(); this.assertEquals(layerHeight+400, layer.getBounds().height); this.assertScroll(200, 0, this.pane); // already prefetched 200 pixel below. Scrolling down 20px and prefetching // again should not change the layers this.pane.setScrollY(410); this.pane.prefetchY(100, 200, 100, 200); this.flush(); this.assertEquals(layerHeight+400, layer.getBounds().height); this.assertScroll(220, 0, this.pane); // scroll more than minBelow down. Prefetching should update the layers this.pane.setScrollY(520); this.pane.prefetchY(100, 200, 100, 200); this.flush(); this.assertEquals(layerHeight+400, layer.getBounds().height); this.assertScroll(200, 0, this.pane); }, testPrefetchXAtLeft : function() { var layerWidth = 300; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: layerWidth, height: 400}); this.flush(); // scroll left is 0 and prefetch left this.pane.prefetchX(100, 200, 0, 0); this.flush(); this.assertEquals(layerWidth, layer.getBounds().width); this.assertScroll(0, 0, this.pane); }, testPrefetchXLimitedAtLeft : function() { var layerWidth = 300; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.getColumnConfig().setDefaultItemSize(10); this.pane.set({width: layerWidth, height: 400}); this.flush(); // scroll top is 100 and prefetch above 200 this.pane.setScrollX(100); this.pane.prefetchX(100, 200, 0, 0); this.flush(); this.assertEquals(layerWidth+100, layer.getBounds().width); this.assertScroll(0, 100, this.pane); }, testPrefetchXAtBottom : function() { var layerWidth = 300; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.getColumnConfig().setDefaultItemSize(10); this.pane.set({width: layerWidth, height: 400}); this.flush(); // scroll left to right and prefetch right 200 this.pane.setScrollX(this.pane.getScrollMaxX()); this.pane.prefetchX(0, 0, 100, 200); this.flush(); this.assertEquals(layerWidth, layer.getBounds().width); this.assertScroll(0, 0, this.pane); }, testPrefetchXLimitedAtBottom : function() { var layerWidth = 300; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.getColumnConfig().setDefaultItemSize(10); this.pane.set({width: layerWidth, height: 400}); this.flush(); // scroll left to right-100 and prefetch right 200 this.pane.setScrollX(this.pane.getScrollMaxX()-100); this.pane.prefetchX(0, 0, 100, 200); this.flush(); this.assertEquals(layerWidth+100, layer.getBounds().width); this.assertScroll(0, 0, this.pane); }, testPrefetchXInMiddle : function() { var layerWidth = 300; var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({width: layerWidth, height: 400}); this.pane.getColumnConfig().setDefaultItemSize(10); this.flush(); // scroll left is 500 and prefetch left 200 this.pane.setScrollX(500); this.pane.prefetchX(100, 200, 100, 200); this.flush(); this.assertEquals(layerWidth+400, layer.getBounds().width); this.assertScroll(0, 200, this.pane); // already prefetched 200 pixel at the left. Scrolling left 20px and prefetching // again should not change the layers this.pane.setScrollX(480); this.pane.prefetchX(100, 200, 100, 200); this.flush(); this.assertEquals(layerWidth+400, layer.getBounds().width); this.assertScroll(0, 180, this.pane); // scroll more than minLeft left. Prefetching should update the layers this.pane.setScrollX(390); this.pane.prefetchX(100, 200, 100, 200); this.flush(); this.assertEquals(layerWidth+400, layer.getBounds().width); this.assertScroll(0, 200, this.pane); // already prefetched 200 pixel right. Scrolling right 20px and prefetching // again should not change the layers this.pane.setScrollX(410); this.pane.prefetchX(100, 200, 100, 200); this.flush(); this.assertEquals(layerWidth+400, layer.getBounds().width); this.assertScroll(0, 220, this.pane); // scroll more than minRight right. Prefetching should update the layers this.pane.setScrollX(520); this.pane.prefetchX(100, 200, 100, 200); this.flush(); this.assertEquals(layerWidth+400, layer.getBounds().width); this.assertScroll(0, 200, this.pane); }, testUpdateLayerWindow : function() { var layer = new qx.test.ui.virtual.layer.LayerMock(); this.pane.addLayer(layer); this.pane.set({ width: 100, height: 50 }); this.flush(); layer.calls = []; this.pane.setScrollY(4); this.flush(); this.assertEquals("updateLayerWindow", layer.calls[0][0]); var args = layer.calls[0][1]; this.assertScrollArgs(0, 0, [10, 10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(4, 0, this.pane); layer.calls = []; this.pane.setScrollY(5); this.flush(); this.assertEquals(0, layer.calls.length); this.assertScroll(5, 0, this.pane); layer.calls = []; this.pane.setScrollY(10); this.flush(); this.assertEquals(0, layer.calls.length); this.assertScroll(10, 0, this.pane); layer.calls = []; this.pane.setScrollY(16); this.flush(); this.assertEquals("updateLayerWindow", layer.calls[0][0]); var args = layer.calls[0][1]; this.assertScrollArgs(1, 0, [10, 10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(6, 0, this.pane); this.pane.setScrollY(0); this.flush(); layer.calls = []; this.pane.setScrollX(4); this.flush(); this.assertEquals(0, layer.calls.length); this.assertScroll(0, 4, this.pane); layer.calls = []; this.pane.setScrollX(30); this.flush(); this.assertEquals("updateLayerWindow", layer.calls[0][0]); var args = layer.calls[0][1]; this.assertScrollArgs(0, 1, [10, 10, 10, 10, 10], [30, 30, 30, 30], args); this.assertScroll(0, 0, this.pane); layer.calls = []; this.pane.setScrollX(36); this.flush(); this.assertEquals(0, layer.calls.length); this.assertScroll(0, 6, this.pane); }, testSrollRowIntoView : function() { this.pane.set({ width : 400, height : 305 }); this.pane.getColumnConfig().setItemCount(1); var layer = new qx.test.ui.virtual.layer.LayerSimple(); this.pane.addLayer(layer); this.flush(); this.pane.scrollRowIntoView(100) this.flush(); var children = layer.getContentElement().getDomElement().childNodes; this.assertScroll(5, 0, this.pane); this.assertEquals("70 / 0", children[0].innerHTML) this.assertEquals("100 / 0", children[children.length-1].innerHTML); }, testSrollColumnIntoView : function() { this.pane.set({ width : 405, height : 305 }); this.pane.getRowConfig().setItemCount(1); var layer = new qx.test.ui.virtual.layer.LayerSimple(); this.pane.addLayer(layer); this.flush(); this.pane.scrollColumnIntoView(100) this.flush(); var children = layer.getContentElement().getDomElement().childNodes; this.assertScroll(0, 15, this.pane); this.assertEquals("0 / 87", children[0].innerHTML) this.assertEquals("0 / 100", children[children.length-1].innerHTML) }, _testSrollRowIntoViewEdgeCase : function() { this.pane.set({ width : 400, height : 305 }); this.pane.getColumnConfig().setItemCount(1); var layer = new qx.test.ui.virtual.layer.LayerSimple(); this.pane.addLayer(layer); this.flush(); this.pane.scrollRowIntoView(2000) this.flush(); var children = layer.getContentElement().getDomElement().childNodes; this.assertScroll(5, 0, this.pane); this.assertEquals("0 / 969", children[0].innerHTML) this.assertEquals("0 / 999", children[children.length-1].innerHTML) }, _testSrollColumnIntoViewEdgeCase : function() { this.pane.set({ width : 405, height : 305 }); this.pane.getRowConfig().setItemCount(1); var layer = new qx.test.ui.virtual.layer.LayerSimple(); this.pane.addLayer(layer); this.flush(); this.pane.scrollColumnIntoView(400) this.flush(); var children = layer.getContentElement().getDomElement().childNodes; this.assertScroll(0, 15, this.pane); this.assertEquals("186 / 0", children[0].innerHTML) this.assertEquals("199 / 0", children[children.length-1].innerHTML) }, testGetCellAtPosition : function() { this.pane.getRowConfig().setItemCount(3); this.pane.getColumnConfig().setItemCount(3); var layer = new qx.test.ui.virtual.layer.LayerSimple(); this.pane.addLayer(layer); this.flush(); this.assertJsonEquals({row : 0, column : 0}, this.pane.getCellAtPosition(0, 0)); this.assertEquals(null, this.pane.getCellAtPosition(400, 0)); this.assertEquals(null, this.pane.getCellAtPosition(0, 300)); this.assertEquals(null, this.pane.getCellAtPosition(400, 300)); this.assertJsonEquals({row : 2, column : 2}, this.pane.getCellAtPosition(89, 29)); }, testGetItemAtPositionEmptySpace : function() { var pane = this.pane; pane.setHeight(100); pane.setWidth(50); this.pane.getRowConfig().setItemCount(1); this.pane.getRowConfig().setDefaultItemSize(50); this.flush(); this.assertJsonEquals({row : 0, column : 0}, this.pane.getCellAtPosition(1, 49)); this.assertEquals(null, this.pane.getCellAtPosition(1, 50)); this.assertEquals(null, this.pane.getCellAtPosition(1, 70)); }, testMouseCellEvents : function() { var rowCount = 2; var colCount = 2; var defaultHeight = 10; var defaultWidth = 50; var pane = new qx.ui.virtual.core.Pane( rowCount, colCount, defaultHeight, defaultWidth ).set({ width: 150, height: 30 }); this.getRoot().add(pane, {left: 100, top: 100}); this.flush(); var calls = []; var listener = function(e) { calls.push(e); } pane.addListener("cellClick", listener); pane.addListener("cellDblclick", listener); pane.addListener("cellContextmenu", listener); var MouseEventMock = qx.test.ui.virtual.MouseEventMock; var eventMouseToCellEvents = { "click" : "cellClick", "dblclick" : "cellDblclick", "contextmenu" : "cellContextmenu" }; for (var mouseEvent in eventMouseToCellEvents) { var cellEvent = eventMouseToCellEvents[mouseEvent]; calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 99, documentTop: 99})); this.assertEquals(0, calls.length); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 100, documentTop: 100})); this.assertEquals(1, calls.length, cellEvent); this.assertEquals(0, calls[0].getRow(), cellEvent); this.assertEquals(0, calls[0].getColumn(), cellEvent); this.assertEquals(cellEvent, calls[0].getType(), cellEvent); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 160, documentTop: 103})); this.assertEquals(1, calls.length, cellEvent); this.assertEquals(0, calls[0].getRow(), cellEvent); this.assertEquals(1, calls[0].getColumn(), cellEvent); this.assertEquals(cellEvent, calls[0].getType(), cellEvent); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 105, documentTop: 110})); this.assertEquals(1, calls.length, cellEvent); this.assertEquals(1, calls[0].getRow(), cellEvent); this.assertEquals(0, calls[0].getColumn(), cellEvent); this.assertEquals(cellEvent, calls[0].getType(), cellEvent); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 105, documentTop: 125})); this.assertEquals(0, calls.length); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 275, documentTop: 105})); this.assertEquals(0, calls.length); calls = []; pane.dispatchEvent(new MouseEventMock(mouseEvent, {documentLeft: 275, documentTop: 105})); this.assertEquals(0, calls.length); } pane.destroy(); this.flush(); }, testDestroy : function() { this.pane.destroy(); this.flush(); this.assertDestroy(function() { var pane = new qx.ui.virtual.core.Pane( this.rowCount, this.colCount, this.defaultHeight, this.defaultWidth ); this.getRoot().add(pane); pane.destroy(); }, this); } }, destruct : function() { this.pane = null; } });
09zwcbupt/undergrad_thesis
ext/poxdesk/qx/framework/source/class/qx/test/ui/virtual/Pane.js
JavaScript
gpl-3.0
24,514
/** * EditorCommands.js * * Copyright, Moxiecode Systems AB * Released under LGPL License. * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class enables you to add custom editor commands and it contains * overrides for native browser commands to address various bugs and issues. * * @class tinymce.EditorCommands */ define("tinymce/EditorCommands", [ "tinymce/html/Serializer", "tinymce/Env", "tinymce/util/Tools" ], function(Serializer, Env, Tools) { // Added for compression purposes var each = Tools.each, extend = Tools.extend; var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; var isGecko = Env.gecko, isIE = Env.ie; var TRUE = true, FALSE = false; return function(editor) { var dom = editor.dom, selection = editor.selection, commands = {state: {}, exec: {}, value: {}}, settings = editor.settings, formatter = editor.formatter, bookmark; /** * Executes the specified command. * * @method execCommand * @param {String} command Command to execute. * @param {Boolean} ui Optional user interface state. * @param {Object} value Optional value for command. * @return {Boolean} true/false if the command was found or not. */ function execCommand(command, ui, value) { var func; command = command.toLowerCase(); if ((func = commands.exec[command])) { func(command, ui, value); return TRUE; } return FALSE; } /** * Queries the current state for a command for example if the current selection is "bold". * * @method queryCommandState * @param {String} command Command to check the state of. * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. */ function queryCommandState(command) { var func; command = command.toLowerCase(); if ((func = commands.state[command])) { return func(command); } return -1; } /** * Queries the command value for example the current fontsize. * * @method queryCommandValue * @param {String} command Command to check the value of. * @return {Object} Command value of false if it's not found. */ function queryCommandValue(command) { var func; command = command.toLowerCase(); if ((func = commands.value[command])) { return func(command); } return FALSE; } /** * Adds commands to the command collection. * * @method addCommands * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. */ function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); } // Expose public methods extend(this, { execCommand: execCommand, queryCommandState: queryCommandState, queryCommandValue: queryCommandValue, addCommands: addCommands }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undefined) { ui = FALSE; } if (value === undefined) { value = null; } return editor.getDoc().execCommand(command, ui, value); } function isFormatMatch(name) { return formatter.match(name); } function toggleFormat(name, value) { formatter.toggle(name, value ? {value: value} : undefined); editor.nodeChanged(); } function storeSelection(type) { bookmark = selection.getBookmark(type); } function restoreSelection() { selection.moveToBookmark(bookmark); } // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel': function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel': function() { editor.undoManager.add(); }, 'Cut,Copy,Paste': function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { if (isGecko) { editor.windowManager.confirm(editor.getLang('clipboard_msg'), function(state) { if (state) { window.open('http://www.mozilla.org/editor/midasdemo/securityprefs.html', '_blank'); } }); } else { editor.windowManager.alert( "Your browser doesn't support direct access to the clipboard. " + "Please use the Ctrl+X/C/V keyboard shortcuts instead." ); } } }, // Override unlink command unlink: function(command) { if (selection.isCollapsed()) { selection.select(selection.getNode()); } execNativeCommand(command); selection.collapse(FALSE); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { var align = command.substring(7); if (align == 'full') { align = 'justify'; } // Remove all other alignments first each('left,center,right,justify'.split(','), function(name) { if (align != name) { formatter.remove('align' + name); } }); toggleFormat('align' + align); execCommand('mceRepaint'); }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList': function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName': function(command, ui, value) { toggleFormat(command, value); }, FontSize: function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = explode(settings.font_size_style_values); fontClasses = explode(settings.font_size_classes); if (fontClasses) { value = fontClasses[value - 1] || value; } else { value = fontSizes[value - 1] || value; } } toggleFormat(command, value); }, RemoveFormat: function(command) { formatter.remove(command); }, mceBlockQuote: function() { toggleFormat('blockquote'); }, FormatBlock: function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup: function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode: function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth: function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode: function(command, ui, value) { selection.select(value); }, mceInsertContent: function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args; var marker, nodeRect, viewPortRect, rng, node, node2, bookmarkHtml, viewportBodyElement; function trimOrPaddLeftRight(html) { var rng, container, offset; rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; function hasSiblingText(siblingName) { return container[siblingName] && container[siblingName].nodeType == 3; } if (container.nodeType == 3) { if (offset > 0) { html = html.replace(/^&nbsp;/, ' '); } else if (!hasSiblingText('previousSibling')) { html = html.replace(/^ /, '&nbsp;'); } if (offset < container.length) { html = html.replace(/&nbsp;(<br>|)$/, ' '); } else if (!hasSiblingText('nextSibling')) { html = html.replace(/(&nbsp;| )(<br>|)$/, '&nbsp;'); } } return html; } // Check for whitespace before/after value if (/^ | $/.test(value)) { value = trimOrPaddLeftRight(value); } // Setup parser and serializer parser = editor.parser; serializer = new Serializer({}, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html', selection: true}; editor.fire('BeforeSetContent', args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) { value += '{$caret}'; } // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) { editor.getDoc().execCommand('Delete', false, null); } parentNode = selection.getNode(); // Parse the fragment within the context of the parent node args = {context: parentNode.nodeName.toLowerCase()}; fragment = parser.parse(value, args); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { node.parent.insert(marker, node, node.name === 'br'); break; } } } // If parser says valid we can insert the contents into that parent if (!args.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) { dom.setHTML(parentNode, value); } else { selection.setContent(value); } } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) { parentNode = node = rootNode; } else { node = parentNode; } // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) { dom.setHTML(rootNode, value); } else { dom.setOuterHTML(parentNode, value); } } marker = dom.get('mce_marker'); // Scroll range into view scrollIntoView on element can't be used since it will scroll the main view port as well nodeRect = dom.getRect(marker); viewPortRect = dom.getViewPort(editor.getWin()); // Check if node is out side the viewport if it is then scroll to it if ((nodeRect.y + nodeRect.h > viewPortRect.y + viewPortRect.h || nodeRect.y < viewPortRect.y) || (nodeRect.x > viewPortRect.x + viewPortRect.w || nodeRect.x < viewPortRect.x)) { viewportBodyElement = isIE ? editor.getDoc().documentElement : editor.getBody(); viewportBodyElement.scrollLeft = nodeRect.x; viewportBodyElement.scrollTop = nodeRect.y - viewPortRect.h + 25; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); // TODO: Why can't we normalize on IE if (!isIE) { node2 = marker.nextSibling; if (node2 && node2.nodeType == 3) { node.appendData(node2.data); node2.parentNode.removeChild(node2); } } } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); // Dispatch after event and add any visual elements needed editor.fire('SetContent', args); editor.addVisual(); }, mceInsertRawHTML: function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent( editor.getContent().replace(/tiny_mce_marker/g, function() { return value; }) ); }, mceToggleFormat: function(command, ui, value) { toggleFormat(value); }, mceSetContent: function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent': function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue, 10); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { var indentStyleName; if (element.nodeName != "LI") { indentStyleName = dom.getStyle(element, 'direction', true) == 'rtl' ? 'paddingRight' : 'paddingLeft'; if (command == 'outdent') { value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); } else { value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; dom.setStyle(element, indentStyleName, value); } } }); } else { execNativeCommand(command); } }, mceRepaint: function() { if (isGecko) { try { storeSelection(TRUE); if (selection.getSel()) { selection.getSel().selectAllChildren(editor.getBody()); } selection.collapse(TRUE); restoreSelection(); } catch (ex) { // Ignore } } }, InsertHorizontalRule: function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid: function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent: function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'}))); }, mceInsertLink: function(command, ui, value) { var anchor; if (typeof(value) == 'string') { value = {href: value}; } anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll: function() { var root = dom.getRoot(), rng = dom.createRng(); // Old IE does a better job with selectall than new versions if (selection.getRng().setStart) { rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); selection.setRng(rng); } else { execNativeCommand('SelectAll'); } }, mceNewDocument: function() { editor.setContent(''); } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { var name = 'align' + command.substring(7); var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); var matches = map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { return isFormatMatch(command); }, mceBlockQuote: function() { return isFormatMatch('blockquote'); }, Outdent: function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } } return ( queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) ); }, 'InsertUnorderedList,InsertOrderedList': function(command) { var list = dom.getParent(selection.getNode(), 'ul,ol'); return list && ( command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL' ); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName': function(command) { var value = 0, parent; if ((parent = dom.getParent(selection.getNode(), 'span'))) { if (command == 'fontsize') { value = parent.style.fontSize; } else { value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo: function() { editor.undoManager.undo(); }, Redo: function() { editor.undoManager.redo(); } }); }; });
CentidoMS/CentidoMS
admin/js/tinymce/classes/EditorCommands.js
JavaScript
gpl-3.0
19,719
var Index = function () { return { //main function to initiate the module init: function () { App.addResponsiveHandler(function () { Index.initCalendar(); jQuery('.vmaps').each(function () { var map = jQuery(this); map.width(map.parent().width()); }); }); }, initJQVMAP: function () { var showMap = function (name) { jQuery('.vmaps').hide(); jQuery('#vmap_' + name).show(); }; var setMap = function (name) { var data = { map: 'world_en', backgroundColor: null, borderColor: '#333333', borderOpacity: 0.5, borderWidth: 1, color: '#c6c6c6', enableZoom: true, hoverColor: '#c9dfaf', hoverOpacity: null, values: sample_data, normalizeFunction: 'linear', scaleColors: ['#b6da93', '#909cae'], selectedColor: '#c9dfaf', selectedRegion: null, showTooltip: true, onLabelShow: function (event, label, code) { }, onRegionOver: function (event, code) { if (code == 'ca') { event.preventDefault(); } }, onRegionClick: function (element, code, region) { var message = 'You clicked "' + region + '" which has the code: ' + code.toUpperCase(); alert(message); } }; data.map = name + '_en'; var map = jQuery('#vmap_' + name); if (!map) { return; } map.width(map.parent().parent().width()); map.show(); map.vectorMap(data); map.hide(); }; setMap("world"); setMap("usa"); setMap("europe"); setMap("russia"); setMap("germany"); showMap("world"); jQuery('#regional_stat_world').click(function () { showMap("world"); }); jQuery('#regional_stat_usa').click(function () { showMap("usa"); }); jQuery('#regional_stat_europe').click(function () { showMap("europe"); }); jQuery('#regional_stat_russia').click(function () { showMap("russia"); }); jQuery('#regional_stat_germany').click(function () { showMap("germany"); }); $('#region_statistics_loading').hide(); $('#region_statistics_content').show(); }, initCalendar: function () { if (!jQuery().fullCalendar) { return; } var that = $("#calendar"); var feeds = ["EventAction!getListEvent"]; var h = {}; if (that.width() <= 400) { that.addClass("mobile"); h = { left: 'title, prev, next', center: '', right: 'today,month,agendaWeek,agendaDay' }; } else { that.removeClass("mobile"); if (App.isRTL()) { h = { right: 'title', center: '', left: 'prev,next,today,month,agendaWeek,agendaDay' }; } else { h = { left: 'title', center: '', right: 'prev,next,today,month,agendaWeek,agendaDay' }; } } // destroy the calendar that.fullCalendar('destroy'); //re-initialize the calendar calendar = that.fullCalendar({ disableDragging: true, header: h, editable: false, eventSources : [ { url: feeds[0], color: "white", textColor: "black", error: function() { window.alert('Fetching events error', feeds[0]); } } ] }); }, initChat: function () { var cont = $('#chats'); var list = $('.chats', cont); var form = $('.chat-form', cont); var input = $('input', form); var btn = $('.btn', form); var handleClick = function (e) { e.preventDefault(); var text = input.val(); if (text.length == 0) { return; } var time = new Date(); var time_str = time.toString('MMM dd, yyyy hh:mm'); var tpl = ''; tpl += '<li class="out">'; tpl += '<img class="avatar" alt="" src="assets/img/avatar1.jpg"/>'; tpl += '<div class="message">'; tpl += '<span class="arrow"></span>'; tpl += '<a href="#" class="name">Bob Nilson</a>&nbsp;'; tpl += '<span class="datetime">at ' + time_str + '</span>'; tpl += '<span class="body">'; tpl += text; tpl += '</span>'; tpl += '</div>'; tpl += '</li>'; var msg = list.append(tpl); input.val(""); $('.scroller', cont).slimScroll({ scrollTo: list.height() }); } /* $('.scroller', cont).slimScroll({ scrollTo: list.height() }); */ btn.click(handleClick); input.keypress(function (e) { if (e.which == 13) { handleClick(); return false; //<---- Add this line } }); }, initIntro: function () { if ($.cookie('intro_show')) { return; } $.cookie('intro_show', 1); setTimeout(function () { var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Meet Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic is a brand new Responsive Admin Dashboard Template you have always been looking for!', // (string | optional) the image to display on the left image: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 12000); }, 2000); setTimeout(function () { var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Buy Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic comes with a huge collection of reusable and easy customizable UI components and plugins. Buy Metronic today!', // (string | optional) the image to display on the left image: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 13000); }, 8000); setTimeout(function () { $('#styler').pulsate({ color: "#bb3319", repeat: 10 }); $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ position: 'top-left', // (string | mandatory) the heading of the notification title: 'Customize Metronic!', // (string | mandatory) the text inside the notification text: 'Metronic allows you to easily customize the theme colors and layout settings.', // (string | optional) the image to display on the left image1: './assets/img/avatar1.png', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); $.extend($.gritter.options, { position: 'top-right' }); // You can have it return a unique id, this can be used to manually remove it later using setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 15000); }, 23000); setTimeout(function () { $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Notification', // (string | mandatory) the text inside the notification text: 'You have 3 new notifications.', // (string | optional) the image to display on the left image1: './assets/img/image1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 4000); $.extend($.gritter.options, { position: 'top-right' }); var number = $('#header_notification_bar .badge').text(); number = parseInt(number); number = number + 3; $('#header_notification_bar .badge').text(number); $('#header_notification_bar').pulsate({ color: "#66bce6", repeat: 5 }); }, 40000); setTimeout(function () { $.extend($.gritter.options, { position: 'top-left' }); var unique_id = $.gritter.add({ // (string | mandatory) the heading of the notification title: 'Inbox', // (string | mandatory) the text inside the notification text: 'You have 2 new messages in your inbox.', // (string | optional) the image to display on the left image1: './assets/img/avatar1.jpg', // (bool | optional) if you want it to fade out on its own or just sit there sticky: true, // (int | optional) the time you want it to be alive for before fading out time: '', // (string | optional) the class name you want to apply to that specific message class_name: 'my-sticky-class' }); $.extend($.gritter.options, { position: 'top-right' }); setTimeout(function () { $.gritter.remove(unique_id, { fade: true, speed: 'slow' }); }, 4000); var number = $('#header_inbox_bar .badge').text(); number = parseInt(number); number = number + 2; $('#header_inbox_bar .badge').text(number); $('#header_inbox_bar').pulsate({ color: "#dd5131", repeat: 5 }); }, 60000); } }; }();
1bigmac/OA
WebRoot/js/dashboard.js
JavaScript
gpl-3.0
14,347
//* TITLE Post Limit Checker **// //* VERSION 0.2.1 **// //* DESCRIPTION Are you close to the limit? **// //* DETAILS Shows you how many posts you can reblog today. **// //* DEVELOPER STUDIOXENIX **// //* FRAME false **// //* BETA false **// XKit.extensions.post_limit_checker = new Object({ running: false, apiKey: "fuiKNFp9vQFvjLNvx4sUwti4Yb5yGutBN4Xh10LXZhhRKjWlV4", run: function() { this.running = true; XKit.tools.init_css("post_limit_checker"); if (XKit.interface.where().dashboard !== true && XKit.interface.where().channel !== true) { return; } var xf_html = '<ul class="controls_section" id="post_limit_checker_ul">' + '<li class="section_header selected">Post Limit</li>' + '<li class="no_push" style="height: 36px;"><a href="#" onclick="return false;" id="post_limit_checker_view">' + '<div class="hide_overflow" style="color: rgba(255, 255, 255, 0.5) !important; font-weight: bold; padding-left: 10px; padding-top: 8px;">Check Post Limit</div>' + '</a></li>' + '</ul>'; $("ul.controls_section:first").before(xf_html); $("#post_limit_checker_view").click(function() { XKit.extensions.post_limit_checker.start(); }); }, window_id: 0, start: function() { var shown_message = XKit.storage.get("post_limit_checker","shown_warning",""); var m_html = "<div id=\"xkit-plc-list\" class=\"nano\"><div id=\"xkit-plc-list-content\" class=\"content\">" + "<div class=\"xkit-warning-plc-text\"><b>Deleted posts</b><br/>Deleted posts are count by Tumblr, but this tool can't count them. For example, if you've made 250 posts since the last reset but then deleted 50 of them, this tool will tell you that you have 50 more posts to go, but in reality you've already hit your post limit.</div>" + "<div class=\"xkit-warning-plc-text\"><b>Original photo posts</b><br/>There is a separate, 75 uploads per day limit for photo posts. This extension does not check for that.</div>" + "<div class=\"xkit-warning-plc-text\"><b>No Guarantee</b><br/>The XKit Guy is not making any guarantees about the reliability of this tool.</div>" + "</div></div>"; XKit.window.show("Important!","Before beginning, please read the following carefully." + m_html,"warning","<div class=\"xkit-button default\" id=\"xkit-plc-continue\">Continue</div><div class=\"xkit-button default\" id=\"xkit-close-message\">Cancel</div>"); $("#xkit-plc-list").nanoScroller(); $("#xkit-plc-list").nanoScroller({ scroll: 'top' }); $("#xkit-plc-continue").click(function() { XKit.extensions.post_limit_checker.window_id = XKit.tools.random_string(); XKit.window.show("Please wait","Gathering the information I need..." + XKit.progress.add("post-limit-checker-progress"),"info"); var posts = []; for (i=0;i<XKit.tools.get_blogs().length;i++) {posts.push([]);} XKit.extensions.post_limit_checker.next(0, posts, XKit.extensions.post_limit_checker.window_id, XKit.tools.get_blogs(), 0); }); }, get_time: function(m_window_id, posts) { // Calculate the date according to NY time. // To-do: DST calculations? var date = XKit.extensions.post_limit_checker.convert_timezone(Math.round(+new Date()/1000) * 1000, - 4); // Now we need to figure out when the next reset is. var next_reset = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1, 0, 0, 0); var difference = (next_reset - date); var hours = Math.floor((difference % 86400000) / 3600000); var minutes = Math.floor(((difference % 86400000) % 3600000) / 60000); // Now get when the last reset was. Lazy coding. var last_reset = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0); var posts_since_reset = 0; for (var i=0;i<posts.length;i++) { var m_timestamp = XKit.extensions.post_limit_checker.convert_timezone(posts[i].timestamp * 1000, - 4); if ((m_timestamp.getTime() <= next_reset.getTime() && m_timestamp.getTime() >= last_reset.getTime())) { posts_since_reset++; } } var remaining = 250 - posts_since_reset; var remaining_color = "#298a51"; if (remaining <= 60) { remaining_color = "#de8c00"; } if (remaining <= 30) { remaining_color = "#ec0000"; } if (remaining === 0) { remaining = "None"; } var reset_str = hours + " hours and " + minutes + " minutes"; if (hours === 0) { reset_str = minutes + " minutes"; } if (minutes <= 1) { reset_str = "a few seconds"; } if (hours >= 1 && minutes === 0) { reset_str = hours + " hours"; } if (hours == 1) { reset_str = reset_str.replace("hours", "hour"); } if (minutes == 1) { reset_str = reset_str.replace("minutes", "minute"); } var m_html = "<div class=\"xkit-plc-division\">" + "<div class=\"xkit-plc-title\">Posts Made</div>" + "<div class=\"xkit-plc-value\">" + posts_since_reset + "</div>" + "</div>" + "<div class=\"xkit-plc-division\">" + "<div class=\"xkit-plc-title\">Posts Remaining</div>" + "<div class=\"xkit-plc-value\" style=\"font-weight: bold; color: " + remaining_color + "\">" + remaining + "</div>" + "</div>" + "<div class=\"xkit-plc-division\">" + "<div class=\"xkit-plc-title\">Next reset in</div>" + "<div class=\"xkit-plc-value\">" + reset_str + "</div>" + "</div>"; XKit.window.show("Results", "Here is what I could gather:" + m_html, "info", "<div class=\"xkit-button default\" id=\"xkit-close-message\">OK</div>"); }, convert_timezone: function(time, offset) { // From: // http://www.techrepublic.com/article/convert-the-local-time-to-another-time-zone-with-this-javascript/ // create Date object for current location d = new Date(time); // convert to msec // add local time zone offset // get UTC time in msec utc = d.getTime() + (d.getTimezoneOffset() * 60000); // create new Date object for different city // using supplied offset nd = new Date(utc + (3600000*offset)); // return time as a string return nd; }, next: function(page, posts, m_window_id, blogs, index) { if (m_window_id !== XKit.extensions.post_limit_checker.window_id) { console.log("wrong window id. 01"); return; } var offset = page * 20; var api_url = "https://api.tumblr.com/v2/blog/" + blogs[index] + ".tumblr.com/posts/?api_key=" + XKit.extensions.post_limit_checker.apiKey + "&offset=" + offset; GM_xmlhttpRequest({ method: "GET", url: api_url, json: true, onerror: function(response) { console.log("Error getting page."); XKit.extensions.post_limit_checker.display_error(m_window_id, "501"); return; }, onload: function(response) { if (XKit.extensions.post_limit_checker.window_id !== m_window_id) { console.log("wrong window id. 02"); return; } try { data = JSON.parse(response.responseText); for (var i=0;i<data.response.posts.length;i++) { // I would check the date here but I'm a lazy man. posts[index].push(data.response.posts[i]); } XKit.progress.value("post-limit-checker-progress", (posts[index].length / 2.5) - 10); if (posts[index].length >= 250 || data.response.posts.length === 0) { if (index < blogs.length - 1) { index++; setTimeout(function() { XKit.extensions.post_limit_checker.next(0, posts, m_window_id, blogs, index);}, 400); } else { var all_posts = []; all_posts = all_posts.concat.apply(all_posts, posts); XKit.extensions.post_limit_checker.get_time(m_window_id, all_posts); } } else { setTimeout(function() { XKit.extensions.post_limit_checker.next((page + 1), posts, m_window_id, blogs, index); }, 400); } } catch(e) { console.log("Error parsing page, " + e.message); XKit.extensions.post_limit_checker.display_error(m_window_id, "551"); return; } } }); }, display_error: function(m_window_id, err_code) { if (XKit.extensions.post_limit_checker.window_id !== m_window_id) { return; } XKit.window.show("Oops.","An error prevented me from gathering the information needed.<br/>Please try again later.<br/>Code: \"XPLC" + err_code + "\"","error","<div id=\"xkit-close-message\" class=\"xkit-button default\">OK</div>"); }, destroy: function() { $("#post_limit_checker_ul").remove(); $("#post_limit_checker_view").remove(); this.running = false; } });
sshao/XKit
Extensions/post_limit_checker.js
JavaScript
gpl-3.0
8,282
/* * 2007-2015 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2015 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ $(document).ready(function(){ if (typeof formatedAddressFieldsValuesList !== 'undefined') updateAddressesDisplay(true); $(document).on('change', 'select[name=id_address_delivery], select[name=id_address_invoice]', function(){ updateAddressesDisplay(); if (typeof opc !=='undefined' && opc) updateAddressSelection(); }); $(document).on('click', 'input[name=same]', function(){ updateAddressesDisplay(); if (typeof opc !=='undefined' && opc) updateAddressSelection(); }); }); //update the display of the addresses function updateAddressesDisplay(first_view) { // update content of delivery address updateAddressDisplay('delivery'); var txtInvoiceTitle = ""; try{ var adrs_titles = getAddressesTitles(); txtInvoiceTitle = adrs_titles.invoice; } catch (e) {} // update content of invoice address //if addresses have to be equals... if ($('#addressesAreEquals:checked').length === 1 && ($('#multishipping_mode_checkbox:checked').length === 0)) { if ($('#multishipping_mode_checkbox:checked').length === 0) { $('#address_invoice_form:visible').hide('fast'); } $('ul#address_invoice').html($('ul#address_delivery').html()); $('ul#address_invoice li.address_title').html(txtInvoiceTitle); } else { $('#address_invoice_form:hidden').show('fast'); if ($('#id_address_invoice').val()) updateAddressDisplay('invoice'); else { $('ul#address_invoice').html($('ul#address_delivery').html()); $('ul#address_invoice li.address_title').html(txtInvoiceTitle); } } if(!first_view) { if (orderProcess === 'order') updateAddresses(); } return true; } function updateAddressDisplay(addressType) { if (typeof formatedAddressFieldsValuesList == 'undefined' || formatedAddressFieldsValuesList.length <= 0) return; var idAddress = parseInt($('#id_address_' + addressType + '').val()); buildAddressBlock(idAddress, addressType, $('#address_' + addressType)); // change update link var link = $('ul#address_' + addressType + ' li.address_update a').attr('href'); var expression = /id_address=\d+/; if (link) { link = link.replace(expression, 'id_address=' + idAddress); $('ul#address_' + addressType + ' li.address_update a').attr('href', link); } } function updateAddresses() { var idAddress_delivery = parseInt($('#id_address_delivery').val()); var idAddress_invoice = $('#addressesAreEquals:checked').length === 1 ? idAddress_delivery : parseInt($('#id_address_invoice').val()); if(isNaN(idAddress_delivery) == false && isNaN(idAddress_invoice) == false) { $('.addresses .waitimage').show(); $('.button[name="processAddress"]').prop('disabled', 'disabled'); $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType : "json", data: { processAddress: true, step: 2, ajax: 'true', controller: 'order', 'multi-shipping': $('#id_address_delivery:hidden').length, id_address_delivery: idAddress_delivery, id_address_invoice: idAddress_invoice, token: static_token }, success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if(error !== 'indexOf') errors += $('<div />').html(jsonData.errors[error]).text() + "\n"; if (!!$.prototype.fancybox) $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: '<p class="fancybox-error">' + errors + '</p>' } ], { padding: 0 }); else alert(errors); } $('.addresses .waitimage').hide(); $('.button[name="processAddress"]').prop('disabled', ''); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $('.addresses .waitimage').hide(); $('.button[name="processAddress"]').prop('disabled', ''); if (textStatus !== 'abort') { error = "TECHNICAL ERROR: unable to save adresses \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus; if (!!$.prototype.fancybox) $.fancybox.open([ { type: 'inline', autoScale: true, minHeight: 30, content: '<p class="fancybox-error">' + error + '</p>' } ], { padding: 0 }); else alert(error); } } }); } } function getAddressesTitles() { if (typeof titleInvoice !== 'undefined' && typeof titleDelivery !== 'undefined') return { 'invoice': titleInvoice, 'delivery': titleDelivery }; else return { 'invoice': '', 'delivery': '' }; } function buildAddressBlock(id_address, address_type, dest_comp) { if (isNaN(id_address)) return; var adr_titles_vals = getAddressesTitles(); var li_content = formatedAddressFieldsValuesList[id_address]['formated_fields_values']; var ordered_fields_name = ['title']; var reg = new RegExp("[ ]+", "g"); ordered_fields_name = ordered_fields_name.concat(formatedAddressFieldsValuesList[id_address]['ordered_fields']); ordered_fields_name = ordered_fields_name.concat(['update']); dest_comp.html(''); li_content['title'] = adr_titles_vals[address_type]; if (typeof liUpdate !== 'undefined') { var items = liUpdate.split(reg); var regUrl = new RegExp('(https?://[^"]*)', 'gi'); liUpdate = liUpdate.replace(regUrl, addressUrlAdd + parseInt(id_address)); li_content['update'] = liUpdate; } appendAddressList(dest_comp, li_content, ordered_fields_name); } function appendAddressList(dest_comp, values, fields_name) { for (var item in fields_name) { var name = fields_name[item].replace(",", ""); var value = getFieldValue(name, values); if (value != "") { var new_li = document.createElement('li'); var reg = new RegExp("[ ]+", "g"); var classes = name.split(reg); new_li.className = ''; for (clas in classes) new_li.className += 'address_' + classes[clas].toLowerCase().replace(":", "_") + ' '; new_li.className = $.trim(new_li.className); new_li.innerHTML = value; dest_comp.append(new_li); } } } function getFieldValue(field_name, values) { var reg = new RegExp("[ ]+", "g"); var items = field_name.split(reg); var vals = new Array(); for (var field_item in items) { items[field_item] = items[field_item].replace(",", ""); vals.push(values[items[field_item]]); } return vals.join(" "); }
tantchontampo/koomaakiti.com
themes/default-bootstrap/js/order-address.js
JavaScript
gpl-3.0
7,731
export default function(visitable, deletable, creatable, clickable, attribute, collection, filter) { return creatable({ visit: visitable('/:dc/acls'), acls: collection( '[data-test-tabular-row]', deletable({ name: attribute('data-test-acl', '[data-test-acl]'), acl: clickable('a'), actions: clickable('label'), use: clickable('[data-test-use]'), confirmUse: clickable('[data-test-confirm-use]'), }) ), filter: filter, }); }
scalp42/consul
ui-v2/tests/pages/dc/acls/index.js
JavaScript
mpl-2.0
502
/* * Disorder is a class for storing genetic disorder info and loading it from the * the OMIM database. These disorders can be attributed to an individual in the Pedigree. * * @param disorderID the id number for the disorder, taken from the OMIM database * @param name a string representing the name of the disorder e.g. "Down Syndrome" */ var Disorder = Class.create( { initialize: function(disorderID, name, callWhenReady) { // user-defined disorders if (name == null && !isInt(disorderID)) { name = disorderID; } this._disorderID = disorderID; this._name = name ? name : "loading..."; if (!name && callWhenReady) this.load(callWhenReady); }, /* * Returns the disorderID of the disorder */ getDisorderID: function() { return this._disorderID; }, /* * Returns the name of the disorder */ getName: function() { return this._name; }, load: function(callWhenReady) { var baseOMIMServiceURL = Disorder.getOMIMServiceURL(); var queryURL = baseOMIMServiceURL + "&q=id:" + this._disorderID; //console.log("queryURL: " + queryURL); new Ajax.Request(queryURL, { method: "GET", onSuccess: this.onDataReady.bind(this), //onComplete: complete.bind(this) onComplete: callWhenReady ? callWhenReady : {} }); }, onDataReady : function(response) { try { var parsed = JSON.parse(response.responseText); //console.log(stringifyObject(parsed)); console.log("LOADED DISORDER: disorder id = " + this._disorderID + ", name = " + parsed.rows[0].name); this._name = parsed.rows[0].name; } catch (err) { console.log("[LOAD DISORDER] Error: " + err); } } }); Disorder.getOMIMServiceURL = function() { return new XWiki.Document('OmimService', 'PhenoTips').getURL("get", "outputSyntax=plain"); }
itaiGershtansky/phenotips
components/pedigree/resources/src/main/resources/pedigree/disorder.js
JavaScript
agpl-3.0
2,042
/** * Copyright (c) 2014, Oracle and/or its affiliates. * All rights reserved. */ "use strict";var l={"EU":["EU","Eurooppa"]};(this?this:window)['DvtBaseMapManager']['_UNPROCESSED_MAPS'][2].push(["europe","continent",l]);
afsinka/jet_jsp
src/main/webapp/js/libs/oj/v1.1.2/resources/internal-deps/dvt/thematicMap/resourceBundles/EuropeContinentBundle_fi.js
JavaScript
lgpl-2.1
224
enyo.depends( "source/VirtualSlidingPane.js", "source/CanonSlidingView.js", "source/CanonSliding.js" );
enyojs/enyo-1.0
support/examples/Layouts/VirtualSliding/depends.js
JavaScript
apache-2.0
106
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest({ id: "15.2.3.5-4-83", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-83.js", description: "Object.create - 'enumerable' property of one property in 'Properties' is a non-empty string (8.10.5 step 3.b)", test: function testcase() { var accessed = false; var newObj = Object.create({}, { prop: { enumerable: "AB\n\\cd" } }); for (var property in newObj) { if (property === "prop") { accessed = true; } } return accessed; }, precondition: function prereq() { return fnExists(Object.create); } });
hnafar/IronJS
Src/Tests/ietestcenter/chapter15/15.2/15.2.3/15.2.3.5/15.2.3.5-4-83.js
JavaScript
apache-2.0
2,261
/** * Copyright 2015 The AMP HTML Authors. 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. */ // Requires polyfills in immediate side effect. import '../polyfills'; import {user} from '../log'; import {fromClass} from '../service'; /** * Helper with all things Timer. */ export class Timer { /** * @param {!Window} win */ constructor(win) { /** @const {!Window} */ this.win = win; /** @private @const {!Promise} */ this.resolved_ = Promise.resolve(); this.taskCount_ = 0; this.canceled_ = {}; /** @const {number} */ this.startTime_ = Date.now(); } /** * Returns time since start in milliseconds. * @return {number} */ timeSinceStart() { return Date.now() - this.startTime_; } /** * Runs the provided callback after the specified delay. This uses a micro * task for 0 or no specified time. This means that the delay will actually * be close to 0 and this will NOT yield to the event queue. * * Returns the timer ID that can be used to cancel the timer (cancel method). * @param {!function()} callback * @param {number=} opt_delay * @return {number|string} */ delay(callback, opt_delay) { if (!opt_delay) { // For a delay of zero, schedule a promise based micro task since // they are predictably fast. const id = 'p' + this.taskCount_++; this.resolved_.then(() => { if (this.canceled_[id]) { delete this.canceled_[id]; return; } callback(); }); return id; } return this.win.setTimeout(callback, opt_delay); } /** * Cancels the previously scheduled callback. * @param {number|string|null} timeoutId */ cancel(timeoutId) { if (typeof timeoutId == 'string') { this.canceled_[timeoutId] = true; return; } this.win.clearTimeout(timeoutId); } /** * Returns a promise that will resolve after the delay. Optionally, the * resolved value can be provided as opt_result argument. * @param {number=} opt_delay * @param {RESULT=} opt_result * @return {!Promise<RESULT>} * @template RESULT */ promise(opt_delay, opt_result) { let timerKey = null; return new Promise((resolve, reject) => { timerKey = this.delay(() => { timerKey = -1; resolve(opt_result); }, opt_delay); if (timerKey == -1) { reject(new Error('Failed to schedule timer.')); } }).catch(error => { // Clear the timer. The most likely reason is "cancel" signal. if (timerKey != -1) { this.cancel(timerKey); } throw error; }); } /** * Returns a promise that will fail after the specified delay. Optionally, * this method can take opt_racePromise parameter. In this case, the * resulting promise will either fail when the specified delay expires or * will resolve based on the opt_racePromise, whichever happens first. * @param {number} delay * @param {!Promise<RESULT>|undefined} opt_racePromise * @param {string=} opt_message * @return {!Promise<RESULT>} * @template RESULT */ timeoutPromise(delay, opt_racePromise, opt_message) { let timerKey = null; const delayPromise = new Promise((_resolve, reject) => { timerKey = this.delay(() => { timerKey = -1; reject(user().createError(opt_message || 'timeout')); }, delay); if (timerKey == -1) { reject(new Error('Failed to schedule timer.')); } }).catch(error => { // Clear the timer. The most likely reason is "cancel" signal. if (timerKey != -1) { this.cancel(timerKey); } throw error; }); if (!opt_racePromise) { return delayPromise; } return Promise.race([delayPromise, opt_racePromise]); } } /** * @param {!Window} window * @return {!Timer} */ export function installTimerService(window) { return fromClass(window, 'timer', Timer); };
Mixpo/amphtml
src/service/timer-impl.js
JavaScript
apache-2.0
4,487
define(function(require, exports, module) { var showMessage = function(type, message, duration) { var $exist = $('.bootstrap-notify-bar'); if ($exist.length > 0) { $exist.remove(); } var html = '<div class="alert alert-' + type + ' bootstrap-notify-bar" style="display:none;">' html += '<button type="button" class="close" data-dismiss="alert">×</button>'; html += message; html += '</div>'; var $html = $(html); $html.appendTo('body'); $html.slideDown(100, function(){ duration = $.type(duration) == 'undefined' ? 3 : duration; if (duration > 0) { setTimeout(function(){ $html.remove(); }, duration * 1000); } }); } var Notify = { primary: function(message, duration) { showMessage('primary', message, duration); }, success: function(message, duration) { showMessage('success', message, duration); }, warning: function(message, duration) { showMessage('warning', message, duration); }, danger: function(message, duration) { showMessage('danger', message, duration); }, info: function(message, duration) { showMessage('info', message, duration); } }; module.exports = Notify; });
18826252059/im
web/assets/libs/common/bootstrap-notify.js
JavaScript
apache-2.0
1,441
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import { Nav, NavItem, NavDropdown, MenuItem, ProgressBar, } from 'react-bootstrap'; import Navbar, {Brand} from 'react-bootstrap/lib/Navbar'; import history from '../../core/history'; import $ from "jquery"; import Sidebar from '../Sidebar'; const logo = require('./logo.png'); function Header() { return ( <div id="wrapper" className="content"> <Navbar fluid={true} style={ {margin: 0} }> <Brand> <span> <img src={logo} alt="Start React" title="Start React" /> <span>&nbsp;SB Admin React - </span> <a href="http://startreact.com/" title="Start React" rel="home">StartReact.com</a> <button type="button" className="navbar-toggle" onClick={() => {toggleMenu();}} style={{position: 'absolute', right: 0, top: 0}}> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> </span> </Brand> <ul className="nav navbar-top-links navbar-right"> <NavDropdown bsClass="dropdown" title={<span><i className="fa fa-envelope fa-fw"></i></span>} id="navDropdown1"> <MenuItem style={ {width: 300} } eventKey="1"> <div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="2"> <div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="3"> <div> <strong>John Smith</strong> <span className="pull-right text-muted"> <em>Yesterday</em> </span> </div> <div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque eleifend...</div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="4" className="text-center"> <strong>Read All Messages</strong> <i className="fa fa-angle-right"></i> </MenuItem> </NavDropdown> <NavDropdown title={<span><i className="fa fa-tasks fa-fw"></i> </span>} id = 'navDropdown2222'> <MenuItem eventKey="1" style={ {width: 300} }> <div> <p> <strong>Task 1</strong> <span className="pull-right text-muted">40% Complete</span> </p> <div> <ProgressBar bsStyle="success" now={40} /> </div> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="2"> <div> <p> <strong>Task 2</strong> <span className="pull-right text-muted">20% Complete</span> </p> <div> <ProgressBar bsStyle="info" now={20} /> </div> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="3"> <div> <p> <strong>Task 3</strong> <span className="pull-right text-muted">60% Complete</span> </p> <div> <ProgressBar bsStyle="warning" now={60} /> </div> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="4"> <div> <p> <strong>Task 4</strong> <span className="pull-right text-muted">80% Complete</span> </p> <div> <ProgressBar bsStyle="danger" now={80} /> </div> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="5"> <strong>See All Tasks</strong> <i className="fa fa-angle-right"></i> </MenuItem> </NavDropdown> <NavDropdown title={<i className="fa fa-bell fa-fw"></i>} id = 'navDropdown3'> <MenuItem eventKey="1" style={ {width: 300} }> <div> <i className="fa fa-comment fa-fw"></i> New Comment <span className="pull-right text-muted small">4 minutes ago</span> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="2"> <div> <i className="fa fa-twitter fa-fw"></i> 3 New Followers <span className="pull-right text-muted small">12 minutes ago</span> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="3"> <div> <i className="fa fa-envelope fa-fw"></i> Message Sent <span className="pull-right text-muted small">4 minutes ago</span> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="4"> <div> <i className="fa fa-tasks fa-fw"></i> New Task <span className="pull-right text-muted small">4 minutes ago</span> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="5"> <div> <i className="fa fa-upload fa-fw"></i> Server Rebooted <span className="pull-right text-muted small">4 minutes ago</span> </div> </MenuItem> <MenuItem divider /> <MenuItem eventKey="6"> <strong>See All Alerts</strong> <i className="fa fa-angle-right"></i> </MenuItem> </NavDropdown> <NavDropdown title={<i className="fa fa-user fa-fw"></i> } id = 'navDropdown4'> <MenuItem eventKey="1"> <span> <i className="fa fa-user fa-fw"></i> User Profile </span> </MenuItem> <MenuItem eventKey="2"> <span><i className="fa fa-gear fa-fw"></i> Settings </span> </MenuItem> <MenuItem divider /> <MenuItem eventKey = "3" href = 'http://www.strapui.com' > <span> <i className = "fa fa-eye fa-fw" /> Premium React Themes </span> </MenuItem> <MenuItem divider /> <MenuItem eventKey = "4" onClick = {(event) => { history.push('/login');}}> <span> <i className = "fa fa-sign-out fa-fw" /> Logout </span> </MenuItem> </NavDropdown> </ul> <Sidebar /> </Navbar> </div> ); } function toggleMenu(){ if($(".navbar-collapse").hasClass('collapse')){ $(".navbar-collapse").removeClass('collapse'); } else{ $(".navbar-collapse").addClass('collapse'); } } export default Header;
webmaster444/webmaster444.github.io
react/dashboard_example/src/components/Header/Header.js
JavaScript
apache-2.0
7,706
// <![CDATA[ /** * Creative Commons has made the contents of this file * available under a CC-GNU-GPL license: * * http://creativecommons.org/licenses/GPL/2.0/ * * A copy of the full license can be found as part of this * distribution in the file COPYING. * * You may use this software in accordance with the * terms of that license. You agree that you are solely * responsible for your use of this software and you * represent and warrant to Creative Commons that your use * of this software will comply with the CC-GNU-GPL. * * $Id: $ * * Copyright 2006, Creative Commons, www.creativecommons.org. * * This is code that is used to generate licenses. * */ function cc_js_$F(id) { if (cc_js_$(id)) { return cc_js_$(id).value; } return null; // if we can't find the form element, pretend it has no contents } function cc_js_$(id) { return document.getElementById("cc_js_" + id); } /* Inspired by Django. Thanks, guys. * http://code.djangoproject.com/browser/django/trunk/django/views/i18n.py * Our use of gettext is incomplete, so I'm just grabbing the one function. * And I've modified it, anyway. * Here is their license - it applies only to the following function: Copyright (c) 2005, the Lawrence Journal-World All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of Django nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ function cc_js_gettext_style_interpolate(fmt, obj) { return fmt.replace(/\${\w+}/g, function(match){return String(obj[match.slice(2,-1)])}); }
DZielke/laudatio
app/webroot/js/creativecommons/js/cc-prereq.js
JavaScript
apache-2.0
2,890
var a = 10; var b; var c = 10, d, e; var c2, d2 = 10; //# sourceMappingURL=sourceMapValidationVariables.js.map
hippich/typescript
tests/baselines/reference/sourceMapValidationVariables.js
JavaScript
apache-2.0
116
// Editor.js (function() { var STORAGE_KEY = slingUserId+'-browser-file'; var editor = ace.edit("editor"); var saveBtn = $('#saveBtn'); // parent file should set the aceMode variable editor.getSession().setMode(aceMode); editor.getSession().setUseWrapMode(false); editor.getSession().on('change', function(e) { saveBtn[0].disabled=false; }); $('#aceThemeSelect').on('change',function () { var theme = $(this).val(); editor.setTheme("ace/theme/"+theme); setLocalStorage(STORAGE_KEY, {theme:theme}); }) saveBtn.on('click', function(e) { this.disabled=true; $('input#jcrData').val(editor.getValue()); $('#updateForm').submit(); }); $('#editor').css('opacity',1); var storage = getJsonLocalStorage(STORAGE_KEY); if (storage && storage.theme) { $('#aceThemeSelect').val(storage.theme).trigger('change'); } })()
cmseifu/sling-browser
src/main/resources/SLING-CONTENT/apps/browser/static/edit/file.js
JavaScript
apache-2.0
844
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */ /* */ /* 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { /* DEPENDENCIES */ var InstantiateTemplateFormPanel = require('tabs/vrouter-templates-tab/form-panels/instantiate'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); var Tips = require('utils/tips'); var VRouterTemplatesTable = require('tabs/vrouter-templates-tab/datatable'); /* TEMPLATES */ var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { InstantiateTemplateFormPanel.call(this); this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.actions = { 'create': { 'title': Locale.tr("Create Virtual Router"), 'buttonText': Locale.tr("Create"), 'resetButton': true } }; this.templatesTable = new VRouterTemplatesTable( 'vr_create', { 'select': true }); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(InstantiateTemplateFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.setup = _setup; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { var that = this; InstantiateTemplateFormPanel.prototype.setup.call(this, context); $(".selectTemplateTable", context).html(this.templatesTable.dataTableHTML); $(".table_wrapper", context).show(); $(".no_table_wrapper", context).hide(); this.templatesTable.initialize(); this.templatesTable.idInput().attr("required", ""); this.templatesTable.idInput().on("change", function(){ var template_id = $(this).val(); that.setTemplateId(context, template_id); }); $(".vr_attributes #name", context).on("input", function(){ $('#vm_name', context).val("vr-"+$(this).val()+"-%i"); }); Tips.setup(context); return false; } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var virtual_router_json = {virtual_router: {virtual_router_raw: template}}; Sunstone.runAction("VirtualRouter.create",virtual_router_json); return false; } } function _onShow(context) { this.templatesTable.refreshResourceTableSelect(); InstantiateTemplateFormPanel.prototype.onShow.call(this, context); } });
unistra/one
src/sunstone/public/app/tabs/vrouters-tab/form-panels/create.js
JavaScript
apache-2.0
3,937
/** * Copyright 2015 The AMP HTML Authors. 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 {Viewer} from '../../src/service/viewer-impl'; import {dev} from '../../src/log'; import {platformFor} from '../../src/platform'; import {installPlatformService} from '../../src/service/platform-impl'; import {installPerformanceService} from '../../src/service/performance-impl'; import {resetServiceForTesting} from '../../src/service'; import {timerFor} from '../../src/timer'; import {installTimerService} from '../../src/service/timer-impl'; import * as sinon from 'sinon'; describe('Viewer', () => { let sandbox; let windowMock; let viewer; let windowApi; let clock; let events; let errorStub; let platform; function changeVisibility(vis) { windowApi.document.hidden = vis !== 'visible'; windowApi.document.visibilityState = vis; if (events.visibilitychange) { events.visibilitychange({ target: windowApi.document, type: 'visibilitychange', bubbles: false, cancelable: false, }); } } beforeEach(() => { sandbox = sinon.sandbox.create(); clock = sandbox.useFakeTimers(); const WindowApi = function() {}; windowApi = new WindowApi(); installPerformanceService(windowApi); installPerformanceService(window); windowApi.setTimeout = window.setTimeout; windowApi.clearTimeout = window.clearTimeout; windowApi.location = { hash: '', href: '/test/viewer', ancestorOrigins: null, }; windowApi.document = { hidden: false, visibilityState: 'visible', addEventListener: function(type, listener) { events[type] = listener; }, referrer: '', body: {style: {}}, documentElement: {style: {}}, title: 'Awesome doc', }; windowApi.navigator = window.navigator; windowApi.history = { replaceState: sandbox.spy(), }; installPlatformService(windowApi); installTimerService(windowApi); events = {}; errorStub = sandbox.stub(dev(), 'error'); windowMock = sandbox.mock(windowApi); platform = platformFor(windowApi); viewer = new Viewer(windowApi); }); afterEach(() => { resetServiceForTesting(windowApi, 'performance'); resetServiceForTesting(window, 'performance'); windowMock.verify(); sandbox.restore(); }); it('should configure as natural viewport by default', () => { expect(viewer.getViewportType()).to.equal('natural'); expect(viewer.getPaddingTop()).to.equal(0); }); it('should configure correctly based on window name and hash', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.location.hash = '#paddingTop=17&other=something'; const viewer = new Viewer(windowApi); expect(viewer.getViewportType()).to.equal('natural'); expect(viewer.getPaddingTop()).to.equal(17); // All of the startup params are also available via getParam. expect(viewer.getParam('paddingTop')).to.equal('17'); expect(viewer.getParam('other')).to.equal('something'); }); it('should expose viewer capabilities', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.location.hash = '#paddingTop=17&cap=foo,bar'; const viewer = new Viewer(windowApi); expect(viewer.hasCapability('foo')).to.be.true; expect(viewer.hasCapability('bar')).to.be.true; expect(viewer.hasCapability('other')).to.be.false; }); it('should not clear fragment in non-embedded mode', () => { windowApi.parent = windowApi; windowApi.location.href = 'http://www.example.com#test=1'; windowApi.location.hash = '#test=1'; const viewer = new Viewer(windowApi); expect(windowApi.history.replaceState.callCount).to.equal(0); expect(viewer.getParam('test')).to.equal('1'); expect(viewer.hasCapability('foo')).to.be.false; }); it('should clear fragment in embedded mode', () => { windowApi.parent = {}; windowApi.location.href = 'http://www.example.com#test=1'; windowApi.location.hash = '#test=1'; const viewer = new Viewer(windowApi); expect(windowApi.history.replaceState.callCount).to.equal(1); const replace = windowApi.history.replaceState.lastCall; expect(replace.args).to.jsonEqual([{}, '', 'http://www.example.com']); expect(viewer.getParam('test')).to.equal('1'); }); it('should clear fragment when click param is present', () => { windowApi.parent = windowApi; windowApi.location.href = 'http://www.example.com#click=abc'; windowApi.location.hash = '#click=abc'; const viewer = new Viewer(windowApi); expect(windowApi.history.replaceState.callCount).to.equal(1); const replace = windowApi.history.replaceState.lastCall; expect(replace.args).to.jsonEqual([{}, '', 'http://www.example.com']); expect(viewer.getParam('click')).to.equal('abc'); }); it('should configure visibilityState visible by default', () => { expect(viewer.getVisibilityState()).to.equal('visible'); expect(viewer.isVisible()).to.equal(true); expect(viewer.getPrerenderSize()).to.equal(1); expect(viewer.getFirstVisibleTime()).to.equal(0); }); it('should initialize firstVisibleTime for initially visible doc', () => { clock.tick(1); const viewer = new Viewer(windowApi); expect(viewer.isVisible()).to.be.true; expect(viewer.getFirstVisibleTime()).to.equal(1); }); it('should initialize firstVisibleTime when doc becomes visible', () => { clock.tick(1); windowApi.location.hash = '#visibilityState=prerender&prerenderSize=3'; const viewer = new Viewer(windowApi); expect(viewer.isVisible()).to.be.false; expect(viewer.getFirstVisibleTime()).to.be.null; viewer.receiveMessage('visibilitychange', { state: 'visible', }); expect(viewer.isVisible()).to.be.true; expect(viewer.getFirstVisibleTime()).to.equal(1); }); it('should configure visibilityState and prerender', () => { windowApi.location.hash = '#visibilityState=prerender&prerenderSize=3'; const viewer = new Viewer(windowApi); expect(viewer.getVisibilityState()).to.equal('prerender'); expect(viewer.isVisible()).to.equal(false); expect(viewer.getPrerenderSize()).to.equal(3); }); it('should configure performance tracking', () => { windowApi.location.hash = ''; let viewer = new Viewer(windowApi); viewer.messagingMaybePromise_ = Promise.resolve(); expect(viewer.isPerformanceTrackingOn()).to.be.false; windowApi.location.hash = '#csi=1'; viewer = new Viewer(windowApi); viewer.messagingMaybePromise_ = Promise.resolve(); expect(viewer.isPerformanceTrackingOn()).to.be.true; windowApi.location.hash = '#csi=0'; viewer = new Viewer(windowApi); viewer.messagingMaybePromise_ = Promise.resolve(); expect(viewer.isPerformanceTrackingOn()).to.be.false; windowApi.location.hash = '#csi=1'; viewer = new Viewer(windowApi); viewer.messagingMaybePromise_ = null; expect(viewer.isPerformanceTrackingOn()).to.be.false; windowApi.location.hash = '#csi=0'; viewer = new Viewer(windowApi); viewer.messagingMaybePromise_ = null; expect(viewer.isPerformanceTrackingOn()).to.be.false; }); it('should get fragment from the url in non-embedded mode', () => { windowApi.parent = windowApi; windowApi.location.hash = '#foo'; const viewer = new Viewer(windowApi); return viewer.getFragment().then(fragment => { expect(fragment).to.be.equal('foo'); }); }); it('should get fragment from the viewer in embedded mode' + 'if the viewer has capability of getting fragment', () => { windowApi.parent = {}; windowApi.location.hash = '#foo&cap=fragment'; const viewer = new Viewer(windowApi); sandbox.stub(viewer, 'sendMessageUnreliable_', name => { expect(name).to.equal('fragment'); return Promise.resolve('from-viewer'); }); return viewer.getFragment().then(fragment => { expect(fragment).to.be.equal('from-viewer'); }); }); it('should NOT get fragment from the viewer in embedded mode' + 'if the viewer does NOT have capability of getting fragment', () => { windowApi.parent = {}; windowApi.location.hash = '#foo'; const viewer = new Viewer(windowApi); sandbox.stub(viewer, 'sendMessageUnreliable_', name => { expect(name).to.equal('fragment'); return Promise.resolve('from-viewer'); }); return viewer.getFragment().then(fragment => { expect(fragment).to.equal(''); }); }); it('should NOT get fragment from the viewer in embedded mode' + 'if the viewer does NOT return a fragment', () => { windowApi.parent = {}; windowApi.location.hash = '#foo'; const viewer = new Viewer(windowApi); sandbox.stub(viewer, 'sendMessageUnreliable_', name => { expect(name).to.equal('fragment'); return Promise.resolve(); }); return viewer.getFragment().then(fragment => { expect(fragment).to.equal(''); }); }); it('should configure correctly for iOS embedding', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.parent = {}; sandbox.mock(platform).expects('isIos').returns(true).atLeast(1); const viewer = new Viewer(windowApi); expect(viewer.getViewportType()).to.equal('natural-ios-embed'); }); it('should NOT configure for iOS embedding if not embedded', () => { windowApi.name = '__AMP__viewportType=natural'; windowApi.parent = windowApi; sandbox.mock(platform).expects('isIos').returns(true).atLeast(1); windowApi.AMP_MODE = { localDev: false, development: false, }; const viewportType = new Viewer(windowApi).getViewportType(); expect(viewportType).to.equal('natural'); }); it('should receive viewport event', () => { let viewportEvent = null; viewer.onViewportEvent(event => { viewportEvent = event; }); viewer.receiveMessage('viewport', { paddingTop: 19, }); expect(viewportEvent).to.not.equal(null); expect(viewer.getPaddingTop()).to.equal(19); }); describe('should receive the visibilitychange event', () => { it('should change prerenderSize', () => { viewer.receiveMessage('visibilitychange', { prerenderSize: 4, }); expect(viewer.getPrerenderSize()).to.equal(4); }); it('should change visibilityState', () => { viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(viewer.getVisibilityState()).to.equal('paused'); expect(viewer.isVisible()).to.equal(false); }); it('should receive "paused" visibilityState', () => { viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(viewer.getVisibilityState()).to.equal('paused'); expect(viewer.isVisible()).to.equal(false); }); it('should receive "inactive" visibilityState', () => { viewer.receiveMessage('visibilitychange', { state: 'inactive', }); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); }); it('should parse "hidden" as "prerender" before first visible', () => { viewer.hasBeenVisible_ = false; viewer.receiveMessage('visibilitychange', { state: 'hidden', }); expect(viewer.getVisibilityState()).to.equal('prerender'); expect(viewer.isVisible()).to.equal(false); }); it('should parse "hidden" as "inactive" after first visible', () => { viewer.hasBeenVisible_ = true; viewer.receiveMessage('visibilitychange', { state: 'hidden', }); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); }); it('should reject unknown values', () => { viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(() => { viewer.receiveMessage('visibilitychange', { state: 'what is this', }); }).to.throw('Unknown VisibilityState value'); expect(viewer.getVisibilityState()).to.equal('paused'); expect(viewer.isVisible()).to.equal(false); }); it('should be inactive when the viewer tells us we are inactive', () => { viewer.receiveMessage('visibilitychange', { state: 'inactive', }); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); }); it('should be prerender when the viewer tells us we are prerender', () => { viewer.receiveMessage('visibilitychange', { state: 'prerender', }); expect(viewer.getVisibilityState()).to.equal('prerender'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('prerender'); expect(viewer.isVisible()).to.equal(false); }); it('should be hidden when the browser document is hidden', () => { changeVisibility('hidden'); viewer.receiveMessage('visibilitychange', { state: 'visible', }); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'visible', }); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); }); it('should be paused when the browser document is visible but viewer is' + 'paused', () => { changeVisibility('visible'); viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(viewer.getVisibilityState()).to.equal('paused'); expect(viewer.isVisible()).to.equal(false); }); it('should be visible when the browser document is visible', () => { changeVisibility('visible'); viewer.receiveMessage('visibilitychange', { state: 'visible', }); expect(viewer.getVisibilityState()).to.equal('visible'); expect(viewer.isVisible()).to.equal(true); }); it('should be hidden when the browser document is unknown state', () => { changeVisibility('what is this'); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'paused', }); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); }); it('should change visibility on visibilitychange event', () => { changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('visible'); expect(viewer.isVisible()).to.equal(true); viewer.receiveMessage('visibilitychange', { state: 'hidden', }); changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'inactive', }); changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('inactive'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'paused', }); changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('paused'); expect(viewer.isVisible()).to.equal(false); viewer.receiveMessage('visibilitychange', { state: 'visible', }); changeVisibility('hidden'); expect(viewer.getVisibilityState()).to.equal('hidden'); expect(viewer.isVisible()).to.equal(false); changeVisibility('visible'); expect(viewer.getVisibilityState()).to.equal('visible'); expect(viewer.isVisible()).to.equal(true); }); }); it('should post documentLoaded event', () => { viewer.postDocumentReady(); const m = viewer.messageQueue_[0]; expect(m.eventType).to.equal('documentLoaded'); expect(m.data.title).to.equal('Awesome doc'); }); it('should post scroll event', () => { viewer.postScroll(111); const m = viewer.messageQueue_[0]; expect(m.eventType).to.equal('scroll'); expect(m.data.scrollTop).to.equal(111); }); it('should post request/cancelFullOverlay event', () => { viewer.requestFullOverlay(); viewer.cancelFullOverlay(); expect(viewer.messageQueue_[0].eventType).to.equal('requestFullOverlay'); expect(viewer.messageQueue_[1].eventType).to.equal('cancelFullOverlay'); }); it('should queue non-dupe events', () => { viewer.postDocumentReady(); viewer.postDocumentReady(); expect(viewer.messageQueue_.length).to.equal(1); expect(viewer.messageQueue_[0].eventType).to.equal('documentLoaded'); }); describe('baseCid', () => { const cidData = JSON.stringify({ time: 100, cid: 'cid-123', }); let trustedViewer; let persistedCidData; let shouldTimeout; beforeEach(() => { shouldTimeout = false; clock.tick(100); trustedViewer = true; persistedCidData = cidData; sandbox.stub(viewer, 'isTrustedViewer', () => Promise.resolve(trustedViewer)); sandbox.stub(viewer, 'sendMessage', (message, payload) => { if (message != 'cid') { return Promise.reject(); } if (shouldTimeout) { return timerFor(window).promise(15000); } if (payload) { persistedCidData = payload; } return Promise.resolve(persistedCidData); }); }); it('should return CID', () => { const p = expect(viewer.baseCid()).to.eventually.equal(cidData); p.then(() => { // This should not trigger a timeout. clock.tick(100000); }); return p; }); it('should not request cid for untrusted viewer', () => { trustedViewer = false; return expect(viewer.baseCid()).to.eventually.be.undefined; }); it('should convert CID returned by legacy API to new format', () => { persistedCidData = 'cid-123'; return expect(viewer.baseCid()).to.eventually.equal(cidData); }); it('should send message to store cid', () => { const newCidData = JSON.stringify({time: 101, cid: 'cid-456'}); return expect(viewer.baseCid(newCidData)) .to.eventually.equal(newCidData); }); it('should time out', () => { shouldTimeout = true; const p = expect(viewer.baseCid()).to.eventually.be.undefined; Promise.resolve().then(() => { clock.tick(9999); Promise.resolve().then(() => { clock.tick(1); }); }); return p.then(() => { // Ticked 100 at start. expect(Date.now()).to.equal(10100); }); }); }); it('should dequeue events when deliverer set', () => { viewer.postDocumentReady(); expect(viewer.messageQueue_.length).to.equal(1); const delivered = []; viewer.setMessageDeliverer((eventType, data) => { delivered.push({eventType, data}); }, 'https://acme.com'); expect(viewer.messageQueue_.length).to.equal(0); expect(delivered.length).to.equal(1); expect(delivered[0].eventType).to.equal('documentLoaded'); }); describe('Messaging not embedded', () => { it('should not expect messaging', () => { expect(viewer.messagingReadyPromise_).to.be.null; expect(viewer.messagingMaybePromise_).to.be.null; }); it('should fail sendMessage', () => { return viewer.sendMessage('message1', {}, /* awaitResponse */ false) .then(() => { throw new Error('should not succeed'); }, error => { expect(error.message).to.match(/No messaging channel/); }); }); it('should post broadcast event but not fail', () => { viewer.broadcast({type: 'type1'}); expect(viewer.messageQueue_.length).to.equal(0); }); }); describe('Messaging', () => { beforeEach(() => { windowApi.parent = {}; viewer = new Viewer(windowApi); }); it('should receive broadcast event', () => { let broadcastMessage = null; viewer.onBroadcast(message => { broadcastMessage = message; }); viewer.receiveMessage('broadcast', {type: 'type1'}); expect(broadcastMessage).to.exist; expect(broadcastMessage.type).to.equal('type1'); }); it('should post broadcast event', () => { const delivered = []; viewer.setMessageDeliverer((eventType, data) => { delivered.push({eventType, data}); }, 'https://acme.com'); viewer.broadcast({type: 'type1'}); expect(viewer.messageQueue_.length).to.equal(0); return viewer.messagingMaybePromise_.then(() => { expect(delivered.length).to.equal(1); const m = delivered[0]; expect(m.eventType).to.equal('broadcast'); expect(m.data.type).to.equal('type1'); }); }); it('should post broadcast event but not fail w/o messaging', () => { viewer.broadcast({type: 'type1'}); expect(viewer.messageQueue_.length).to.equal(0); clock.tick(20001); return viewer.messagingReadyPromise_.then(() => 'OK', () => 'ERROR') .then(res => { expect(res).to.equal('ERROR'); return viewer.messagingMaybePromise_; }).then(() => { expect(viewer.messageQueue_.length).to.equal(0); }); }); it('should wait for messaging channel', () => { let m1Resolved = false; let m2Resolved = false; const m1 = viewer.sendMessage('message1', {}, /* awaitResponse */ false) .then(() => { m1Resolved = true; }); const m2 = viewer.sendMessage('message2', {}, /* awaitResponse */ true) .then(() => { m2Resolved = true; }); return Promise.resolve().then(() => { // Not resolved yet. expect(m1Resolved).to.be.false; expect(m2Resolved).to.be.false; // Set message deliverer. viewer.setMessageDeliverer(() => { return Promise.resolve(); }, 'https://acme.com'); expect(m1Resolved).to.be.false; expect(m2Resolved).to.be.false; return Promise.all([m1, m2]); }).then(() => { // All resolved now. expect(m1Resolved).to.be.true; expect(m2Resolved).to.be.true; }); }); it('should timeout messaging channel', () => { let m1Resolved = false; let m2Resolved = false; const m1 = viewer.sendMessage('message1', {}, /* awaitResponse */ false) .then(() => { m1Resolved = true; }); const m2 = viewer.sendMessage('message2', {}, /* awaitResponse */ true) .then(() => { m2Resolved = true; }); return Promise.resolve().then(() => { // Not resolved yet. expect(m1Resolved).to.be.false; expect(m2Resolved).to.be.false; // Timeout. clock.tick(20001); return Promise.all([m1, m2]); }).then(() => { throw new Error('must never be here'); }, () => { // Not resolved ever. expect(m1Resolved).to.be.false; expect(m2Resolved).to.be.false; }); }); }); describe('isEmbedded', () => { it('should NOT be embedded when not iframed or w/o "origin"', () => { windowApi.parent = windowApi; expect(new Viewer(windowApi).isEmbedded()).to.be.false; }); it('should be embedded when iframed', () => { windowApi.parent = {}; expect(new Viewer(windowApi).isEmbedded()).to.be.true; }); it('should be embedded with "origin" param', () => { windowApi.parent = windowApi; windowApi.location.hash = '#webview=1'; expect(new Viewer(windowApi).isEmbedded()).to.be.true; }); }); describe('isTrustedViewer', () => { function test(origin, toBeTrusted) { const viewer = new Viewer(windowApi); expect(viewer.isTrustedViewerOrigin_(origin)).to.equal(toBeTrusted); } it('should consider non-trusted when not iframed', () => { windowApi.parent = windowApi; windowApi.location.ancestorOrigins = ['https://google.com']; return new Viewer(windowApi).isTrustedViewer().then(res => { expect(res).to.be.false; }); }); it('should consider trusted by ancestor', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = ['https://google.com']; return new Viewer(windowApi).isTrustedViewer().then(res => { expect(res).to.be.true; }); }); it('should consider non-trusted without ancestor', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = []; return new Viewer(windowApi).isTrustedViewer().then(res => { expect(res).to.be.false; }); }); it('should consider non-trusted with wrong ancestor', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = ['https://untrusted.com']; return new Viewer(windowApi).isTrustedViewer().then(res => { expect(res).to.be.false; }); }); it('should decide trusted on connection with origin', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = null; const viewer = new Viewer(windowApi); viewer.setMessageDeliverer(() => {}, 'https://google.com'); return viewer.isTrustedViewer().then(res => { expect(res).to.be.true; }); }); it('should NOT allow channel without origin', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = null; const viewer = new Viewer(windowApi); expect(() => { viewer.setMessageDeliverer(() => {}); }).to.throw(/message channel must have an origin/); }); it('should decide non-trusted on connection with wrong origin', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = null; const viewer = new Viewer(windowApi); viewer.setMessageDeliverer(() => {}, 'https://untrusted.com'); return viewer.isTrustedViewer().then(res => { expect(res).to.be.false; }); }); it('should give precedence to ancestor', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); viewer.setMessageDeliverer(() => {}, 'https://untrusted.com'); return viewer.isTrustedViewer().then(res => { expect(res).to.be.true; }); }); it('should trust domain variations', () => { test('https://google.com', true); test('https://www.google.com', true); test('https://news.google.com', true); test('https://google.co', true); test('https://www.google.co', true); test('https://news.google.co', true); test('https://www.google.co.uk', true); test('https://www.google.co.au', true); test('https://news.google.co.uk', true); test('https://news.google.co.au', true); test('https://google.de', true); test('https://www.google.de', true); test('https://news.google.de', true); test('https://abc.www.google.com', true); }); it('should not trust host as referrer with http', () => { test('http://google.com', false); }); it('should NOT trust wrong or non-whitelisted domain variations', () => { test('https://google.net', false); test('https://google.other.com', false); test('https://www.google.other.com', false); test('https://withgoogle.com', false); test('https://acme.com', false); test('https://google', false); test('https://www.google', false); }); }); describe('referrer', () => { it('should return document referrer if not overriden', () => { windowApi.parent = {}; windowApi.location.hash = '#'; windowApi.document.referrer = 'https://acme.org/docref'; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/docref'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/docref'); expect(errorStub.callCount).to.equal(0); }); }); it('should NOT allow override if not iframed', () => { windowApi.parent = windowApi; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/docref'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/docref'); expect(errorStub.callCount).to.equal(0); }); }); it('should NOT allow override if not trusted', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; windowApi.location.ancestorOrigins = ['https://untrusted.com']; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/docref'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/docref'); expect(errorStub.callCount).to.equal(0); }); }); it('should NOT allow override if ancestor is empty', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; windowApi.location.ancestorOrigins = []; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/docref'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/docref'); expect(errorStub.callCount).to.equal(0); }); }); it('should allow partial override if async not trusted', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; const viewer = new Viewer(windowApi); // Unconfirmed referrer is overriden, but not confirmed yet. expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/viewer'); viewer.setMessageDeliverer(() => {}, 'https://untrusted.com'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/docref'); // Unconfirmed referrer is reset. Async error is thrown. expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/docref'); expect(errorStub.callCount).to.equal(1); expect(errorStub.calledWith('Viewer', sinon.match(arg => { return !!arg.match(/Untrusted viewer referrer override/); }))).to.be.true; }); }); it('should allow full override if async trusted', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; const viewer = new Viewer(windowApi); // Unconfirmed referrer is overriden and will be confirmed next. expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/viewer'); viewer.setMessageDeliverer(() => {}, 'https://google.com'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/viewer'); // Unconfirmed is confirmed and kept. expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/viewer'); expect(errorStub.callCount).to.equal(0); }); }); it('should allow override if iframed and trusted', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer=' + encodeURIComponent('https://acme.org/viewer'); windowApi.document.referrer = 'https://acme.org/docref'; windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal('https://acme.org/viewer'); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal('https://acme.org/viewer'); expect(errorStub.callCount).to.equal(0); }); }); it('should allow override to empty if iframed and trusted', () => { windowApi.parent = {}; windowApi.location.hash = '#referrer='; windowApi.document.referrer = 'https://acme.org/docref'; windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); expect(viewer.getUnconfirmedReferrerUrl()) .to.equal(''); return viewer.getReferrerUrl().then(referrerUrl => { expect(referrerUrl).to.equal(''); expect(errorStub.callCount).to.equal(0); }); }); }); describe('viewerUrl', () => { it('should initially always return current location', () => { windowApi.location.href = 'https://acme.org/doc1#hash'; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); }); it('should always return current location for top-level window', () => { windowApi.parent = windowApi; windowApi.location.href = 'https://acme.org/doc1#hash'; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(0); }); }); it('should NOT allow override if not iframed', () => { windowApi.parent = windowApi; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(0); }); }); it('should NOT allow override if not trusted', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); windowApi.location.ancestorOrigins = ['https://untrusted.com']; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(1); expect(errorStub.calledWith('Viewer', sinon.match(arg => { return !!arg.match(/Untrusted viewer url override/); }))).to.be.true; }); }); it('should NOT allow override if ancestor is empty', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); windowApi.location.ancestorOrigins = []; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(1); expect(errorStub.calledWith('Viewer', sinon.match(arg => { return !!arg.match(/Untrusted viewer url override/); }))).to.be.true; }); }); it('should allow partial override if async not trusted', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); viewer.setMessageDeliverer(() => {}, 'https://untrusted.com'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(1); expect(errorStub.calledWith('Viewer', sinon.match(arg => { return !!arg.match(/Untrusted viewer url override/); }))).to.be.true; }); }); it('should allow full override if async trusted', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); viewer.setMessageDeliverer(() => {}, 'https://google.com'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/viewer'); expect(viewer.getResolvedViewerUrl()) .to.equal('https://acme.org/viewer'); expect(errorStub.callCount).to.equal(0); }); }); it('should allow override if iframed and trusted', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl=' + encodeURIComponent('https://acme.org/viewer'); windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/viewer'); expect(viewer.getResolvedViewerUrl()) .to.equal('https://acme.org/viewer'); expect(errorStub.callCount).to.equal(0); }); }); it('should ignore override to empty if iframed and trusted', () => { windowApi.parent = {}; windowApi.location.href = 'https://acme.org/doc1'; windowApi.location.hash = '#viewerUrl='; windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); return viewer.getViewerUrl().then(viewerUrl => { expect(viewerUrl).to.equal('https://acme.org/doc1'); expect(viewer.getResolvedViewerUrl()).to.equal('https://acme.org/doc1'); expect(errorStub.callCount).to.equal(0); }); }); }); describe('viewerOrigin', () => { it('should return empty string if origin is not known', () => { const viewer = new Viewer(windowApi); return viewer.getViewerOrigin().then(viewerOrigin => { expect(viewerOrigin).to.equal(''); }); }); it('should return ancestor origin if known', () => { windowApi.parent = {}; windowApi.location.ancestorOrigins = ['https://google.com']; const viewer = new Viewer(windowApi); return viewer.getViewerOrigin().then(viewerOrigin => { expect(viewerOrigin).to.equal('https://google.com'); }); }); it('should return viewer origin if set via handshake', () => { windowApi.parent = {}; const viewer = new Viewer(windowApi); const result = viewer.getViewerOrigin().then(viewerOrigin => { expect(viewerOrigin).to.equal('https://foobar.com'); }); viewer.setMessageDeliverer(() => {}, 'https://foobar.com'); return result; }); it('should return empty string if handshake does not happen', () => { windowApi.parent = {}; const viewer = new Viewer(windowApi); const result = viewer.getViewerOrigin().then(viewerOrigin => { expect(viewerOrigin).to.equal(''); }); clock.tick(1010); return result; }); }); describe('navigateTo', () => { const ampUrl = 'https://cdn.ampproject.org/test/123'; it('should initiate a2a navigation', () => { windowApi.location.hash = '#cap=a2a'; windowApi.top = { location: {}, }; const viewer = new Viewer(windowApi); const send = sandbox.stub(viewer, 'sendMessage'); viewer.navigateTo(ampUrl, 'abc123'); expect(send.lastCall.args[0]).to.equal('a2a'); expect(send.lastCall.args[1]).to.jsonEqual({ url: ampUrl, requestedBy: 'abc123', }); expect(windowApi.top.location.href).to.be.undefined; }); it('should fail for non-amp url', () => { windowApi.location.hash = '#cap=a2a'; const viewer = new Viewer(windowApi); sandbox.stub(viewer, 'sendMessage'); expect(() => { viewer.navigateTo('http://www.test.com', 'abc123'); }).to.throw(/Invalid A2A URL/); }); it('should perform fallback navigation', () => { windowApi.top = { location: {}, }; const viewer = new Viewer(windowApi); const send = sandbox.stub(viewer, 'sendMessage'); viewer.navigateTo(ampUrl, 'abc123'); expect(send.callCount).to.equal(0); expect(windowApi.top.location.href).to.equal(ampUrl); }); }); });
Mixpo/amphtml
test/functional/test-viewer.js
JavaScript
apache-2.0
43,772
define(function (require) { 'use strict'; var modules = require('modules'); var $ = require('jquery'); modules.get('a4c-common').factory('resizeServices', ['$timeout', function($timeout) { // the default min width and height for the application var minWidth = 640; var minHeight = 200; return { registerContainer: function(callback, selector) { var container = $(selector); var instance = this; window.onresize = function() { if (container.size()) { var offsets = container.offset(); if (offsets && offsets.top && offsets.left) { callback(instance.getWidth(offsets.left), instance.getHeight(offsets.top)); } } }; this.initSize(); }, register: function(callback, widthOffset, heightOffset) { var instance = this; window.onresize = function() { callback(instance.getWidth(widthOffset), instance.getHeight(heightOffset)); }; this.initSize(); }, initSize: function() { $timeout(function() { window.onresize(); }); }, getHeight : function(offset){ var height = $(window).height(); if(height < minHeight) { height = minHeight; } return height - offset; }, getWidth : function(offset) { var width = $(window).width(); if(width < minWidth) { width = minWidth; } return width - offset; } }; }]); // factory }); // define
broly-git/alien4cloud
alien4cloud-ui/src/main/webapp/scripts/common/services/resize_services.js
JavaScript
apache-2.0
1,572
/* global girderTest, describe, it, expect, runs, waitsFor, girder, beforeEach */ girderTest.importPlugin('terms'); girderTest.startApp(); describe('Create and log in to a user for testing', function () { it('create an admin user', girderTest.createUser('rocky', 'rocky@phila.pa.us', 'Robert', 'Balboa', 'adrian')); it('allow all users to create collections', function () { var settingSaved; runs(function () { settingSaved = false; girder.rest.restRequest({ url: 'system/setting', method: 'PUT', data: { key: 'core.collection_create_policy', value: JSON.stringify({ groups: [], open: true, users: [] }) } }) .done(function () { settingSaved = true; }); }); waitsFor(function () { return settingSaved; }); }); it('logout', girderTest.logout()); it('create a collection admin user', girderTest.createUser('creed', 'creed@la.ca.us', 'Apollo', 'Creed', 'the1best')); }); describe('Ensure that basic collections still work', function () { it('go to collections page', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-create-button:visible').length > 0; }); runs(function () { expect($('.g-collection-list-entry').length).toBe(0); }); }); it('create a basic collection', girderTest.createCollection('Basic Collection', 'Some description.', 'Basic Folder')); }); describe('Navigate to a non-collection folder and item', function () { it('navigate to user folders page', function () { runs(function () { $('a.g-my-folders').trigger('click'); }); waitsFor(function () { return $('.g-user-header').length > 0 && $('.g-folder-list-entry').length > 0; }); }); it('navigate to the Public folder', function () { runs(function () { var folderLink = $('.g-folder-list-link:contains("Public")'); expect(folderLink.length).toBe(1); folderLink.trigger('click'); }); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); girderTest.waitForLoad(); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Public'); var folderId = window.location.hash.split('/')[3]; expect(folderId).toMatch(/[0-9a-f]{24}/); window.location.assign('#folder/' + folderId); }); // after setting a window location, waitForLoad is insufficient, as the // page hasn't yet started making requests and it looks similar to // before the location change. Wait for the user header to be hidden, // and then wait for load. waitsFor(function () { return $('.g-user-header').length === 0; }, 'the user header to go away'); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); }); it('create an item', function () { runs(function () { $('.g-create-item').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('User Item'); $('.g-save-item').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-list-link').length > 0; }); }); it('navigate to the new item', function () { runs(function () { var itemLink = $('.g-item-list-link:contains("User Item")'); expect(itemLink.length).toBe(1); itemLink.trigger('click'); }); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('User Item'); termsItemId = window.location.hash.split('/')[1]; expect(termsItemId).toMatch(/[0-9a-f]{24}/); }); }); }); var termsCollectionId, termsFolderId, termsItemId; describe('Create a collection with terms', function () { it('go to collections page', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-create-button:visible').length > 0; }); }); it('open the create collection dialog', function () { waitsFor(function () { return $('.g-collection-create-button').is(':enabled'); }); runs(function () { $('.g-collection-create-button').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('#collection-terms-write .g-markdown-text').is(':visible'); }); }); it('fill and submit the create collection dialog', function () { runs(function () { $('#g-name').val('Terms Collection'); $('#collection-description-write .g-markdown-text').val('Some other description.'); $('#collection-terms-write .g-markdown-text').val('# Sample Terms of Use\n\n**\u00af\\\\\\_(\u30c4)\\_/\u00af**'); $('.g-save-collection').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); termsCollectionId = window.location.hash.split('/')[1]; expect(termsCollectionId).toMatch(/[0-9a-f]{24}/); }); }); it('make the collection public', function () { runs(function () { $('.g-edit-access').trigger('click'); }); girderTest.waitForDialog(); runs(function () { $('#g-access-public').trigger('click'); $('.g-save-access-list').trigger('click'); }); girderTest.waitForLoad(); }); it('check the collection info dialog', function () { runs(function () { $('.g-collection-info-button').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.g-terms-info').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); }); runs(function () { $('.modal-header .close').trigger('click'); }); girderTest.waitForLoad(); }); it('create a folder', function () { runs(function () { return $('.g-create-subfolder').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('Terms Folder'); $('.g-save-folder').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-folder-list-link').length > 0; }); }); it('navigate to the new folder', function () { runs(function () { var folderLink = $('.g-folder-list-link:contains("Terms Folder")'); expect(folderLink.length).toBe(1); folderLink.trigger('click'); }); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Terms Folder'); termsFolderId = window.location.hash.split('/')[3]; expect(termsFolderId).toMatch(/[0-9a-f]{24}/); }); }); it('create an item', function () { runs(function () { return $('.g-create-item').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('.modal-body input#g-name').length > 0; }); runs(function () { $('#g-name').val('Terms Item'); $('.g-save-item').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-list-link').length > 0; }); }); it('navigate to the new item', function () { runs(function () { var itemLink = $('.g-item-list-link:contains("Terms Item")'); expect(itemLink.length).toBe(1); itemLink.trigger('click'); }); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('Terms Item'); termsItemId = window.location.hash.split('/')[1]; expect(termsItemId).toMatch(/[0-9a-f]{24}/); }); }); }); // TODO: rerun this whole suite while logged in describe('Ensure that anonymous users are presented with terms', function () { beforeEach(function () { window.localStorage.clear(); }); it('logout', girderTest.logout()); it('navigate to the collection page, rejecting terms', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-reject').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-frontpage-header').length > 0; }); }); it('navigate to the collection page', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); it('navigate to the folder page', function () { runs(function () { window.location.assign('#folder/' + termsFolderId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-count-container:visible').length === 1; }); runs(function () { expect($('.g-hierarchy-breadcrumb-bar>.breadcrumb>.active').text()).toBe('Terms Folder'); }); }); it('navigate to the item page', function () { runs(function () { window.location.assign('#item/' + termsItemId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('Sample Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-item-header').length > 0; }); runs(function () { expect($('.g-item-header .g-item-name').text()).toBe('Terms Item'); }); }); }); // TODO: edit the collection with WRITE permissions only describe('Change the terms', function () { it('login as collection admin', girderTest.login('creed', 'Apollo', 'Creed', 'the1best')); it('navigate to the terms collection', function () { runs(function () { $('a.g-nav-link[g-target="collections"]').trigger('click'); }); waitsFor(function () { return $('.g-collection-list-entry').length > 0; }); girderTest.waitForLoad(); runs(function () { $('.g-collection-link:contains("Terms Collection")').trigger('click'); }); waitsFor(function () { return $('.g-collection-header').length > 0; }); girderTest.waitForLoad(); }); it('edit the collection terms', function () { runs(function () { $('.g-edit-folder').trigger('click'); }); girderTest.waitForDialog(); waitsFor(function () { return $('#collection-terms-write .g-markdown-text').is(':visible'); }); runs(function () { $('#collection-terms-write .g-markdown-text').val('# New Terms of Use\n\nThese have changed.'); $('.g-save-collection').trigger('click'); }); girderTest.waitForLoad(); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); }); describe('Ensure that anonymous users need to re-accept the updated terms', function () { it('logout', girderTest.logout()); it('ensure that the old terms acceptance is still stored', function () { expect(window.localStorage.length).toBe(1); }); it('navigate to the collection page', function () { runs(function () { window.location.assign('#collection/' + termsCollectionId); }); waitsFor(function () { return $('.g-terms-container').length > 0; }); runs(function () { expect($('.g-terms-info>h1').text()).toBe('New Terms of Use'); $('#g-terms-accept').trigger('click'); }); girderTest.waitForLoad(); waitsFor(function () { return $('.g-collection-header').length > 0; }); runs(function () { expect($('.g-collection-header .g-collection-name').text()).toBe('Terms Collection'); }); }); });
Kitware/girder
plugins/terms/plugin_tests/termsSpec.js
JavaScript
apache-2.0
14,763
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- info: The length property of shift has the attribute DontEnum es5id: 15.4.4.9_A5.1 description: Checking use propertyIsEnumerable, for-in ---*/ //CHECK#1 if (Array.prototype.shift.propertyIsEnumerable('length') !== false) { $ERROR('#1: Array.prototype.shift.propertyIsEnumerable(\'length\') === false. Actual: ' + (Array.prototype.shift.propertyIsEnumerable('length'))); } //CHECK#2 var result = true; for (var p in Array.prototype.shift){ if (p === "length") { result = false; } } if (result !== true) { $ERROR('#2: result = true; for (p in Array.prototype.shift) { if (p === "length") result = false; } result === true;'); }
m0ppers/arangodb
3rdParty/V8/V8-5.0.71.39/test/test262/data/test/built-ins/Array/prototype/shift/S15.4.4.9_A5.1.js
JavaScript
apache-2.0
782
//>>built define( "dojox/editor/plugins/nls/hr/CollapsibleToolbar", ({ "collapse": "Spusti traku s alatima editora", "expand": "Proširi traku s alatima editora" }) );
cfxram/grails-dojo
web-app/js/dojo/1.7.2/dojox/editor/plugins/nls/hr/CollapsibleToolbar.js
JavaScript
apache-2.0
170
'use strict'; // Meta data used by the AngularJS docs app angular.module('pagesData', []) .value('NG_PAGES', { "api": { "name": "API Reference", "area": "api", "path": "api" }, "error/$animate/nocb": { "name": "nocb", "area": "error", "path": "error/$animate/nocb" }, "error/$animate/notcsel": { "name": "notcsel", "area": "error", "path": "error/$animate/notcsel" }, "error/$cacheFactory/iid": { "name": "iid", "area": "error", "path": "error/$cacheFactory/iid" }, "error/$compile/baddir": { "name": "baddir", "area": "error", "path": "error/$compile/baddir" }, "error/$compile/ctreq": { "name": "ctreq", "area": "error", "path": "error/$compile/ctreq" }, "error/$compile/infchng": { "name": "infchng", "area": "error", "path": "error/$compile/infchng" }, "error/$compile/iscp": { "name": "iscp", "area": "error", "path": "error/$compile/iscp" }, "error/$compile/multidir": { "name": "multidir", "area": "error", "path": "error/$compile/multidir" }, "error/$compile/noctrl": { "name": "noctrl", "area": "error", "path": "error/$compile/noctrl" }, "error/$compile/nodomevents": { "name": "nodomevents", "area": "error", "path": "error/$compile/nodomevents" }, "error/$compile/noident": { "name": "noident", "area": "error", "path": "error/$compile/noident" }, "error/$compile/nonassign": { "name": "nonassign", "area": "error", "path": "error/$compile/nonassign" }, "error/$compile/reqslot": { "name": "reqslot", "area": "error", "path": "error/$compile/reqslot" }, "error/$compile/selmulti": { "name": "selmulti", "area": "error", "path": "error/$compile/selmulti" }, "error/$compile/tpload": { "name": "tpload", "area": "error", "path": "error/$compile/tpload" }, "error/$compile/tplrt": { "name": "tplrt", "area": "error", "path": "error/$compile/tplrt" }, "error/$compile/uterdir": { "name": "uterdir", "area": "error", "path": "error/$compile/uterdir" }, "error/$controller/ctrlfmt": { "name": "ctrlfmt", "area": "error", "path": "error/$controller/ctrlfmt" }, "error/$controller/noscp": { "name": "noscp", "area": "error", "path": "error/$controller/noscp" }, "error/$http/badreq": { "name": "badreq", "area": "error", "path": "error/$http/badreq" }, "error/$http/legacy": { "name": "legacy", "area": "error", "path": "error/$http/legacy" }, "error/$injector/cdep": { "name": "cdep", "area": "error", "path": "error/$injector/cdep" }, "error/$injector/itkn": { "name": "itkn", "area": "error", "path": "error/$injector/itkn" }, "error/$injector/modulerr": { "name": "modulerr", "area": "error", "path": "error/$injector/modulerr" }, "error/$injector/nomod": { "name": "nomod", "area": "error", "path": "error/$injector/nomod" }, "error/$injector/pget": { "name": "pget", "area": "error", "path": "error/$injector/pget" }, "error/$injector/strictdi": { "name": "strictdi", "area": "error", "path": "error/$injector/strictdi" }, "error/$injector/undef": { "name": "undef", "area": "error", "path": "error/$injector/undef" }, "error/$injector/unpr": { "name": "unpr", "area": "error", "path": "error/$injector/unpr" }, "error/$interpolate/badexpr": { "name": "badexpr", "area": "error", "path": "error/$interpolate/badexpr" }, "error/$interpolate/dupvalue": { "name": "dupvalue", "area": "error", "path": "error/$interpolate/dupvalue" }, "error/$interpolate/interr": { "name": "interr", "area": "error", "path": "error/$interpolate/interr" }, "error/$interpolate/logicbug": { "name": "logicbug", "area": "error", "path": "error/$interpolate/logicbug" }, "error/$interpolate/nochgmustache": { "name": "nochgmustache", "area": "error", "path": "error/$interpolate/nochgmustache" }, "error/$interpolate/noconcat": { "name": "noconcat", "area": "error", "path": "error/$interpolate/noconcat" }, "error/$interpolate/reqarg": { "name": "reqarg", "area": "error", "path": "error/$interpolate/reqarg" }, "error/$interpolate/reqcomma": { "name": "reqcomma", "area": "error", "path": "error/$interpolate/reqcomma" }, "error/$interpolate/reqendbrace": { "name": "reqendbrace", "area": "error", "path": "error/$interpolate/reqendbrace" }, "error/$interpolate/reqendinterp": { "name": "reqendinterp", "area": "error", "path": "error/$interpolate/reqendinterp" }, "error/$interpolate/reqopenbrace": { "name": "reqopenbrace", "area": "error", "path": "error/$interpolate/reqopenbrace" }, "error/$interpolate/reqother": { "name": "reqother", "area": "error", "path": "error/$interpolate/reqother" }, "error/$interpolate/unknarg": { "name": "unknarg", "area": "error", "path": "error/$interpolate/unknarg" }, "error/$interpolate/unsafe": { "name": "unsafe", "area": "error", "path": "error/$interpolate/unsafe" }, "error/$interpolate/untermstr": { "name": "untermstr", "area": "error", "path": "error/$interpolate/untermstr" }, "error/$interpolate/wantstring": { "name": "wantstring", "area": "error", "path": "error/$interpolate/wantstring" }, "error/$location/badpath": { "name": "badpath", "area": "error", "path": "error/$location/badpath" }, "error/$location/ipthprfx": { "name": "ipthprfx", "area": "error", "path": "error/$location/ipthprfx" }, "error/$location/isrcharg": { "name": "isrcharg", "area": "error", "path": "error/$location/isrcharg" }, "error/$location/nobase": { "name": "nobase", "area": "error", "path": "error/$location/nobase" }, "error/$location/nostate": { "name": "nostate", "area": "error", "path": "error/$location/nostate" }, "error/$parse/isecaf": { "name": "isecaf", "area": "error", "path": "error/$parse/isecaf" }, "error/$parse/isecdom": { "name": "isecdom", "area": "error", "path": "error/$parse/isecdom" }, "error/$parse/isecff": { "name": "isecff", "area": "error", "path": "error/$parse/isecff" }, "error/$parse/isecfld": { "name": "isecfld", "area": "error", "path": "error/$parse/isecfld" }, "error/$parse/isecfn": { "name": "isecfn", "area": "error", "path": "error/$parse/isecfn" }, "error/$parse/isecobj": { "name": "isecobj", "area": "error", "path": "error/$parse/isecobj" }, "error/$parse/isecwindow": { "name": "isecwindow", "area": "error", "path": "error/$parse/isecwindow" }, "error/$parse/lexerr": { "name": "lexerr", "area": "error", "path": "error/$parse/lexerr" }, "error/$parse/syntax": { "name": "syntax", "area": "error", "path": "error/$parse/syntax" }, "error/$parse/ueoe": { "name": "ueoe", "area": "error", "path": "error/$parse/ueoe" }, "error/$q/norslvr": { "name": "norslvr", "area": "error", "path": "error/$q/norslvr" }, "error/$q/qcycle": { "name": "qcycle", "area": "error", "path": "error/$q/qcycle" }, "error/$resource/badargs": { "name": "badargs", "area": "error", "path": "error/$resource/badargs" }, "error/$resource/badcfg": { "name": "badcfg", "area": "error", "path": "error/$resource/badcfg" }, "error/$resource/badmember": { "name": "badmember", "area": "error", "path": "error/$resource/badmember" }, "error/$resource/badname": { "name": "badname", "area": "error", "path": "error/$resource/badname" }, "error/$rootScope/infdig": { "name": "infdig", "area": "error", "path": "error/$rootScope/infdig" }, "error/$rootScope/inprog": { "name": "inprog", "area": "error", "path": "error/$rootScope/inprog" }, "error/$sanitize/noinert": { "name": "noinert", "area": "error", "path": "error/$sanitize/noinert" }, "error/$sanitize/uinput": { "name": "uinput", "area": "error", "path": "error/$sanitize/uinput" }, "error/$sce/icontext": { "name": "icontext", "area": "error", "path": "error/$sce/icontext" }, "error/$sce/iequirks": { "name": "iequirks", "area": "error", "path": "error/$sce/iequirks" }, "error/$sce/imatcher": { "name": "imatcher", "area": "error", "path": "error/$sce/imatcher" }, "error/$sce/insecurl": { "name": "insecurl", "area": "error", "path": "error/$sce/insecurl" }, "error/$sce/itype": { "name": "itype", "area": "error", "path": "error/$sce/itype" }, "error/$sce/iwcard": { "name": "iwcard", "area": "error", "path": "error/$sce/iwcard" }, "error/$sce/unsafe": { "name": "unsafe", "area": "error", "path": "error/$sce/unsafe" }, "error/filter/notarray": { "name": "notarray", "area": "error", "path": "error/filter/notarray" }, "error": { "name": "Error Reference", "area": "error", "path": "error" }, "error/jqLite/nosel": { "name": "nosel", "area": "error", "path": "error/jqLite/nosel" }, "error/jqLite/offargs": { "name": "offargs", "area": "error", "path": "error/jqLite/offargs" }, "error/jqLite/onargs": { "name": "onargs", "area": "error", "path": "error/jqLite/onargs" }, "error/linky/notstring": { "name": "notstring", "area": "error", "path": "error/linky/notstring" }, "error/ng/areq": { "name": "areq", "area": "error", "path": "error/ng/areq" }, "error/ng/badname": { "name": "badname", "area": "error", "path": "error/ng/badname" }, "error/ng/btstrpd": { "name": "btstrpd", "area": "error", "path": "error/ng/btstrpd" }, "error/ng/cpi": { "name": "cpi", "area": "error", "path": "error/ng/cpi" }, "error/ng/cpta": { "name": "cpta", "area": "error", "path": "error/ng/cpta" }, "error/ng/cpws": { "name": "cpws", "area": "error", "path": "error/ng/cpws" }, "error/ng/test": { "name": "test", "area": "error", "path": "error/ng/test" }, "error/ngModel/constexpr": { "name": "constexpr", "area": "error", "path": "error/ngModel/constexpr" }, "error/ngModel/datefmt": { "name": "datefmt", "area": "error", "path": "error/ngModel/datefmt" }, "error/ngModel/nonassign": { "name": "nonassign", "area": "error", "path": "error/ngModel/nonassign" }, "error/ngModel/nopromise": { "name": "nopromise", "area": "error", "path": "error/ngModel/nopromise" }, "error/ngModel/numfmt": { "name": "numfmt", "area": "error", "path": "error/ngModel/numfmt" }, "error/ngOptions/iexp": { "name": "iexp", "area": "error", "path": "error/ngOptions/iexp" }, "error/ngPattern/noregexp": { "name": "noregexp", "area": "error", "path": "error/ngPattern/noregexp" }, "error/ngRepeat/badident": { "name": "badident", "area": "error", "path": "error/ngRepeat/badident" }, "error/ngRepeat/dupes": { "name": "dupes", "area": "error", "path": "error/ngRepeat/dupes" }, "error/ngRepeat/iexp": { "name": "iexp", "area": "error", "path": "error/ngRepeat/iexp" }, "error/ngRepeat/iidexp": { "name": "iidexp", "area": "error", "path": "error/ngRepeat/iidexp" }, "error/ngTransclude/orphan": { "name": "orphan", "area": "error", "path": "error/ngTransclude/orphan" }, "error/orderBy/notarray": { "name": "notarray", "area": "error", "path": "error/orderBy/notarray" }, "guide/$location": { "name": "Using $location", "area": "guide", "path": "guide/$location" }, "guide/accessibility": { "name": "Accessibility", "area": "guide", "path": "guide/accessibility" }, "guide/animations": { "name": "Animations", "area": "guide", "path": "guide/animations" }, "guide/bootstrap": { "name": "Bootstrap", "area": "guide", "path": "guide/bootstrap" }, "guide/compiler": { "name": "HTML Compiler", "area": "guide", "path": "guide/compiler" }, "guide/component-router": { "name": "Component Router", "area": "guide", "path": "guide/component-router" }, "guide/component": { "name": "Components", "area": "guide", "path": "guide/component" }, "guide/concepts": { "name": "Conceptual Overview", "area": "guide", "path": "guide/concepts" }, "guide/controller": { "name": "Controllers", "area": "guide", "path": "guide/controller" }, "guide/css-styling": { "name": "Working With CSS", "area": "guide", "path": "guide/css-styling" }, "guide/databinding": { "name": "Data Binding", "area": "guide", "path": "guide/databinding" }, "guide/decorators": { "name": "Decorators", "area": "guide", "path": "guide/decorators" }, "guide/di": { "name": "Dependency Injection", "area": "guide", "path": "guide/di" }, "guide/directive": { "name": "Directives", "area": "guide", "path": "guide/directive" }, "guide/e2e-testing": { "name": "E2E Testing", "area": "guide", "path": "guide/e2e-testing" }, "guide/expression": { "name": "Expressions", "area": "guide", "path": "guide/expression" }, "guide/external-resources": { "name": "External Resources", "area": "guide", "path": "guide/external-resources" }, "guide/filter": { "name": "Filters", "area": "guide", "path": "guide/filter" }, "guide/forms": { "name": "Forms", "area": "guide", "path": "guide/forms" }, "guide/i18n": { "name": "i18n and l10n", "area": "guide", "path": "guide/i18n" }, "guide/ie": { "name": "Internet Explorer Compatibility", "area": "guide", "path": "guide/ie" }, "guide": { "name": "Developer Guide", "area": "guide", "path": "guide" }, "guide/interpolation": { "name": "Interpolation", "area": "guide", "path": "guide/interpolation" }, "guide/introduction": { "name": "Introduction", "area": "guide", "path": "guide/introduction" }, "guide/migration": { "name": "Migrating from Previous Versions", "area": "guide", "path": "guide/migration" }, "guide/module": { "name": "Modules", "area": "guide", "path": "guide/module" }, "guide/production": { "name": "Running in Production", "area": "guide", "path": "guide/production" }, "guide/providers": { "name": "Providers", "area": "guide", "path": "guide/providers" }, "guide/scope": { "name": "Scopes", "area": "guide", "path": "guide/scope" }, "guide/security": { "name": "Security", "area": "guide", "path": "guide/security" }, "guide/services": { "name": "Services", "area": "guide", "path": "guide/services" }, "guide/templates": { "name": "Templates", "area": "guide", "path": "guide/templates" }, "guide/unit-testing": { "name": "Unit Testing", "area": "guide", "path": "guide/unit-testing" }, "misc/contribute": { "name": "Develop", "area": "misc", "path": "misc/contribute" }, "misc/downloading": { "name": "Downloading", "area": "misc", "path": "misc/downloading" }, "misc/faq": { "name": "FAQ", "area": "misc", "path": "misc/faq" }, "misc": { "name": "Miscellaneous", "area": "misc", "path": "misc" }, "misc/started": { "name": "Getting Started", "area": "misc", "path": "misc/started" }, "tutorial": { "name": "Tutorial", "area": "tutorial", "path": "tutorial" }, "tutorial/step_00": { "name": "0 - Bootstrapping", "area": "tutorial", "path": "tutorial/step_00" }, "tutorial/step_01": { "name": "1 - Static Template", "area": "tutorial", "path": "tutorial/step_01" }, "tutorial/step_02": { "name": "2 - Angular Templates", "area": "tutorial", "path": "tutorial/step_02" }, "tutorial/step_03": { "name": "3 - Components", "area": "tutorial", "path": "tutorial/step_03" }, "tutorial/step_04": { "name": "4 - Directory and File Organization", "area": "tutorial", "path": "tutorial/step_04" }, "tutorial/step_05": { "name": "5 - Filtering Repeaters", "area": "tutorial", "path": "tutorial/step_05" }, "tutorial/step_06": { "name": "6 - Two-way Data Binding", "area": "tutorial", "path": "tutorial/step_06" }, "tutorial/step_07": { "name": "7 - XHR & Dependency Injection", "area": "tutorial", "path": "tutorial/step_07" }, "tutorial/step_08": { "name": "8 - Templating Links & Images", "area": "tutorial", "path": "tutorial/step_08" }, "tutorial/step_09": { "name": "9 - Routing & Multiple Views", "area": "tutorial", "path": "tutorial/step_09" }, "tutorial/step_10": { "name": "10 - More Templating", "area": "tutorial", "path": "tutorial/step_10" }, "tutorial/step_11": { "name": "11 - Custom Filters", "area": "tutorial", "path": "tutorial/step_11" }, "tutorial/step_12": { "name": "12 - Event Handlers", "area": "tutorial", "path": "tutorial/step_12" }, "tutorial/step_13": { "name": "13 - REST and Custom Services", "area": "tutorial", "path": "tutorial/step_13" }, "tutorial/step_14": { "name": "14 - Animations", "area": "tutorial", "path": "tutorial/step_14" }, "tutorial/the_end": { "name": "The End", "area": "tutorial", "path": "tutorial/the_end" }, "api/ng": { "name": "ng", "area": "api", "path": "api/ng" }, "api/ng/function/angular.forEach": { "name": "angular.forEach", "area": "api", "path": "api/ng/function/angular.forEach" }, "api/ng/function/angular.extend": { "name": "angular.extend", "area": "api", "path": "api/ng/function/angular.extend" }, "api/ng/function/angular.merge": { "name": "angular.merge", "area": "api", "path": "api/ng/function/angular.merge" }, "api/ng/function/angular.noop": { "name": "angular.noop", "area": "api", "path": "api/ng/function/angular.noop" }, "api/ng/function/angular.identity": { "name": "angular.identity", "area": "api", "path": "api/ng/function/angular.identity" }, "api/ng/function/angular.isUndefined": { "name": "angular.isUndefined", "area": "api", "path": "api/ng/function/angular.isUndefined" }, "api/ng/function/angular.isDefined": { "name": "angular.isDefined", "area": "api", "path": "api/ng/function/angular.isDefined" }, "api/ng/function/angular.isObject": { "name": "angular.isObject", "area": "api", "path": "api/ng/function/angular.isObject" }, "api/ng/function/angular.isString": { "name": "angular.isString", "area": "api", "path": "api/ng/function/angular.isString" }, "api/ng/function/angular.isNumber": { "name": "angular.isNumber", "area": "api", "path": "api/ng/function/angular.isNumber" }, "api/ng/function/angular.isDate": { "name": "angular.isDate", "area": "api", "path": "api/ng/function/angular.isDate" }, "api/ng/function/angular.isArray": { "name": "angular.isArray", "area": "api", "path": "api/ng/function/angular.isArray" }, "api/ng/function/angular.isFunction": { "name": "angular.isFunction", "area": "api", "path": "api/ng/function/angular.isFunction" }, "api/ng/function/angular.isElement": { "name": "angular.isElement", "area": "api", "path": "api/ng/function/angular.isElement" }, "api/ng/function/angular.copy": { "name": "angular.copy", "area": "api", "path": "api/ng/function/angular.copy" }, "api/ng/function/angular.equals": { "name": "angular.equals", "area": "api", "path": "api/ng/function/angular.equals" }, "api/ng/directive/ngJq": { "name": "ngJq", "area": "api", "path": "api/ng/directive/ngJq" }, "api/ng/function/angular.bind": { "name": "angular.bind", "area": "api", "path": "api/ng/function/angular.bind" }, "api/ng/function/angular.toJson": { "name": "angular.toJson", "area": "api", "path": "api/ng/function/angular.toJson" }, "api/ng/function/angular.fromJson": { "name": "angular.fromJson", "area": "api", "path": "api/ng/function/angular.fromJson" }, "api/ng/directive/ngApp": { "name": "ngApp", "area": "api", "path": "api/ng/directive/ngApp" }, "api/ng/function/angular.bootstrap": { "name": "angular.bootstrap", "area": "api", "path": "api/ng/function/angular.bootstrap" }, "api/ng/function/angular.reloadWithDebugInfo": { "name": "angular.reloadWithDebugInfo", "area": "api", "path": "api/ng/function/angular.reloadWithDebugInfo" }, "api/ng/object/angular.version": { "name": "angular.version", "area": "api", "path": "api/ng/object/angular.version" }, "api/ng/function/angular.injector": { "name": "angular.injector", "area": "api", "path": "api/ng/function/angular.injector" }, "api/auto": { "name": "auto", "area": "api", "path": "api/auto" }, "api/auto/service/$injector": { "name": "$injector", "area": "api", "path": "api/auto/service/$injector" }, "api/auto/service/$provide": { "name": "$provide", "area": "api", "path": "api/auto/service/$provide" }, "api/ng/function/angular.element": { "name": "angular.element", "area": "api", "path": "api/ng/function/angular.element" }, "api/ng/type/angular.Module": { "name": "angular.Module", "area": "api", "path": "api/ng/type/angular.Module" }, "api/ng/function/angular.module": { "name": "angular.module", "area": "api", "path": "api/ng/function/angular.module" }, "api/ng/provider/$anchorScrollProvider": { "name": "$anchorScrollProvider", "area": "api", "path": "api/ng/provider/$anchorScrollProvider" }, "api/ng/service/$anchorScroll": { "name": "$anchorScroll", "area": "api", "path": "api/ng/service/$anchorScroll" }, "api/ng/provider/$animateProvider": { "name": "$animateProvider", "area": "api", "path": "api/ng/provider/$animateProvider" }, "api/ng/service/$animate": { "name": "$animate", "area": "api", "path": "api/ng/service/$animate" }, "api/ng/service/$animateCss": { "name": "$animateCss", "area": "api", "path": "api/ng/service/$animateCss" }, "api/ng/service/$cacheFactory": { "name": "$cacheFactory", "area": "api", "path": "api/ng/service/$cacheFactory" }, "api/ng/type/$cacheFactory.Cache": { "name": "$cacheFactory.Cache", "area": "api", "path": "api/ng/type/$cacheFactory.Cache" }, "api/ng/service/$templateCache": { "name": "$templateCache", "area": "api", "path": "api/ng/service/$templateCache" }, "api/ng/service/$compile": { "name": "$compile", "area": "api", "path": "api/ng/service/$compile" }, "api/ng/provider/$compileProvider": { "name": "$compileProvider", "area": "api", "path": "api/ng/provider/$compileProvider" }, "api/ng/type/$compile.directive.Attributes": { "name": "$compile.directive.Attributes", "area": "api", "path": "api/ng/type/$compile.directive.Attributes" }, "api/ng/provider/$controllerProvider": { "name": "$controllerProvider", "area": "api", "path": "api/ng/provider/$controllerProvider" }, "api/ng/service/$controller": { "name": "$controller", "area": "api", "path": "api/ng/service/$controller" }, "api/ng/directive/a": { "name": "a", "area": "api", "path": "api/ng/directive/a" }, "api/ng/directive/ngHref": { "name": "ngHref", "area": "api", "path": "api/ng/directive/ngHref" }, "api/ng/directive/ngSrc": { "name": "ngSrc", "area": "api", "path": "api/ng/directive/ngSrc" }, "api/ng/directive/ngSrcset": { "name": "ngSrcset", "area": "api", "path": "api/ng/directive/ngSrcset" }, "api/ng/directive/ngDisabled": { "name": "ngDisabled", "area": "api", "path": "api/ng/directive/ngDisabled" }, "api/ng/directive/ngChecked": { "name": "ngChecked", "area": "api", "path": "api/ng/directive/ngChecked" }, "api/ng/directive/ngReadonly": { "name": "ngReadonly", "area": "api", "path": "api/ng/directive/ngReadonly" }, "api/ng/directive/ngSelected": { "name": "ngSelected", "area": "api", "path": "api/ng/directive/ngSelected" }, "api/ng/directive/ngOpen": { "name": "ngOpen", "area": "api", "path": "api/ng/directive/ngOpen" }, "api/ng/type/form.FormController": { "name": "form.FormController", "area": "api", "path": "api/ng/type/form.FormController" }, "api/ng/directive/ngForm": { "name": "ngForm", "area": "api", "path": "api/ng/directive/ngForm" }, "api/ng/directive/form": { "name": "form", "area": "api", "path": "api/ng/directive/form" }, "api/ng/input/input[text]": { "name": "input[text]", "area": "api", "path": "api/ng/input/input[text]" }, "api/ng/input/input[date]": { "name": "input[date]", "area": "api", "path": "api/ng/input/input[date]" }, "api/ng/input/input[datetime-local]": { "name": "input[datetime-local]", "area": "api", "path": "api/ng/input/input[datetime-local]" }, "api/ng/input/input[time]": { "name": "input[time]", "area": "api", "path": "api/ng/input/input[time]" }, "api/ng/input/input[week]": { "name": "input[week]", "area": "api", "path": "api/ng/input/input[week]" }, "api/ng/input/input[month]": { "name": "input[month]", "area": "api", "path": "api/ng/input/input[month]" }, "api/ng/input/input[number]": { "name": "input[number]", "area": "api", "path": "api/ng/input/input[number]" }, "api/ng/input/input[url]": { "name": "input[url]", "area": "api", "path": "api/ng/input/input[url]" }, "api/ng/input/input[email]": { "name": "input[email]", "area": "api", "path": "api/ng/input/input[email]" }, "api/ng/input/input[radio]": { "name": "input[radio]", "area": "api", "path": "api/ng/input/input[radio]" }, "api/ng/input/input[range]": { "name": "input[range]", "area": "api", "path": "api/ng/input/input[range]" }, "api/ng/input/input[checkbox]": { "name": "input[checkbox]", "area": "api", "path": "api/ng/input/input[checkbox]" }, "api/ng/directive/textarea": { "name": "textarea", "area": "api", "path": "api/ng/directive/textarea" }, "api/ng/directive/input": { "name": "input", "area": "api", "path": "api/ng/directive/input" }, "api/ng/directive/ngValue": { "name": "ngValue", "area": "api", "path": "api/ng/directive/ngValue" }, "api/ng/directive/ngBind": { "name": "ngBind", "area": "api", "path": "api/ng/directive/ngBind" }, "api/ng/directive/ngBindTemplate": { "name": "ngBindTemplate", "area": "api", "path": "api/ng/directive/ngBindTemplate" }, "api/ng/directive/ngBindHtml": { "name": "ngBindHtml", "area": "api", "path": "api/ng/directive/ngBindHtml" }, "api/ng/directive/ngChange": { "name": "ngChange", "area": "api", "path": "api/ng/directive/ngChange" }, "api/ng/directive/ngClass": { "name": "ngClass", "area": "api", "path": "api/ng/directive/ngClass" }, "api/ng/directive/ngClassOdd": { "name": "ngClassOdd", "area": "api", "path": "api/ng/directive/ngClassOdd" }, "api/ng/directive/ngClassEven": { "name": "ngClassEven", "area": "api", "path": "api/ng/directive/ngClassEven" }, "api/ng/directive/ngCloak": { "name": "ngCloak", "area": "api", "path": "api/ng/directive/ngCloak" }, "api/ng/directive/ngController": { "name": "ngController", "area": "api", "path": "api/ng/directive/ngController" }, "api/ng/directive/ngCsp": { "name": "ngCsp", "area": "api", "path": "api/ng/directive/ngCsp" }, "api/ng/directive/ngClick": { "name": "ngClick", "area": "api", "path": "api/ng/directive/ngClick" }, "api/ng/directive/ngDblclick": { "name": "ngDblclick", "area": "api", "path": "api/ng/directive/ngDblclick" }, "api/ng/directive/ngMousedown": { "name": "ngMousedown", "area": "api", "path": "api/ng/directive/ngMousedown" }, "api/ng/directive/ngMouseup": { "name": "ngMouseup", "area": "api", "path": "api/ng/directive/ngMouseup" }, "api/ng/directive/ngMouseover": { "name": "ngMouseover", "area": "api", "path": "api/ng/directive/ngMouseover" }, "api/ng/directive/ngMouseenter": { "name": "ngMouseenter", "area": "api", "path": "api/ng/directive/ngMouseenter" }, "api/ng/directive/ngMouseleave": { "name": "ngMouseleave", "area": "api", "path": "api/ng/directive/ngMouseleave" }, "api/ng/directive/ngMousemove": { "name": "ngMousemove", "area": "api", "path": "api/ng/directive/ngMousemove" }, "api/ng/directive/ngKeydown": { "name": "ngKeydown", "area": "api", "path": "api/ng/directive/ngKeydown" }, "api/ng/directive/ngKeyup": { "name": "ngKeyup", "area": "api", "path": "api/ng/directive/ngKeyup" }, "api/ng/directive/ngKeypress": { "name": "ngKeypress", "area": "api", "path": "api/ng/directive/ngKeypress" }, "api/ng/directive/ngSubmit": { "name": "ngSubmit", "area": "api", "path": "api/ng/directive/ngSubmit" }, "api/ng/directive/ngFocus": { "name": "ngFocus", "area": "api", "path": "api/ng/directive/ngFocus" }, "api/ng/directive/ngBlur": { "name": "ngBlur", "area": "api", "path": "api/ng/directive/ngBlur" }, "api/ng/directive/ngCopy": { "name": "ngCopy", "area": "api", "path": "api/ng/directive/ngCopy" }, "api/ng/directive/ngCut": { "name": "ngCut", "area": "api", "path": "api/ng/directive/ngCut" }, "api/ng/directive/ngPaste": { "name": "ngPaste", "area": "api", "path": "api/ng/directive/ngPaste" }, "api/ng/directive/ngIf": { "name": "ngIf", "area": "api", "path": "api/ng/directive/ngIf" }, "api/ng/directive/ngInclude": { "name": "ngInclude", "area": "api", "path": "api/ng/directive/ngInclude" }, "api/ng/directive/ngInit": { "name": "ngInit", "area": "api", "path": "api/ng/directive/ngInit" }, "api/ng/directive/ngList": { "name": "ngList", "area": "api", "path": "api/ng/directive/ngList" }, "api/ng/type/ngModel.NgModelController": { "name": "ngModel.NgModelController", "area": "api", "path": "api/ng/type/ngModel.NgModelController" }, "api/ng/directive/ngModel": { "name": "ngModel", "area": "api", "path": "api/ng/directive/ngModel" }, "api/ng/directive/ngModelOptions": { "name": "ngModelOptions", "area": "api", "path": "api/ng/directive/ngModelOptions" }, "api/ng/directive/ngNonBindable": { "name": "ngNonBindable", "area": "api", "path": "api/ng/directive/ngNonBindable" }, "api/ng/directive/ngOptions": { "name": "ngOptions", "area": "api", "path": "api/ng/directive/ngOptions" }, "api/ng/directive/ngPluralize": { "name": "ngPluralize", "area": "api", "path": "api/ng/directive/ngPluralize" }, "api/ng/directive/ngRepeat": { "name": "ngRepeat", "area": "api", "path": "api/ng/directive/ngRepeat" }, "api/ng/directive/ngShow": { "name": "ngShow", "area": "api", "path": "api/ng/directive/ngShow" }, "api/ng/directive/ngHide": { "name": "ngHide", "area": "api", "path": "api/ng/directive/ngHide" }, "api/ng/directive/ngStyle": { "name": "ngStyle", "area": "api", "path": "api/ng/directive/ngStyle" }, "api/ng/directive/ngSwitch": { "name": "ngSwitch", "area": "api", "path": "api/ng/directive/ngSwitch" }, "api/ng/directive/ngTransclude": { "name": "ngTransclude", "area": "api", "path": "api/ng/directive/ngTransclude" }, "api/ng/directive/script": { "name": "script", "area": "api", "path": "api/ng/directive/script" }, "api/ng/type/select.SelectController": { "name": "select.SelectController", "area": "api", "path": "api/ng/type/select.SelectController" }, "api/ng/directive/select": { "name": "select", "area": "api", "path": "api/ng/directive/select" }, "api/ng/directive/ngRequired": { "name": "ngRequired", "area": "api", "path": "api/ng/directive/ngRequired" }, "api/ng/directive/ngPattern": { "name": "ngPattern", "area": "api", "path": "api/ng/directive/ngPattern" }, "api/ng/directive/ngMaxlength": { "name": "ngMaxlength", "area": "api", "path": "api/ng/directive/ngMaxlength" }, "api/ng/directive/ngMinlength": { "name": "ngMinlength", "area": "api", "path": "api/ng/directive/ngMinlength" }, "api/ng/service/$document": { "name": "$document", "area": "api", "path": "api/ng/service/$document" }, "api/ng/service/$exceptionHandler": { "name": "$exceptionHandler", "area": "api", "path": "api/ng/service/$exceptionHandler" }, "api/ng/provider/$filterProvider": { "name": "$filterProvider", "area": "api", "path": "api/ng/provider/$filterProvider" }, "api/ng/service/$filter": { "name": "$filter", "area": "api", "path": "api/ng/service/$filter" }, "api/ng/filter/filter": { "name": "filter", "area": "api", "path": "api/ng/filter/filter" }, "api/ng/filter/currency": { "name": "currency", "area": "api", "path": "api/ng/filter/currency" }, "api/ng/filter/number": { "name": "number", "area": "api", "path": "api/ng/filter/number" }, "api/ng/filter/date": { "name": "date", "area": "api", "path": "api/ng/filter/date" }, "api/ng/filter/json": { "name": "json", "area": "api", "path": "api/ng/filter/json" }, "api/ng/filter/lowercase": { "name": "lowercase", "area": "api", "path": "api/ng/filter/lowercase" }, "api/ng/filter/uppercase": { "name": "uppercase", "area": "api", "path": "api/ng/filter/uppercase" }, "api/ng/filter/limitTo": { "name": "limitTo", "area": "api", "path": "api/ng/filter/limitTo" }, "api/ng/filter/orderBy": { "name": "orderBy", "area": "api", "path": "api/ng/filter/orderBy" }, "api/ng/service/$httpParamSerializer": { "name": "$httpParamSerializer", "area": "api", "path": "api/ng/service/$httpParamSerializer" }, "api/ng/service/$httpParamSerializerJQLike": { "name": "$httpParamSerializerJQLike", "area": "api", "path": "api/ng/service/$httpParamSerializerJQLike" }, "api/ng/provider/$httpProvider": { "name": "$httpProvider", "area": "api", "path": "api/ng/provider/$httpProvider" }, "api/ng/service/$http": { "name": "$http", "area": "api", "path": "api/ng/service/$http" }, "api/ng/service/$xhrFactory": { "name": "$xhrFactory", "area": "api", "path": "api/ng/service/$xhrFactory" }, "api/ng/service/$httpBackend": { "name": "$httpBackend", "area": "api", "path": "api/ng/service/$httpBackend" }, "api/ng/provider/$interpolateProvider": { "name": "$interpolateProvider", "area": "api", "path": "api/ng/provider/$interpolateProvider" }, "api/ng/service/$interpolate": { "name": "$interpolate", "area": "api", "path": "api/ng/service/$interpolate" }, "api/ng/service/$interval": { "name": "$interval", "area": "api", "path": "api/ng/service/$interval" }, "api/ng/service/$jsonpCallbacks": { "name": "$jsonpCallbacks", "area": "api", "path": "api/ng/service/$jsonpCallbacks" }, "api/ng/service/$locale": { "name": "$locale", "area": "api", "path": "api/ng/service/$locale" }, "api/ng/service/$location": { "name": "$location", "area": "api", "path": "api/ng/service/$location" }, "api/ng/provider/$locationProvider": { "name": "$locationProvider", "area": "api", "path": "api/ng/provider/$locationProvider" }, "api/ng/service/$log": { "name": "$log", "area": "api", "path": "api/ng/service/$log" }, "api/ng/provider/$logProvider": { "name": "$logProvider", "area": "api", "path": "api/ng/provider/$logProvider" }, "api/ng/service/$parse": { "name": "$parse", "area": "api", "path": "api/ng/service/$parse" }, "api/ng/provider/$parseProvider": { "name": "$parseProvider", "area": "api", "path": "api/ng/provider/$parseProvider" }, "api/ng/service/$q": { "name": "$q", "area": "api", "path": "api/ng/service/$q" }, "api/ng/service/$rootElement": { "name": "$rootElement", "area": "api", "path": "api/ng/service/$rootElement" }, "api/ng/provider/$rootScopeProvider": { "name": "$rootScopeProvider", "area": "api", "path": "api/ng/provider/$rootScopeProvider" }, "api/ng/service/$rootScope": { "name": "$rootScope", "area": "api", "path": "api/ng/service/$rootScope" }, "api/ng/type/$rootScope.Scope": { "name": "$rootScope.Scope", "area": "api", "path": "api/ng/type/$rootScope.Scope" }, "api/ng/service/$sceDelegate": { "name": "$sceDelegate", "area": "api", "path": "api/ng/service/$sceDelegate" }, "api/ng/provider/$sceDelegateProvider": { "name": "$sceDelegateProvider", "area": "api", "path": "api/ng/provider/$sceDelegateProvider" }, "api/ng/provider/$sceProvider": { "name": "$sceProvider", "area": "api", "path": "api/ng/provider/$sceProvider" }, "api/ng/service/$sce": { "name": "$sce", "area": "api", "path": "api/ng/service/$sce" }, "api/ng/provider/$templateRequestProvider": { "name": "$templateRequestProvider", "area": "api", "path": "api/ng/provider/$templateRequestProvider" }, "api/ng/service/$templateRequest": { "name": "$templateRequest", "area": "api", "path": "api/ng/service/$templateRequest" }, "api/ng/service/$timeout": { "name": "$timeout", "area": "api", "path": "api/ng/service/$timeout" }, "api/ng/service/$window": { "name": "$window", "area": "api", "path": "api/ng/service/$window" }, "api/ngAnimate/directive/ngAnimateChildren": { "name": "ngAnimateChildren", "area": "api", "path": "api/ngAnimate/directive/ngAnimateChildren" }, "api/ngAnimate/service/$animateCss": { "name": "$animateCss", "area": "api", "path": "api/ngAnimate/service/$animateCss" }, "api/ngAnimate": { "name": "ngAnimate", "area": "api", "path": "api/ngAnimate" }, "api/ngAnimate/service/$animate": { "name": "$animate", "area": "api", "path": "api/ngAnimate/service/$animate" }, "api/ngAnimate/directive/ngAnimateSwap": { "name": "ngAnimateSwap", "area": "api", "path": "api/ngAnimate/directive/ngAnimateSwap" }, "api/ngAria": { "name": "ngAria", "area": "api", "path": "api/ngAria" }, "api/ngAria/provider/$ariaProvider": { "name": "$ariaProvider", "area": "api", "path": "api/ngAria/provider/$ariaProvider" }, "api/ngAria/service/$aria": { "name": "$aria", "area": "api", "path": "api/ngAria/service/$aria" }, "api/ngComponentRouter": { "name": "ngComponentRouter", "area": "api", "path": "api/ngComponentRouter" }, "api/ngComponentRouter/type/Router": { "name": "Router", "area": "api", "path": "api/ngComponentRouter/type/Router" }, "api/ngComponentRouter/type/ChildRouter": { "name": "ChildRouter", "area": "api", "path": "api/ngComponentRouter/type/ChildRouter" }, "api/ngComponentRouter/type/RootRouter": { "name": "RootRouter", "area": "api", "path": "api/ngComponentRouter/type/RootRouter" }, "api/ngComponentRouter/type/ComponentInstruction": { "name": "ComponentInstruction", "area": "api", "path": "api/ngComponentRouter/type/ComponentInstruction" }, "api/ngComponentRouter/type/RouteDefinition": { "name": "RouteDefinition", "area": "api", "path": "api/ngComponentRouter/type/RouteDefinition" }, "api/ngComponentRouter/type/RouteParams": { "name": "RouteParams", "area": "api", "path": "api/ngComponentRouter/type/RouteParams" }, "api/ngComponentRouter/directive/ngOutlet": { "name": "ngOutlet", "area": "api", "path": "api/ngComponentRouter/directive/ngOutlet" }, "api/ngComponentRouter/service/$rootRouter": { "name": "$rootRouter", "area": "api", "path": "api/ngComponentRouter/service/$rootRouter" }, "api/ngComponentRouter/service/$routerRootComponent": { "name": "$routerRootComponent", "area": "api", "path": "api/ngComponentRouter/service/$routerRootComponent" }, "api/ngCookies": { "name": "ngCookies", "area": "api", "path": "api/ngCookies" }, "api/ngCookies/provider/$cookiesProvider": { "name": "$cookiesProvider", "area": "api", "path": "api/ngCookies/provider/$cookiesProvider" }, "api/ngCookies/service/$cookies": { "name": "$cookies", "area": "api", "path": "api/ngCookies/service/$cookies" }, "api/ngCookies/service/$cookieStore": { "name": "$cookieStore", "area": "api", "path": "api/ngCookies/service/$cookieStore" }, "api/ngMessageFormat": { "name": "ngMessageFormat", "area": "api", "path": "api/ngMessageFormat" }, "api/ngMessages": { "name": "ngMessages", "area": "api", "path": "api/ngMessages" }, "api/ngMessages/directive/ngMessages": { "name": "ngMessages", "area": "api", "path": "api/ngMessages/directive/ngMessages" }, "api/ngMessages/directive/ngMessagesInclude": { "name": "ngMessagesInclude", "area": "api", "path": "api/ngMessages/directive/ngMessagesInclude" }, "api/ngMessages/directive/ngMessage": { "name": "ngMessage", "area": "api", "path": "api/ngMessages/directive/ngMessage" }, "api/ngMessages/directive/ngMessageExp": { "name": "ngMessageExp", "area": "api", "path": "api/ngMessages/directive/ngMessageExp" }, "api/ngMock/object/angular.mock": { "name": "angular.mock", "area": "api", "path": "api/ngMock/object/angular.mock" }, "api/ngMock/provider/$exceptionHandlerProvider": { "name": "$exceptionHandlerProvider", "area": "api", "path": "api/ngMock/provider/$exceptionHandlerProvider" }, "api/ngMock/service/$exceptionHandler": { "name": "$exceptionHandler", "area": "api", "path": "api/ngMock/service/$exceptionHandler" }, "api/ngMock/service/$log": { "name": "$log", "area": "api", "path": "api/ngMock/service/$log" }, "api/ngMock/service/$interval": { "name": "$interval", "area": "api", "path": "api/ngMock/service/$interval" }, "api/ngMock/type/angular.mock.TzDate": { "name": "angular.mock.TzDate", "area": "api", "path": "api/ngMock/type/angular.mock.TzDate" }, "api/ngMock/service/$animate": { "name": "$animate", "area": "api", "path": "api/ngMock/service/$animate" }, "api/ngMock/function/angular.mock.dump": { "name": "angular.mock.dump", "area": "api", "path": "api/ngMock/function/angular.mock.dump" }, "api/ngMock/service/$httpBackend": { "name": "$httpBackend", "area": "api", "path": "api/ngMock/service/$httpBackend" }, "api/ngMock/service/$timeout": { "name": "$timeout", "area": "api", "path": "api/ngMock/service/$timeout" }, "api/ngMock/service/$controller": { "name": "$controller", "area": "api", "path": "api/ngMock/service/$controller" }, "api/ngMock/service/$componentController": { "name": "$componentController", "area": "api", "path": "api/ngMock/service/$componentController" }, "api/ngMock": { "name": "ngMock", "area": "api", "path": "api/ngMock" }, "api/ngMockE2E": { "name": "ngMockE2E", "area": "api", "path": "api/ngMockE2E" }, "api/ngMockE2E/service/$httpBackend": { "name": "$httpBackend", "area": "api", "path": "api/ngMockE2E/service/$httpBackend" }, "api/ngMock/type/$rootScope.Scope": { "name": "$rootScope.Scope", "area": "api", "path": "api/ngMock/type/$rootScope.Scope" }, "api/ngMock/function/angular.mock.module": { "name": "angular.mock.module", "area": "api", "path": "api/ngMock/function/angular.mock.module" }, "api/ngMock/function/angular.mock.module.sharedInjector": { "name": "angular.mock.module.sharedInjector", "area": "api", "path": "api/ngMock/function/angular.mock.module.sharedInjector" }, "api/ngMock/function/angular.mock.inject": { "name": "angular.mock.inject", "area": "api", "path": "api/ngMock/function/angular.mock.inject" }, "api/ngParseExt": { "name": "ngParseExt", "area": "api", "path": "api/ngParseExt" }, "api/ngResource": { "name": "ngResource", "area": "api", "path": "api/ngResource" }, "api/ngResource/provider/$resourceProvider": { "name": "$resourceProvider", "area": "api", "path": "api/ngResource/provider/$resourceProvider" }, "api/ngResource/service/$resource": { "name": "$resource", "area": "api", "path": "api/ngResource/service/$resource" }, "api/ngRoute/directive/ngView": { "name": "ngView", "area": "api", "path": "api/ngRoute/directive/ngView" }, "api/ngRoute": { "name": "ngRoute", "area": "api", "path": "api/ngRoute" }, "api/ngRoute/provider/$routeProvider": { "name": "$routeProvider", "area": "api", "path": "api/ngRoute/provider/$routeProvider" }, "api/ngRoute/service/$route": { "name": "$route", "area": "api", "path": "api/ngRoute/service/$route" }, "api/ngRoute/service/$routeParams": { "name": "$routeParams", "area": "api", "path": "api/ngRoute/service/$routeParams" }, "api/ngSanitize/filter/linky": { "name": "linky", "area": "api", "path": "api/ngSanitize/filter/linky" }, "api/ngSanitize": { "name": "ngSanitize", "area": "api", "path": "api/ngSanitize" }, "api/ngSanitize/service/$sanitize": { "name": "$sanitize", "area": "api", "path": "api/ngSanitize/service/$sanitize" }, "api/ngSanitize/provider/$sanitizeProvider": { "name": "$sanitizeProvider", "area": "api", "path": "api/ngSanitize/provider/$sanitizeProvider" }, "api/ngTouch/directive/ngClick": { "name": "ngClick", "area": "api", "path": "api/ngTouch/directive/ngClick" }, "api/ngTouch/directive/ngSwipeLeft": { "name": "ngSwipeLeft", "area": "api", "path": "api/ngTouch/directive/ngSwipeLeft" }, "api/ngTouch/directive/ngSwipeRight": { "name": "ngSwipeRight", "area": "api", "path": "api/ngTouch/directive/ngSwipeRight" }, "api/ngTouch/service/$swipe": { "name": "$swipe", "area": "api", "path": "api/ngTouch/service/$swipe" }, "api/ngTouch": { "name": "ngTouch", "area": "api", "path": "api/ngTouch" }, "api/ngTouch/provider/$touchProvider": { "name": "$touchProvider", "area": "api", "path": "api/ngTouch/provider/$touchProvider" }, "api/ngTouch/service/$touch": { "name": "$touch", "area": "api", "path": "api/ngTouch/service/$touch" }, "app.js": { "path": "app.js" }, "examples/example-error-$rootScope-inprog": { "path": "examples/example-error-$rootScope-inprog" }, "undefined": {}, "examples/example-number-format-error": { "path": "examples/example-number-format-error" }, "fakeBrowser.js": { "path": "fakeBrowser.js" }, "addressBar.js": { "path": "addressBar.js" }, "protractor.js": { "path": "protractor.js" }, "examples/example-location-html5-mode": { "path": "examples/example-location-html5-mode" }, "examples/example-location-hashbang-mode": { "path": "examples/example-location-hashbang-mode" }, "script.js": { "path": "script.js" }, "examples/example-location-two-way-binding": { "path": "examples/example-location-two-way-binding" }, "style.css": { "path": "style.css" }, "examples/example-accessibility-ng-model": { "path": "examples/example-accessibility-ng-model" }, "examples/example-accessibility-ng-click": { "path": "examples/example-accessibility-ng-click" }, "animations.css": { "path": "animations.css" }, "examples/example-animate-ng-show": { "path": "examples/example-animate-ng-show" }, "examples/example-animate-css-class": { "path": "examples/example-animate-css-class" }, "examples/example-draggable": { "path": "examples/example-draggable" }, "heroes.js": { "path": "heroes.js" }, "crisis.js": { "path": "crisis.js" }, "crisisDetail.html": { "path": "crisisDetail.html" }, "dialog.js": { "path": "dialog.js" }, "styles.css": { "path": "styles.css" }, "examples/example-componentRouter": { "path": "examples/example-componentRouter" }, "index.js": { "path": "index.js" }, "heroDetail.js": { "path": "heroDetail.js" }, "heroDetail.html": { "path": "heroDetail.html" }, "examples/example-heroComponentSimple": { "path": "examples/example-heroComponentSimple" }, "heroList.js": { "path": "heroList.js" }, "editableField.js": { "path": "editableField.js" }, "heroList.html": { "path": "heroList.html" }, "editableField.html": { "path": "editableField.html" }, "examples/example-heroComponentTree": { "path": "examples/example-heroComponentTree" }, "my-tabs.html": { "path": "my-tabs.html" }, "my-pane.html": { "path": "my-pane.html" }, "examples/example-component-tabs-pane": { "path": "examples/example-component-tabs-pane" }, "examples/example-guide-concepts-1": { "path": "examples/example-guide-concepts-1" }, "invoice1.js": { "path": "invoice1.js" }, "examples/example-guide-concepts-2": { "path": "examples/example-guide-concepts-2" }, "finance2.js": { "path": "finance2.js" }, "invoice2.js": { "path": "invoice2.js" }, "examples/example-guide-concepts-21": { "path": "examples/example-guide-concepts-21" }, "invoice3.js": { "path": "invoice3.js" }, "finance3.js": { "path": "finance3.js" }, "examples/example-guide-concepts-3": { "path": "examples/example-guide-concepts-3" }, "examples/example-controller-spicy-1": { "path": "examples/example-controller-spicy-1" }, "examples/example-controller-spicy-2": { "path": "examples/example-controller-spicy-2" }, "app.css": { "path": "app.css" }, "examples/example-controller-scope-inheritance": { "path": "examples/example-controller-scope-inheritance" }, "examples/example-service-decorator": { "path": "examples/example-service-decorator" }, "examples/example-directive-decorator": { "path": "examples/example-directive-decorator" }, "examples/example-filter-decorator": { "path": "examples/example-filter-decorator" }, "examples/example-directive-bind": { "path": "examples/example-directive-bind" }, "examples/example-directive-simple": { "path": "examples/example-directive-simple" }, "my-customer.html": { "path": "my-customer.html" }, "examples/example-directive-template-url": { "path": "examples/example-directive-template-url" }, "customer-name.html": { "path": "customer-name.html" }, "customer-address.html": { "path": "customer-address.html" }, "examples/example-directive-template-url-fn": { "path": "examples/example-directive-template-url-fn" }, "examples/example-directive-restrict": { "path": "examples/example-directive-restrict" }, "examples/example-directive-scope-problem": { "path": "examples/example-directive-scope-problem" }, "my-customer-iso.html": { "path": "my-customer-iso.html" }, "examples/example-directive-isolate": { "path": "examples/example-directive-isolate" }, "my-customer-plus-vojta.html": { "path": "my-customer-plus-vojta.html" }, "examples/example-directive-isolate-2": { "path": "examples/example-directive-isolate-2" }, "examples/example-directive-link": { "path": "examples/example-directive-link" }, "my-dialog.html": { "path": "my-dialog.html" }, "examples/example-directive-transclude": { "path": "examples/example-directive-transclude" }, "examples/example-directive-transclusion": { "path": "examples/example-directive-transclusion" }, "my-dialog-close.html": { "path": "my-dialog-close.html" }, "examples/example-directive-transclusion-scope": { "path": "examples/example-directive-transclusion-scope" }, "examples/example-directive-drag": { "path": "examples/example-directive-drag" }, "examples/example-directive-tabs": { "path": "examples/example-directive-tabs" }, "examples/example-expression-simple": { "path": "examples/example-expression-simple" }, "examples/example-expression-eval": { "path": "examples/example-expression-eval" }, "examples/example-expression-locals": { "path": "examples/example-expression-locals" }, "examples/example-expression-events": { "path": "examples/example-expression-events" }, "examples/example-expression-one-time": { "path": "examples/example-expression-one-time" }, "examples/example-filter-in-controller": { "path": "examples/example-filter-in-controller" }, "examples/example-filter-reverse": { "path": "examples/example-filter-reverse" }, "examples/example-filter-stateful": { "path": "examples/example-filter-stateful" }, "examples/example-forms-simple": { "path": "examples/example-forms-simple" }, "examples/example-forms-css-classes": { "path": "examples/example-forms-css-classes" }, "examples/example-forms-custom-error-messages": { "path": "examples/example-forms-custom-error-messages" }, "examples/example-forms-custom-triggers": { "path": "examples/example-forms-custom-triggers" }, "examples/example-forms-debounce": { "path": "examples/example-forms-debounce" }, "examples/example-forms-async-validation": { "path": "examples/example-forms-async-validation" }, "examples/example-forms-modify-validators": { "path": "examples/example-forms-modify-validators" }, "examples/example-forms-custom-form-controls": { "path": "examples/example-forms-custom-form-controls" }, "examples/example-message-format-example": { "path": "examples/example-message-format-example" }, "examples/example-module-hello-world": { "path": "examples/example-module-hello-world" }, "examples/example-module-suggested-layout": { "path": "examples/example-module-suggested-layout" }, "examples/example-scope-data-model": { "path": "examples/example-scope-data-model" }, "examples/example-scope-hierarchies": { "path": "examples/example-scope-hierarchies" }, "examples/example-scope-events-propagation": { "path": "examples/example-scope-events-propagation" }, "examples/example-services-usage": { "path": "examples/example-services-usage" }, "examples/example-angular-copy": { "path": "examples/example-angular-copy" }, "examples/example-equalsExample": { "path": "examples/example-equalsExample" }, "examples/example-ng-app": { "path": "examples/example-ng-app" }, "examples/example-strict-di": { "path": "examples/example-strict-di" }, "examples/example-anchor-scroll": { "path": "examples/example-anchor-scroll" }, "examples/example-anchor-scroll-offset": { "path": "examples/example-anchor-scroll-offset" }, "examples/example-cache-factory": { "path": "examples/example-cache-factory" }, "examples/example-doCheckDateExample": { "path": "examples/example-doCheckDateExample" }, "examples/example-doCheckArrayExample": { "path": "examples/example-doCheckArrayExample" }, "examples/example-compile": { "path": "examples/example-compile" }, "examples/example-ng-href": { "path": "examples/example-ng-href" }, "examples/example-ng-disabled": { "path": "examples/example-ng-disabled" }, "examples/example-ng-checked": { "path": "examples/example-ng-checked" }, "examples/example-ng-readonly": { "path": "examples/example-ng-readonly" }, "examples/example-ng-selected": { "path": "examples/example-ng-selected" }, "examples/example-ng-open": { "path": "examples/example-ng-open" }, "examples/example-ng-form": { "path": "examples/example-ng-form" }, "examples/example-text-input-directive": { "path": "examples/example-text-input-directive" }, "examples/example-date-input-directive": { "path": "examples/example-date-input-directive" }, "examples/example-datetimelocal-input-directive": { "path": "examples/example-datetimelocal-input-directive" }, "examples/example-time-input-directive": { "path": "examples/example-time-input-directive" }, "examples/example-week-input-directive": { "path": "examples/example-week-input-directive" }, "examples/example-month-input-directive": { "path": "examples/example-month-input-directive" }, "examples/example-number-input-directive": { "path": "examples/example-number-input-directive" }, "examples/example-url-input-directive": { "path": "examples/example-url-input-directive" }, "examples/example-email-input-directive": { "path": "examples/example-email-input-directive" }, "examples/example-radio-input-directive": { "path": "examples/example-radio-input-directive" }, "examples/example-range-input-directive": { "path": "examples/example-range-input-directive" }, "examples/example-range-input-directive-ng": { "path": "examples/example-range-input-directive-ng" }, "examples/example-checkbox-input-directive": { "path": "examples/example-checkbox-input-directive" }, "examples/example-input-directive": { "path": "examples/example-input-directive" }, "examples/example-ngValue-directive": { "path": "examples/example-ngValue-directive" }, "examples/example-ng-bind": { "path": "examples/example-ng-bind" }, "examples/example-ng-bind-template": { "path": "examples/example-ng-bind-template" }, "examples/example-ng-bind-html": { "path": "examples/example-ng-bind-html" }, "examples/example-ngChange-directive": { "path": "examples/example-ngChange-directive" }, "examples/example-ng-class": { "path": "examples/example-ng-class" }, "examples/example-ng-class1": { "path": "examples/example-ng-class1" }, "examples/example-ng-class-odd": { "path": "examples/example-ng-class-odd" }, "examples/example-ng-class-even": { "path": "examples/example-ng-class-even" }, "examples/example-ng-cloak": { "path": "examples/example-ng-cloak" }, "examples/example-ngControllerAs": { "path": "examples/example-ngControllerAs" }, "examples/example-ngController": { "path": "examples/example-ngController" }, "examples/example-example.csp": { "path": "examples/example-example.csp" }, "examples/example-ng-click": { "path": "examples/example-ng-click" }, "examples/example-ng-dblclick": { "path": "examples/example-ng-dblclick" }, "examples/example-ng-mousedown": { "path": "examples/example-ng-mousedown" }, "examples/example-ng-mouseup": { "path": "examples/example-ng-mouseup" }, "examples/example-ng-mouseover": { "path": "examples/example-ng-mouseover" }, "examples/example-ng-mouseenter": { "path": "examples/example-ng-mouseenter" }, "examples/example-ng-mouseleave": { "path": "examples/example-ng-mouseleave" }, "examples/example-ng-mousemove": { "path": "examples/example-ng-mousemove" }, "examples/example-ng-keydown": { "path": "examples/example-ng-keydown" }, "examples/example-ng-keyup": { "path": "examples/example-ng-keyup" }, "examples/example-ng-keypress": { "path": "examples/example-ng-keypress" }, "examples/example-ng-submit": { "path": "examples/example-ng-submit" }, "examples/example-ng-copy": { "path": "examples/example-ng-copy" }, "examples/example-ng-cut": { "path": "examples/example-ng-cut" }, "examples/example-ng-paste": { "path": "examples/example-ng-paste" }, "examples/example-ng-if": { "path": "examples/example-ng-if" }, "template1.html": { "path": "template1.html" }, "template2.html": { "path": "template2.html" }, "examples/example-ng-include": { "path": "examples/example-ng-include" }, "examples/example-ng-init": { "path": "examples/example-ng-init" }, "examples/example-ngList-directive": { "path": "examples/example-ngList-directive" }, "examples/example-ngList-directive-newlines": { "path": "examples/example-ngList-directive-newlines" }, "examples/example-NgModelController": { "path": "examples/example-NgModelController" }, "examples/example-ng-model-cancel-update": { "path": "examples/example-ng-model-cancel-update" }, "examples/example-ng-model": { "path": "examples/example-ng-model" }, "examples/example-ngModel-getter-setter": { "path": "examples/example-ngModel-getter-setter" }, "examples/example-ngModelOptions-directive-blur": { "path": "examples/example-ngModelOptions-directive-blur" }, "examples/example-ngModelOptions-directive-debounce": { "path": "examples/example-ngModelOptions-directive-debounce" }, "examples/example-ngModelOptions-directive-getter-setter": { "path": "examples/example-ngModelOptions-directive-getter-setter" }, "examples/example-ng-non-bindable": { "path": "examples/example-ng-non-bindable" }, "examples/example-select": { "path": "examples/example-select" }, "examples/example-ng-pluralize": { "path": "examples/example-ng-pluralize" }, "examples/example-ng-repeat": { "path": "examples/example-ng-repeat" }, "glyphicons.css": { "path": "glyphicons.css" }, "examples/example-ng-show": { "path": "examples/example-ng-show" }, "examples/example-ng-hide": { "path": "examples/example-ng-hide" }, "examples/example-ng-style": { "path": "examples/example-ng-style" }, "examples/example-ng-switch": { "path": "examples/example-ng-switch" }, "examples/example-simpleTranscludeExample": { "path": "examples/example-simpleTranscludeExample" }, "examples/example-ng-transclude": { "path": "examples/example-ng-transclude" }, "examples/example-multiSlotTranscludeExample": { "path": "examples/example-multiSlotTranscludeExample" }, "examples/example-script-tag": { "path": "examples/example-script-tag" }, "examples/example-static-select": { "path": "examples/example-static-select" }, "examples/example-ngrepeat-select": { "path": "examples/example-ngrepeat-select" }, "examples/example-select-with-default-values": { "path": "examples/example-select-with-default-values" }, "examples/example-select-with-non-string-options": { "path": "examples/example-select-with-non-string-options" }, "examples/example-ngRequiredDirective": { "path": "examples/example-ngRequiredDirective" }, "examples/example-ngPatternDirective": { "path": "examples/example-ngPatternDirective" }, "examples/example-ngMaxlengthDirective": { "path": "examples/example-ngMaxlengthDirective" }, "examples/example-ngMinlengthDirective": { "path": "examples/example-ngMinlengthDirective" }, "examples/example-document": { "path": "examples/example-document" }, "examples/example-$filter": { "path": "examples/example-$filter" }, "examples/example-filter-filter": { "path": "examples/example-filter-filter" }, "examples/example-currency-filter": { "path": "examples/example-currency-filter" }, "examples/example-number-filter": { "path": "examples/example-number-filter" }, "examples/example-filter-date": { "path": "examples/example-filter-date" }, "examples/example-filter-json": { "path": "examples/example-filter-json" }, "examples/example-limit-to-filter": { "path": "examples/example-limit-to-filter" }, "examples/example-orderBy-static": { "path": "examples/example-orderBy-static" }, "examples/example-orderBy-dynamic": { "path": "examples/example-orderBy-dynamic" }, "examples/example-orderBy-call-manually": { "path": "examples/example-orderBy-call-manually" }, "examples/example-orderBy-custom-comparator": { "path": "examples/example-orderBy-custom-comparator" }, "http-hello.html": { "path": "http-hello.html" }, "examples/example-http-service": { "path": "examples/example-http-service" }, "examples/example-custom-interpolation-markup": { "path": "examples/example-custom-interpolation-markup" }, "examples/example-interpolation": { "path": "examples/example-interpolation" }, "examples/example-interval-service": { "path": "examples/example-interval-service" }, "examples/example-log-service": { "path": "examples/example-log-service" }, "test_data.json": { "path": "test_data.json" }, "examples/example-sce-service": { "path": "examples/example-sce-service" }, "examples/example-window-service": { "path": "examples/example-window-service" }, "examples/example-ngAnimateChildren": { "path": "examples/example-ngAnimateChildren" }, "home.html": { "path": "home.html" }, "profile.html": { "path": "profile.html" }, "examples/example-anchoringExample": { "path": "examples/example-anchoringExample" }, "examples/example-ngAnimateSwap-directive": { "path": "examples/example-ngAnimateSwap-directive" }, "examples/example-ngMessageFormat-example-gender": { "path": "examples/example-ngMessageFormat-example-gender" }, "examples/example-ngMessageFormat-example-plural": { "path": "examples/example-ngMessageFormat-example-plural" }, "examples/example-ngMessageFormat-example-plural-gender": { "path": "examples/example-ngMessageFormat-example-plural-gender" }, "examples/example-ngMessages-directive": { "path": "examples/example-ngMessages-directive" }, "e2e.js": { "path": "e2e.js" }, "examples/example-httpbackend-e2e-testing": { "path": "examples/example-httpbackend-e2e-testing" }, "book.html": { "path": "book.html" }, "chapter.html": { "path": "chapter.html" }, "examples/example-ngView-directive": { "path": "examples/example-ngView-directive" }, "examples/example-$route-service": { "path": "examples/example-$route-service" }, "examples/example-linky-filter": { "path": "examples/example-linky-filter" }, "examples/example-sanitize-service": { "path": "examples/example-sanitize-service" }, "examples/example-ng-touch-ng-click": { "path": "examples/example-ng-touch-ng-click" }, "examples/example-ng-swipe-left": { "path": "examples/example-ng-swipe-left" }, "examples/example-ng-swipe-right": { "path": "examples/example-ng-swipe-right" }, "error/$animate": { "name": "$animate", "area": "error", "path": "error/$animate" }, "error/$cacheFactory": { "name": "$cacheFactory", "area": "error", "path": "error/$cacheFactory" }, "error/$compile": { "name": "$compile", "area": "error", "path": "error/$compile" }, "error/$controller": { "name": "$controller", "area": "error", "path": "error/$controller" }, "error/$http": { "name": "$http", "area": "error", "path": "error/$http" }, "error/$injector": { "name": "$injector", "area": "error", "path": "error/$injector" }, "error/$interpolate": { "name": "$interpolate", "area": "error", "path": "error/$interpolate" }, "error/$location": { "name": "$location", "area": "error", "path": "error/$location" }, "error/$parse": { "name": "$parse", "area": "error", "path": "error/$parse" }, "error/$q": { "name": "$q", "area": "error", "path": "error/$q" }, "error/$resource": { "name": "$resource", "area": "error", "path": "error/$resource" }, "error/$rootScope": { "name": "$rootScope", "area": "error", "path": "error/$rootScope" }, "error/$sanitize": { "name": "$sanitize", "area": "error", "path": "error/$sanitize" }, "error/$sce": { "name": "$sce", "area": "error", "path": "error/$sce" }, "error/filter": { "name": "filter", "area": "error", "path": "error/filter" }, "error/jqLite": { "name": "jqLite", "area": "error", "path": "error/jqLite" }, "error/linky": { "name": "linky", "area": "error", "path": "error/linky" }, "error/ng": { "name": "ng", "area": "error", "path": "error/ng" }, "error/ngModel": { "name": "ngModel", "area": "error", "path": "error/ngModel" }, "error/ngOptions": { "name": "ngOptions", "area": "error", "path": "error/ngOptions" }, "error/ngPattern": { "name": "ngPattern", "area": "error", "path": "error/ngPattern" }, "error/ngRepeat": { "name": "ngRepeat", "area": "error", "path": "error/ngRepeat" }, "error/ngTransclude": { "name": "ngTransclude", "area": "error", "path": "error/ngTransclude" }, "error/orderBy": { "name": "orderBy", "area": "error", "path": "error/orderBy" }, ".": { "name": "production", "path": "." }, "api/ng/function": { "name": "function components in ng", "area": "api", "path": "api/ng/function" }, "api/ng/directive": { "name": "directive components in ng", "area": "api", "path": "api/ng/directive" }, "api/ng/object": { "name": "object components in ng", "area": "api", "path": "api/ng/object" }, "api/ng/type": { "name": "type components in ng", "area": "api", "path": "api/ng/type" }, "api/ng/provider": { "name": "provider components in ng", "area": "api", "path": "api/ng/provider" }, "api/ng/service": { "name": "service components in ng", "area": "api", "path": "api/ng/service" }, "api/ng/input": { "name": "input components in ng", "area": "api", "path": "api/ng/input" }, "api/ng/filter": { "name": "filter components in ng", "area": "api", "path": "api/ng/filter" }, "api/auto/service": { "name": "service components in auto", "area": "api", "path": "api/auto/service" }, "api/ngAnimate/directive": { "name": "directive components in ngAnimate", "area": "api", "path": "api/ngAnimate/directive" }, "api/ngAnimate/service": { "name": "service components in ngAnimate", "area": "api", "path": "api/ngAnimate/service" }, "api/ngAria/provider": { "name": "provider components in ngAria", "area": "api", "path": "api/ngAria/provider" }, "api/ngAria/service": { "name": "service components in ngAria", "area": "api", "path": "api/ngAria/service" }, "api/ngComponentRouter/type": { "name": "type components in ngComponentRouter", "area": "api", "path": "api/ngComponentRouter/type" }, "api/ngComponentRouter/directive": { "name": "directive components in ngComponentRouter", "area": "api", "path": "api/ngComponentRouter/directive" }, "api/ngComponentRouter/service": { "name": "service components in ngComponentRouter", "area": "api", "path": "api/ngComponentRouter/service" }, "api/ngCookies/provider": { "name": "provider components in ngCookies", "area": "api", "path": "api/ngCookies/provider" }, "api/ngCookies/service": { "name": "service components in ngCookies", "area": "api", "path": "api/ngCookies/service" }, "api/ngMessages/directive": { "name": "directive components in ngMessages", "area": "api", "path": "api/ngMessages/directive" }, "api/ngMock/object": { "name": "object components in ngMock", "area": "api", "path": "api/ngMock/object" }, "api/ngMock/provider": { "name": "provider components in ngMock", "area": "api", "path": "api/ngMock/provider" }, "api/ngMock/service": { "name": "service components in ngMock", "area": "api", "path": "api/ngMock/service" }, "api/ngMock/type": { "name": "type components in ngMock", "area": "api", "path": "api/ngMock/type" }, "api/ngMock/function": { "name": "function components in ngMock", "area": "api", "path": "api/ngMock/function" }, "api/ngMockE2E/service": { "name": "service components in ngMockE2E", "area": "api", "path": "api/ngMockE2E/service" }, "api/ngResource/provider": { "name": "provider components in ngResource", "area": "api", "path": "api/ngResource/provider" }, "api/ngResource/service": { "name": "service components in ngResource", "area": "api", "path": "api/ngResource/service" }, "api/ngRoute/directive": { "name": "directive components in ngRoute", "area": "api", "path": "api/ngRoute/directive" }, "api/ngRoute/provider": { "name": "provider components in ngRoute", "area": "api", "path": "api/ngRoute/provider" }, "api/ngRoute/service": { "name": "service components in ngRoute", "area": "api", "path": "api/ngRoute/service" }, "api/ngSanitize/filter": { "name": "filter components in ngSanitize", "area": "api", "path": "api/ngSanitize/filter" }, "api/ngSanitize/service": { "name": "service components in ngSanitize", "area": "api", "path": "api/ngSanitize/service" }, "api/ngSanitize/provider": { "name": "provider components in ngSanitize", "area": "api", "path": "api/ngSanitize/provider" }, "api/ngTouch/directive": { "name": "directive components in ngTouch", "area": "api", "path": "api/ngTouch/directive" }, "api/ngTouch/service": { "name": "service components in ngTouch", "area": "api", "path": "api/ngTouch/service" }, "api/ngTouch/provider": { "name": "provider components in ngTouch", "area": "api", "path": "api/ngTouch/provider" } });
LADOSSIFPB/nutrif
nutrif-web-refactor/lib/angular/docs/js/pages-data.js
JavaScript
apache-2.0
75,469
'use strict'; describe('Service: backend', function () { // load the service's module beforeEach(module('yeomanIonicAngularPhonegapSeedApp')); // instantiate service var backend; beforeEach(inject(function(_backend_) { backend = _backend_; })); it('should do something', function () { expect(!!backend).toBe(true); }); });
nadavelyashiv/metal_finder
test/spec/services/backend.js
JavaScript
apache-2.0
352
//>>built define( "dojox/editor/plugins/nls/cs/InsertAnchor", //begin v1.x content ({ insertAnchor: "Vložit kotvu", title: "Vlastnosti kotvy", anchor: "Název:", text: "Popis:", set: "Nastavit", cancel: "Storno" }) //end v1.x content );
cfxram/grails-dojo
web-app/js/dojo/1.7.2/dojox/editor/plugins/nls/cs/InsertAnchor.js
JavaScript
apache-2.0
245
/* Copyright 2017 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; var xhr = new XMLHttpRequest(); xhr.open('GET', 'data.json'); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { var data = JSON.parse(xhr.responseText); document.querySelector('#data').innerHTML = JSON.stringify(data); } }; /* // can do this in Chrome, Firefox, etc.: xhr.onload = function(event) { var data = JSON.parse(this.response); document.querySelector('#data').innerHTML = JSON.stringify(data); } */ xhr.send();
samdutton/simpl
xhr/js/main.js
JavaScript
apache-2.0
1,051
/** * Copyright 2016 The AMP HTML Authors. 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 {FrameOverlayManager} from './frame-overlay-manager'; import { MessageType, deserializeMessage, serializeMessage, } from '../../src/3p-frame-messaging'; import {PositionObserver} from './position-observer'; import {dev} from '../../src/log'; import {dict} from '../../src/utils/object'; import {getData} from '../../src/event-helper'; import {layoutRectFromDomRect} from '../../src/layout-rect'; /** @const */ const TAG = 'InaboxMessagingHost'; /** Simple helper for named callbacks. */ class NamedObservable { /** * Creates an instance of NamedObservable. */ constructor() { /** @private {!Object<string, !Function>} */ this.map_ = {}; } /** * @param {string} key * @param {!Function} callback */ listen(key, callback) { if (key in this.map_) { dev().fine(TAG, `Overriding message callback [${key}]`); } this.map_[key] = callback; } /** * @param {string} key * @param {*} thisArg * @param {!Array} args * @return {boolean} True when a callback was found and successfully executed. */ fire(key, thisArg, args) { if (key in this.map_) { return this.map_[key].apply(thisArg, args); } return false; } } /** @typedef {{ iframe: !HTMLIFrameElement, measurableFrame: !HTMLIFrameElement, observeUnregisterFn: (!UnlistenDef|undefined), }} */ let AdFrameDef; export class InaboxMessagingHost { /** * @param {!Window} win * @param {!Array<!HTMLIFrameElement>} iframes */ constructor(win, iframes) { /** @private {!Array<!HTMLIFrameElement>} */ this.iframes_ = iframes; /** @private {!Object<string,!AdFrameDef>} */ this.iframeMap_ = Object.create(null); /** @private {!PositionObserver} */ this.positionObserver_ = new PositionObserver(win); /** @private {!NamedObservable} */ this.msgObservable_ = new NamedObservable(); /** @private {!FrameOverlayManager} */ this.frameOverlayManager_ = new FrameOverlayManager(win); this.msgObservable_.listen( MessageType.SEND_POSITIONS, this.handleSendPositions_); this.msgObservable_.listen( MessageType.FULL_OVERLAY_FRAME, this.handleEnterFullOverlay_); this.msgObservable_.listen( MessageType.CANCEL_FULL_OVERLAY_FRAME, this.handleCancelFullOverlay_); } /** * Process a single post message. * * A valid message has to be formatted as a string starting with "amp-". The * rest part should be a stringified JSON object of * {type: string, sentinel: string}. The allowed types are listed in the * REQUEST_TYPE enum. * * @param {!MessageEvent} message * @return {boolean} true if message get successfully processed */ processMessage(message) { const request = deserializeMessage(getData(message)); if (!request || !request['sentinel']) { dev().fine(TAG, 'Ignored non-AMP message:', message); return false; } const iframe = this.getFrameElement_(message.source, request['sentinel']); if (!iframe) { dev().info(TAG, 'Ignored message from untrusted iframe:', message); return false; } if (!this.msgObservable_.fire(request['type'], this, [iframe, request, message.source, message.origin])) { dev().warn(TAG, 'Unprocessed AMP message:', message); return false; } return true; } /** * @param {!HTMLIFrameElement} iframe * @param {!Object} request * @param {!Window} source * @param {string} origin * @return {boolean} */ handleSendPositions_(iframe, request, source, origin) { const viewportRect = this.positionObserver_.getViewportRect(); const targetRect = layoutRectFromDomRect(iframe./*OK*/getBoundingClientRect()); this.sendPosition_(request, source, origin, dict({ 'viewportRect': viewportRect, 'targetRect': targetRect, })); dev().assert(this.iframeMap_[request.sentinel]); this.iframeMap_[request.sentinel].observeUnregisterFn = this.iframeMap_[request.sentinel].observeUnregisterFn || this.positionObserver_.observe(iframe, data => this.sendPosition_(request, source, origin, /** @type ?JsonObject */(data))); return true; } /** * * @param {!Object} request * @param {!Window} source * @param {string} origin * @param {?JsonObject} data */ sendPosition_(request, source, origin, data) { dev().fine(TAG, `Sent position data to [${request.sentinel}]`, data); source./*OK*/postMessage( serializeMessage(MessageType.POSITION, request.sentinel, data), origin); } /** * @param {!HTMLIFrameElement} iframe * @param {!Object} request * @param {!Window} source * @param {string} origin * @return {boolean} * TODO(alanorozco): * 1. Reject request if frame is out of focus * 2. Disable zoom and scroll on parent doc */ handleEnterFullOverlay_(iframe, request, source, origin) { this.frameOverlayManager_.expandFrame(iframe, boxRect => { source./*OK*/postMessage( serializeMessage( MessageType.FULL_OVERLAY_FRAME_RESPONSE, request.sentinel, dict({ 'success': true, 'boxRect': boxRect, })), origin); }); return true; } /** * @param {!HTMLIFrameElement} iframe * @param {!Object} request * @param {!Window} source * @param {string} origin * @return {boolean} */ handleCancelFullOverlay_(iframe, request, source, origin) { this.frameOverlayManager_.collapseFrame(iframe, boxRect => { source./*OK*/postMessage( serializeMessage( MessageType.CANCEL_FULL_OVERLAY_FRAME_RESPONSE, request.sentinel, dict({ 'success': true, 'boxRect': boxRect, })), origin); }); return true; } /** This method is doing two things. * 1. It checks that the source of the message is valid. * Validity means that the message comes from a frame that * is either directly registered in this.iframes_, or is a * child of one of those frames. * 2. It returns whichever iframe is the deepest frame in the source's * hierarchy that the outer host window can still measure, which is * the top most cross domained frame, or the creative frame. * EXAMPLE: * If we have a frame hierarchy: * Host -> Friendly Frame -> X Domain Frame 1 -> Message Source Frame * and "Friendly Frame" is registered in this.iframes_, then * "Message Source Frame" is valid, because one of its parent frames * is registered in this.iframes_, and the result of the call to * getFrameElement_ would be the iframe "X Domain Frame 1" as it is * the deepest frame that the host doc can accurately measure. * Note: The sentinel should be unique to the source window, and the result * is cached using the sentinel as the key. * * @param {?Window} source * @param {string} sentinel * @return {?HTMLIFrameElement} * @private */ getFrameElement_(source, sentinel) { if (this.iframeMap_[sentinel]) { return this.iframeMap_[sentinel].measurableFrame; } const measurableFrame = this.getMeasureableFrame(source); if (!measurableFrame) { return null; } const measurableWin = measurableFrame.contentWindow; for (let i = 0; i < this.iframes_.length; i++) { const iframe = this.iframes_[i]; for (let j = 0, tempWin = measurableWin; j < 10; j++, tempWin = tempWin.parent) { if (iframe.contentWindow == tempWin) { this.iframeMap_[sentinel] = {iframe, measurableFrame}; return measurableFrame; } if (tempWin == window.top) { break; } } } return null; } /** * Returns whichever window in win's parent hierarchy is the deepest window * that is measurable from the perspective of the current window. * For when win is nested within a x-domain frame, walks up the window's * parent hierarchy until the top-most x-domain frame in the hierarchy * is found. Then, it returns the frame element for that window. * For when win is friendly framed, returns the frame element for win. * @param {?Window} win * @return {?HTMLIFrameElement} * @visibleForTesting */ getMeasureableFrame(win) { if (!win) { return null; } // First, we try to find the top-most x-domain window in win's parent // hierarchy. If win is not nested within x-domain framing, then // this loop breaks immediately. let topXDomainWin; for (let j = 0, tempWin = win; j < 10 && tempWin != tempWin.top && !canInspectWindow_(tempWin); j++, topXDomainWin = tempWin, tempWin = tempWin.parent) {} // If topXDomainWin exists, we know that the frame we want to measure // is a x-domain frame. Unfortunately, you can not access properties // on a x-domain window, so we can not do window.frameElement, and // instead must instead get topXDomainWin's parent, and then iterate // over that parent's child iframes until we find the frame element // that corresponds to topXDomainWin. if (!!topXDomainWin) { const iframes = topXDomainWin.parent.document.querySelectorAll('iframe'); for (let k = 0, frame = iframes[k]; k < iframes.length; k++, frame = iframes[k]) { if (frame.contentWindow == topXDomainWin) { return /** @type {!HTMLIFrameElement} */(frame); } } } // If topXDomainWin does not exist, then win is friendly, and we can // just return its frameElement directly. return /** @type {!HTMLIFrameElement} */(win.frameElement); } /** * Removes an iframe from the set of iframes we watch, along with executing * any necessary cleanup. Available at win.AMP.inaboxUnregisterIframe(). * * @param {!HTMLIFrameElement} iframe */ unregisterIframe(iframe) { // Remove iframe from the list of iframes we're watching. const iframeIndex = this.iframes_.indexOf(iframe); if (iframeIndex != -1) { this.iframes_.splice(iframeIndex, 1); } // Also remove it and all of its descendents from our sentinel cache. // TODO(jeffkaufman): save more info so we don't have to walk the dom here. for (const sentinel in this.iframeMap_) { if (this.iframeMap_[sentinel].iframe == iframe) { if (this.iframeMap_[sentinel].observeUnregisterFn) { this.iframeMap_[sentinel].observeUnregisterFn(); } delete this.iframeMap_[sentinel]; } } } } /** * Returns true if win's properties can be accessed and win is defined. * This functioned is used to determine if a window is cross-domained * from the perspective of the current window. * @param {!Window} win * @return {boolean} * @private */ function canInspectWindow_(win) { try { const unused = !!win.location.href && win['test']; // eslint-disable-line no-unused-vars return true; } catch (unusedErr) { // eslint-disable-line no-unused-vars return false; } }
chaveznvg/amphtml
ads/inabox/inabox-messaging-host.js
JavaScript
apache-2.0
11,809
var accordion = function() { var e = new Foundation.Accordion($('.accordion')); }
georgemarshall/habitat
www/source/javascripts/accordion.js
JavaScript
apache-2.0
83
'use strict'; const { Readable } = require('stream'); const SILENCE_FRAME = Buffer.from([0xF8, 0xFF, 0xFE]); class Silence extends Readable { _read() { this.push(SILENCE_FRAME); } } module.exports = Silence;
Lewdcario/discord.js
src/client/voice/util/Silence.js
JavaScript
apache-2.0
220
describe('IDBIndex.count', function() { 'use strict'; it('should return an IDBRequest', function(done) { util.createDatabase('inline', 'inline-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); tx.onerror = function(event) { done(event.target.error); }; var store = tx.objectStore('inline'); var storeCount = store.count(); var indexCount = store.index('inline-index') .count(); expect(storeCount).to.be.an.instanceOf(IDBRequest); expect(indexCount).to.be.an.instanceOf(IDBRequest); tx.oncomplete = function() { db.close(); done(); }; }); }); it('should have a reference to the transaction', function(done) { util.createDatabase('inline', 'inline-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); tx.onerror = done; var store = tx.objectStore('inline'); var storeCount = store.count(); var indexCount = store.index('inline-index') .count(); expect(storeCount.transaction).to.equal(tx); expect(indexCount.transaction).to.equal(tx); expect(storeCount.transaction.db).to.equal(db); expect(indexCount.transaction.db).to.equal(db); tx.oncomplete = function() { db.close(); done(); }; }); }); it('should pass the IDBRequest to the onsuccess event', function(done) { util.createDatabase('inline', 'inline-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); tx.onerror = done; var store = tx.objectStore('inline'); var storeCount = store.count(); storeCount.onerror = sinon.spy(); storeCount.onsuccess = sinon.spy(function(event) { expect(event).to.be.an.instanceOf(env.Event); expect(event.target).to.equal(storeCount); }); var indexCount = store.index('inline-index') .count(); indexCount.onerror = sinon.spy(); indexCount.onsuccess = sinon.spy(function(event) { expect(event).to.be.an.instanceOf(env.Event); expect(event.target).to.equal(indexCount); }); tx.oncomplete = function() { sinon.assert.calledOnce(storeCount.onsuccess); sinon.assert.calledOnce(indexCount.onsuccess); sinon.assert.notCalled(storeCount.onerror); sinon.assert.notCalled(indexCount.onerror); db.close(); done(); }; }); }); it('should return zero if there are no records', function(done) { util.createDatabase('out-of-line', 'inline-index', function(err, db) { var tx = db.transaction('out-of-line', 'readwrite'); tx.onerror = done; var store = tx.objectStore('out-of-line'); var storeCount = store.count(); var indexCount = store.index('inline-index') .count(); tx.oncomplete = function() { expect(storeCount.result).to.equal(0); expect(indexCount.result).to.equal(0); db.close(); done(); }; }); }); it('should return one if there is one record', function(done) { util.createDatabase('out-of-line', 'inline-index', function(err, db) { var tx = db.transaction('out-of-line', 'readwrite'); tx.onerror = function(evt) { done(evt.target.error); }; var store = tx.objectStore('out-of-line'); store.add({id: 'a'}, 12345); var storeCount = store.count(); var indexCount = store.index('inline-index') .count(); tx.oncomplete = function() { expect(storeCount.result).to.equal(1); expect(indexCount.result).to.equal(1); db.close(); done(); }; }); }); it('should return the count for multiple records', function(done) { util.createDatabase('out-of-line', 'inline-index', function(err, db) { var tx = db.transaction('out-of-line', 'readwrite'); tx.onerror = done; var store = tx.objectStore('out-of-line'); store.add({id: 'a'}, 111); store.add({id: 'b'}, 2222); store.add({id: 'c'}, 33); var storeCount = store.count(); var indexCount = store.index('inline-index') .count(); tx.oncomplete = function() { expect(storeCount.result).to.equal(3); expect(indexCount.result).to.equal(3); db.close(); done(); }; }); }); util.skipIf(env.browser.isIE && (env.isNative || env.isPolyfilled),'should return the count for multi-entry indexes', function(done) { // BUG: IE's native IndexedDB does not support multi-entry indexes this.timeout(10000); this.slow(10000); util.createDatabase('inline', 'multi-entry-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('multi-entry-index'); tx.onerror = function(event) { done(event.target.error.message); }; for (var i = 0; i < 500; i++) { store.add({id: ['a', 'b', i]}); store.add({id: ['a', 'c', i]}); } var storeCount1 = store.count(); var indexCount1 = index.count(); var storeCount2 = store.count('a'); var indexCount2 = index.count('a'); var storeCount3 = store.count('b'); var indexCount3 = index.count('b'); var storeCount4 = store.count('c'); var indexCount4 = index.count('c'); var storeCount5 = store.count(['a', 'b', 5]); var indexCount5 = index.count(['a', 'b', 5]); var storeCount6 = store.count(['b']); var indexCount6 = index.count(['b']); tx.oncomplete = function() { expect(storeCount1.result).to.equal(1000); expect(storeCount2.result).to.equal(0); expect(storeCount3.result).to.equal(0); expect(storeCount4.result).to.equal(0); expect(storeCount5.result).to.equal(1); expect(storeCount6.result).to.equal(0); expect(indexCount1.result).to.equal(3000); expect(indexCount2.result).to.equal(1000); expect(indexCount3.result).to.equal(500); expect(indexCount4.result).to.equal(500); expect(indexCount5.result).to.equal(0); expect(indexCount6.result).to.equal(0); db.close(); done(); }; }); }); util.skipIf(env.browser.isIE && (env.isNative || env.isPolyfilled),'should return the count for unique, multi-entry indexes', function(done) { // BUG: IE's native IndexedDB does not support multi-entry indexes this.timeout(10000); this.slow(10000); util.createDatabase('inline', 'unique-multi-entry-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('unique-multi-entry-index'); tx.onerror = function(event) { done(event.target.error.message); }; for (var i = 0; i < 500; i++) { store.add({id: ['a' + i, 'b' + i]}); store.add({id: ['c' + i]}); } var storeCount1 = store.count(); var indexCount1 = index.count(); var storeCount2 = store.count('a250'); var indexCount2 = index.count('a250'); var storeCount3 = store.count('b499'); var indexCount3 = index.count('b499'); var storeCount4 = store.count('c9'); var indexCount4 = index.count('c9'); var storeCount5 = store.count(['a5', 'b5']); var indexCount5 = index.count(['a5', 'b5']); var storeCount6 = store.count(['b42']); var indexCount6 = index.count(['b42']); tx.oncomplete = function() { expect(storeCount1.result).to.equal(1000); expect(storeCount2.result).to.equal(0); expect(storeCount3.result).to.equal(0); expect(storeCount4.result).to.equal(0); expect(storeCount5.result).to.equal(1); expect(storeCount6.result).to.equal(0); expect(indexCount1.result).to.equal(1500); expect(indexCount2.result).to.equal(1); expect(indexCount3.result).to.equal(1); expect(indexCount4.result).to.equal(1); expect(indexCount5.result).to.equal(0); expect(indexCount6.result).to.equal(0); db.close(); done(); }; }); }); it('should return different values as records are added/removed', function(done) { util.createDatabase('inline', 'inline-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('inline-index') ; tx.onerror = done; var storeCount1 = store.count(); var indexCount1 = index.count(); store.add({id: 'a'}); store.add({id: 'b'}); var storeCount2 = store.count(); var indexCount2 = index.count(); store.delete('a'); var storeCount3 = store.count(); var indexCount3 = index.count(); store.add({id: 'a'}); store.add({id: 'c'}); store.add({id: 'd'}); var storeCount4 = store.count(); var indexCount4 = index.count(); tx.oncomplete = function() { expect(storeCount1.result).to.equal(0); expect(indexCount1.result).to.equal(0); expect(storeCount2.result).to.equal(2); expect(indexCount2.result).to.equal(2); expect(storeCount3.result).to.equal(1); expect(indexCount3.result).to.equal(1); expect(storeCount4.result).to.equal(4); expect(indexCount4.result).to.equal(4); db.close(); done(); }; }); }); util.skipIf(env.browser.isIE && (env.isNative || env.isPolyfilled),'should return different values as records are added/removed from multi-entry indexes', function(done) { // BUG: IE's native IndexedDB does not support multi-entry indexes util.createDatabase('inline', 'multi-entry-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('multi-entry-index'); tx.onerror = done; var storeCount1 = store.count(); var indexCount1 = index.count(); store.add({id: ['a']}); var storeCount2 = store.count(); var indexCount2 = index.count(); store.add({id: ['a', 'b']}); var storeCount3 = store.count(); var indexCount3 = index.count(); store.delete(['a']); var storeCount4 = store.count(); var indexCount4 = index.count(); store.add({id: ['a']}); var storeCount5 = store.count(); var indexCount5 = index.count(); store.add({id: ['c', 'a', 'd']}); var storeCount6 = store.count(); var indexCount6 = index.count(); store.add({id: ['d', 'c']}); var storeCount7 = store.count(); var indexCount7 = index.count(); tx.oncomplete = function() { expect(storeCount1.result).to.equal(0); expect(storeCount2.result).to.equal(1); expect(storeCount3.result).to.equal(2); expect(storeCount4.result).to.equal(1); expect(storeCount5.result).to.equal(2); expect(storeCount6.result).to.equal(3); expect(storeCount7.result).to.equal(4); expect(indexCount1.result).to.equal(0); expect(indexCount2.result).to.equal(1); expect(indexCount3.result).to.equal(3); expect(indexCount4.result).to.equal(2); expect(indexCount5.result).to.equal(3); expect(indexCount6.result).to.equal(6); expect(indexCount7.result).to.equal(8); db.close(); done(); }; }); }); util.skipIf(env.browser.isIE && (env.isNative || env.isPolyfilled),'should return different values as records are added/removed from unique, multi-entry indexes', function(done) { // BUG: IE's native IndexedDB does not support multi-entry indexes util.createDatabase('inline', 'unique-multi-entry-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('unique-multi-entry-index'); tx.onerror = done; var storeCount1 = store.count(); var indexCount1 = index.count(); store.add({id: ['a']}); var storeCount2 = store.count(); var indexCount2 = index.count(); store.add({id: ['b', 'c']}); var storeCount3 = store.count(); var indexCount3 = index.count(); store.delete(['b']); var storeCount4 = store.count(); var indexCount4 = index.count(); store.add({id: ['d', 'e']}); var storeCount5 = store.count(); var indexCount5 = index.count(); store.delete(['b', 'c']); var storeCount6 = store.count(); var indexCount6 = index.count(); tx.oncomplete = function() { expect(storeCount1.result).to.equal(0); expect(storeCount2.result).to.equal(1); expect(storeCount3.result).to.equal(2); expect(storeCount4.result).to.equal(2); expect(storeCount5.result).to.equal(3); expect(storeCount6.result).to.equal(2); expect(indexCount1.result).to.equal(0); expect(indexCount2.result).to.equal(1); expect(indexCount3.result).to.equal(3); expect(indexCount4.result).to.equal(3); expect(indexCount5.result).to.equal(5); expect(indexCount6.result).to.equal(3); db.close(); done(); }; }); }); it('should throw an error if the transaction is closed', function(done) { util.createDatabase('inline', 'inline-index', function(err, db) { var tx = db.transaction('inline', 'readwrite'); var store = tx.objectStore('inline'); var index = store.index('inline-index') ; setTimeout(function() { tryToCount(store); tryToCount(index); function tryToCount(obj) { var err = null; try { obj.count(); } catch (e) { err = e; } expect(err).to.be.an.instanceOf(env.DOMException); expect(err.name).to.equal('TransactionInactiveError'); } db.close(); done(); }, 50); }); }); });
kberryman/IndexedDBShim
tests/IDBIndex/count-spec.js
JavaScript
apache-2.0
16,279
goog.provide('ol.animation'); goog.require('ol'); goog.require('ol.PreRenderFunction'); goog.require('ol.ViewHint'); goog.require('ol.coordinate'); goog.require('ol.easing'); /** * Generate an animated transition that will "bounce" the resolution as it * approaches the final value. * @param {olx.animation.BounceOptions} options Bounce options. * @return {ol.PreRenderFunction} Pre-render function. * @api */ ol.animation.bounce = function(options) { var resolution = options.resolution; var start = options.start ? options.start : Date.now(); var duration = options.duration !== undefined ? options.duration : 1000; var easing = options.easing ? options.easing : ol.easing.upAndDown; return ( /** * @param {ol.Map} map Map. * @param {?olx.FrameState} frameState Frame state. * @return {boolean} Run this function in the next frame. */ function(map, frameState) { if (frameState.time < start) { frameState.animate = true; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else if (frameState.time < start + duration) { var delta = easing((frameState.time - start) / duration); var deltaResolution = resolution - frameState.viewState.resolution; frameState.animate = true; frameState.viewState.resolution += delta * deltaResolution; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else { return false; } }); }; /** * Generate an animated transition while updating the view center. * @param {olx.animation.PanOptions} options Pan options. * @return {ol.PreRenderFunction} Pre-render function. * @api */ ol.animation.pan = function(options) { var source = options.source; var start = options.start ? options.start : Date.now(); var sourceX = source[0]; var sourceY = source[1]; var duration = options.duration !== undefined ? options.duration : 1000; var easing = options.easing ? options.easing : ol.easing.inAndOut; return ( /** * @param {ol.Map} map Map. * @param {?olx.FrameState} frameState Frame state. * @return {boolean} Run this function in the next frame. */ function(map, frameState) { if (frameState.time < start) { frameState.animate = true; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else if (frameState.time < start + duration) { var delta = 1 - easing((frameState.time - start) / duration); var deltaX = sourceX - frameState.viewState.center[0]; var deltaY = sourceY - frameState.viewState.center[1]; frameState.animate = true; frameState.viewState.center[0] += delta * deltaX; frameState.viewState.center[1] += delta * deltaY; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else { return false; } }); }; /** * Generate an animated transition while updating the view rotation. * @param {olx.animation.RotateOptions} options Rotate options. * @return {ol.PreRenderFunction} Pre-render function. * @api */ ol.animation.rotate = function(options) { var sourceRotation = options.rotation ? options.rotation : 0; var start = options.start ? options.start : Date.now(); var duration = options.duration !== undefined ? options.duration : 1000; var easing = options.easing ? options.easing : ol.easing.inAndOut; var anchor = options.anchor ? options.anchor : null; return ( /** * @param {ol.Map} map Map. * @param {?olx.FrameState} frameState Frame state. * @return {boolean} Run this function in the next frame. */ function(map, frameState) { if (frameState.time < start) { frameState.animate = true; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else if (frameState.time < start + duration) { var delta = 1 - easing((frameState.time - start) / duration); var deltaRotation = (sourceRotation - frameState.viewState.rotation) * delta; frameState.animate = true; frameState.viewState.rotation += deltaRotation; if (anchor) { var center = frameState.viewState.center; ol.coordinate.sub(center, anchor); ol.coordinate.rotate(center, deltaRotation); ol.coordinate.add(center, anchor); } frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else { return false; } }); }; /** * Generate an animated transition while updating the view resolution. * @param {olx.animation.ZoomOptions} options Zoom options. * @return {ol.PreRenderFunction} Pre-render function. * @api */ ol.animation.zoom = function(options) { var sourceResolution = options.resolution; var start = options.start ? options.start : Date.now(); var duration = options.duration !== undefined ? options.duration : 1000; var easing = options.easing ? options.easing : ol.easing.inAndOut; return ( /** * @param {ol.Map} map Map. * @param {?olx.FrameState} frameState Frame state. * @return {boolean} Run this function in the next frame. */ function(map, frameState) { if (frameState.time < start) { frameState.animate = true; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else if (frameState.time < start + duration) { var delta = 1 - easing((frameState.time - start) / duration); var deltaResolution = sourceResolution - frameState.viewState.resolution; frameState.animate = true; frameState.viewState.resolution += delta * deltaResolution; frameState.viewHints[ol.ViewHint.ANIMATING] += 1; return true; } else { return false; } }); };
NOAA-ORR-ERD/ol3
src/ol/animation.js
JavaScript
bsd-2-clause
6,053
require('fis3-smarty')(fis); fis.set('namespace', 'common');
moohing/fis3-smarty
doc/demo/common/fis-conf.js
JavaScript
bsd-2-clause
61
'use strict'; var util = require('../node_modules/mapbox-gl/js/util/util'); try { main(); } catch (err) { log('red', err.toString()); throw err; } function main() { var benchmarks = { simple_select_small: require('./tests/simple_select_small'), simple_select_large: require('./tests/simple_select_large'), simple_select_large_two_maps: require('./tests/simple_select_large_two_maps'), simple_select_large_zoomed: require('./tests/simple_select_large_zoomed'), direct_select_small: require('./tests/direct_select_small'), direct_select_small_zoomed: require('./tests/direct_select_small_zoomed'), direct_select_large: require('./tests/direct_select_large'), direct_select_large_zoomed: require('./tests/direct_select_large_zoomed'), draw_line_string_small: require('./tests/draw_line_string_small'), draw_line_string_large: require('./tests/draw_line_string_large'), draw_line_string_large_zoomed: require('./tests/draw_line_string_large_zoomed'), draw_polygon_small: require('./tests/draw_polygon_small'), draw_polygon_large: require('./tests/draw_polygon_large'), draw_polygon_large_zoomed: require('./tests/draw_polygon_large_zoomed'), draw_land_polygon_small: require('./tests/draw_land_polygon_small'), draw_land_polygon_large: require('./tests/draw_land_polygon_large'), draw_urban_areas_polygon_small: require('./tests/draw_urban_areas_polygon_small'), draw_urban_areas_polygon_large: require('./tests/draw_urban_areas_polygon_large'), draw_point_small: require('./tests/draw_point_small'), draw_point_large: require('./tests/draw_point_large'), draw_point_large_zoomed: require('./tests/draw_point_large_zoomed'), }; var pathnameArray = location.pathname.split('/'); var benchmarkName = pathnameArray[pathnameArray.length - 1] || pathnameArray[pathnameArray.length - 2]; var testDiv = document.getElementById('tests'); var tests = Object.keys(benchmarks); var innerHTML = ''; tests.forEach(function(test) { innerHTML += '<div class="test">'; innerHTML += '<a href="/bench/'+test+'">'+test+'</a>'; innerHTML += '</div>'; if (test === benchmarkName) { innerHTML += '<div id="logs"></div>'; } }); testDiv.innerHTML = innerHTML; log('dark', 'please keep this window in the foreground and close the debugger'); var createBenchmark = benchmarks[benchmarkName]; if (!createBenchmark) { log('dark', benchmarkName+' is not a valid test name'); return; } var benchmark = createBenchmark({ accessToken: getAccessToken(), createMap: createMap }); benchmark.on('log', function(event) { log(event.color || 'blue', event.message); }); benchmark.on('pass', function(event) { log('green', '<strong class="prose-big">' + event.message + '</strong>'); }); benchmark.on('fail', function(event) { log('red', '<strong class="prose-big">' + event.message + '</strong>'); }); } function log(color, message) { document.getElementById('logs').innerHTML += '<div class="log dark fill-' + color + '"><p>' + message + '</p></div>'; } function getAccessToken() { var accessToken = ( process.env.MapboxAccessToken || process.env.MAPBOX_ACCESS_TOKEN || getURLParameter('access_token') || localStorage.getItem('accessToken') ); localStorage.setItem('accessToken', accessToken); return accessToken; } function getURLParameter(name) { var regexp = new RegExp('[?&]' + name + '=([^&#]*)', 'i'); var output = regexp.exec(window.location.href); return output && output[1]; } function createMap(options) { var mapElement = document.getElementById('map'); options = util.extend({width: 512, height: 512}, options); mapElement.style.display = 'block'; mapElement.style.width = options.width + 'px'; mapElement.style.height = options.height + 'px'; mapboxgl.accessToken = getAccessToken(); var map = new mapboxgl.Map(util.extend({ container: 'map', style: 'mapbox://styles/mapbox/streets-v8' }, options)); var draw = mapboxgl.Draw(options); map.addControl(draw); return { draw: draw, map: map } }
hendrikusR/open-layer
widget/assets/draw/mapbox-gl-draw/bench/index.js
JavaScript
bsd-3-clause
4,416
/* depends_on_multi_main 2.1.1 */
gocept/bowerstatic
bowerstatic/tests/bower_components/depends_on_multi_main/dist/resource.js
JavaScript
bsd-3-clause
34
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('simple-model', 'SimpleModel', { // Specify the other units that are required for this test. needs: [] }); test('it exists', function() { var model = this.subject(); // var store = this.store(); ok(!!model); });
CENDARI/portia
slyd/tests/unit/models/simple-model-test.js
JavaScript
bsd-3-clause
295
/*! jQuery Colorbox v1.4.10 - 2013-04-02 (c) 2013 Jack Moore - jacklmoore.com/colorbox license: http://www.opensource.org/licenses/mit-license.php */ (function ($, document, window) { var // Default settings object. // See http://jacklmoore.com/colorbox for details. defaults = { transition: "elastic", speed: 300, width: false, initialWidth: "600", innerWidth: false, maxWidth: false, height: false, initialHeight: "450", innerHeight: false, maxHeight: false, scalePhotos: true, scrolling: true, inline: false, html: false, iframe: false, fastIframe: true, photo: false, href: false, title: false, rel: false, opacity: 0.9, preloading: true, className: false, // alternate image paths for high-res displays retinaImage: false, retinaUrl: false, retinaSuffix: '@2x.$1', // internationalization current: "image {current} of {total}", previous: "previous", next: "next", close: "close", xhrError: "This content failed to load.", imgError: "This image failed to load.", open: false, returnFocus: true, reposition: true, loop: true, slideshow: false, slideshowAuto: true, slideshowSpeed: 2500, slideshowStart: "start slideshow", slideshowStop: "stop slideshow", photoRegex: /\.(gif|png|jp(e|g|eg)|bmp|ico)((#|\?).*)?$/i, onOpen: false, onLoad: false, onComplete: false, onCleanup: false, onClosed: false, overlayClose: true, escKey: true, arrowKey: true, top: false, bottom: false, left: false, right: false, fixed: false, data: undefined }, // Abstracting the HTML and event identifiers for easy rebranding colorbox = 'colorbox', prefix = 'cbox', boxElement = prefix + 'Element', // Events event_open = prefix + '_open', event_load = prefix + '_load', event_complete = prefix + '_complete', event_cleanup = prefix + '_cleanup', event_closed = prefix + '_closed', event_purge = prefix + '_purge', // Cached jQuery Object Variables $overlay, $box, $wrap, $content, $topBorder, $leftBorder, $rightBorder, $bottomBorder, $related, $window, $loaded, $loadingBay, $loadingOverlay, $title, $current, $slideshow, $next, $prev, $close, $groupControls, $events = $('<a/>'), // Variables for cached values or use across multiple functions settings, interfaceHeight, interfaceWidth, loadedHeight, loadedWidth, element, index, photo, open, active, closing, loadingTimer, publicMethod, div = "div", className, requests = 0, init; // **************** // HELPER FUNCTIONS // **************** // Convience function for creating new jQuery objects function $tag(tag, id, css) { var element = document.createElement(tag); if (id) { element.id = prefix + id; } if (css) { element.style.cssText = css; } return $(element); } // Get the window height using innerHeight when available to avoid an issue with iOS // http://bugs.jquery.com/ticket/6724 function winheight() { return window.innerHeight ? window.innerHeight : $(window).height(); } // Determine the next and previous members in a group. function getIndex(increment) { var max = $related.length, newIndex = (index + increment) % max; return (newIndex < 0) ? max + newIndex : newIndex; } // Convert '%' and 'px' values to integers function setSize(size, dimension) { return Math.round((/%/.test(size) ? ((dimension === 'x' ? $window.width() : winheight()) / 100) : 1) * parseInt(size, 10)); } // Checks an href to see if it is a photo. // There is a force photo option (photo: true) for hrefs that cannot be matched by the regex. function isImage(settings, url) { return settings.photo || settings.photoRegex.test(url); } function retinaUrl(settings, url) { return settings.retinaUrl && window.devicePixelRatio > 1 ? url.replace(settings.photoRegex, settings.retinaSuffix) : url; } function trapFocus(e) { if ('contains' in $box[0] && !$box[0].contains(e.target)) { e.stopPropagation(); $box.focus(); } } // Assigns function results to their respective properties function makeSettings() { var i, data = $.data(element, colorbox); if (data == null) { settings = $.extend({}, defaults); if (console && console.log) { console.log('Error: cboxElement missing settings object'); } } else { settings = $.extend({}, data); } for (i in settings) { if ($.isFunction(settings[i]) && i.slice(0, 2) !== 'on') { // checks to make sure the function isn't one of the callbacks, they will be handled at the appropriate time. settings[i] = settings[i].call(element); } } settings.rel = settings.rel || element.rel || $(element).data('rel') || 'nofollow'; settings.href = settings.href || $(element).attr('href'); settings.title = settings.title || element.title; if (typeof settings.href === "string") { settings.href = $.trim(settings.href); } } function trigger(event, callback) { // for external use $(document).trigger(event); // for internal use $events.trigger(event); if ($.isFunction(callback)) { callback.call(element); } } // Slideshow functionality function slideshow() { var timeOut, className = prefix + "Slideshow_", click = "click." + prefix, clear, set, start, stop; if (settings.slideshow && $related[1]) { clear = function () { clearTimeout(timeOut); }; set = function () { if (settings.loop || $related[index + 1]) { timeOut = setTimeout(publicMethod.next, settings.slideshowSpeed); } }; start = function () { $slideshow .html(settings.slideshowStop) .unbind(click) .one(click, stop); $events .bind(event_complete, set) .bind(event_load, clear) .bind(event_cleanup, stop); $box.removeClass(className + "off").addClass(className + "on"); }; stop = function () { clear(); $events .unbind(event_complete, set) .unbind(event_load, clear) .unbind(event_cleanup, stop); $slideshow .html(settings.slideshowStart) .unbind(click) .one(click, function () { publicMethod.next(); start(); }); $box.removeClass(className + "on").addClass(className + "off"); }; if (settings.slideshowAuto) { start(); } else { stop(); } } else { $box.removeClass(className + "off " + className + "on"); } } function launch(target) { if (!closing) { element = target; makeSettings(); $related = $(element); index = 0; if (settings.rel !== 'nofollow') { $related = $('.' + boxElement).filter(function () { var data = $.data(this, colorbox), relRelated; if (data) { relRelated = $(this).data('rel') || data.rel || this.rel; } return (relRelated === settings.rel); }); index = $related.index(element); // Check direct calls to Colorbox. if (index === -1) { $related = $related.add(element); index = $related.length - 1; } } $overlay.css({ opacity: parseFloat(settings.opacity), cursor: settings.overlayClose ? "pointer" : "auto", visibility: 'visible' }).show(); if (className) { $box.add($overlay).removeClass(className); } if (settings.className) { $box.add($overlay).addClass(settings.className); } className = settings.className; $close.html(settings.close).show(); if (!open) { open = active = true; // Prevents the page-change action from queuing up if the visitor holds down the left or right keys. // Show colorbox so the sizes can be calculated in older versions of jQuery $box.css({visibility:'hidden', display:'block'}); $loaded = $tag(div, 'LoadedContent', 'width:0; height:0; overflow:hidden').appendTo($content); // Cache values needed for size calculations interfaceHeight = $topBorder.height() + $bottomBorder.height() + $content.outerHeight(true) - $content.height(); interfaceWidth = $leftBorder.width() + $rightBorder.width() + $content.outerWidth(true) - $content.width(); loadedHeight = $loaded.outerHeight(true); loadedWidth = $loaded.outerWidth(true); // Opens inital empty Colorbox prior to content being loaded. settings.w = setSize(settings.initialWidth, 'x'); settings.h = setSize(settings.initialHeight, 'y'); publicMethod.position(); slideshow(); trigger(event_open, settings.onOpen); $groupControls.add($title).hide(); $box.focus(); // Confine focus to the modal // Uses event capturing that is not supported in IE8- if (document.addEventListener) { document.addEventListener('focus', trapFocus, true); $events.one(event_closed, function () { document.removeEventListener('focus', trapFocus, true); }); } // Return focus on closing if (settings.returnFocus) { $events.one(event_closed, function () { $(element).focus(); }); } } load(); } } // Colorbox's markup needs to be added to the DOM prior to being called // so that the browser will go ahead and load the CSS background images. function appendHTML() { if (!$box && document.body) { init = false; $window = $(window); $box = $tag(div).attr({ id: colorbox, 'class': $.support.opacity === false ? prefix + 'IE' : '', // class for optional IE8 & lower targeted CSS. role: 'dialog', tabindex: '-1' }).hide(); $overlay = $tag(div, "Overlay").hide(); $loadingOverlay = $tag(div, "LoadingOverlay").add($tag(div, "LoadingGraphic")); $wrap = $tag(div, "Wrapper"); $content = $tag(div, "Content").append( $title = $tag(div, "Title"), $current = $tag(div, "Current"), $prev = $tag('button', "Previous"), $next = $tag('button', "Next"), $slideshow = $tag('button', "Slideshow"), $loadingOverlay, $close = $tag('button', "Close") ); $wrap.append( // The 3x3 Grid that makes up Colorbox $tag(div).append( $tag(div, "TopLeft"), $topBorder = $tag(div, "TopCenter"), $tag(div, "TopRight") ), $tag(div, false, 'clear:left').append( $leftBorder = $tag(div, "MiddleLeft"), $content, $rightBorder = $tag(div, "MiddleRight") ), $tag(div, false, 'clear:left').append( $tag(div, "BottomLeft"), $bottomBorder = $tag(div, "BottomCenter"), $tag(div, "BottomRight") ) ).find('div div').css({'float': 'left'}); $loadingBay = $tag(div, false, 'position:absolute; width:9999px; visibility:hidden; display:none'); $groupControls = $next.add($prev).add($current).add($slideshow); $(document.body).append($overlay, $box.append($wrap, $loadingBay)); } } // Add Colorbox's event bindings function addBindings() { function clickHandler(e) { // ignore non-left-mouse-clicks and clicks modified with ctrl / command, shift, or alt. // See: http://jacklmoore.com/notes/click-events/ if (!(e.which > 1 || e.shiftKey || e.altKey || e.metaKey || e.control)) { e.preventDefault(); launch(this); } } if ($box) { if (!init) { init = true; // Anonymous functions here keep the public method from being cached, thereby allowing them to be redefined on the fly. $next.click(function () { publicMethod.next(); }); $prev.click(function () { publicMethod.prev(); }); $close.click(function () { publicMethod.close(); }); $overlay.click(function () { if (settings.overlayClose) { publicMethod.close(); } }); // Key Bindings $(document).bind('keydown.' + prefix, function (e) { var key = e.keyCode; if (open && settings.escKey && key === 27) { e.preventDefault(); publicMethod.close(); } if (open && settings.arrowKey && $related[1] && !e.altKey) { if (key === 37) { e.preventDefault(); $prev.click(); } else if (key === 39) { e.preventDefault(); $next.click(); } } }); if ($.isFunction($.fn.on)) { // For jQuery 1.7+ $(document).on('click.'+prefix, '.'+boxElement, clickHandler); } else { // For jQuery 1.3.x -> 1.6.x // This code is never reached in jQuery 1.9, so do not contact me about 'live' being removed. // This is not here for jQuery 1.9, it's here for legacy users. $('.'+boxElement).live('click.'+prefix, clickHandler); } } return true; } return false; } // Don't do anything if Colorbox already exists. if ($.colorbox) { return; } // Append the HTML when the DOM loads $(appendHTML); // **************** // PUBLIC FUNCTIONS // Usage format: $.colorbox.close(); // Usage from within an iframe: parent.jQuery.colorbox.close(); // **************** publicMethod = $.fn[colorbox] = $[colorbox] = function (options, callback) { var $this = this; options = options || {}; appendHTML(); if (addBindings()) { if ($.isFunction($this)) { // assume a call to $.colorbox $this = $('<a/>'); options.open = true; } else if (!$this[0]) { // colorbox being applied to empty collection return $this; } if (callback) { options.onComplete = callback; } $this.each(function () { $.data(this, colorbox, $.extend({}, $.data(this, colorbox) || defaults, options)); }).addClass(boxElement); if (($.isFunction(options.open) && options.open.call($this)) || options.open) { launch($this[0]); } } return $this; }; publicMethod.position = function (speed, loadedCallback) { var css, top = 0, left = 0, offset = $box.offset(), scrollTop, scrollLeft; $window.unbind('resize.' + prefix); // remove the modal so that it doesn't influence the document width/height $box.css({top: -9e4, left: -9e4}); scrollTop = $window.scrollTop(); scrollLeft = $window.scrollLeft(); if (settings.fixed) { offset.top -= scrollTop; offset.left -= scrollLeft; $box.css({position: 'fixed'}); } else { top = scrollTop; left = scrollLeft; $box.css({position: 'absolute'}); } // keeps the top and left positions within the browser's viewport. if (settings.right !== false) { left += Math.max($window.width() - settings.w - loadedWidth - interfaceWidth - setSize(settings.right, 'x'), 0); } else if (settings.left !== false) { left += setSize(settings.left, 'x'); } else { left += Math.round(Math.max($window.width() - settings.w - loadedWidth - interfaceWidth, 0) / 2); } if (settings.bottom !== false) { top += Math.max(winheight() - settings.h - loadedHeight - interfaceHeight - setSize(settings.bottom, 'y'), 0); } else if (settings.top !== false) { top += setSize(settings.top, 'y'); } else { top += Math.round(Math.max(winheight() - settings.h - loadedHeight - interfaceHeight, 0) / 2); } $box.css({top: offset.top, left: offset.left, visibility:'visible'}); // setting the speed to 0 to reduce the delay between same-sized content. speed = ($box.width() === settings.w + loadedWidth && $box.height() === settings.h + loadedHeight) ? 0 : speed || 0; // this gives the wrapper plenty of breathing room so it's floated contents can move around smoothly, // but it has to be shrank down around the size of div#colorbox when it's done. If not, // it can invoke an obscure IE bug when using iframes. $wrap[0].style.width = $wrap[0].style.height = "9999px"; function modalDimensions(that) { $topBorder[0].style.width = $bottomBorder[0].style.width = $content[0].style.width = (parseInt(that.style.width,10) - interfaceWidth)+'px'; $content[0].style.height = $leftBorder[0].style.height = $rightBorder[0].style.height = (parseInt(that.style.height,10) - interfaceHeight)+'px'; } css = {width: settings.w + loadedWidth + interfaceWidth, height: settings.h + loadedHeight + interfaceHeight, top: top, left: left}; if(speed===0){ // temporary workaround to side-step jQuery-UI 1.8 bug (http://bugs.jquery.com/ticket/12273) $box.css(css); } $box.dequeue().animate(css, { duration: speed, complete: function () { modalDimensions(this); active = false; // shrink the wrapper down to exactly the size of colorbox to avoid a bug in IE's iframe implementation. $wrap[0].style.width = (settings.w + loadedWidth + interfaceWidth) + "px"; $wrap[0].style.height = (settings.h + loadedHeight + interfaceHeight) + "px"; if (settings.reposition) { setTimeout(function () { // small delay before binding onresize due to an IE8 bug. $window.bind('resize.' + prefix, publicMethod.position); }, 1); } if (loadedCallback) { loadedCallback(); } }, step: function () { modalDimensions(this); } }); }; publicMethod.resize = function (options) { if (open) { options = options || {}; if (options.width) { settings.w = setSize(options.width, 'x') - loadedWidth - interfaceWidth; } if (options.innerWidth) { settings.w = setSize(options.innerWidth, 'x'); } $loaded.css({width: settings.w}); if (options.height) { settings.h = setSize(options.height, 'y') - loadedHeight - interfaceHeight; } if (options.innerHeight) { settings.h = setSize(options.innerHeight, 'y'); } if (!options.innerHeight && !options.height) { $loaded.css({height: "auto"}); settings.h = $loaded.height(); } $loaded.css({height: settings.h}); publicMethod.position(settings.transition === "none" ? 0 : settings.speed); } }; publicMethod.prep = function (object) { if (!open) { return; } var callback, speed = settings.transition === "none" ? 0 : settings.speed; $loaded.empty().remove(); // Using empty first may prevent some IE7 issues. $loaded = $tag(div, 'LoadedContent').append(object); function getWidth() { settings.w = settings.w || $loaded.width(); settings.w = settings.mw && settings.mw < settings.w ? settings.mw : settings.w; return settings.w; } function getHeight() { settings.h = settings.h || $loaded.height(); settings.h = settings.mh && settings.mh < settings.h ? settings.mh : settings.h; return settings.h; } $loaded.hide() .appendTo($loadingBay.show())// content has to be appended to the DOM for accurate size calculations. .css({width: getWidth(), overflow: settings.scrolling ? 'auto' : 'hidden'}) .css({height: getHeight()})// sets the height independently from the width in case the new width influences the value of height. .prependTo($content); $loadingBay.hide(); // floating the IMG removes the bottom line-height and fixed a problem where IE miscalculates the width of the parent element as 100% of the document width. $(photo).css({'float': 'none'}); callback = function () { var total = $related.length, iframe, frameBorder = 'frameBorder', allowTransparency = 'allowTransparency', complete; if (!open) { return; } function removeFilter() { // Needed for IE7 & IE8 in versions of jQuery prior to 1.7.2 if ($.support.opacity === false) { $box[0].style.removeAttribute('filter'); } } complete = function () { clearTimeout(loadingTimer); $loadingOverlay.hide(); trigger(event_complete, settings.onComplete); }; $title.html(settings.title).add($loaded).show(); if (total > 1) { // handle grouping if (typeof settings.current === "string") { $current.html(settings.current.replace('{current}', index + 1).replace('{total}', total)).show(); } $next[(settings.loop || index < total - 1) ? "show" : "hide"]().html(settings.next); $prev[(settings.loop || index) ? "show" : "hide"]().html(settings.previous); if (settings.slideshow) { $slideshow.show(); } // Preloads images within a rel group if (settings.preloading) { $.each([getIndex(-1), getIndex(1)], function(){ var src, img, i = $related[this], data = $.data(i, colorbox); if (data && data.href) { src = data.href; if ($.isFunction(src)) { src = src.call(i); } } else { src = $(i).attr('href'); } if (src && isImage(data, src)) { src = retinaUrl(data, src); img = new Image(); img.src = src; } }); } } else { $groupControls.hide(); } if (settings.iframe) { iframe = $tag('iframe')[0]; if (frameBorder in iframe) { iframe[frameBorder] = 0; } if (allowTransparency in iframe) { iframe[allowTransparency] = "true"; } if (!settings.scrolling) { iframe.scrolling = "no"; } $(iframe) .attr({ src: settings.href, name: (new Date()).getTime(), // give the iframe a unique name to prevent caching 'class': prefix + 'Iframe', allowFullScreen : true, // allow HTML5 video to go fullscreen webkitAllowFullScreen : true, mozallowfullscreen : true }) .one('load', complete) .appendTo($loaded); $events.one(event_purge, function () { iframe.src = "//about:blank"; }); if (settings.fastIframe) { $(iframe).trigger('load'); } } else { complete(); } if (settings.transition === 'fade') { $box.fadeTo(speed, 1, removeFilter); } else { removeFilter(); } }; if (settings.transition === 'fade') { $box.fadeTo(speed, 0, function () { publicMethod.position(0, callback); }); } else { publicMethod.position(speed, callback); } }; function load () { var href, setResize, prep = publicMethod.prep, $inline, request = ++requests; active = true; photo = false; element = $related[index]; makeSettings(); trigger(event_purge); trigger(event_load, settings.onLoad); settings.h = settings.height ? setSize(settings.height, 'y') - loadedHeight - interfaceHeight : settings.innerHeight && setSize(settings.innerHeight, 'y'); settings.w = settings.width ? setSize(settings.width, 'x') - loadedWidth - interfaceWidth : settings.innerWidth && setSize(settings.innerWidth, 'x'); // Sets the minimum dimensions for use in image scaling settings.mw = settings.w; settings.mh = settings.h; // Re-evaluate the minimum width and height based on maxWidth and maxHeight values. // If the width or height exceed the maxWidth or maxHeight, use the maximum values instead. if (settings.maxWidth) { settings.mw = setSize(settings.maxWidth, 'x') - loadedWidth - interfaceWidth; settings.mw = settings.w && settings.w < settings.mw ? settings.w : settings.mw; } if (settings.maxHeight) { settings.mh = setSize(settings.maxHeight, 'y') - loadedHeight - interfaceHeight; settings.mh = settings.h && settings.h < settings.mh ? settings.h : settings.mh; } href = settings.href; loadingTimer = setTimeout(function () { $loadingOverlay.show(); }, 100); if (settings.inline) { // Inserts an empty placeholder where inline content is being pulled from. // An event is bound to put inline content back when Colorbox closes or loads new content. $inline = $tag(div).hide().insertBefore($(href)[0]); $events.one(event_purge, function () { $inline.replaceWith($loaded.children()); }); prep($(href)); } else if (settings.iframe) { // IFrame element won't be added to the DOM until it is ready to be displayed, // to avoid problems with DOM-ready JS that might be trying to run in that iframe. prep(" "); } else if (settings.html) { prep(settings.html); } else if (isImage(settings, href)) { href = retinaUrl(settings, href); $(photo = new Image()) .addClass(prefix + 'Photo') .bind('error',function () { settings.title = false; prep($tag(div, 'Error').html(settings.imgError)); }) .one('load', function () { var percent; if (request !== requests) { return; } if (settings.retinaImage && window.devicePixelRatio > 1) { photo.height = photo.height / window.devicePixelRatio; photo.width = photo.width / window.devicePixelRatio; } if (settings.scalePhotos) { setResize = function () { photo.height -= photo.height * percent; photo.width -= photo.width * percent; }; if (settings.mw && photo.width > settings.mw) { percent = (photo.width - settings.mw) / photo.width; setResize(); } if (settings.mh && photo.height > settings.mh) { percent = (photo.height - settings.mh) / photo.height; setResize(); } } if (settings.h) { photo.style.marginTop = Math.max(settings.mh - photo.height, 0) / 2 + 'px'; } if ($related[1] && (settings.loop || $related[index + 1])) { photo.style.cursor = 'pointer'; photo.onclick = function () { publicMethod.next(); }; } setTimeout(function () { // A pause because Chrome will sometimes report a 0 by 0 size otherwise. prep(photo); }, 1); }); setTimeout(function () { // A pause because Opera 10.6+ will sometimes not run the onload function otherwise. photo.src = href; }, 1); } else if (href) { $loadingBay.load(href, settings.data, function (data, status) { if (request === requests) { prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents()); } }); } } // Navigates to the next page/image in a set. publicMethod.next = function () { if (!active && $related[1] && (settings.loop || $related[index + 1])) { index = getIndex(1); launch($related[index]); } }; publicMethod.prev = function () { if (!active && $related[1] && (settings.loop || index)) { index = getIndex(-1); launch($related[index]); } }; // Note: to use this within an iframe use the following format: parent.jQuery.colorbox.close(); publicMethod.close = function () { if (open && !closing) { closing = true; open = false; trigger(event_cleanup, settings.onCleanup); $window.unbind('.' + prefix); $overlay.fadeTo(200, 0); $box.stop().fadeTo(300, 0, function () { $box.add($overlay).css({'opacity': 1, cursor: 'auto'}).hide(); trigger(event_purge); $loaded.empty().remove(); // Using empty first may prevent some IE7 issues. setTimeout(function () { closing = false; trigger(event_closed, settings.onClosed); }, 1); }); } }; // Removes changes Colorbox made to the document, but does not remove the plugin. publicMethod.remove = function () { if (!$box) { return; } $box.stop(); $.colorbox.close(); $box.stop().remove(); $overlay.remove(); closing = false; $box = null; $('.' + boxElement) .removeData(colorbox) .removeClass(boxElement); $(document).unbind('click.'+prefix); }; // A method for fetching the current element Colorbox is referencing. // returns a jQuery object. publicMethod.element = function () { return $(element); }; publicMethod.settings = defaults; }(jQuery, document, window));
jdages/AndrewsHouse
src/Orchard.Web/Modules/Orchard.jQuery/Scripts/jquery.colorbox.js
JavaScript
bsd-3-clause
28,161
/** * rcmuserAdminUsersApp.rcmuserAdminUsers */ angular.module('rcmuserAdminUsersApp').controller( 'rcmuserAdminUsers', [ '$window', '$scope', '$log', '$uibModal', 'RcmUserResult', 'RcmResults', 'rcmUserUserService', function ( $window, $scope, $log, $uibModal, RcmUserResult, RcmResults, rcmUserUserService ) { var self = this; var userServiceEventManager = rcmUserUserService.getEventManager(); $scope.loading = true; userServiceEventManager.on( 'RcmUserHttp.loading', function (loading) { $scope.loading = loading; } ); $scope.userQuery = ''; $scope.availableStates = [ 'enabled', 'disabled' ]; // User $scope.showMessages = false; var onError = function (data) { $window.alert('An error occurred'); console.error(data); }; var onGetUsersSuccess = function (data) { $scope.users = data.data; $scope.messages = data.messages; }; rcmUserUserService.getUsers( onGetUsersSuccess, onError ); var onGetRolesSuccess = function (data) { $scope.roles = data.data; $scope.messages = data.messages; }; // User Roles rcmUserUserService.getRoles( onGetRolesSuccess, onError ); var onValidUserStatesSuccess = function (data, status) { $scope.availableStates = data.data; }; // valid user states rcmUserUserService.getValidUserStates( onValidUserStatesSuccess ); $scope.rolePropertyId = rcmUserUserService.getPropertyRoleId(); $scope.oneAtATime = false; $scope.addUser = function () { var user = { username: '', password: null, state: 'disabled', email: '', name: '', properties: {}, isNew: true }; user.properties[$scope.rolePropertyId] = []; $scope.users.unshift(user); // clear filter $scope.userQuery = ''; } } ] );
rodmcnew/Rcm
user-ui/public/admin-users-app/rcmuser-admin-users-controller.js
JavaScript
isc
2,694
(function(w){function D(c,b,f,k){if(b.points.errorbars){c=[{x:!0,number:!0,required:!0},{y:!0,number:!0,required:!0}];f=b.points.errorbars;if("x"==f||"xy"==f)b.points.xerr.asymmetric&&c.push({x:!0,number:!0,required:!0}),c.push({x:!0,number:!0,required:!0});if("y"==f||"xy"==f)b.points.yerr.asymmetric&&c.push({y:!0,number:!0,required:!0}),c.push({y:!0,number:!0,required:!0});k.format=c}}function A(c,b,f,k,e,u,h,B,a,C,n){k+=C;e+=C;u+=C;"x"==b.err?(e>f+a?v(c,[[e,k],[Math.max(f+a,n[0]),k]]):h=!1,u<f- a?v(c,[[Math.min(f-a,n[1]),k],[u,k]]):B=!1):(e<k-a?v(c,[[f,e],[f,Math.min(k-a,n[0])]]):h=!1,u>k+a?v(c,[[f,Math.max(k+a,n[1])],[f,u]]):B=!1);a=null!=b.radius?b.radius:a;h&&("-"==b.upperCap?"x"==b.err?v(c,[[e,k-a],[e,k+a]]):v(c,[[f-a,e],[f+a,e]]):w.isFunction(b.upperCap)&&("x"==b.err?b.upperCap(c,e,k,a):b.upperCap(c,f,e,a)));B&&("-"==b.lowerCap?"x"==b.err?v(c,[[u,k-a],[u,k+a]]):v(c,[[f-a,u],[f+a,u]]):w.isFunction(b.lowerCap)&&("x"==b.err?b.lowerCap(c,u,k,a):b.lowerCap(c,f,u,a)))}function v(c,b){c.beginPath(); c.moveTo(b[0][0],b[0][1]);for(var f=1;f<b.length;f++)c.lineTo(b[f][0],b[f][1]);c.stroke()}function E(c,b){var f=c.getPlotOffset();b.save();b.translate(f.left,f.top);w.each(c.getData(),function(c,e){if(e.points.errorbars&&(e.points.xerr.show||e.points.yerr.show)){c=e.datapoints.points;var f=e.datapoints.pointsize,h=[e.xaxis,e.yaxis],k=e.points.radius,a=[e.points.xerr,e.points.yerr],v=!1;if(h[0].p2c(h[0].max)<h[0].p2c(h[0].min)){v=!0;var n=a[0].lowerCap;a[0].lowerCap=a[0].upperCap;a[0].upperCap=n}var w= !1;h[1].p2c(h[1].min)<h[1].p2c(h[1].max)&&(w=!0,n=a[1].lowerCap,a[1].lowerCap=a[1].upperCap,a[1].upperCap=n);for(var p=0;p<e.datapoints.points.length;p+=f){var d=e.datapoints.points,q=null,r=null,l=null,m=null;var x=e.points.xerr;var g=e.points.yerr,t=e.points.errorbars;"x"==t||"xy"==t?x.asymmetric?(q=d[p+2],r=d[p+3],"xy"==t&&(g.asymmetric?(l=d[p+4],m=d[p+5]):l=d[p+4])):(q=d[p+2],"xy"==t&&(g.asymmetric?(l=d[p+3],m=d[p+4]):l=d[p+3])):"y"==t&&(g.asymmetric?(l=d[p+2],m=d[p+3]):l=d[p+2]);null==r&&(r= q);null==m&&(m=l);d=[q,r,l,m];x.show||(d[0]=null,d[1]=null);g.show||(d[2]=null,d[3]=null);x=d;for(g=0;g<a.length;g++)if(d=[h[g].min,h[g].max],x[g*a.length]&&(q=c[p],r=c[p+1],l=[q,r][g]+x[g*a.length+1],m=[q,r][g]-x[g*a.length],"x"!=a[g].err||!(r>h[1].max||r<h[1].min||l<h[0].min||m>h[0].max)))if("y"!=a[g].err||!(q>h[0].max||q<h[0].min||l<h[1].min||m>h[1].max)){var y=t=!0;l>d[1]&&(t=!1,l=d[1]);m<d[0]&&(y=!1,m=d[0]);if("x"==a[g].err&&v||"y"==a[g].err&&w)n=m,m=l,l=n,n=y,y=t,t=n,n=d[0],d[0]=d[1],d[1]=n; q=h[0].p2c(q);r=h[1].p2c(r);l=h[g].p2c(l);m=h[g].p2c(m);d[0]=h[g].p2c(d[0]);d[1]=h[g].p2c(d[1]);n=a[g].lineWidth?a[g].lineWidth:e.points.lineWidth;var z=null!=e.points.shadowSize?e.points.shadowSize:e.shadowSize;0<n&&0<z&&(z/=2,b.lineWidth=z,b.strokeStyle="rgba(0,0,0,0.1)",A(b,a[g],q,r,l,m,t,y,k,z+z/2,d),b.strokeStyle="rgba(0,0,0,0.2)",A(b,a[g],q,r,l,m,t,y,k,z/2,d));b.strokeStyle=a[g].color?a[g].color:e.color;b.lineWidth=n;A(b,a[g],q,r,l,m,t,y,k,0,d)}}}});b.restore()}w.plot.plugins.push({init:function(c){c.hooks.processRawData.push(D); c.hooks.draw.push(E)},options:{series:{points:{errorbars:null,xerr:{err:"x",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null},yerr:{err:"y",show:null,asymmetric:null,upperCap:null,lowerCap:null,color:null,radius:null}}}},name:"errorbars",version:"1.0"})})(jQuery);
teuben/masc
www/js/lib/js9-3.5/js/jquery.flot.errorbars.min.js
JavaScript
mit
3,362
(function () { 'use strict'; function foo () { return embiggen( 6, 7 ); } /** * Embiggens a number * @param {number} num - the number to embiggen * @param {number} factor - the factor to embiggen it by * @returns {number} */ function embiggen ( num, factor ) { return num * factor; } alert( foo() ); }());
corneliusweig/rollup
test/form/samples/block-comments/_expected/iife.js
JavaScript
mit
331
require('./options-styles'); var CodeMirror = require('codemirror'); require('codemirror/addon/fold/foldcode'); require('codemirror/addon/fold/foldgutter'); require('codemirror/addon/fold/brace-fold'); require('codemirror/mode/javascript/javascript'); require('codemirror/addon/hint/show-hint'); require('codemirror/addon/hint/css-hint'); require('codemirror/mode/css/css'); var sweetAlert = require('sweetalert'); var Storage = require('./json-viewer/storage'); var renderThemeList = require('./json-viewer/options/render-theme-list'); var renderAddons = require('./json-viewer/options/render-addons'); var renderStructure = require('./json-viewer/options/render-structure'); var renderStyle = require('./json-viewer/options/render-style'); var bindSaveButton = require('./json-viewer/options/bind-save-button'); var bindResetButton = require('./json-viewer/options/bind-reset-button'); function isValidJSON(pseudoJSON) { try { JSON.parse(pseudoJSON); return true; } catch(e) { return false; } } function renderVersion() { var version = process.env.VERSION; var versionLink = document.getElementsByClassName('version')[0]; versionLink.innerHTML = version; versionLink.href = "https://github.com/tulios/json-viewer/tree/" + version; } function onLoaded() { var currentOptions = Storage.load(); renderVersion(); renderThemeList(CodeMirror, currentOptions.theme); var addonsEditor = renderAddons(CodeMirror, currentOptions.addons); var structureEditor = renderStructure(CodeMirror, currentOptions.structure); var styleEditor = renderStyle(CodeMirror, currentOptions.style); bindResetButton(); bindSaveButton([addonsEditor, structureEditor, styleEditor], function(options) { if (!isValidJSON(options.addons)) { sweetAlert("Ops!", "\"Add-ons\" isn't a valid JSON", "error"); } else if (!isValidJSON(options.structure)) { sweetAlert("Ops!", "\"Structure\" isn't a valid JSON", "error"); } else { Storage.save(options); sweetAlert("Success", "Options saved!", "success"); } }); } document.addEventListener("DOMContentLoaded", onLoaded, false);
Randykerley/me
extension/src/options.js
JavaScript
mit
2,132
/** * Theme: Simple Admin Template * Author: Coderthemes * VectorMap */ ! function($) { "use strict"; var VectorMap = function() { }; VectorMap.prototype.init = function() { //various examples $('#world-map-markers').vectorMap({ map : 'world_mill_en', scaleColors : ['#4bd396', '#4bd396'], normalizeFunction : 'polynomial', hoverOpacity : 0.7, hoverColor : false, regionStyle : { initial : { fill : '#ddd' } }, markerStyle: { initial: { r: 9, 'fill': '#4bd396', 'fill-opacity': 0.9, 'stroke': '#fff', 'stroke-width' : 7, 'stroke-opacity': 0.4 }, hover: { 'stroke': '#fff', 'fill-opacity': 1, 'stroke-width': 1.5 } }, backgroundColor : 'transparent', markers : [{ latLng : [41.90, 12.45], name : 'Vatican City' }, { latLng : [43.73, 7.41], name : 'Monaco' }, { latLng : [-0.52, 166.93], name : 'Nauru' }, { latLng : [-8.51, 179.21], name : 'Tuvalu' }, { latLng : [43.93, 12.46], name : 'San Marino' }, { latLng : [47.14, 9.52], name : 'Liechtenstein' }, { latLng : [7.11, 171.06], name : 'Marshall Islands' }, { latLng : [17.3, -62.73], name : 'Saint Kitts and Nevis' }, { latLng : [3.2, 73.22], name : 'Maldives' }, { latLng : [35.88, 14.5], name : 'Malta' }, { latLng : [12.05, -61.75], name : 'Grenada' }, { latLng : [13.16, -61.23], name : 'Saint Vincent and the Grenadines' }, { latLng : [13.16, -59.55], name : 'Barbados' }, { latLng : [17.11, -61.85], name : 'Antigua and Barbuda' }, { latLng : [-4.61, 55.45], name : 'Seychelles' }, { latLng : [7.35, 134.46], name : 'Palau' }, { latLng : [42.5, 1.51], name : 'Andorra' }, { latLng : [14.01, -60.98], name : 'Saint Lucia' }, { latLng : [6.91, 158.18], name : 'Federated States of Micronesia' }, { latLng : [1.3, 103.8], name : 'Singapore' }, { latLng : [1.46, 173.03], name : 'Kiribati' }, { latLng : [-21.13, -175.2], name : 'Tonga' }, { latLng : [15.3, -61.38], name : 'Dominica' }, { latLng : [-20.2, 57.5], name : 'Mauritius' }, { latLng : [26.02, 50.55], name : 'Bahrain' }, { latLng : [0.33, 6.73], name : 'São Tomé and Príncipe' }] }); $('#usa').vectorMap({ map : 'us_aea_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#india').vectorMap({ map : 'in_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#uk').vectorMap({ map : 'uk_mill_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#chicago').vectorMap({ map : 'us-il-chicago_mill_en', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#australia').vectorMap({ map : 'au_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#canada').vectorMap({ map : 'ca_lcc', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#germany').vectorMap({ map : 'de_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); $('#asia').vectorMap({ map : 'asia_mill', backgroundColor : 'transparent', regionStyle : { initial : { fill : '#ddd' } } }); }, //init $.VectorMap = new VectorMap, $.VectorMap.Constructor = VectorMap }(window.jQuery), //initializing function($) { "use strict"; $.VectorMap.init() }(window.jQuery);
Fadhilamadan/Reminder
public/assets_multi/pages/jquery.jvectormap.init.js
JavaScript
mit
4,052
/*eslint-env node */ module.exports = function (grunt) { grunt.initConfig({ "bolt-init": { "plugin": { config_dir: "config/bolt" } }, "bolt-build": { "plugin": { config_js: "config/bolt/prod.js", output_dir: "scratch", main: "tinymce.wordcount.Plugin", filename: "plugin", generate_inline: true, minimise_module_names: true, files: { src: ["src/main/js/tinymce/wordcount/Plugin.js"] } } }, copy: { "plugin": { files: [ { src: "scratch/inline/plugin.raw.js", dest: "plugin.js" } ] } }, eslint: { options: { config: "../../../../.eslintrc" }, src: [ "src" ] }, uglify: { options: { beautify: { ascii_only: true, screw_ie8: false }, compress: { screw_ie8: false } }, "plugin": { files: [ { src: "scratch/inline/plugin.js", dest: "plugin.min.js" } ] } } }); grunt.task.loadTasks("../../../../node_modules/@ephox/bolt/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-contrib-copy/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-contrib-uglify/tasks"); grunt.task.loadTasks("../../../../node_modules/grunt-eslint/tasks"); grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify"]); };
oncebuilder/OnceBuilder
libs/tinymce/js/tinymce/plugins/wordcount/Gruntfile.js
JavaScript
mit
1,355
'use strict'; Editor.polymerElement({ });
jwu/ui-kit
src/widget/toolbar/toolbar.js
JavaScript
mit
44