PageRenderTime 36ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 0ms

/files/zeroclipboard/2.1.3/ZeroClipboard.js

https://gitlab.com/Mirros/jsdelivr
JavaScript | 1537 lines | 1162 code | 11 blank | 364 comment | 435 complexity | 821f69f8630266f6e062a1b6f9f5f6a9 MD5 | raw file
  1. /*!
  2. * ZeroClipboard
  3. * The ZeroClipboard library provides an easy way to copy text to the clipboard using an invisible Adobe Flash movie and a JavaScript interface.
  4. * Copyright (c) 2014 Jon Rohan, James M. Greene
  5. * Licensed MIT
  6. * http://zeroclipboard.org/
  7. * v2.1.3
  8. */
  9. (function(window, undefined) {
  10. "use strict";
  11. /**
  12. * Store references to critically important global functions that may be
  13. * overridden on certain web pages.
  14. */
  15. var _window = window, _document = _window.document, _navigator = _window.navigator, _setTimeout = _window.setTimeout, _encodeURIComponent = _window.encodeURIComponent, _ActiveXObject = _window.ActiveXObject, _Error = _window.Error, _parseInt = _window.Number.parseInt || _window.parseInt, _parseFloat = _window.Number.parseFloat || _window.parseFloat, _isNaN = _window.Number.isNaN || _window.isNaN, _round = _window.Math.round, _now = _window.Date.now, _keys = _window.Object.keys, _defineProperty = _window.Object.defineProperty, _hasOwn = _window.Object.prototype.hasOwnProperty, _slice = _window.Array.prototype.slice;
  16. /**
  17. * Convert an `arguments` object into an Array.
  18. *
  19. * @returns The arguments as an Array
  20. * @private
  21. */
  22. var _args = function(argumentsObj) {
  23. return _slice.call(argumentsObj, 0);
  24. };
  25. /**
  26. * Shallow-copy the owned, enumerable properties of one object over to another, similar to jQuery's `$.extend`.
  27. *
  28. * @returns The target object, augmented
  29. * @private
  30. */
  31. var _extend = function() {
  32. var i, len, arg, prop, src, copy, args = _args(arguments), target = args[0] || {};
  33. for (i = 1, len = args.length; i < len; i++) {
  34. if ((arg = args[i]) != null) {
  35. for (prop in arg) {
  36. if (_hasOwn.call(arg, prop)) {
  37. src = target[prop];
  38. copy = arg[prop];
  39. if (target !== copy && copy !== undefined) {
  40. target[prop] = copy;
  41. }
  42. }
  43. }
  44. }
  45. }
  46. return target;
  47. };
  48. /**
  49. * Return a deep copy of the source object or array.
  50. *
  51. * @returns Object or Array
  52. * @private
  53. */
  54. var _deepCopy = function(source) {
  55. var copy, i, len, prop;
  56. if (typeof source !== "object" || source == null) {
  57. copy = source;
  58. } else if (typeof source.length === "number") {
  59. copy = [];
  60. for (i = 0, len = source.length; i < len; i++) {
  61. if (_hasOwn.call(source, i)) {
  62. copy[i] = _deepCopy(source[i]);
  63. }
  64. }
  65. } else {
  66. copy = {};
  67. for (prop in source) {
  68. if (_hasOwn.call(source, prop)) {
  69. copy[prop] = _deepCopy(source[prop]);
  70. }
  71. }
  72. }
  73. return copy;
  74. };
  75. /**
  76. * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to keep.
  77. * The inverse of `_omit`, mostly. The big difference is that these properties do NOT need to be enumerable to
  78. * be kept.
  79. *
  80. * @returns A new filtered object.
  81. * @private
  82. */
  83. var _pick = function(obj, keys) {
  84. var newObj = {};
  85. for (var i = 0, len = keys.length; i < len; i++) {
  86. if (keys[i] in obj) {
  87. newObj[keys[i]] = obj[keys[i]];
  88. }
  89. }
  90. return newObj;
  91. };
  92. /**
  93. * Makes a shallow copy of `obj` (like `_extend`) but filters its properties based on a list of `keys` to omit.
  94. * The inverse of `_pick`.
  95. *
  96. * @returns A new filtered object.
  97. * @private
  98. */
  99. var _omit = function(obj, keys) {
  100. var newObj = {};
  101. for (var prop in obj) {
  102. if (keys.indexOf(prop) === -1) {
  103. newObj[prop] = obj[prop];
  104. }
  105. }
  106. return newObj;
  107. };
  108. /**
  109. * Remove all owned, enumerable properties from an object.
  110. *
  111. * @returns The original object without its owned, enumerable properties.
  112. * @private
  113. */
  114. var _deleteOwnProperties = function(obj) {
  115. if (obj) {
  116. for (var prop in obj) {
  117. if (_hasOwn.call(obj, prop)) {
  118. delete obj[prop];
  119. }
  120. }
  121. }
  122. return obj;
  123. };
  124. /**
  125. * Determine if an element is contained within another element.
  126. *
  127. * @returns Boolean
  128. * @private
  129. */
  130. var _containedBy = function(el, ancestorEl) {
  131. if (el && el.nodeType === 1 && el.ownerDocument && ancestorEl && (ancestorEl.nodeType === 1 && ancestorEl.ownerDocument && ancestorEl.ownerDocument === el.ownerDocument || ancestorEl.nodeType === 9 && !ancestorEl.ownerDocument && ancestorEl === el.ownerDocument)) {
  132. do {
  133. if (el === ancestorEl) {
  134. return true;
  135. }
  136. el = el.parentNode;
  137. } while (el);
  138. }
  139. return false;
  140. };
  141. /**
  142. * Get the URL path's parent directory.
  143. *
  144. * @returns String or `undefined`
  145. * @private
  146. */
  147. var _getDirPathOfUrl = function(url) {
  148. var dir;
  149. if (typeof url === "string" && url) {
  150. dir = url.split("#")[0].split("?")[0];
  151. dir = url.slice(0, url.lastIndexOf("/") + 1);
  152. }
  153. return dir;
  154. };
  155. /**
  156. * Get the current script's URL by throwing an `Error` and analyzing it.
  157. *
  158. * @returns String or `undefined`
  159. * @private
  160. */
  161. var _getCurrentScriptUrlFromErrorStack = function(stack) {
  162. var url, matches;
  163. if (typeof stack === "string" && stack) {
  164. matches = stack.match(/^(?:|[^:@]*@|.+\)@(?=http[s]?|file)|.+?\s+(?: at |@)(?:[^:\(]+ )*[\(]?)((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
  165. if (matches && matches[1]) {
  166. url = matches[1];
  167. } else {
  168. matches = stack.match(/\)@((?:http[s]?|file):\/\/[\/]?.+?\/[^:\)]*?)(?::\d+)(?::\d+)?/);
  169. if (matches && matches[1]) {
  170. url = matches[1];
  171. }
  172. }
  173. }
  174. return url;
  175. };
  176. /**
  177. * Get the current script's URL by throwing an `Error` and analyzing it.
  178. *
  179. * @returns String or `undefined`
  180. * @private
  181. */
  182. var _getCurrentScriptUrlFromError = function() {
  183. var url, err;
  184. try {
  185. throw new _Error();
  186. } catch (e) {
  187. err = e;
  188. }
  189. if (err) {
  190. url = err.sourceURL || err.fileName || _getCurrentScriptUrlFromErrorStack(err.stack);
  191. }
  192. return url;
  193. };
  194. /**
  195. * Get the current script's URL.
  196. *
  197. * @returns String or `undefined`
  198. * @private
  199. */
  200. var _getCurrentScriptUrl = function() {
  201. var jsPath, scripts, i;
  202. if (_document.currentScript && (jsPath = _document.currentScript.src)) {
  203. return jsPath;
  204. }
  205. scripts = _document.getElementsByTagName("script");
  206. if (scripts.length === 1) {
  207. return scripts[0].src || undefined;
  208. }
  209. if ("readyState" in scripts[0]) {
  210. for (i = scripts.length; i--; ) {
  211. if (scripts[i].readyState === "interactive" && (jsPath = scripts[i].src)) {
  212. return jsPath;
  213. }
  214. }
  215. }
  216. if (_document.readyState === "loading" && (jsPath = scripts[scripts.length - 1].src)) {
  217. return jsPath;
  218. }
  219. if (jsPath = _getCurrentScriptUrlFromError()) {
  220. return jsPath;
  221. }
  222. return undefined;
  223. };
  224. /**
  225. * Get the unanimous parent directory of ALL script tags.
  226. * If any script tags are either (a) inline or (b) from differing parent
  227. * directories, this method must return `undefined`.
  228. *
  229. * @returns String or `undefined`
  230. * @private
  231. */
  232. var _getUnanimousScriptParentDir = function() {
  233. var i, jsDir, jsPath, scripts = _document.getElementsByTagName("script");
  234. for (i = scripts.length; i--; ) {
  235. if (!(jsPath = scripts[i].src)) {
  236. jsDir = null;
  237. break;
  238. }
  239. jsPath = _getDirPathOfUrl(jsPath);
  240. if (jsDir == null) {
  241. jsDir = jsPath;
  242. } else if (jsDir !== jsPath) {
  243. jsDir = null;
  244. break;
  245. }
  246. }
  247. return jsDir || undefined;
  248. };
  249. /**
  250. * Get the presumed location of the "ZeroClipboard.swf" file, based on the location
  251. * of the executing JavaScript file (e.g. "ZeroClipboard.js", etc.).
  252. *
  253. * @returns String
  254. * @private
  255. */
  256. var _getDefaultSwfPath = function() {
  257. var jsDir = _getDirPathOfUrl(_getCurrentScriptUrl()) || _getUnanimousScriptParentDir() || "";
  258. return jsDir + "ZeroClipboard.swf";
  259. };
  260. /**
  261. * Keep track of the state of the Flash object.
  262. * @private
  263. */
  264. var _flashState = {
  265. bridge: null,
  266. version: "0.0.0",
  267. pluginType: "unknown",
  268. disabled: null,
  269. outdated: null,
  270. unavailable: null,
  271. deactivated: null,
  272. overdue: null,
  273. ready: null
  274. };
  275. /**
  276. * The minimum Flash Player version required to use ZeroClipboard completely.
  277. * @readonly
  278. * @private
  279. */
  280. var _minimumFlashVersion = "11.0.0";
  281. /**
  282. * Keep track of all event listener registrations.
  283. * @private
  284. */
  285. var _handlers = {};
  286. /**
  287. * Keep track of the currently activated element.
  288. * @private
  289. */
  290. var _currentElement;
  291. /**
  292. * Keep track of data for the pending clipboard transaction.
  293. * @private
  294. */
  295. var _clipData = {};
  296. /**
  297. * Keep track of data formats for the pending clipboard transaction.
  298. * @private
  299. */
  300. var _clipDataFormatMap = null;
  301. /**
  302. * The `message` store for events
  303. * @private
  304. */
  305. var _eventMessages = {
  306. ready: "Flash communication is established",
  307. error: {
  308. "flash-disabled": "Flash is disabled or not installed",
  309. "flash-outdated": "Flash is too outdated to support ZeroClipboard",
  310. "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript",
  311. "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate",
  312. "flash-overdue": "Flash communication was established but NOT within the acceptable time limit"
  313. }
  314. };
  315. /**
  316. * ZeroClipboard configuration defaults for the Core module.
  317. * @private
  318. */
  319. var _globalConfig = {
  320. swfPath: _getDefaultSwfPath(),
  321. trustedDomains: window.location.host ? [ window.location.host ] : [],
  322. cacheBust: true,
  323. forceEnhancedClipboard: false,
  324. flashLoadTimeout: 3e4,
  325. autoActivate: true,
  326. bubbleEvents: true,
  327. containerId: "global-zeroclipboard-html-bridge",
  328. containerClass: "global-zeroclipboard-container",
  329. swfObjectId: "global-zeroclipboard-flash-bridge",
  330. hoverClass: "zeroclipboard-is-hover",
  331. activeClass: "zeroclipboard-is-active",
  332. forceHandCursor: false,
  333. title: null,
  334. zIndex: 999999999
  335. };
  336. /**
  337. * The underlying implementation of `ZeroClipboard.config`.
  338. * @private
  339. */
  340. var _config = function(options) {
  341. if (typeof options === "object" && options !== null) {
  342. for (var prop in options) {
  343. if (_hasOwn.call(options, prop)) {
  344. if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) {
  345. _globalConfig[prop] = options[prop];
  346. } else if (_flashState.bridge == null) {
  347. if (prop === "containerId" || prop === "swfObjectId") {
  348. if (_isValidHtml4Id(options[prop])) {
  349. _globalConfig[prop] = options[prop];
  350. } else {
  351. throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
  352. }
  353. } else {
  354. _globalConfig[prop] = options[prop];
  355. }
  356. }
  357. }
  358. }
  359. }
  360. if (typeof options === "string" && options) {
  361. if (_hasOwn.call(_globalConfig, options)) {
  362. return _globalConfig[options];
  363. }
  364. return;
  365. }
  366. return _deepCopy(_globalConfig);
  367. };
  368. /**
  369. * The underlying implementation of `ZeroClipboard.state`.
  370. * @private
  371. */
  372. var _state = function() {
  373. return {
  374. browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]),
  375. flash: _omit(_flashState, [ "bridge" ]),
  376. zeroclipboard: {
  377. version: ZeroClipboard.version,
  378. config: ZeroClipboard.config()
  379. }
  380. };
  381. };
  382. /**
  383. * The underlying implementation of `ZeroClipboard.isFlashUnusable`.
  384. * @private
  385. */
  386. var _isFlashUnusable = function() {
  387. return !!(_flashState.disabled || _flashState.outdated || _flashState.unavailable || _flashState.deactivated);
  388. };
  389. /**
  390. * The underlying implementation of `ZeroClipboard.on`.
  391. * @private
  392. */
  393. var _on = function(eventType, listener) {
  394. var i, len, events, added = {};
  395. if (typeof eventType === "string" && eventType) {
  396. events = eventType.toLowerCase().split(/\s+/);
  397. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  398. for (i in eventType) {
  399. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  400. ZeroClipboard.on(i, eventType[i]);
  401. }
  402. }
  403. }
  404. if (events && events.length) {
  405. for (i = 0, len = events.length; i < len; i++) {
  406. eventType = events[i].replace(/^on/, "");
  407. added[eventType] = true;
  408. if (!_handlers[eventType]) {
  409. _handlers[eventType] = [];
  410. }
  411. _handlers[eventType].push(listener);
  412. }
  413. if (added.ready && _flashState.ready) {
  414. ZeroClipboard.emit({
  415. type: "ready"
  416. });
  417. }
  418. if (added.error) {
  419. var errorTypes = [ "disabled", "outdated", "unavailable", "deactivated", "overdue" ];
  420. for (i = 0, len = errorTypes.length; i < len; i++) {
  421. if (_flashState[errorTypes[i]] === true) {
  422. ZeroClipboard.emit({
  423. type: "error",
  424. name: "flash-" + errorTypes[i]
  425. });
  426. break;
  427. }
  428. }
  429. }
  430. }
  431. return ZeroClipboard;
  432. };
  433. /**
  434. * The underlying implementation of `ZeroClipboard.off`.
  435. * @private
  436. */
  437. var _off = function(eventType, listener) {
  438. var i, len, foundIndex, events, perEventHandlers;
  439. if (arguments.length === 0) {
  440. events = _keys(_handlers);
  441. } else if (typeof eventType === "string" && eventType) {
  442. events = eventType.split(/\s+/);
  443. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  444. for (i in eventType) {
  445. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  446. ZeroClipboard.off(i, eventType[i]);
  447. }
  448. }
  449. }
  450. if (events && events.length) {
  451. for (i = 0, len = events.length; i < len; i++) {
  452. eventType = events[i].toLowerCase().replace(/^on/, "");
  453. perEventHandlers = _handlers[eventType];
  454. if (perEventHandlers && perEventHandlers.length) {
  455. if (listener) {
  456. foundIndex = perEventHandlers.indexOf(listener);
  457. while (foundIndex !== -1) {
  458. perEventHandlers.splice(foundIndex, 1);
  459. foundIndex = perEventHandlers.indexOf(listener, foundIndex);
  460. }
  461. } else {
  462. perEventHandlers.length = 0;
  463. }
  464. }
  465. }
  466. }
  467. return ZeroClipboard;
  468. };
  469. /**
  470. * The underlying implementation of `ZeroClipboard.handlers`.
  471. * @private
  472. */
  473. var _listeners = function(eventType) {
  474. var copy;
  475. if (typeof eventType === "string" && eventType) {
  476. copy = _deepCopy(_handlers[eventType]) || null;
  477. } else {
  478. copy = _deepCopy(_handlers);
  479. }
  480. return copy;
  481. };
  482. /**
  483. * The underlying implementation of `ZeroClipboard.emit`.
  484. * @private
  485. */
  486. var _emit = function(event) {
  487. var eventCopy, returnVal, tmp;
  488. event = _createEvent(event);
  489. if (!event) {
  490. return;
  491. }
  492. if (_preprocessEvent(event)) {
  493. return;
  494. }
  495. if (event.type === "ready" && _flashState.overdue === true) {
  496. return ZeroClipboard.emit({
  497. type: "error",
  498. name: "flash-overdue"
  499. });
  500. }
  501. eventCopy = _extend({}, event);
  502. _dispatchCallbacks.call(this, eventCopy);
  503. if (event.type === "copy") {
  504. tmp = _mapClipDataToFlash(_clipData);
  505. returnVal = tmp.data;
  506. _clipDataFormatMap = tmp.formatMap;
  507. }
  508. return returnVal;
  509. };
  510. /**
  511. * The underlying implementation of `ZeroClipboard.create`.
  512. * @private
  513. */
  514. var _create = function() {
  515. if (typeof _flashState.ready !== "boolean") {
  516. _flashState.ready = false;
  517. }
  518. if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
  519. var maxWait = _globalConfig.flashLoadTimeout;
  520. if (typeof maxWait === "number" && maxWait >= 0) {
  521. _setTimeout(function() {
  522. if (typeof _flashState.deactivated !== "boolean") {
  523. _flashState.deactivated = true;
  524. }
  525. if (_flashState.deactivated === true) {
  526. ZeroClipboard.emit({
  527. type: "error",
  528. name: "flash-deactivated"
  529. });
  530. }
  531. }, maxWait);
  532. }
  533. _flashState.overdue = false;
  534. _embedSwf();
  535. }
  536. };
  537. /**
  538. * The underlying implementation of `ZeroClipboard.destroy`.
  539. * @private
  540. */
  541. var _destroy = function() {
  542. ZeroClipboard.clearData();
  543. ZeroClipboard.blur();
  544. ZeroClipboard.emit("destroy");
  545. _unembedSwf();
  546. ZeroClipboard.off();
  547. };
  548. /**
  549. * The underlying implementation of `ZeroClipboard.setData`.
  550. * @private
  551. */
  552. var _setData = function(format, data) {
  553. var dataObj;
  554. if (typeof format === "object" && format && typeof data === "undefined") {
  555. dataObj = format;
  556. ZeroClipboard.clearData();
  557. } else if (typeof format === "string" && format) {
  558. dataObj = {};
  559. dataObj[format] = data;
  560. } else {
  561. return;
  562. }
  563. for (var dataFormat in dataObj) {
  564. if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
  565. _clipData[dataFormat] = dataObj[dataFormat];
  566. }
  567. }
  568. };
  569. /**
  570. * The underlying implementation of `ZeroClipboard.clearData`.
  571. * @private
  572. */
  573. var _clearData = function(format) {
  574. if (typeof format === "undefined") {
  575. _deleteOwnProperties(_clipData);
  576. _clipDataFormatMap = null;
  577. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  578. delete _clipData[format];
  579. }
  580. };
  581. /**
  582. * The underlying implementation of `ZeroClipboard.getData`.
  583. * @private
  584. */
  585. var _getData = function(format) {
  586. if (typeof format === "undefined") {
  587. return _deepCopy(_clipData);
  588. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  589. return _clipData[format];
  590. }
  591. };
  592. /**
  593. * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`.
  594. * @private
  595. */
  596. var _focus = function(element) {
  597. if (!(element && element.nodeType === 1)) {
  598. return;
  599. }
  600. if (_currentElement) {
  601. _removeClass(_currentElement, _globalConfig.activeClass);
  602. if (_currentElement !== element) {
  603. _removeClass(_currentElement, _globalConfig.hoverClass);
  604. }
  605. }
  606. _currentElement = element;
  607. _addClass(element, _globalConfig.hoverClass);
  608. var newTitle = element.getAttribute("title") || _globalConfig.title;
  609. if (typeof newTitle === "string" && newTitle) {
  610. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  611. if (htmlBridge) {
  612. htmlBridge.setAttribute("title", newTitle);
  613. }
  614. }
  615. var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
  616. _setHandCursor(useHandCursor);
  617. _reposition();
  618. };
  619. /**
  620. * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`.
  621. * @private
  622. */
  623. var _blur = function() {
  624. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  625. if (htmlBridge) {
  626. htmlBridge.removeAttribute("title");
  627. htmlBridge.style.left = "0px";
  628. htmlBridge.style.top = "-9999px";
  629. htmlBridge.style.width = "1px";
  630. htmlBridge.style.top = "1px";
  631. }
  632. if (_currentElement) {
  633. _removeClass(_currentElement, _globalConfig.hoverClass);
  634. _removeClass(_currentElement, _globalConfig.activeClass);
  635. _currentElement = null;
  636. }
  637. };
  638. /**
  639. * The underlying implementation of `ZeroClipboard.activeElement`.
  640. * @private
  641. */
  642. var _activeElement = function() {
  643. return _currentElement || null;
  644. };
  645. /**
  646. * Check if a value is a valid HTML4 `ID` or `Name` token.
  647. * @private
  648. */
  649. var _isValidHtml4Id = function(id) {
  650. return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id);
  651. };
  652. /**
  653. * Create or update an `event` object, based on the `eventType`.
  654. * @private
  655. */
  656. var _createEvent = function(event) {
  657. var eventType;
  658. if (typeof event === "string" && event) {
  659. eventType = event;
  660. event = {};
  661. } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
  662. eventType = event.type;
  663. }
  664. if (!eventType) {
  665. return;
  666. }
  667. _extend(event, {
  668. type: eventType.toLowerCase(),
  669. target: event.target || _currentElement || null,
  670. relatedTarget: event.relatedTarget || null,
  671. currentTarget: _flashState && _flashState.bridge || null,
  672. timeStamp: event.timeStamp || _now() || null
  673. });
  674. var msg = _eventMessages[event.type];
  675. if (event.type === "error" && event.name && msg) {
  676. msg = msg[event.name];
  677. }
  678. if (msg) {
  679. event.message = msg;
  680. }
  681. if (event.type === "ready") {
  682. _extend(event, {
  683. target: null,
  684. version: _flashState.version
  685. });
  686. }
  687. if (event.type === "error") {
  688. if (/^flash-(disabled|outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
  689. _extend(event, {
  690. target: null,
  691. minimumVersion: _minimumFlashVersion
  692. });
  693. }
  694. if (/^flash-(outdated|unavailable|deactivated|overdue)$/.test(event.name)) {
  695. _extend(event, {
  696. version: _flashState.version
  697. });
  698. }
  699. }
  700. if (event.type === "copy") {
  701. event.clipboardData = {
  702. setData: ZeroClipboard.setData,
  703. clearData: ZeroClipboard.clearData
  704. };
  705. }
  706. if (event.type === "aftercopy") {
  707. event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
  708. }
  709. if (event.target && !event.relatedTarget) {
  710. event.relatedTarget = _getRelatedTarget(event.target);
  711. }
  712. event = _addMouseData(event);
  713. return event;
  714. };
  715. /**
  716. * Get a relatedTarget from the target's `data-clipboard-target` attribute
  717. * @private
  718. */
  719. var _getRelatedTarget = function(targetEl) {
  720. var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
  721. return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
  722. };
  723. /**
  724. * Add element and position data to `MouseEvent` instances
  725. * @private
  726. */
  727. var _addMouseData = function(event) {
  728. if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  729. var srcElement = event.target;
  730. var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
  731. var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
  732. var pos = _getDOMObjectPosition(srcElement);
  733. var screenLeft = _window.screenLeft || _window.screenX || 0;
  734. var screenTop = _window.screenTop || _window.screenY || 0;
  735. var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
  736. var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
  737. var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
  738. var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
  739. var clientX = pageX - scrollLeft;
  740. var clientY = pageY - scrollTop;
  741. var screenX = screenLeft + clientX;
  742. var screenY = screenTop + clientY;
  743. var moveX = typeof event.movementX === "number" ? event.movementX : 0;
  744. var moveY = typeof event.movementY === "number" ? event.movementY : 0;
  745. delete event._stageX;
  746. delete event._stageY;
  747. _extend(event, {
  748. srcElement: srcElement,
  749. fromElement: fromElement,
  750. toElement: toElement,
  751. screenX: screenX,
  752. screenY: screenY,
  753. pageX: pageX,
  754. pageY: pageY,
  755. clientX: clientX,
  756. clientY: clientY,
  757. x: clientX,
  758. y: clientY,
  759. movementX: moveX,
  760. movementY: moveY,
  761. offsetX: 0,
  762. offsetY: 0,
  763. layerX: 0,
  764. layerY: 0
  765. });
  766. }
  767. return event;
  768. };
  769. /**
  770. * Determine if an event's registered handlers should be execute synchronously or asynchronously.
  771. *
  772. * @returns {boolean}
  773. * @private
  774. */
  775. var _shouldPerformAsync = function(event) {
  776. var eventType = event && typeof event.type === "string" && event.type || "";
  777. return !/^(?:(?:before)?copy|destroy)$/.test(eventType);
  778. };
  779. /**
  780. * Control if a callback should be executed asynchronously or not.
  781. *
  782. * @returns `undefined`
  783. * @private
  784. */
  785. var _dispatchCallback = function(func, context, args, async) {
  786. if (async) {
  787. _setTimeout(function() {
  788. func.apply(context, args);
  789. }, 0);
  790. } else {
  791. func.apply(context, args);
  792. }
  793. };
  794. /**
  795. * Handle the actual dispatching of events to client instances.
  796. *
  797. * @returns `undefined`
  798. * @private
  799. */
  800. var _dispatchCallbacks = function(event) {
  801. if (!(typeof event === "object" && event && event.type)) {
  802. return;
  803. }
  804. var async = _shouldPerformAsync(event);
  805. var wildcardTypeHandlers = _handlers["*"] || [];
  806. var specificTypeHandlers = _handlers[event.type] || [];
  807. var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
  808. if (handlers && handlers.length) {
  809. var i, len, func, context, eventCopy, originalContext = this;
  810. for (i = 0, len = handlers.length; i < len; i++) {
  811. func = handlers[i];
  812. context = originalContext;
  813. if (typeof func === "string" && typeof _window[func] === "function") {
  814. func = _window[func];
  815. }
  816. if (typeof func === "object" && func && typeof func.handleEvent === "function") {
  817. context = func;
  818. func = func.handleEvent;
  819. }
  820. if (typeof func === "function") {
  821. eventCopy = _extend({}, event);
  822. _dispatchCallback(func, context, [ eventCopy ], async);
  823. }
  824. }
  825. }
  826. return this;
  827. };
  828. /**
  829. * Preprocess any special behaviors, reactions, or state changes after receiving this event.
  830. * Executes only once per event emitted, NOT once per client.
  831. * @private
  832. */
  833. var _preprocessEvent = function(event) {
  834. var element = event.target || _currentElement || null;
  835. var sourceIsSwf = event._source === "swf";
  836. delete event._source;
  837. var flashErrorNames = [ "flash-disabled", "flash-outdated", "flash-unavailable", "flash-deactivated", "flash-overdue" ];
  838. switch (event.type) {
  839. case "error":
  840. if (flashErrorNames.indexOf(event.name) !== -1) {
  841. _extend(_flashState, {
  842. disabled: event.name === "flash-disabled",
  843. outdated: event.name === "flash-outdated",
  844. unavailable: event.name === "flash-unavailable",
  845. deactivated: event.name === "flash-deactivated",
  846. overdue: event.name === "flash-overdue",
  847. ready: false
  848. });
  849. }
  850. break;
  851. case "ready":
  852. var wasDeactivated = _flashState.deactivated === true;
  853. _extend(_flashState, {
  854. disabled: false,
  855. outdated: false,
  856. unavailable: false,
  857. deactivated: false,
  858. overdue: wasDeactivated,
  859. ready: !wasDeactivated
  860. });
  861. break;
  862. case "copy":
  863. var textContent, htmlContent, targetEl = event.relatedTarget;
  864. if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) {
  865. event.clipboardData.clearData();
  866. event.clipboardData.setData("text/plain", textContent);
  867. if (htmlContent !== textContent) {
  868. event.clipboardData.setData("text/html", htmlContent);
  869. }
  870. } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) {
  871. event.clipboardData.clearData();
  872. event.clipboardData.setData("text/plain", textContent);
  873. }
  874. break;
  875. case "aftercopy":
  876. ZeroClipboard.clearData();
  877. if (element && element !== _safeActiveElement() && element.focus) {
  878. element.focus();
  879. }
  880. break;
  881. case "_mouseover":
  882. ZeroClipboard.focus(element);
  883. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  884. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  885. _fireMouseEvent(_extend({}, event, {
  886. type: "mouseenter",
  887. bubbles: false,
  888. cancelable: false
  889. }));
  890. }
  891. _fireMouseEvent(_extend({}, event, {
  892. type: "mouseover"
  893. }));
  894. }
  895. break;
  896. case "_mouseout":
  897. ZeroClipboard.blur();
  898. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  899. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  900. _fireMouseEvent(_extend({}, event, {
  901. type: "mouseleave",
  902. bubbles: false,
  903. cancelable: false
  904. }));
  905. }
  906. _fireMouseEvent(_extend({}, event, {
  907. type: "mouseout"
  908. }));
  909. }
  910. break;
  911. case "_mousedown":
  912. _addClass(element, _globalConfig.activeClass);
  913. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  914. _fireMouseEvent(_extend({}, event, {
  915. type: event.type.slice(1)
  916. }));
  917. }
  918. break;
  919. case "_mouseup":
  920. _removeClass(element, _globalConfig.activeClass);
  921. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  922. _fireMouseEvent(_extend({}, event, {
  923. type: event.type.slice(1)
  924. }));
  925. }
  926. break;
  927. case "_click":
  928. case "_mousemove":
  929. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  930. _fireMouseEvent(_extend({}, event, {
  931. type: event.type.slice(1)
  932. }));
  933. }
  934. break;
  935. }
  936. if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  937. return true;
  938. }
  939. };
  940. /**
  941. * Dispatch a synthetic MouseEvent.
  942. *
  943. * @returns `undefined`
  944. * @private
  945. */
  946. var _fireMouseEvent = function(event) {
  947. if (!(event && typeof event.type === "string" && event)) {
  948. return;
  949. }
  950. var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
  951. view: doc.defaultView || _window,
  952. canBubble: true,
  953. cancelable: true,
  954. detail: event.type === "click" ? 1 : 0,
  955. button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
  956. }, args = _extend(defaults, event);
  957. if (!target) {
  958. return;
  959. }
  960. if (doc.createEvent && target.dispatchEvent) {
  961. args = [ args.type, args.canBubble, args.cancelable, args.view, args.detail, args.screenX, args.screenY, args.clientX, args.clientY, args.ctrlKey, args.altKey, args.shiftKey, args.metaKey, args.button, args.relatedTarget ];
  962. e = doc.createEvent("MouseEvents");
  963. if (e.initMouseEvent) {
  964. e.initMouseEvent.apply(e, args);
  965. e._source = "js";
  966. target.dispatchEvent(e);
  967. }
  968. }
  969. };
  970. /**
  971. * Create the HTML bridge element to embed the Flash object into.
  972. * @private
  973. */
  974. var _createHtmlBridge = function() {
  975. var container = _document.createElement("div");
  976. container.id = _globalConfig.containerId;
  977. container.className = _globalConfig.containerClass;
  978. container.style.position = "absolute";
  979. container.style.left = "0px";
  980. container.style.top = "-9999px";
  981. container.style.width = "1px";
  982. container.style.height = "1px";
  983. container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
  984. return container;
  985. };
  986. /**
  987. * Get the HTML element container that wraps the Flash bridge object/element.
  988. * @private
  989. */
  990. var _getHtmlBridge = function(flashBridge) {
  991. var htmlBridge = flashBridge && flashBridge.parentNode;
  992. while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) {
  993. htmlBridge = htmlBridge.parentNode;
  994. }
  995. return htmlBridge || null;
  996. };
  997. /**
  998. * Create the SWF object.
  999. *
  1000. * @returns The SWF object reference.
  1001. * @private
  1002. */
  1003. var _embedSwf = function() {
  1004. var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
  1005. if (!flashBridge) {
  1006. var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
  1007. var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
  1008. var flashvars = _vars(_globalConfig);
  1009. var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
  1010. container = _createHtmlBridge();
  1011. var divToBeReplaced = _document.createElement("div");
  1012. container.appendChild(divToBeReplaced);
  1013. _document.body.appendChild(container);
  1014. var tmpDiv = _document.createElement("div");
  1015. var oldIE = _flashState.pluginType === "activex";
  1016. tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (oldIE ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (oldIE ? '<param name="movie" value="' + swfUrl + '"/>' : "") + '<param name="allowScriptAccess" value="' + allowScriptAccess + '"/>' + '<param name="allowNetworking" value="' + allowNetworking + '"/>' + '<param name="menu" value="false"/>' + '<param name="wmode" value="transparent"/>' + '<param name="flashvars" value="' + flashvars + '"/>' + "</object>";
  1017. flashBridge = tmpDiv.firstChild;
  1018. tmpDiv = null;
  1019. flashBridge.ZeroClipboard = ZeroClipboard;
  1020. container.replaceChild(flashBridge, divToBeReplaced);
  1021. }
  1022. if (!flashBridge) {
  1023. flashBridge = _document[_globalConfig.swfObjectId];
  1024. if (flashBridge && (len = flashBridge.length)) {
  1025. flashBridge = flashBridge[len - 1];
  1026. }
  1027. if (!flashBridge && container) {
  1028. flashBridge = container.firstChild;
  1029. }
  1030. }
  1031. _flashState.bridge = flashBridge || null;
  1032. return flashBridge;
  1033. };
  1034. /**
  1035. * Destroy the SWF object.
  1036. * @private
  1037. */
  1038. var _unembedSwf = function() {
  1039. var flashBridge = _flashState.bridge;
  1040. if (flashBridge) {
  1041. var htmlBridge = _getHtmlBridge(flashBridge);
  1042. if (htmlBridge) {
  1043. if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
  1044. flashBridge.style.display = "none";
  1045. (function removeSwfFromIE() {
  1046. if (flashBridge.readyState === 4) {
  1047. for (var prop in flashBridge) {
  1048. if (typeof flashBridge[prop] === "function") {
  1049. flashBridge[prop] = null;
  1050. }
  1051. }
  1052. if (flashBridge.parentNode) {
  1053. flashBridge.parentNode.removeChild(flashBridge);
  1054. }
  1055. if (htmlBridge.parentNode) {
  1056. htmlBridge.parentNode.removeChild(htmlBridge);
  1057. }
  1058. } else {
  1059. _setTimeout(removeSwfFromIE, 10);
  1060. }
  1061. })();
  1062. } else {
  1063. if (flashBridge.parentNode) {
  1064. flashBridge.parentNode.removeChild(flashBridge);
  1065. }
  1066. if (htmlBridge.parentNode) {
  1067. htmlBridge.parentNode.removeChild(htmlBridge);
  1068. }
  1069. }
  1070. }
  1071. _flashState.ready = null;
  1072. _flashState.bridge = null;
  1073. _flashState.deactivated = null;
  1074. }
  1075. };
  1076. /**
  1077. * Map the data format names of the "clipData" to Flash-friendly names.
  1078. *
  1079. * @returns A new transformed object.
  1080. * @private
  1081. */
  1082. var _mapClipDataToFlash = function(clipData) {
  1083. var newClipData = {}, formatMap = {};
  1084. if (!(typeof clipData === "object" && clipData)) {
  1085. return;
  1086. }
  1087. for (var dataFormat in clipData) {
  1088. if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
  1089. switch (dataFormat.toLowerCase()) {
  1090. case "text/plain":
  1091. case "text":
  1092. case "air:text":
  1093. case "flash:text":
  1094. newClipData.text = clipData[dataFormat];
  1095. formatMap.text = dataFormat;
  1096. break;
  1097. case "text/html":
  1098. case "html":
  1099. case "air:html":
  1100. case "flash:html":
  1101. newClipData.html = clipData[dataFormat];
  1102. formatMap.html = dataFormat;
  1103. break;
  1104. case "application/rtf":
  1105. case "text/rtf":
  1106. case "rtf":
  1107. case "richtext":
  1108. case "air:rtf":
  1109. case "flash:rtf":
  1110. newClipData.rtf = clipData[dataFormat];
  1111. formatMap.rtf = dataFormat;
  1112. break;
  1113. default:
  1114. break;
  1115. }
  1116. }
  1117. }
  1118. return {
  1119. data: newClipData,
  1120. formatMap: formatMap
  1121. };
  1122. };
  1123. /**
  1124. * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping).
  1125. *
  1126. * @returns A new transformed object.
  1127. * @private
  1128. */
  1129. var _mapClipResultsFromFlash = function(clipResults, formatMap) {
  1130. if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) {
  1131. return clipResults;
  1132. }
  1133. var newResults = {};
  1134. for (var prop in clipResults) {
  1135. if (_hasOwn.call(clipResults, prop)) {
  1136. if (prop !== "success" && prop !== "data") {
  1137. newResults[prop] = clipResults[prop];
  1138. continue;
  1139. }
  1140. newResults[prop] = {};
  1141. var tmpHash = clipResults[prop];
  1142. for (var dataFormat in tmpHash) {
  1143. if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) {
  1144. newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat];
  1145. }
  1146. }
  1147. }
  1148. }
  1149. return newResults;
  1150. };
  1151. /**
  1152. * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}"
  1153. * query param string to return. Does NOT append that string to the original path.
  1154. * This is useful because ExternalInterface often breaks when a Flash SWF is cached.
  1155. *
  1156. * @returns The `noCache` query param with necessary "?"/"&" prefix.
  1157. * @private
  1158. */
  1159. var _cacheBust = function(path, options) {
  1160. var cacheBust = options == null || options && options.cacheBust === true;
  1161. if (cacheBust) {
  1162. return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now();
  1163. } else {
  1164. return "";
  1165. }
  1166. };
  1167. /**
  1168. * Creates a query string for the FlashVars param.
  1169. * Does NOT include the cache-busting query param.
  1170. *
  1171. * @returns FlashVars query string
  1172. * @private
  1173. */
  1174. var _vars = function(options) {
  1175. var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
  1176. if (options.trustedDomains) {
  1177. if (typeof options.trustedDomains === "string") {
  1178. domains = [ options.trustedDomains ];
  1179. } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
  1180. domains = options.trustedDomains;
  1181. }
  1182. }
  1183. if (domains && domains.length) {
  1184. for (i = 0, len = domains.length; i < len; i++) {
  1185. if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
  1186. domain = _extractDomain(domains[i]);
  1187. if (!domain) {
  1188. continue;
  1189. }
  1190. if (domain === "*") {
  1191. trustedOriginsExpanded.length = 0;
  1192. trustedOriginsExpanded.push(domain);
  1193. break;
  1194. }
  1195. trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
  1196. }
  1197. }
  1198. }
  1199. if (trustedOriginsExpanded.length) {
  1200. str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
  1201. }
  1202. if (options.forceEnhancedClipboard === true) {
  1203. str += (str ? "&" : "") + "forceEnhancedClipboard=true";
  1204. }
  1205. if (typeof options.swfObjectId === "string" && options.swfObjectId) {
  1206. str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
  1207. }
  1208. return str;
  1209. };
  1210. /**
  1211. * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or
  1212. * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/").
  1213. *
  1214. * @returns the domain
  1215. * @private
  1216. */
  1217. var _extractDomain = function(originOrUrl) {
  1218. if (originOrUrl == null || originOrUrl === "") {
  1219. return null;
  1220. }
  1221. originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
  1222. if (originOrUrl === "") {
  1223. return null;
  1224. }
  1225. var protocolIndex = originOrUrl.indexOf("//");
  1226. originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
  1227. var pathIndex = originOrUrl.indexOf("/");
  1228. originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
  1229. if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
  1230. return null;
  1231. }
  1232. return originOrUrl || null;
  1233. };
  1234. /**
  1235. * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`.
  1236. *
  1237. * @returns The appropriate script access level.
  1238. * @private
  1239. */
  1240. var _determineScriptAccess = function() {
  1241. var _extractAllDomains = function(origins) {
  1242. var i, len, tmp, resultsArray = [];
  1243. if (typeof origins === "string") {
  1244. origins = [ origins ];
  1245. }
  1246. if (!(typeof origins === "object" && origins && typeof origins.length === "number")) {
  1247. return resultsArray;
  1248. }
  1249. for (i = 0, len = origins.length; i < len; i++) {
  1250. if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) {
  1251. if (tmp === "*") {
  1252. resultsArray.length = 0;
  1253. resultsArray.push("*");
  1254. break;
  1255. }
  1256. if (resultsArray.indexOf(tmp) === -1) {
  1257. resultsArray.push(tmp);
  1258. }
  1259. }
  1260. }
  1261. return resultsArray;
  1262. };
  1263. return function(currentDomain, configOptions) {
  1264. var swfDomain = _extractDomain(configOptions.swfPath);
  1265. if (swfDomain === null) {
  1266. swfDomain = currentDomain;
  1267. }
  1268. var trustedDomains = _extractAllDomains(configOptions.trustedDomains);
  1269. var len = trustedDomains.length;
  1270. if (len > 0) {
  1271. if (len === 1 && trustedDomains[0] === "*") {
  1272. return "always";
  1273. }
  1274. if (trustedDomains.indexOf(currentDomain) !== -1) {
  1275. if (len === 1 && currentDomain === swfDomain) {
  1276. return "sameDomain";
  1277. }
  1278. return "always";
  1279. }
  1280. }
  1281. return "never";
  1282. };
  1283. }();
  1284. /**
  1285. * Get the currently active/focused DOM element.
  1286. *
  1287. * @returns the currently active/focused element, or `null`
  1288. * @private
  1289. */
  1290. var _safeActiveElement = function() {
  1291. try {
  1292. return _document.activeElement;
  1293. } catch (err) {
  1294. return null;
  1295. }
  1296. };
  1297. /**
  1298. * Add a class to an element, if it doesn't already have it.
  1299. *
  1300. * @returns The element, with its new class added.
  1301. * @private
  1302. */
  1303. var _addClass = function(element, value) {
  1304. if (!element || element.nodeType !== 1) {
  1305. return element;
  1306. }
  1307. if (element.classList) {
  1308. if (!element.classList.contains(value)) {
  1309. element.classList.add(value);
  1310. }
  1311. return element;
  1312. }
  1313. if (value && typeof value === "string") {
  1314. var classNames = (value || "").split(/\s+/);
  1315. if (element.nodeType === 1) {
  1316. if (!element.className) {
  1317. element.className = value;
  1318. } else {
  1319. var className = " " + element.className + " ", setClass = element.className;
  1320. for (var c = 0, cl = classNames.length; c < cl; c++) {
  1321. if (className.indexOf(" " + classNames[c] + " ") < 0) {
  1322. setClass += " " + classNames[c];
  1323. }
  1324. }
  1325. element.className = setClass.replace(/^\s+|\s+$/g, "");
  1326. }
  1327. }
  1328. }
  1329. return element;
  1330. };
  1331. /**
  1332. * Remove a class from an element, if it has it.
  1333. *
  1334. * @returns The element, with its class removed.
  1335. * @private
  1336. */
  1337. var _removeClass = function(element, value) {
  1338. if (!element || element.nodeType !== 1) {
  1339. return element;
  1340. }
  1341. if (element.classList) {
  1342. if (element.classList.contains(value)) {
  1343. element.classList.remove(value);
  1344. }
  1345. return element;
  1346. }
  1347. if (typeof value === "string" && value) {
  1348. var classNames = value.split(/\s+/);
  1349. if (element.nodeType === 1 && element.className) {
  1350. var className = (" " + element.className + " ").replace(/[\n\t]/g, " ");
  1351. for (var c = 0, cl = classNames.length; c < cl; c++) {
  1352. className = className.replace(" " + classNames[c] + " ", " ");
  1353. }
  1354. element.className = className.replace(/^\s+|\s+$/g, "");
  1355. }
  1356. }
  1357. return element;
  1358. };
  1359. /**
  1360. * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`,
  1361. * then we assume that it should be a hand ("pointer") cursor if the element
  1362. * is an anchor element ("a" tag).
  1363. *
  1364. * @returns The computed style property.
  1365. * @private
  1366. */
  1367. var _getStyle = function(el, prop) {
  1368. var value = _window.getComputedStyle(el, null).getPropertyValue(prop);
  1369. if (prop === "cursor") {
  1370. if (!value || value === "auto") {
  1371. if (el.nodeName === "A") {
  1372. return "pointer";
  1373. }
  1374. }
  1375. }
  1376. return value;
  1377. };
  1378. /**
  1379. * Get the zoom factor of the browser. Always returns `1.0`, except at
  1380. * non-default zoom levels in IE<8 and some older versions of WebKit.
  1381. *
  1382. * @returns Floating unit percentage of the zoom factor (e.g. 150% = `1.5`).
  1383. * @private
  1384. */
  1385. var _getZoomFactor = function() {
  1386. var rect, physicalWidth, logicalWidth, zoomFactor = 1;
  1387. if (typeof _document.body.getBoundingClientRect === "function") {
  1388. rect = _document.body.getBoundingClientRect();
  1389. physicalWidth = rect.right - rect.left;
  1390. logicalWidth = _document.body.offsetWidth;
  1391. zoomFactor = _round(physicalWidth / logicalWidth * 100) / 100;
  1392. }
  1393. return zoomFactor;
  1394. };
  1395. /**
  1396. * Get the DOM positioning info of an element.
  1397. *
  1398. * @returns Object containing the element's position, width, and height.
  1399. * @private
  1400. */
  1401. var _getDOMObjectPosition = function(obj) {
  1402. var info = {
  1403. left: 0,
  1404. top: 0,
  1405. width: 0,
  1406. height: 0
  1407. };
  1408. if (obj.getBoundingClientRect) {
  1409. var rect = obj.getBoundingClientRect();
  1410. var pageXOffset, pageYOffset, zoomFactor;
  1411. if ("pageXOffset" in _window && "pageYOffset" in _window) {
  1412. pageXOffset = _window.pageXOffset;
  1413. pageYOffset = _window.pageYOffset;
  1414. } else {
  1415. zoomFactor = _getZoomFactor();
  1416. pageXOffset = _round(_document.documentElement.scrollLeft / zoomFactor);
  1417. pageYOffset = _round(_document.documentElement.scrollTop / zoomFactor);
  1418. }
  1419. var leftBorderWidth = _document.documentElement.clientLeft || 0;
  1420. var topBorderWidth = _document.documentElement.clientTop || 0;
  1421. info.left = rect.left + pageXOffset - leftBorderWidth;
  1422. info.top = rect.top + pageYOffset - topBorderWidth;
  1423. info.width = "width" in rect ? rect.width : rect.right - rect.left;
  1424. info.height = "height" in rect ? rect.height : rect.bottom - rect.top;
  1425. }
  1426. return info;
  1427. };
  1428. /**
  1429. * Reposition the Flash object to cover the currently activated element.
  1430. *
  1431. * @returns `undefined`
  1432. * @private
  1433. */
  1434. var _reposition = function() {
  1435. var htmlBridge;
  1436. if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
  1437. var pos = _getDOMObjectPosition(_currentElement);
  1438. _extend(htmlBridge.style, {
  1439. width: pos.width + "px",
  1440. height: pos.height + "px",
  1441. top: pos.top + "px",
  1442. left: pos.left + "px",
  1443. zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
  1444. });
  1445. }
  1446. };
  1447. /**
  1448. * Sends a signal to the Flash object to display the hand cursor if `true`.
  1449. *
  1450. * @returns `undefined`
  1451. * @private
  1452. */
  1453. var _setHandCursor = function(enabled) {
  1454. if (_flashState.ready === true) {
  1455. if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
  1456. _flashState.bridge.setHandCursor(enabled);
  1457. } else {
  1458. _flashState.ready = false;
  1459. }
  1460. }
  1461. };
  1462. /**
  1463. * Get a safe value for `zIndex`
  1464. *
  1465. * @returns an integer, or "auto"
  1466. * @private
  1467. */
  1468. var _getSafeZIndex = function(val) {
  1469. if (/^(?:auto|inherit)$/.test(val)) {
  1470. return val;
  1471. }
  1472. var zIndex;
  1473. if (typeof val === "number" && !_isNaN(val)) {
  1474. zIndex = val;
  1475. } else if (typeof val === "string") {
  1476. zIndex = _getSafeZIndex(_parseInt(val, 10));
  1477. }
  1478. return typeof zIndex === "number" ? zIndex : "auto";
  1479. };
  1480. /**
  1481. * Detect the Flash Player status, version, and plugin type.
  1482. *
  1483. * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code}
  1484. * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript}
  1485. *
  1486. * @returns `undefined`
  1487. * @private
  1488. */
  1489. var _detectFlashSupport = function(ActiveXObject) {
  1490. var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = "";
  1491. /**
  1492. * Derived from Apple's suggested sniffer.
  1493. * @param {String} desc e.g. "Shockwave Flash 7.0 r61"
  1494. * @returns {String} "7.0.61"
  1495. * @private
  1496. */
  1497. function parseFlashVersion(desc) {
  1498. var matches = desc.match(/[\d]+/g);
  1499. matches.length = 3;
  1500. return matches.join(".");
  1501. }
  1502. function isPepperFlash(flashPlayerFileName) {
  1503. return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin");
  1504. }
  1505. function inspectPlugin(plugin) {
  1506. if (plugin) {
  1507. hasFlash = true;
  1508. if (plugin.version) {
  1509. flashVersion = parseFlashVersion(plugin.version);
  1510. }
  1511. if (!flashVersion && plugin.description) {
  1512. flashVersion = parseFlashVersion(plugin.description);
  1513. }
  1514. if (plugin.filename) {
  1515. isPPAPI = isPepperFlash(plugin.filename);
  1516. }
  1517. }
  1518. }
  1519. if (_navigator.plugins && _navigator.plugins.length) {
  1520. plugin = _navigator.plugins["Shockwave Flash"];
  1521. inspectPlugin(plugin);
  1522. if (_navigator.plugins["Shockwave Flash 2.0"]) {
  1523. hasFlash = true;
  1524. flashVersion = "2.0.0.11";
  1525. }
  1526. } else if (_navigator.mimeTypes &&