PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/files/zeroclipboard/2.1.5/ZeroClipboard.js

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