PageRenderTime 46ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/files/zeroclipboard/2.1.1/ZeroClipboard.js

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