ZeroClipboard.js 84 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581
  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) 2009-2014 Jon Rohan, James M. Greene
  5. * Licensed MIT
  6. * http://zeroclipboard.org/
  7. * v2.2.0
  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, _clearTimeout = _window.clearTimeout, _setInterval = _window.setInterval, _clearInterval = _window.clearInterval, _getComputedStyle = _window.getComputedStyle, _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, _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 || typeof source.nodeType === "number") {
  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 if the page is framed (in an `iframe`). This can never change.
  276. * @private
  277. */
  278. var _pageIsFramed = function() {
  279. return window.opener == null && (!!window.top && window != window.top || !!window.parent && window != window.parent);
  280. }();
  281. /**
  282. * Keep track of the state of the Flash object.
  283. * @private
  284. */
  285. var _flashState = {
  286. bridge: null,
  287. version: "0.0.0",
  288. pluginType: "unknown",
  289. disabled: null,
  290. outdated: null,
  291. sandboxed: null,
  292. unavailable: null,
  293. degraded: null,
  294. deactivated: null,
  295. overdue: null,
  296. ready: null
  297. };
  298. /**
  299. * The minimum Flash Player version required to use ZeroClipboard completely.
  300. * @readonly
  301. * @private
  302. */
  303. var _minimumFlashVersion = "11.0.0";
  304. /**
  305. * The ZeroClipboard library version number, as reported by Flash, at the time the SWF was compiled.
  306. */
  307. var _zcSwfVersion;
  308. /**
  309. * Keep track of all event listener registrations.
  310. * @private
  311. */
  312. var _handlers = {};
  313. /**
  314. * Keep track of the currently activated element.
  315. * @private
  316. */
  317. var _currentElement;
  318. /**
  319. * Keep track of the element that was activated when a `copy` process started.
  320. * @private
  321. */
  322. var _copyTarget;
  323. /**
  324. * Keep track of data for the pending clipboard transaction.
  325. * @private
  326. */
  327. var _clipData = {};
  328. /**
  329. * Keep track of data formats for the pending clipboard transaction.
  330. * @private
  331. */
  332. var _clipDataFormatMap = null;
  333. /**
  334. * Keep track of the Flash availability check timeout.
  335. * @private
  336. */
  337. var _flashCheckTimeout = 0;
  338. /**
  339. * Keep track of SWF network errors interval polling.
  340. * @private
  341. */
  342. var _swfFallbackCheckInterval = 0;
  343. /**
  344. * The `message` store for events
  345. * @private
  346. */
  347. var _eventMessages = {
  348. ready: "Flash communication is established",
  349. error: {
  350. "flash-disabled": "Flash is disabled or not installed. May also be attempting to run Flash in a sandboxed iframe, which is impossible.",
  351. "flash-outdated": "Flash is too outdated to support ZeroClipboard",
  352. "flash-sandboxed": "Attempting to run Flash in a sandboxed iframe, which is impossible",
  353. "flash-unavailable": "Flash is unable to communicate bidirectionally with JavaScript",
  354. "flash-degraded": "Flash is unable to preserve data fidelity when communicating with JavaScript",
  355. "flash-deactivated": "Flash is too outdated for your browser and/or is configured as click-to-activate.\nThis may also mean that the ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity.\nMay also be attempting to run Flash in a sandboxed iframe, which is impossible.",
  356. "flash-overdue": "Flash communication was established but NOT within the acceptable time limit",
  357. "version-mismatch": "ZeroClipboard JS version number does not match ZeroClipboard SWF version number",
  358. "clipboard-error": "At least one error was thrown while ZeroClipboard was attempting to inject your data into the clipboard",
  359. "config-mismatch": "ZeroClipboard configuration does not match Flash's reality",
  360. "swf-not-found": "The ZeroClipboard SWF object could not be loaded, so please check your `swfPath` configuration and/or network connectivity"
  361. }
  362. };
  363. /**
  364. * The `name`s of `error` events that can only occur is Flash has at least
  365. * been able to load the SWF successfully.
  366. * @private
  367. */
  368. var _errorsThatOnlyOccurAfterFlashLoads = [ "flash-unavailable", "flash-degraded", "flash-overdue", "version-mismatch", "config-mismatch", "clipboard-error" ];
  369. /**
  370. * The `name`s of `error` events that should likely result in the `_flashState`
  371. * variable's property values being updated.
  372. * @private
  373. */
  374. var _flashStateErrorNames = [ "flash-disabled", "flash-outdated", "flash-sandboxed", "flash-unavailable", "flash-degraded", "flash-deactivated", "flash-overdue" ];
  375. /**
  376. * A RegExp to match the `name` property of `error` events related to Flash.
  377. * @private
  378. */
  379. var _flashStateErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.map(function(errorName) {
  380. return errorName.replace(/^flash-/, "");
  381. }).join("|") + ")$");
  382. /**
  383. * A RegExp to match the `name` property of `error` events related to Flash,
  384. * which is enabled.
  385. * @private
  386. */
  387. var _flashStateEnabledErrorNameMatchingRegex = new RegExp("^flash-(" + _flashStateErrorNames.slice(1).map(function(errorName) {
  388. return errorName.replace(/^flash-/, "");
  389. }).join("|") + ")$");
  390. /**
  391. * ZeroClipboard configuration defaults for the Core module.
  392. * @private
  393. */
  394. var _globalConfig = {
  395. swfPath: _getDefaultSwfPath(),
  396. trustedDomains: window.location.host ? [ window.location.host ] : [],
  397. cacheBust: true,
  398. forceEnhancedClipboard: false,
  399. flashLoadTimeout: 3e4,
  400. autoActivate: true,
  401. bubbleEvents: true,
  402. containerId: "global-zeroclipboard-html-bridge",
  403. containerClass: "global-zeroclipboard-container",
  404. swfObjectId: "global-zeroclipboard-flash-bridge",
  405. hoverClass: "zeroclipboard-is-hover",
  406. activeClass: "zeroclipboard-is-active",
  407. forceHandCursor: false,
  408. title: null,
  409. zIndex: 999999999
  410. };
  411. /**
  412. * The underlying implementation of `ZeroClipboard.config`.
  413. * @private
  414. */
  415. var _config = function(options) {
  416. if (typeof options === "object" && options !== null) {
  417. for (var prop in options) {
  418. if (_hasOwn.call(options, prop)) {
  419. if (/^(?:forceHandCursor|title|zIndex|bubbleEvents)$/.test(prop)) {
  420. _globalConfig[prop] = options[prop];
  421. } else if (_flashState.bridge == null) {
  422. if (prop === "containerId" || prop === "swfObjectId") {
  423. if (_isValidHtml4Id(options[prop])) {
  424. _globalConfig[prop] = options[prop];
  425. } else {
  426. throw new Error("The specified `" + prop + "` value is not valid as an HTML4 Element ID");
  427. }
  428. } else {
  429. _globalConfig[prop] = options[prop];
  430. }
  431. }
  432. }
  433. }
  434. }
  435. if (typeof options === "string" && options) {
  436. if (_hasOwn.call(_globalConfig, options)) {
  437. return _globalConfig[options];
  438. }
  439. return;
  440. }
  441. return _deepCopy(_globalConfig);
  442. };
  443. /**
  444. * The underlying implementation of `ZeroClipboard.state`.
  445. * @private
  446. */
  447. var _state = function() {
  448. _detectSandbox();
  449. return {
  450. browser: _pick(_navigator, [ "userAgent", "platform", "appName" ]),
  451. flash: _omit(_flashState, [ "bridge" ]),
  452. zeroclipboard: {
  453. version: ZeroClipboard.version,
  454. config: ZeroClipboard.config()
  455. }
  456. };
  457. };
  458. /**
  459. * The underlying implementation of `ZeroClipboard.isFlashUnusable`.
  460. * @private
  461. */
  462. var _isFlashUnusable = function() {
  463. return !!(_flashState.disabled || _flashState.outdated || _flashState.sandboxed || _flashState.unavailable || _flashState.degraded || _flashState.deactivated);
  464. };
  465. /**
  466. * The underlying implementation of `ZeroClipboard.on`.
  467. * @private
  468. */
  469. var _on = function(eventType, listener) {
  470. var i, len, events, added = {};
  471. if (typeof eventType === "string" && eventType) {
  472. events = eventType.toLowerCase().split(/\s+/);
  473. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  474. for (i in eventType) {
  475. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  476. ZeroClipboard.on(i, eventType[i]);
  477. }
  478. }
  479. }
  480. if (events && events.length) {
  481. for (i = 0, len = events.length; i < len; i++) {
  482. eventType = events[i].replace(/^on/, "");
  483. added[eventType] = true;
  484. if (!_handlers[eventType]) {
  485. _handlers[eventType] = [];
  486. }
  487. _handlers[eventType].push(listener);
  488. }
  489. if (added.ready && _flashState.ready) {
  490. ZeroClipboard.emit({
  491. type: "ready"
  492. });
  493. }
  494. if (added.error) {
  495. for (i = 0, len = _flashStateErrorNames.length; i < len; i++) {
  496. if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")] === true) {
  497. ZeroClipboard.emit({
  498. type: "error",
  499. name: _flashStateErrorNames[i]
  500. });
  501. break;
  502. }
  503. }
  504. if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) {
  505. ZeroClipboard.emit({
  506. type: "error",
  507. name: "version-mismatch",
  508. jsVersion: ZeroClipboard.version,
  509. swfVersion: _zcSwfVersion
  510. });
  511. }
  512. }
  513. }
  514. return ZeroClipboard;
  515. };
  516. /**
  517. * The underlying implementation of `ZeroClipboard.off`.
  518. * @private
  519. */
  520. var _off = function(eventType, listener) {
  521. var i, len, foundIndex, events, perEventHandlers;
  522. if (arguments.length === 0) {
  523. events = _keys(_handlers);
  524. } else if (typeof eventType === "string" && eventType) {
  525. events = eventType.split(/\s+/);
  526. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  527. for (i in eventType) {
  528. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  529. ZeroClipboard.off(i, eventType[i]);
  530. }
  531. }
  532. }
  533. if (events && events.length) {
  534. for (i = 0, len = events.length; i < len; i++) {
  535. eventType = events[i].toLowerCase().replace(/^on/, "");
  536. perEventHandlers = _handlers[eventType];
  537. if (perEventHandlers && perEventHandlers.length) {
  538. if (listener) {
  539. foundIndex = perEventHandlers.indexOf(listener);
  540. while (foundIndex !== -1) {
  541. perEventHandlers.splice(foundIndex, 1);
  542. foundIndex = perEventHandlers.indexOf(listener, foundIndex);
  543. }
  544. } else {
  545. perEventHandlers.length = 0;
  546. }
  547. }
  548. }
  549. }
  550. return ZeroClipboard;
  551. };
  552. /**
  553. * The underlying implementation of `ZeroClipboard.handlers`.
  554. * @private
  555. */
  556. var _listeners = function(eventType) {
  557. var copy;
  558. if (typeof eventType === "string" && eventType) {
  559. copy = _deepCopy(_handlers[eventType]) || null;
  560. } else {
  561. copy = _deepCopy(_handlers);
  562. }
  563. return copy;
  564. };
  565. /**
  566. * The underlying implementation of `ZeroClipboard.emit`.
  567. * @private
  568. */
  569. var _emit = function(event) {
  570. var eventCopy, returnVal, tmp;
  571. event = _createEvent(event);
  572. if (!event) {
  573. return;
  574. }
  575. if (_preprocessEvent(event)) {
  576. return;
  577. }
  578. if (event.type === "ready" && _flashState.overdue === true) {
  579. return ZeroClipboard.emit({
  580. type: "error",
  581. name: "flash-overdue"
  582. });
  583. }
  584. eventCopy = _extend({}, event);
  585. _dispatchCallbacks.call(this, eventCopy);
  586. if (event.type === "copy") {
  587. tmp = _mapClipDataToFlash(_clipData);
  588. returnVal = tmp.data;
  589. _clipDataFormatMap = tmp.formatMap;
  590. }
  591. return returnVal;
  592. };
  593. /**
  594. * The underlying implementation of `ZeroClipboard.create`.
  595. * @private
  596. */
  597. var _create = function() {
  598. var previousState = _flashState.sandboxed;
  599. _detectSandbox();
  600. if (typeof _flashState.ready !== "boolean") {
  601. _flashState.ready = false;
  602. }
  603. if (_flashState.sandboxed !== previousState && _flashState.sandboxed === true) {
  604. _flashState.ready = false;
  605. ZeroClipboard.emit({
  606. type: "error",
  607. name: "flash-sandboxed"
  608. });
  609. } else if (!ZeroClipboard.isFlashUnusable() && _flashState.bridge === null) {
  610. var maxWait = _globalConfig.flashLoadTimeout;
  611. if (typeof maxWait === "number" && maxWait >= 0) {
  612. _flashCheckTimeout = _setTimeout(function() {
  613. if (typeof _flashState.deactivated !== "boolean") {
  614. _flashState.deactivated = true;
  615. }
  616. if (_flashState.deactivated === true) {
  617. ZeroClipboard.emit({
  618. type: "error",
  619. name: "flash-deactivated"
  620. });
  621. }
  622. }, maxWait);
  623. }
  624. _flashState.overdue = false;
  625. _embedSwf();
  626. }
  627. };
  628. /**
  629. * The underlying implementation of `ZeroClipboard.destroy`.
  630. * @private
  631. */
  632. var _destroy = function() {
  633. ZeroClipboard.clearData();
  634. ZeroClipboard.blur();
  635. ZeroClipboard.emit("destroy");
  636. _unembedSwf();
  637. ZeroClipboard.off();
  638. };
  639. /**
  640. * The underlying implementation of `ZeroClipboard.setData`.
  641. * @private
  642. */
  643. var _setData = function(format, data) {
  644. var dataObj;
  645. if (typeof format === "object" && format && typeof data === "undefined") {
  646. dataObj = format;
  647. ZeroClipboard.clearData();
  648. } else if (typeof format === "string" && format) {
  649. dataObj = {};
  650. dataObj[format] = data;
  651. } else {
  652. return;
  653. }
  654. for (var dataFormat in dataObj) {
  655. if (typeof dataFormat === "string" && dataFormat && _hasOwn.call(dataObj, dataFormat) && typeof dataObj[dataFormat] === "string" && dataObj[dataFormat]) {
  656. _clipData[dataFormat] = dataObj[dataFormat];
  657. }
  658. }
  659. };
  660. /**
  661. * The underlying implementation of `ZeroClipboard.clearData`.
  662. * @private
  663. */
  664. var _clearData = function(format) {
  665. if (typeof format === "undefined") {
  666. _deleteOwnProperties(_clipData);
  667. _clipDataFormatMap = null;
  668. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  669. delete _clipData[format];
  670. }
  671. };
  672. /**
  673. * The underlying implementation of `ZeroClipboard.getData`.
  674. * @private
  675. */
  676. var _getData = function(format) {
  677. if (typeof format === "undefined") {
  678. return _deepCopy(_clipData);
  679. } else if (typeof format === "string" && _hasOwn.call(_clipData, format)) {
  680. return _clipData[format];
  681. }
  682. };
  683. /**
  684. * The underlying implementation of `ZeroClipboard.focus`/`ZeroClipboard.activate`.
  685. * @private
  686. */
  687. var _focus = function(element) {
  688. if (!(element && element.nodeType === 1)) {
  689. return;
  690. }
  691. if (_currentElement) {
  692. _removeClass(_currentElement, _globalConfig.activeClass);
  693. if (_currentElement !== element) {
  694. _removeClass(_currentElement, _globalConfig.hoverClass);
  695. }
  696. }
  697. _currentElement = element;
  698. _addClass(element, _globalConfig.hoverClass);
  699. var newTitle = element.getAttribute("title") || _globalConfig.title;
  700. if (typeof newTitle === "string" && newTitle) {
  701. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  702. if (htmlBridge) {
  703. htmlBridge.setAttribute("title", newTitle);
  704. }
  705. }
  706. var useHandCursor = _globalConfig.forceHandCursor === true || _getStyle(element, "cursor") === "pointer";
  707. _setHandCursor(useHandCursor);
  708. _reposition();
  709. };
  710. /**
  711. * The underlying implementation of `ZeroClipboard.blur`/`ZeroClipboard.deactivate`.
  712. * @private
  713. */
  714. var _blur = function() {
  715. var htmlBridge = _getHtmlBridge(_flashState.bridge);
  716. if (htmlBridge) {
  717. htmlBridge.removeAttribute("title");
  718. htmlBridge.style.left = "0px";
  719. htmlBridge.style.top = "-9999px";
  720. htmlBridge.style.width = "1px";
  721. htmlBridge.style.height = "1px";
  722. }
  723. if (_currentElement) {
  724. _removeClass(_currentElement, _globalConfig.hoverClass);
  725. _removeClass(_currentElement, _globalConfig.activeClass);
  726. _currentElement = null;
  727. }
  728. };
  729. /**
  730. * The underlying implementation of `ZeroClipboard.activeElement`.
  731. * @private
  732. */
  733. var _activeElement = function() {
  734. return _currentElement || null;
  735. };
  736. /**
  737. * Check if a value is a valid HTML4 `ID` or `Name` token.
  738. * @private
  739. */
  740. var _isValidHtml4Id = function(id) {
  741. return typeof id === "string" && id && /^[A-Za-z][A-Za-z0-9_:\-\.]*$/.test(id);
  742. };
  743. /**
  744. * Create or update an `event` object, based on the `eventType`.
  745. * @private
  746. */
  747. var _createEvent = function(event) {
  748. var eventType;
  749. if (typeof event === "string" && event) {
  750. eventType = event;
  751. event = {};
  752. } else if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
  753. eventType = event.type;
  754. }
  755. if (!eventType) {
  756. return;
  757. }
  758. eventType = eventType.toLowerCase();
  759. if (!event.target && (/^(copy|aftercopy|_click)$/.test(eventType) || eventType === "error" && event.name === "clipboard-error")) {
  760. event.target = _copyTarget;
  761. }
  762. _extend(event, {
  763. type: eventType,
  764. target: event.target || _currentElement || null,
  765. relatedTarget: event.relatedTarget || null,
  766. currentTarget: _flashState && _flashState.bridge || null,
  767. timeStamp: event.timeStamp || _now() || null
  768. });
  769. var msg = _eventMessages[event.type];
  770. if (event.type === "error" && event.name && msg) {
  771. msg = msg[event.name];
  772. }
  773. if (msg) {
  774. event.message = msg;
  775. }
  776. if (event.type === "ready") {
  777. _extend(event, {
  778. target: null,
  779. version: _flashState.version
  780. });
  781. }
  782. if (event.type === "error") {
  783. if (_flashStateErrorNameMatchingRegex.test(event.name)) {
  784. _extend(event, {
  785. target: null,
  786. minimumVersion: _minimumFlashVersion
  787. });
  788. }
  789. if (_flashStateEnabledErrorNameMatchingRegex.test(event.name)) {
  790. _extend(event, {
  791. version: _flashState.version
  792. });
  793. }
  794. }
  795. if (event.type === "copy") {
  796. event.clipboardData = {
  797. setData: ZeroClipboard.setData,
  798. clearData: ZeroClipboard.clearData
  799. };
  800. }
  801. if (event.type === "aftercopy") {
  802. event = _mapClipResultsFromFlash(event, _clipDataFormatMap);
  803. }
  804. if (event.target && !event.relatedTarget) {
  805. event.relatedTarget = _getRelatedTarget(event.target);
  806. }
  807. return _addMouseData(event);
  808. };
  809. /**
  810. * Get a relatedTarget from the target's `data-clipboard-target` attribute
  811. * @private
  812. */
  813. var _getRelatedTarget = function(targetEl) {
  814. var relatedTargetId = targetEl && targetEl.getAttribute && targetEl.getAttribute("data-clipboard-target");
  815. return relatedTargetId ? _document.getElementById(relatedTargetId) : null;
  816. };
  817. /**
  818. * Add element and position data to `MouseEvent` instances
  819. * @private
  820. */
  821. var _addMouseData = function(event) {
  822. if (event && /^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  823. var srcElement = event.target;
  824. var fromElement = event.type === "_mouseover" && event.relatedTarget ? event.relatedTarget : undefined;
  825. var toElement = event.type === "_mouseout" && event.relatedTarget ? event.relatedTarget : undefined;
  826. var pos = _getElementPosition(srcElement);
  827. var screenLeft = _window.screenLeft || _window.screenX || 0;
  828. var screenTop = _window.screenTop || _window.screenY || 0;
  829. var scrollLeft = _document.body.scrollLeft + _document.documentElement.scrollLeft;
  830. var scrollTop = _document.body.scrollTop + _document.documentElement.scrollTop;
  831. var pageX = pos.left + (typeof event._stageX === "number" ? event._stageX : 0);
  832. var pageY = pos.top + (typeof event._stageY === "number" ? event._stageY : 0);
  833. var clientX = pageX - scrollLeft;
  834. var clientY = pageY - scrollTop;
  835. var screenX = screenLeft + clientX;
  836. var screenY = screenTop + clientY;
  837. var moveX = typeof event.movementX === "number" ? event.movementX : 0;
  838. var moveY = typeof event.movementY === "number" ? event.movementY : 0;
  839. delete event._stageX;
  840. delete event._stageY;
  841. _extend(event, {
  842. srcElement: srcElement,
  843. fromElement: fromElement,
  844. toElement: toElement,
  845. screenX: screenX,
  846. screenY: screenY,
  847. pageX: pageX,
  848. pageY: pageY,
  849. clientX: clientX,
  850. clientY: clientY,
  851. x: clientX,
  852. y: clientY,
  853. movementX: moveX,
  854. movementY: moveY,
  855. offsetX: 0,
  856. offsetY: 0,
  857. layerX: 0,
  858. layerY: 0
  859. });
  860. }
  861. return event;
  862. };
  863. /**
  864. * Determine if an event's registered handlers should be execute synchronously or asynchronously.
  865. *
  866. * @returns {boolean}
  867. * @private
  868. */
  869. var _shouldPerformAsync = function(event) {
  870. var eventType = event && typeof event.type === "string" && event.type || "";
  871. return !/^(?:(?:before)?copy|destroy)$/.test(eventType);
  872. };
  873. /**
  874. * Control if a callback should be executed asynchronously or not.
  875. *
  876. * @returns `undefined`
  877. * @private
  878. */
  879. var _dispatchCallback = function(func, context, args, async) {
  880. if (async) {
  881. _setTimeout(function() {
  882. func.apply(context, args);
  883. }, 0);
  884. } else {
  885. func.apply(context, args);
  886. }
  887. };
  888. /**
  889. * Handle the actual dispatching of events to client instances.
  890. *
  891. * @returns `undefined`
  892. * @private
  893. */
  894. var _dispatchCallbacks = function(event) {
  895. if (!(typeof event === "object" && event && event.type)) {
  896. return;
  897. }
  898. var async = _shouldPerformAsync(event);
  899. var wildcardTypeHandlers = _handlers["*"] || [];
  900. var specificTypeHandlers = _handlers[event.type] || [];
  901. var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
  902. if (handlers && handlers.length) {
  903. var i, len, func, context, eventCopy, originalContext = this;
  904. for (i = 0, len = handlers.length; i < len; i++) {
  905. func = handlers[i];
  906. context = originalContext;
  907. if (typeof func === "string" && typeof _window[func] === "function") {
  908. func = _window[func];
  909. }
  910. if (typeof func === "object" && func && typeof func.handleEvent === "function") {
  911. context = func;
  912. func = func.handleEvent;
  913. }
  914. if (typeof func === "function") {
  915. eventCopy = _extend({}, event);
  916. _dispatchCallback(func, context, [ eventCopy ], async);
  917. }
  918. }
  919. }
  920. return this;
  921. };
  922. /**
  923. * Check an `error` event's `name` property to see if Flash has
  924. * already loaded, which rules out possible `iframe` sandboxing.
  925. * @private
  926. */
  927. var _getSandboxStatusFromErrorEvent = function(event) {
  928. var isSandboxed = null;
  929. if (_pageIsFramed === false || event && event.type === "error" && event.name && _errorsThatOnlyOccurAfterFlashLoads.indexOf(event.name) !== -1) {
  930. isSandboxed = false;
  931. }
  932. return isSandboxed;
  933. };
  934. /**
  935. * Preprocess any special behaviors, reactions, or state changes after receiving this event.
  936. * Executes only once per event emitted, NOT once per client.
  937. * @private
  938. */
  939. var _preprocessEvent = function(event) {
  940. var element = event.target || _currentElement || null;
  941. var sourceIsSwf = event._source === "swf";
  942. delete event._source;
  943. switch (event.type) {
  944. case "error":
  945. var isSandboxed = event.name === "flash-sandboxed" || _getSandboxStatusFromErrorEvent(event);
  946. if (typeof isSandboxed === "boolean") {
  947. _flashState.sandboxed = isSandboxed;
  948. }
  949. if (_flashStateErrorNames.indexOf(event.name) !== -1) {
  950. _extend(_flashState, {
  951. disabled: event.name === "flash-disabled",
  952. outdated: event.name === "flash-outdated",
  953. unavailable: event.name === "flash-unavailable",
  954. degraded: event.name === "flash-degraded",
  955. deactivated: event.name === "flash-deactivated",
  956. overdue: event.name === "flash-overdue",
  957. ready: false
  958. });
  959. } else if (event.name === "version-mismatch") {
  960. _zcSwfVersion = event.swfVersion;
  961. _extend(_flashState, {
  962. disabled: false,
  963. outdated: false,
  964. unavailable: false,
  965. degraded: false,
  966. deactivated: false,
  967. overdue: false,
  968. ready: false
  969. });
  970. }
  971. _clearTimeoutsAndPolling();
  972. break;
  973. case "ready":
  974. _zcSwfVersion = event.swfVersion;
  975. var wasDeactivated = _flashState.deactivated === true;
  976. _extend(_flashState, {
  977. disabled: false,
  978. outdated: false,
  979. sandboxed: false,
  980. unavailable: false,
  981. degraded: false,
  982. deactivated: false,
  983. overdue: wasDeactivated,
  984. ready: !wasDeactivated
  985. });
  986. _clearTimeoutsAndPolling();
  987. break;
  988. case "beforecopy":
  989. _copyTarget = element;
  990. break;
  991. case "copy":
  992. var textContent, htmlContent, targetEl = event.relatedTarget;
  993. if (!(_clipData["text/html"] || _clipData["text/plain"]) && targetEl && (htmlContent = targetEl.value || targetEl.outerHTML || targetEl.innerHTML) && (textContent = targetEl.value || targetEl.textContent || targetEl.innerText)) {
  994. event.clipboardData.clearData();
  995. event.clipboardData.setData("text/plain", textContent);
  996. if (htmlContent !== textContent) {
  997. event.clipboardData.setData("text/html", htmlContent);
  998. }
  999. } else if (!_clipData["text/plain"] && event.target && (textContent = event.target.getAttribute("data-clipboard-text"))) {
  1000. event.clipboardData.clearData();
  1001. event.clipboardData.setData("text/plain", textContent);
  1002. }
  1003. break;
  1004. case "aftercopy":
  1005. _queueEmitClipboardErrors(event);
  1006. ZeroClipboard.clearData();
  1007. if (element && element !== _safeActiveElement() && element.focus) {
  1008. element.focus();
  1009. }
  1010. break;
  1011. case "_mouseover":
  1012. ZeroClipboard.focus(element);
  1013. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1014. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  1015. _fireMouseEvent(_extend({}, event, {
  1016. type: "mouseenter",
  1017. bubbles: false,
  1018. cancelable: false
  1019. }));
  1020. }
  1021. _fireMouseEvent(_extend({}, event, {
  1022. type: "mouseover"
  1023. }));
  1024. }
  1025. break;
  1026. case "_mouseout":
  1027. ZeroClipboard.blur();
  1028. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1029. if (element && element !== event.relatedTarget && !_containedBy(event.relatedTarget, element)) {
  1030. _fireMouseEvent(_extend({}, event, {
  1031. type: "mouseleave",
  1032. bubbles: false,
  1033. cancelable: false
  1034. }));
  1035. }
  1036. _fireMouseEvent(_extend({}, event, {
  1037. type: "mouseout"
  1038. }));
  1039. }
  1040. break;
  1041. case "_mousedown":
  1042. _addClass(element, _globalConfig.activeClass);
  1043. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1044. _fireMouseEvent(_extend({}, event, {
  1045. type: event.type.slice(1)
  1046. }));
  1047. }
  1048. break;
  1049. case "_mouseup":
  1050. _removeClass(element, _globalConfig.activeClass);
  1051. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1052. _fireMouseEvent(_extend({}, event, {
  1053. type: event.type.slice(1)
  1054. }));
  1055. }
  1056. break;
  1057. case "_click":
  1058. _copyTarget = null;
  1059. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1060. _fireMouseEvent(_extend({}, event, {
  1061. type: event.type.slice(1)
  1062. }));
  1063. }
  1064. break;
  1065. case "_mousemove":
  1066. if (_globalConfig.bubbleEvents === true && sourceIsSwf) {
  1067. _fireMouseEvent(_extend({}, event, {
  1068. type: event.type.slice(1)
  1069. }));
  1070. }
  1071. break;
  1072. }
  1073. if (/^_(?:click|mouse(?:over|out|down|up|move))$/.test(event.type)) {
  1074. return true;
  1075. }
  1076. };
  1077. /**
  1078. * Check an "aftercopy" event for clipboard errors and emit a corresponding "error" event.
  1079. * @private
  1080. */
  1081. var _queueEmitClipboardErrors = function(aftercopyEvent) {
  1082. if (aftercopyEvent.errors && aftercopyEvent.errors.length > 0) {
  1083. var errorEvent = _deepCopy(aftercopyEvent);
  1084. _extend(errorEvent, {
  1085. type: "error",
  1086. name: "clipboard-error"
  1087. });
  1088. delete errorEvent.success;
  1089. _setTimeout(function() {
  1090. ZeroClipboard.emit(errorEvent);
  1091. }, 0);
  1092. }
  1093. };
  1094. /**
  1095. * Dispatch a synthetic MouseEvent.
  1096. *
  1097. * @returns `undefined`
  1098. * @private
  1099. */
  1100. var _fireMouseEvent = function(event) {
  1101. if (!(event && typeof event.type === "string" && event)) {
  1102. return;
  1103. }
  1104. var e, target = event.target || null, doc = target && target.ownerDocument || _document, defaults = {
  1105. view: doc.defaultView || _window,
  1106. canBubble: true,
  1107. cancelable: true,
  1108. detail: event.type === "click" ? 1 : 0,
  1109. button: typeof event.which === "number" ? event.which - 1 : typeof event.button === "number" ? event.button : doc.createEvent ? 0 : 1
  1110. }, args = _extend(defaults, event);
  1111. if (!target) {
  1112. return;
  1113. }
  1114. if (doc.createEvent && target.dispatchEvent) {
  1115. 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 ];
  1116. e = doc.createEvent("MouseEvents");
  1117. if (e.initMouseEvent) {
  1118. e.initMouseEvent.apply(e, args);
  1119. e._source = "js";
  1120. target.dispatchEvent(e);
  1121. }
  1122. }
  1123. };
  1124. /**
  1125. * Continuously poll the DOM until either:
  1126. * (a) the fallback content becomes visible, or
  1127. * (b) we receive an event from SWF (handled elsewhere)
  1128. *
  1129. * IMPORTANT:
  1130. * This is NOT a necessary check but it can result in significantly faster
  1131. * detection of bad `swfPath` configuration and/or network/server issues [in
  1132. * supported browsers] than waiting for the entire `flashLoadTimeout` duration
  1133. * to elapse before detecting that the SWF cannot be loaded. The detection
  1134. * duration can be anywhere from 10-30 times faster [in supported browsers] by
  1135. * using this approach.
  1136. *
  1137. * @returns `undefined`
  1138. * @private
  1139. */
  1140. var _watchForSwfFallbackContent = function() {
  1141. var maxWait = _globalConfig.flashLoadTimeout;
  1142. if (typeof maxWait === "number" && maxWait >= 0) {
  1143. var pollWait = Math.min(1e3, maxWait / 10);
  1144. var fallbackContentId = _globalConfig.swfObjectId + "_fallbackContent";
  1145. _swfFallbackCheckInterval = _setInterval(function() {
  1146. var el = _document.getElementById(fallbackContentId);
  1147. if (_isElementVisible(el)) {
  1148. _clearTimeoutsAndPolling();
  1149. _flashState.deactivated = null;
  1150. ZeroClipboard.emit({
  1151. type: "error",
  1152. name: "swf-not-found"
  1153. });
  1154. }
  1155. }, pollWait);
  1156. }
  1157. };
  1158. /**
  1159. * Create the HTML bridge element to embed the Flash object into.
  1160. * @private
  1161. */
  1162. var _createHtmlBridge = function() {
  1163. var container = _document.createElement("div");
  1164. container.id = _globalConfig.containerId;
  1165. container.className = _globalConfig.containerClass;
  1166. container.style.position = "absolute";
  1167. container.style.left = "0px";
  1168. container.style.top = "-9999px";
  1169. container.style.width = "1px";
  1170. container.style.height = "1px";
  1171. container.style.zIndex = "" + _getSafeZIndex(_globalConfig.zIndex);
  1172. return container;
  1173. };
  1174. /**
  1175. * Get the HTML element container that wraps the Flash bridge object/element.
  1176. * @private
  1177. */
  1178. var _getHtmlBridge = function(flashBridge) {
  1179. var htmlBridge = flashBridge && flashBridge.parentNode;
  1180. while (htmlBridge && htmlBridge.nodeName === "OBJECT" && htmlBridge.parentNode) {
  1181. htmlBridge = htmlBridge.parentNode;
  1182. }
  1183. return htmlBridge || null;
  1184. };
  1185. /**
  1186. * Create the SWF object.
  1187. *
  1188. * @returns The SWF object reference.
  1189. * @private
  1190. */
  1191. var _embedSwf = function() {
  1192. var len, flashBridge = _flashState.bridge, container = _getHtmlBridge(flashBridge);
  1193. if (!flashBridge) {
  1194. var allowScriptAccess = _determineScriptAccess(_window.location.host, _globalConfig);
  1195. var allowNetworking = allowScriptAccess === "never" ? "none" : "all";
  1196. var flashvars = _vars(_extend({
  1197. jsVersion: ZeroClipboard.version
  1198. }, _globalConfig));
  1199. var swfUrl = _globalConfig.swfPath + _cacheBust(_globalConfig.swfPath, _globalConfig);
  1200. container = _createHtmlBridge();
  1201. var divToBeReplaced = _document.createElement("div");
  1202. container.appendChild(divToBeReplaced);
  1203. _document.body.appendChild(container);
  1204. var tmpDiv = _document.createElement("div");
  1205. var usingActiveX = _flashState.pluginType === "activex";
  1206. tmpDiv.innerHTML = '<object id="' + _globalConfig.swfObjectId + '" name="' + _globalConfig.swfObjectId + '" ' + 'width="100%" height="100%" ' + (usingActiveX ? 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"' : 'type="application/x-shockwave-flash" data="' + swfUrl + '"') + ">" + (usingActiveX ? '<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 + '"/>' + '<div id="' + _globalConfig.swfObjectId + '_fallbackContent">&nbsp;</div>' + "</object>";
  1207. flashBridge = tmpDiv.firstChild;
  1208. tmpDiv = null;
  1209. _unwrap(flashBridge).ZeroClipboard = ZeroClipboard;
  1210. container.replaceChild(flashBridge, divToBeReplaced);
  1211. _watchForSwfFallbackContent();
  1212. }
  1213. if (!flashBridge) {
  1214. flashBridge = _document[_globalConfig.swfObjectId];
  1215. if (flashBridge && (len = flashBridge.length)) {
  1216. flashBridge = flashBridge[len - 1];
  1217. }
  1218. if (!flashBridge && container) {
  1219. flashBridge = container.firstChild;
  1220. }
  1221. }
  1222. _flashState.bridge = flashBridge || null;
  1223. return flashBridge;
  1224. };
  1225. /**
  1226. * Destroy the SWF object.
  1227. * @private
  1228. */
  1229. var _unembedSwf = function() {
  1230. var flashBridge = _flashState.bridge;
  1231. if (flashBridge) {
  1232. var htmlBridge = _getHtmlBridge(flashBridge);
  1233. if (htmlBridge) {
  1234. if (_flashState.pluginType === "activex" && "readyState" in flashBridge) {
  1235. flashBridge.style.display = "none";
  1236. (function removeSwfFromIE() {
  1237. if (flashBridge.readyState === 4) {
  1238. for (var prop in flashBridge) {
  1239. if (typeof flashBridge[prop] === "function") {
  1240. flashBridge[prop] = null;
  1241. }
  1242. }
  1243. if (flashBridge.parentNode) {
  1244. flashBridge.parentNode.removeChild(flashBridge);
  1245. }
  1246. if (htmlBridge.parentNode) {
  1247. htmlBridge.parentNode.removeChild(htmlBridge);
  1248. }
  1249. } else {
  1250. _setTimeout(removeSwfFromIE, 10);
  1251. }
  1252. })();
  1253. } else {
  1254. if (flashBridge.parentNode) {
  1255. flashBridge.parentNode.removeChild(flashBridge);
  1256. }
  1257. if (htmlBridge.parentNode) {
  1258. htmlBridge.parentNode.removeChild(htmlBridge);
  1259. }
  1260. }
  1261. }
  1262. _clearTimeoutsAndPolling();
  1263. _flashState.ready = null;
  1264. _flashState.bridge = null;
  1265. _flashState.deactivated = null;
  1266. _zcSwfVersion = undefined;
  1267. }
  1268. };
  1269. /**
  1270. * Map the data format names of the "clipData" to Flash-friendly names.
  1271. *
  1272. * @returns A new transformed object.
  1273. * @private
  1274. */
  1275. var _mapClipDataToFlash = function(clipData) {
  1276. var newClipData = {}, formatMap = {};
  1277. if (!(typeof clipData === "object" && clipData)) {
  1278. return;
  1279. }
  1280. for (var dataFormat in clipData) {
  1281. if (dataFormat && _hasOwn.call(clipData, dataFormat) && typeof clipData[dataFormat] === "string" && clipData[dataFormat]) {
  1282. switch (dataFormat.toLowerCase()) {
  1283. case "text/plain":
  1284. case "text":
  1285. case "air:text":
  1286. case "flash:text":
  1287. newClipData.text = clipData[dataFormat];
  1288. formatMap.text = dataFormat;
  1289. break;
  1290. case "text/html":
  1291. case "html":
  1292. case "air:html":
  1293. case "flash:html":
  1294. newClipData.html = clipData[dataFormat];
  1295. formatMap.html = dataFormat;
  1296. break;
  1297. case "application/rtf":
  1298. case "text/rtf":
  1299. case "rtf":
  1300. case "richtext":
  1301. case "air:rtf":
  1302. case "flash:rtf":
  1303. newClipData.rtf = clipData[dataFormat];
  1304. formatMap.rtf = dataFormat;
  1305. break;
  1306. default:
  1307. break;
  1308. }
  1309. }
  1310. }
  1311. return {
  1312. data: newClipData,
  1313. formatMap: formatMap
  1314. };
  1315. };
  1316. /**
  1317. * Map the data format names from Flash-friendly names back to their original "clipData" names (via a format mapping).
  1318. *
  1319. * @returns A new transformed object.
  1320. * @private
  1321. */
  1322. var _mapClipResultsFromFlash = function(clipResults, formatMap) {
  1323. if (!(typeof clipResults === "object" && clipResults && typeof formatMap === "object" && formatMap)) {
  1324. return clipResults;
  1325. }
  1326. var newResults = {};
  1327. for (var prop in clipResults) {
  1328. if (_hasOwn.call(clipResults, prop)) {
  1329. if (prop === "errors") {
  1330. newResults[prop] = clipResults[prop] ? clipResults[prop].slice() : [];
  1331. for (var i = 0, len = newResults[prop].length; i < len; i++) {
  1332. newResults[prop][i].format = formatMap[newResults[prop][i].format];
  1333. }
  1334. } else if (prop !== "success" && prop !== "data") {
  1335. newResults[prop] = clipResults[prop];
  1336. } else {
  1337. newResults[prop] = {};
  1338. var tmpHash = clipResults[prop];
  1339. for (var dataFormat in tmpHash) {
  1340. if (dataFormat && _hasOwn.call(tmpHash, dataFormat) && _hasOwn.call(formatMap, dataFormat)) {
  1341. newResults[prop][formatMap[dataFormat]] = tmpHash[dataFormat];
  1342. }
  1343. }
  1344. }
  1345. }
  1346. }
  1347. return newResults;
  1348. };
  1349. /**
  1350. * Will look at a path, and will create a "?noCache={time}" or "&noCache={time}"
  1351. * query param string to return. Does NOT append that string to the original path.
  1352. * This is useful because ExternalInterface often breaks when a Flash SWF is cached.
  1353. *
  1354. * @returns The `noCache` query param with necessary "?"/"&" prefix.
  1355. * @private
  1356. */
  1357. var _cacheBust = function(path, options) {
  1358. var cacheBust = options == null || options && options.cacheBust === true;
  1359. if (cacheBust) {
  1360. return (path.indexOf("?") === -1 ? "?" : "&") + "noCache=" + _now();
  1361. } else {
  1362. return "";
  1363. }
  1364. };
  1365. /**
  1366. * Creates a query string for the FlashVars param.
  1367. * Does NOT include the cache-busting query param.
  1368. *
  1369. * @returns FlashVars query string
  1370. * @private
  1371. */
  1372. var _vars = function(options) {
  1373. var i, len, domain, domains, str = "", trustedOriginsExpanded = [];
  1374. if (options.trustedDomains) {
  1375. if (typeof options.trustedDomains === "string") {
  1376. domains = [ options.trustedDomains ];
  1377. } else if (typeof options.trustedDomains === "object" && "length" in options.trustedDomains) {
  1378. domains = options.trustedDomains;
  1379. }
  1380. }
  1381. if (domains && domains.length) {
  1382. for (i = 0, len = domains.length; i < len; i++) {
  1383. if (_hasOwn.call(domains, i) && domains[i] && typeof domains[i] === "string") {
  1384. domain = _extractDomain(domains[i]);
  1385. if (!domain) {
  1386. continue;
  1387. }
  1388. if (domain === "*") {
  1389. trustedOriginsExpanded.length = 0;
  1390. trustedOriginsExpanded.push(domain);
  1391. break;
  1392. }
  1393. trustedOriginsExpanded.push.apply(trustedOriginsExpanded, [ domain, "//" + domain, _window.location.protocol + "//" + domain ]);
  1394. }
  1395. }
  1396. }
  1397. if (trustedOriginsExpanded.length) {
  1398. str += "trustedOrigins=" + _encodeURIComponent(trustedOriginsExpanded.join(","));
  1399. }
  1400. if (options.forceEnhancedClipboard === true) {
  1401. str += (str ? "&" : "") + "forceEnhancedClipboard=true";
  1402. }
  1403. if (typeof options.swfObjectId === "string" && options.swfObjectId) {
  1404. str += (str ? "&" : "") + "swfObjectId=" + _encodeURIComponent(options.swfObjectId);
  1405. }
  1406. if (typeof options.jsVersion === "string" && options.jsVersion) {
  1407. str += (str ? "&" : "") + "jsVersion=" + _encodeURIComponent(options.jsVersion);
  1408. }
  1409. return str;
  1410. };
  1411. /**
  1412. * Extract the domain (e.g. "github.com") from an origin (e.g. "https://github.com") or
  1413. * URL (e.g. "https://github.com/zeroclipboard/zeroclipboard/").
  1414. *
  1415. * @returns the domain
  1416. * @private
  1417. */
  1418. var _extractDomain = function(originOrUrl) {
  1419. if (originOrUrl == null || originOrUrl === "") {
  1420. return null;
  1421. }
  1422. originOrUrl = originOrUrl.replace(/^\s+|\s+$/g, "");
  1423. if (originOrUrl === "") {
  1424. return null;
  1425. }
  1426. var protocolIndex = originOrUrl.indexOf("//");
  1427. originOrUrl = protocolIndex === -1 ? originOrUrl : originOrUrl.slice(protocolIndex + 2);
  1428. var pathIndex = originOrUrl.indexOf("/");
  1429. originOrUrl = pathIndex === -1 ? originOrUrl : protocolIndex === -1 || pathIndex === 0 ? null : originOrUrl.slice(0, pathIndex);
  1430. if (originOrUrl && originOrUrl.slice(-4).toLowerCase() === ".swf") {
  1431. return null;
  1432. }
  1433. return originOrUrl || null;
  1434. };
  1435. /**
  1436. * Set `allowScriptAccess` based on `trustedDomains` and `window.location.host` vs. `swfPath`.
  1437. *
  1438. * @returns The appropriate script access level.
  1439. * @private
  1440. */
  1441. var _determineScriptAccess = function() {
  1442. var _extractAllDomains = function(origins) {
  1443. var i, len, tmp, resultsArray = [];
  1444. if (typeof origins === "string") {
  1445. origins = [ origins ];
  1446. }
  1447. if (!(typeof origins === "object" && origins && typeof origins.length === "number")) {
  1448. return resultsArray;
  1449. }
  1450. for (i = 0, len = origins.length; i < len; i++) {
  1451. if (_hasOwn.call(origins, i) && (tmp = _extractDomain(origins[i]))) {
  1452. if (tmp === "*") {
  1453. resultsArray.length = 0;
  1454. resultsArray.push("*");
  1455. break;
  1456. }
  1457. if (resultsArray.indexOf(tmp) === -1) {
  1458. resultsArray.push(tmp);
  1459. }
  1460. }
  1461. }
  1462. return resultsArray;
  1463. };
  1464. return function(currentDomain, configOptions) {
  1465. var swfDomain = _extractDomain(configOptions.swfPath);
  1466. if (swfDomain === null) {
  1467. swfDomain = currentDomain;
  1468. }
  1469. var trustedDomains = _extractAllDomains(configOptions.trustedDomains);
  1470. var len = trustedDomains.length;
  1471. if (len > 0) {
  1472. if (len === 1 && trustedDomains[0] === "*") {
  1473. return "always";
  1474. }
  1475. if (trustedDomains.indexOf(currentDomain) !== -1) {
  1476. if (len === 1 && currentDomain === swfDomain) {
  1477. return "sameDomain";
  1478. }
  1479. return "always";
  1480. }
  1481. }
  1482. return "never";
  1483. };
  1484. }();
  1485. /**
  1486. * Get the currently active/focused DOM element.
  1487. *
  1488. * @returns the currently active/focused element, or `null`
  1489. * @private
  1490. */
  1491. var _safeActiveElement = function() {
  1492. try {
  1493. return _document.activeElement;
  1494. } catch (err) {
  1495. return null;
  1496. }
  1497. };
  1498. /**
  1499. * Add a class to an element, if it doesn't already have it.
  1500. *
  1501. * @returns The element, with its new class added.
  1502. * @private
  1503. */
  1504. var _addClass = function(element, value) {
  1505. var c, cl, className, classNames = [];
  1506. if (typeof value === "string" && value) {
  1507. classNames = value.split(/\s+/);
  1508. }
  1509. if (element && element.nodeType === 1 && classNames.length > 0) {
  1510. if (element.classList) {
  1511. for (c = 0, cl = classNames.length; c < cl; c++) {
  1512. element.classList.add(classNames[c]);
  1513. }
  1514. } else if (element.hasOwnProperty("className")) {
  1515. className = " " + element.className + " ";
  1516. for (c = 0, cl = classNames.length; c < cl; c++) {
  1517. if (className.indexOf(" " + classNames[c] + " ") === -1) {
  1518. className += classNames[c] + " ";
  1519. }
  1520. }
  1521. element.className = className.replace(/^\s+|\s+$/g, "");
  1522. }
  1523. }
  1524. return element;
  1525. };
  1526. /**
  1527. * Remove a class from an element, if it has it.
  1528. *
  1529. * @returns The element, with its class removed.
  1530. * @private
  1531. */
  1532. var _removeClass = function(element, value) {
  1533. var c, cl, className, classNames = [];
  1534. if (typeof value === "string" && value) {
  1535. classNames = value.split(/\s+/);
  1536. }
  1537. if (element && element.nodeType === 1 && classNames.length > 0) {
  1538. if (element.classList && element.classList.length > 0) {
  1539. for (c = 0, cl = classNames.length; c < cl; c++) {
  1540. element.classList.remove(classNames[c]);
  1541. }
  1542. } else if (element.className) {
  1543. className = (" " + element.className + " ").replace(/[\r\n\t]/g, " ");
  1544. for (c = 0, cl = classNames.length; c < cl; c++) {
  1545. className = className.replace(" " + classNames[c] + " ", " ");
  1546. }
  1547. element.className = className.replace(/^\s+|\s+$/g, "");
  1548. }
  1549. }
  1550. return element;
  1551. };
  1552. /**
  1553. * Attempt to interpret the element's CSS styling. If `prop` is `"cursor"`,
  1554. * then we assume that it should be a hand ("pointer") cursor if the element
  1555. * is an anchor element ("a" tag).
  1556. *
  1557. * @returns The computed style property.
  1558. * @private
  1559. */
  1560. var _getStyle = function(el, prop) {
  1561. var value = _getComputedStyle(el, null).getPropertyValue(prop);
  1562. if (prop === "cursor") {
  1563. if (!value || value === "auto") {
  1564. if (el.nodeName === "A") {
  1565. return "pointer";
  1566. }
  1567. }
  1568. }
  1569. return value;
  1570. };
  1571. /**
  1572. * Get the absolutely positioned coordinates of a DOM element.
  1573. *
  1574. * @returns Object containing the element's position, width, and height.
  1575. * @private
  1576. */
  1577. var _getElementPosition = function(el) {
  1578. var pos = {
  1579. left: 0,
  1580. top: 0,
  1581. width: 0,
  1582. height: 0
  1583. };
  1584. if (el.getBoundingClientRect) {
  1585. var elRect = el.getBoundingClientRect();
  1586. var pageXOffset = _window.pageXOffset;
  1587. var pageYOffset = _window.pageYOffset;
  1588. var leftBorderWidth = _document.documentElement.clientLeft || 0;
  1589. var topBorderWidth = _document.documentElement.clientTop || 0;
  1590. var leftBodyOffset = 0;
  1591. var topBodyOffset = 0;
  1592. if (_getStyle(_document.body, "position") === "relative") {
  1593. var bodyRect = _document.body.getBoundingClientRect();
  1594. var htmlRect = _document.documentElement.getBoundingClientRect();
  1595. leftBodyOffset = bodyRect.left - htmlRect.left || 0;
  1596. topBodyOffset = bodyRect.top - htmlRect.top || 0;
  1597. }
  1598. pos.left = elRect.left + pageXOffset - leftBorderWidth - leftBodyOffset;
  1599. pos.top = elRect.top + pageYOffset - topBorderWidth - topBodyOffset;
  1600. pos.width = "width" in elRect ? elRect.width : elRect.right - elRect.left;
  1601. pos.height = "height" in elRect ? elRect.height : elRect.bottom - elRect.top;
  1602. }
  1603. return pos;
  1604. };
  1605. /**
  1606. * Determine is an element is visible somewhere within the document (page).
  1607. *
  1608. * @returns Boolean
  1609. * @private
  1610. */
  1611. var _isElementVisible = function(el) {
  1612. if (!el) {
  1613. return false;
  1614. }
  1615. var styles = _getComputedStyle(el, null);
  1616. var hasCssHeight = _parseFloat(styles.height) > 0;
  1617. var hasCssWidth = _parseFloat(styles.width) > 0;
  1618. var hasCssTop = _parseFloat(styles.top) >= 0;
  1619. var hasCssLeft = _parseFloat(styles.left) >= 0;
  1620. var cssKnows = hasCssHeight && hasCssWidth && hasCssTop && hasCssLeft;
  1621. var rect = cssKnows ? null : _getElementPosition(el);
  1622. var isVisible = styles.display !== "none" && styles.visibility !== "collapse" && (cssKnows || !!rect && (hasCssHeight || rect.height > 0) && (hasCssWidth || rect.width > 0) && (hasCssTop || rect.top >= 0) && (hasCssLeft || rect.left >= 0));
  1623. return isVisible;
  1624. };
  1625. /**
  1626. * Clear all existing timeouts and interval polling delegates.
  1627. *
  1628. * @returns `undefined`
  1629. * @private
  1630. */
  1631. var _clearTimeoutsAndPolling = function() {
  1632. _clearTimeout(_flashCheckTimeout);
  1633. _flashCheckTimeout = 0;
  1634. _clearInterval(_swfFallbackCheckInterval);
  1635. _swfFallbackCheckInterval = 0;
  1636. };
  1637. /**
  1638. * Reposition the Flash object to cover the currently activated element.
  1639. *
  1640. * @returns `undefined`
  1641. * @private
  1642. */
  1643. var _reposition = function() {
  1644. var htmlBridge;
  1645. if (_currentElement && (htmlBridge = _getHtmlBridge(_flashState.bridge))) {
  1646. var pos = _getElementPosition(_currentElement);
  1647. _extend(htmlBridge.style, {
  1648. width: pos.width + "px",
  1649. height: pos.height + "px",
  1650. top: pos.top + "px",
  1651. left: pos.left + "px",
  1652. zIndex: "" + _getSafeZIndex(_globalConfig.zIndex)
  1653. });
  1654. }
  1655. };
  1656. /**
  1657. * Sends a signal to the Flash object to display the hand cursor if `true`.
  1658. *
  1659. * @returns `undefined`
  1660. * @private
  1661. */
  1662. var _setHandCursor = function(enabled) {
  1663. if (_flashState.ready === true) {
  1664. if (_flashState.bridge && typeof _flashState.bridge.setHandCursor === "function") {
  1665. _flashState.bridge.setHandCursor(enabled);
  1666. } else {
  1667. _flashState.ready = false;
  1668. }
  1669. }
  1670. };
  1671. /**
  1672. * Get a safe value for `zIndex`
  1673. *
  1674. * @returns an integer, or "auto"
  1675. * @private
  1676. */
  1677. var _getSafeZIndex = function(val) {
  1678. if (/^(?:auto|inherit)$/.test(val)) {
  1679. return val;
  1680. }
  1681. var zIndex;
  1682. if (typeof val === "number" && !_isNaN(val)) {
  1683. zIndex = val;
  1684. } else if (typeof val === "string") {
  1685. zIndex = _getSafeZIndex(_parseInt(val, 10));
  1686. }
  1687. return typeof zIndex === "number" ? zIndex : "auto";
  1688. };
  1689. /**
  1690. * Attempt to detect if ZeroClipboard is executing inside of a sandboxed iframe.
  1691. * If it is, Flash Player cannot be used, so ZeroClipboard is dead in the water.
  1692. *
  1693. * @see {@link http://lists.w3.org/Archives/Public/public-whatwg-archive/2014Dec/0002.html}
  1694. * @see {@link https://github.com/zeroclipboard/zeroclipboard/issues/511}
  1695. * @see {@link http://zeroclipboard.org/test-iframes.html}
  1696. *
  1697. * @returns `true` (is sandboxed), `false` (is not sandboxed), or `null` (uncertain)
  1698. * @private
  1699. */
  1700. var _detectSandbox = function(doNotReassessFlashSupport) {
  1701. var effectiveScriptOrigin, frame, frameError, previousState = _flashState.sandboxed, isSandboxed = null;
  1702. doNotReassessFlashSupport = doNotReassessFlashSupport === true;
  1703. if (_pageIsFramed === false) {
  1704. isSandboxed = false;
  1705. } else {
  1706. try {
  1707. frame = window.frameElement || null;
  1708. } catch (e) {
  1709. frameError = {
  1710. name: e.name,
  1711. message: e.message
  1712. };
  1713. }
  1714. if (frame && frame.nodeType === 1 && frame.nodeName === "IFRAME") {
  1715. try {
  1716. isSandboxed = frame.hasAttribute("sandbox");
  1717. } catch (e) {
  1718. isSandboxed = null;
  1719. }
  1720. } else {
  1721. try {
  1722. effectiveScriptOrigin = document.domain || null;
  1723. } catch (e) {
  1724. effectiveScriptOrigin = null;
  1725. }
  1726. if (effectiveScriptOrigin === null || frameError && frameError.name === "SecurityError" && /(^|[\s\(\[@])sandbox(es|ed|ing|[\s\.,!\)\]@]|$)/.test(frameError.message.toLowerCase())) {
  1727. isSandboxed = true;
  1728. }
  1729. }
  1730. }
  1731. _flashState.sandboxed = isSandboxed;
  1732. if (previousState !== isSandboxed && !doNotReassessFlashSupport) {
  1733. _detectFlashSupport(_ActiveXObject);
  1734. }
  1735. return isSandboxed;
  1736. };
  1737. /**
  1738. * Detect the Flash Player status, version, and plugin type.
  1739. *
  1740. * @see {@link https://code.google.com/p/doctype-mirror/wiki/ArticleDetectFlash#The_code}
  1741. * @see {@link http://stackoverflow.com/questions/12866060/detecting-pepper-ppapi-flash-with-javascript}
  1742. *
  1743. * @returns `undefined`
  1744. * @private
  1745. */
  1746. var _detectFlashSupport = function(ActiveXObject) {
  1747. var plugin, ax, mimeType, hasFlash = false, isActiveX = false, isPPAPI = false, flashVersion = "";
  1748. /**
  1749. * Derived from Apple's suggested sniffer.
  1750. * @param {String} desc e.g. "Shockwave Flash 7.0 r61"
  1751. * @returns {String} "7.0.61"
  1752. * @private
  1753. */
  1754. function parseFlashVersion(desc) {
  1755. var matches = desc.match(/[\d]+/g);
  1756. matches.length = 3;
  1757. return matches.join(".");
  1758. }
  1759. function isPepperFlash(flashPlayerFileName) {
  1760. return !!flashPlayerFileName && (flashPlayerFileName = flashPlayerFileName.toLowerCase()) && (/^(pepflashplayer\.dll|libpepflashplayer\.so|pepperflashplayer\.plugin)$/.test(flashPlayerFileName) || flashPlayerFileName.slice(-13) === "chrome.plugin");
  1761. }
  1762. function inspectPlugin(plugin) {
  1763. if (plugin) {
  1764. hasFlash = true;
  1765. if (plugin.version) {
  1766. flashVersion = parseFlashVersion(plugin.version);
  1767. }
  1768. if (!flashVersion && plugin.description) {
  1769. flashVersion = parseFlashVersion(plugin.description);
  1770. }
  1771. if (plugin.filename) {
  1772. isPPAPI = isPepperFlash(plugin.filename);
  1773. }
  1774. }
  1775. }
  1776. if (_navigator.plugins && _navigator.plugins.length) {
  1777. plugin = _navigator.plugins["Shockwave Flash"];
  1778. inspectPlugin(plugin);
  1779. if (_navigator.plugins["Shockwave Flash 2.0"]) {
  1780. hasFlash = true;
  1781. flashVersion = "2.0.0.11";
  1782. }
  1783. } else if (_navigator.mimeTypes && _navigator.mimeTypes.length) {
  1784. mimeType = _navigator.mimeTypes["application/x-shockwave-flash"];
  1785. plugin = mimeType && mimeType.enabledPlugin;
  1786. inspectPlugin(plugin);
  1787. } else if (typeof ActiveXObject !== "undefined") {
  1788. isActiveX = true;
  1789. try {
  1790. ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
  1791. hasFlash = true;
  1792. flashVersion = parseFlashVersion(ax.GetVariable("$version"));
  1793. } catch (e1) {
  1794. try {
  1795. ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
  1796. hasFlash = true;
  1797. flashVersion = "6.0.21";
  1798. } catch (e2) {
  1799. try {
  1800. ax = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
  1801. hasFlash = true;
  1802. flashVersion = parseFlashVersion(ax.GetVariable("$version"));
  1803. } catch (e3) {
  1804. isActiveX = false;
  1805. }
  1806. }
  1807. }
  1808. }
  1809. _flashState.disabled = hasFlash !== true;
  1810. _flashState.outdated = flashVersion && _parseFloat(flashVersion) < _parseFloat(_minimumFlashVersion);
  1811. _flashState.version = flashVersion || "0.0.0";
  1812. _flashState.pluginType = isPPAPI ? "pepper" : isActiveX ? "activex" : hasFlash ? "netscape" : "unknown";
  1813. };
  1814. /**
  1815. * Invoke the Flash detection algorithms immediately upon inclusion so we're not waiting later.
  1816. */
  1817. _detectFlashSupport(_ActiveXObject);
  1818. /**
  1819. * Always assess the `sandboxed` state of the page at important Flash-related moments.
  1820. */
  1821. _detectSandbox(true);
  1822. /**
  1823. * A shell constructor for `ZeroClipboard` client instances.
  1824. *
  1825. * @constructor
  1826. */
  1827. var ZeroClipboard = function() {
  1828. if (!(this instanceof ZeroClipboard)) {
  1829. return new ZeroClipboard();
  1830. }
  1831. if (typeof ZeroClipboard._createClient === "function") {
  1832. ZeroClipboard._createClient.apply(this, _args(arguments));
  1833. }
  1834. };
  1835. /**
  1836. * The ZeroClipboard library's version number.
  1837. *
  1838. * @static
  1839. * @readonly
  1840. * @property {string}
  1841. */
  1842. _defineProperty(ZeroClipboard, "version", {
  1843. value: "2.2.0",
  1844. writable: false,
  1845. configurable: true,
  1846. enumerable: true
  1847. });
  1848. /**
  1849. * Update or get a copy of the ZeroClipboard global configuration.
  1850. * Returns a copy of the current/updated configuration.
  1851. *
  1852. * @returns Object
  1853. * @static
  1854. */
  1855. ZeroClipboard.config = function() {
  1856. return _config.apply(this, _args(arguments));
  1857. };
  1858. /**
  1859. * Diagnostic method that describes the state of the browser, Flash Player, and ZeroClipboard.
  1860. *
  1861. * @returns Object
  1862. * @static
  1863. */
  1864. ZeroClipboard.state = function() {
  1865. return _state.apply(this, _args(arguments));
  1866. };
  1867. /**
  1868. * Check if Flash is unusable for any reason: disabled, outdated, deactivated, etc.
  1869. *
  1870. * @returns Boolean
  1871. * @static
  1872. */
  1873. ZeroClipboard.isFlashUnusable = function() {
  1874. return _isFlashUnusable.apply(this, _args(arguments));
  1875. };
  1876. /**
  1877. * Register an event listener.
  1878. *
  1879. * @returns `ZeroClipboard`
  1880. * @static
  1881. */
  1882. ZeroClipboard.on = function() {
  1883. return _on.apply(this, _args(arguments));
  1884. };
  1885. /**
  1886. * Unregister an event listener.
  1887. * If no `listener` function/object is provided, it will unregister all listeners for the provided `eventType`.
  1888. * If no `eventType` is provided, it will unregister all listeners for every event type.
  1889. *
  1890. * @returns `ZeroClipboard`
  1891. * @static
  1892. */
  1893. ZeroClipboard.off = function() {
  1894. return _off.apply(this, _args(arguments));
  1895. };
  1896. /**
  1897. * Retrieve event listeners for an `eventType`.
  1898. * If no `eventType` is provided, it will retrieve all listeners for every event type.
  1899. *
  1900. * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null`
  1901. */
  1902. ZeroClipboard.handlers = function() {
  1903. return _listeners.apply(this, _args(arguments));
  1904. };
  1905. /**
  1906. * Event emission receiver from the Flash object, forwarding to any registered JavaScript event listeners.
  1907. *
  1908. * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`.
  1909. * @static
  1910. */
  1911. ZeroClipboard.emit = function() {
  1912. return _emit.apply(this, _args(arguments));
  1913. };
  1914. /**
  1915. * Create and embed the Flash object.
  1916. *
  1917. * @returns The Flash object
  1918. * @static
  1919. */
  1920. ZeroClipboard.create = function() {
  1921. return _create.apply(this, _args(arguments));
  1922. };
  1923. /**
  1924. * Self-destruct and clean up everything, including the embedded Flash object.
  1925. *
  1926. * @returns `undefined`
  1927. * @static
  1928. */
  1929. ZeroClipboard.destroy = function() {
  1930. return _destroy.apply(this, _args(arguments));
  1931. };
  1932. /**
  1933. * Set the pending data for clipboard injection.
  1934. *
  1935. * @returns `undefined`
  1936. * @static
  1937. */
  1938. ZeroClipboard.setData = function() {
  1939. return _setData.apply(this, _args(arguments));
  1940. };
  1941. /**
  1942. * Clear the pending data for clipboard injection.
  1943. * If no `format` is provided, all pending data formats will be cleared.
  1944. *
  1945. * @returns `undefined`
  1946. * @static
  1947. */
  1948. ZeroClipboard.clearData = function() {
  1949. return _clearData.apply(this, _args(arguments));
  1950. };
  1951. /**
  1952. * Get a copy of the pending data for clipboard injection.
  1953. * If no `format` is provided, a copy of ALL pending data formats will be returned.
  1954. *
  1955. * @returns `String` or `Object`
  1956. * @static
  1957. */
  1958. ZeroClipboard.getData = function() {
  1959. return _getData.apply(this, _args(arguments));
  1960. };
  1961. /**
  1962. * Sets the current HTML object that the Flash object should overlay. This will put the global
  1963. * Flash object on top of the current element; depending on the setup, this may also set the
  1964. * pending clipboard text data as well as the Flash object's wrapping element's title attribute
  1965. * based on the underlying HTML element and ZeroClipboard configuration.
  1966. *
  1967. * @returns `undefined`
  1968. * @static
  1969. */
  1970. ZeroClipboard.focus = ZeroClipboard.activate = function() {
  1971. return _focus.apply(this, _args(arguments));
  1972. };
  1973. /**
  1974. * Un-overlays the Flash object. This will put the global Flash object off-screen; depending on
  1975. * the setup, this may also unset the Flash object's wrapping element's title attribute based on
  1976. * the underlying HTML element and ZeroClipboard configuration.
  1977. *
  1978. * @returns `undefined`
  1979. * @static
  1980. */
  1981. ZeroClipboard.blur = ZeroClipboard.deactivate = function() {
  1982. return _blur.apply(this, _args(arguments));
  1983. };
  1984. /**
  1985. * Returns the currently focused/"activated" HTML element that the Flash object is wrapping.
  1986. *
  1987. * @returns `HTMLElement` or `null`
  1988. * @static
  1989. */
  1990. ZeroClipboard.activeElement = function() {
  1991. return _activeElement.apply(this, _args(arguments));
  1992. };
  1993. /**
  1994. * Keep track of the ZeroClipboard client instance counter.
  1995. */
  1996. var _clientIdCounter = 0;
  1997. /**
  1998. * Keep track of the state of the client instances.
  1999. *
  2000. * Entry structure:
  2001. * _clientMeta[client.id] = {
  2002. * instance: client,
  2003. * elements: [],
  2004. * handlers: {}
  2005. * };
  2006. */
  2007. var _clientMeta = {};
  2008. /**
  2009. * Keep track of the ZeroClipboard clipped elements counter.
  2010. */
  2011. var _elementIdCounter = 0;
  2012. /**
  2013. * Keep track of the state of the clipped element relationships to clients.
  2014. *
  2015. * Entry structure:
  2016. * _elementMeta[element.zcClippingId] = [client1.id, client2.id];
  2017. */
  2018. var _elementMeta = {};
  2019. /**
  2020. * Keep track of the state of the mouse event handlers for clipped elements.
  2021. *
  2022. * Entry structure:
  2023. * _mouseHandlers[element.zcClippingId] = {
  2024. * mouseover: function(event) {},
  2025. * mouseout: function(event) {},
  2026. * mouseenter: function(event) {},
  2027. * mouseleave: function(event) {},
  2028. * mousemove: function(event) {}
  2029. * };
  2030. */
  2031. var _mouseHandlers = {};
  2032. /**
  2033. * Extending the ZeroClipboard configuration defaults for the Client module.
  2034. */
  2035. _extend(_globalConfig, {
  2036. autoActivate: true
  2037. });
  2038. /**
  2039. * The real constructor for `ZeroClipboard` client instances.
  2040. * @private
  2041. */
  2042. var _clientConstructor = function(elements) {
  2043. var client = this;
  2044. client.id = "" + _clientIdCounter++;
  2045. _clientMeta[client.id] = {
  2046. instance: client,
  2047. elements: [],
  2048. handlers: {}
  2049. };
  2050. if (elements) {
  2051. client.clip(elements);
  2052. }
  2053. ZeroClipboard.on("*", function(event) {
  2054. return client.emit(event);
  2055. });
  2056. ZeroClipboard.on("destroy", function() {
  2057. client.destroy();
  2058. });
  2059. ZeroClipboard.create();
  2060. };
  2061. /**
  2062. * The underlying implementation of `ZeroClipboard.Client.prototype.on`.
  2063. * @private
  2064. */
  2065. var _clientOn = function(eventType, listener) {
  2066. var i, len, events, added = {}, meta = _clientMeta[this.id], handlers = meta && meta.handlers;
  2067. if (!meta) {
  2068. throw new Error("Attempted to add new listener(s) to a destroyed ZeroClipboard client instance");
  2069. }
  2070. if (typeof eventType === "string" && eventType) {
  2071. events = eventType.toLowerCase().split(/\s+/);
  2072. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  2073. for (i in eventType) {
  2074. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  2075. this.on(i, eventType[i]);
  2076. }
  2077. }
  2078. }
  2079. if (events && events.length) {
  2080. for (i = 0, len = events.length; i < len; i++) {
  2081. eventType = events[i].replace(/^on/, "");
  2082. added[eventType] = true;
  2083. if (!handlers[eventType]) {
  2084. handlers[eventType] = [];
  2085. }
  2086. handlers[eventType].push(listener);
  2087. }
  2088. if (added.ready && _flashState.ready) {
  2089. this.emit({
  2090. type: "ready",
  2091. client: this
  2092. });
  2093. }
  2094. if (added.error) {
  2095. for (i = 0, len = _flashStateErrorNames.length; i < len; i++) {
  2096. if (_flashState[_flashStateErrorNames[i].replace(/^flash-/, "")]) {
  2097. this.emit({
  2098. type: "error",
  2099. name: _flashStateErrorNames[i],
  2100. client: this
  2101. });
  2102. break;
  2103. }
  2104. }
  2105. if (_zcSwfVersion !== undefined && ZeroClipboard.version !== _zcSwfVersion) {
  2106. this.emit({
  2107. type: "error",
  2108. name: "version-mismatch",
  2109. jsVersion: ZeroClipboard.version,
  2110. swfVersion: _zcSwfVersion
  2111. });
  2112. }
  2113. }
  2114. }
  2115. return this;
  2116. };
  2117. /**
  2118. * The underlying implementation of `ZeroClipboard.Client.prototype.off`.
  2119. * @private
  2120. */
  2121. var _clientOff = function(eventType, listener) {
  2122. var i, len, foundIndex, events, perEventHandlers, meta = _clientMeta[this.id], handlers = meta && meta.handlers;
  2123. if (!handlers) {
  2124. return this;
  2125. }
  2126. if (arguments.length === 0) {
  2127. events = _keys(handlers);
  2128. } else if (typeof eventType === "string" && eventType) {
  2129. events = eventType.split(/\s+/);
  2130. } else if (typeof eventType === "object" && eventType && typeof listener === "undefined") {
  2131. for (i in eventType) {
  2132. if (_hasOwn.call(eventType, i) && typeof i === "string" && i && typeof eventType[i] === "function") {
  2133. this.off(i, eventType[i]);
  2134. }
  2135. }
  2136. }
  2137. if (events && events.length) {
  2138. for (i = 0, len = events.length; i < len; i++) {
  2139. eventType = events[i].toLowerCase().replace(/^on/, "");
  2140. perEventHandlers = handlers[eventType];
  2141. if (perEventHandlers && perEventHandlers.length) {
  2142. if (listener) {
  2143. foundIndex = perEventHandlers.indexOf(listener);
  2144. while (foundIndex !== -1) {
  2145. perEventHandlers.splice(foundIndex, 1);
  2146. foundIndex = perEventHandlers.indexOf(listener, foundIndex);
  2147. }
  2148. } else {
  2149. perEventHandlers.length = 0;
  2150. }
  2151. }
  2152. }
  2153. }
  2154. return this;
  2155. };
  2156. /**
  2157. * The underlying implementation of `ZeroClipboard.Client.prototype.handlers`.
  2158. * @private
  2159. */
  2160. var _clientListeners = function(eventType) {
  2161. var copy = null, handlers = _clientMeta[this.id] && _clientMeta[this.id].handlers;
  2162. if (handlers) {
  2163. if (typeof eventType === "string" && eventType) {
  2164. copy = handlers[eventType] ? handlers[eventType].slice(0) : [];
  2165. } else {
  2166. copy = _deepCopy(handlers);
  2167. }
  2168. }
  2169. return copy;
  2170. };
  2171. /**
  2172. * The underlying implementation of `ZeroClipboard.Client.prototype.emit`.
  2173. * @private
  2174. */
  2175. var _clientEmit = function(event) {
  2176. if (_clientShouldEmit.call(this, event)) {
  2177. if (typeof event === "object" && event && typeof event.type === "string" && event.type) {
  2178. event = _extend({}, event);
  2179. }
  2180. var eventCopy = _extend({}, _createEvent(event), {
  2181. client: this
  2182. });
  2183. _clientDispatchCallbacks.call(this, eventCopy);
  2184. }
  2185. return this;
  2186. };
  2187. /**
  2188. * The underlying implementation of `ZeroClipboard.Client.prototype.clip`.
  2189. * @private
  2190. */
  2191. var _clientClip = function(elements) {
  2192. if (!_clientMeta[this.id]) {
  2193. throw new Error("Attempted to clip element(s) to a destroyed ZeroClipboard client instance");
  2194. }
  2195. elements = _prepClip(elements);
  2196. for (var i = 0; i < elements.length; i++) {
  2197. if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
  2198. if (!elements[i].zcClippingId) {
  2199. elements[i].zcClippingId = "zcClippingId_" + _elementIdCounter++;
  2200. _elementMeta[elements[i].zcClippingId] = [ this.id ];
  2201. if (_globalConfig.autoActivate === true) {
  2202. _addMouseHandlers(elements[i]);
  2203. }
  2204. } else if (_elementMeta[elements[i].zcClippingId].indexOf(this.id) === -1) {
  2205. _elementMeta[elements[i].zcClippingId].push(this.id);
  2206. }
  2207. var clippedElements = _clientMeta[this.id] && _clientMeta[this.id].elements;
  2208. if (clippedElements.indexOf(elements[i]) === -1) {
  2209. clippedElements.push(elements[i]);
  2210. }
  2211. }
  2212. }
  2213. return this;
  2214. };
  2215. /**
  2216. * The underlying implementation of `ZeroClipboard.Client.prototype.unclip`.
  2217. * @private
  2218. */
  2219. var _clientUnclip = function(elements) {
  2220. var meta = _clientMeta[this.id];
  2221. if (!meta) {
  2222. return this;
  2223. }
  2224. var clippedElements = meta.elements;
  2225. var arrayIndex;
  2226. if (typeof elements === "undefined") {
  2227. elements = clippedElements.slice(0);
  2228. } else {
  2229. elements = _prepClip(elements);
  2230. }
  2231. for (var i = elements.length; i--; ) {
  2232. if (_hasOwn.call(elements, i) && elements[i] && elements[i].nodeType === 1) {
  2233. arrayIndex = 0;
  2234. while ((arrayIndex = clippedElements.indexOf(elements[i], arrayIndex)) !== -1) {
  2235. clippedElements.splice(arrayIndex, 1);
  2236. }
  2237. var clientIds = _elementMeta[elements[i].zcClippingId];
  2238. if (clientIds) {
  2239. arrayIndex = 0;
  2240. while ((arrayIndex = clientIds.indexOf(this.id, arrayIndex)) !== -1) {
  2241. clientIds.splice(arrayIndex, 1);
  2242. }
  2243. if (clientIds.length === 0) {
  2244. if (_globalConfig.autoActivate === true) {
  2245. _removeMouseHandlers(elements[i]);
  2246. }
  2247. delete elements[i].zcClippingId;
  2248. }
  2249. }
  2250. }
  2251. }
  2252. return this;
  2253. };
  2254. /**
  2255. * The underlying implementation of `ZeroClipboard.Client.prototype.elements`.
  2256. * @private
  2257. */
  2258. var _clientElements = function() {
  2259. var meta = _clientMeta[this.id];
  2260. return meta && meta.elements ? meta.elements.slice(0) : [];
  2261. };
  2262. /**
  2263. * The underlying implementation of `ZeroClipboard.Client.prototype.destroy`.
  2264. * @private
  2265. */
  2266. var _clientDestroy = function() {
  2267. if (!_clientMeta[this.id]) {
  2268. return;
  2269. }
  2270. this.unclip();
  2271. this.off();
  2272. delete _clientMeta[this.id];
  2273. };
  2274. /**
  2275. * Inspect an Event to see if the Client (`this`) should honor it for emission.
  2276. * @private
  2277. */
  2278. var _clientShouldEmit = function(event) {
  2279. if (!(event && event.type)) {
  2280. return false;
  2281. }
  2282. if (event.client && event.client !== this) {
  2283. return false;
  2284. }
  2285. var meta = _clientMeta[this.id];
  2286. var clippedEls = meta && meta.elements;
  2287. var hasClippedEls = !!clippedEls && clippedEls.length > 0;
  2288. var goodTarget = !event.target || hasClippedEls && clippedEls.indexOf(event.target) !== -1;
  2289. var goodRelTarget = event.relatedTarget && hasClippedEls && clippedEls.indexOf(event.relatedTarget) !== -1;
  2290. var goodClient = event.client && event.client === this;
  2291. if (!meta || !(goodTarget || goodRelTarget || goodClient)) {
  2292. return false;
  2293. }
  2294. return true;
  2295. };
  2296. /**
  2297. * Handle the actual dispatching of events to a client instance.
  2298. *
  2299. * @returns `undefined`
  2300. * @private
  2301. */
  2302. var _clientDispatchCallbacks = function(event) {
  2303. var meta = _clientMeta[this.id];
  2304. if (!(typeof event === "object" && event && event.type && meta)) {
  2305. return;
  2306. }
  2307. var async = _shouldPerformAsync(event);
  2308. var wildcardTypeHandlers = meta && meta.handlers["*"] || [];
  2309. var specificTypeHandlers = meta && meta.handlers[event.type] || [];
  2310. var handlers = wildcardTypeHandlers.concat(specificTypeHandlers);
  2311. if (handlers && handlers.length) {
  2312. var i, len, func, context, eventCopy, originalContext = this;
  2313. for (i = 0, len = handlers.length; i < len; i++) {
  2314. func = handlers[i];
  2315. context = originalContext;
  2316. if (typeof func === "string" && typeof _window[func] === "function") {
  2317. func = _window[func];
  2318. }
  2319. if (typeof func === "object" && func && typeof func.handleEvent === "function") {
  2320. context = func;
  2321. func = func.handleEvent;
  2322. }
  2323. if (typeof func === "function") {
  2324. eventCopy = _extend({}, event);
  2325. _dispatchCallback(func, context, [ eventCopy ], async);
  2326. }
  2327. }
  2328. }
  2329. };
  2330. /**
  2331. * Prepares the elements for clipping/unclipping.
  2332. *
  2333. * @returns An Array of elements.
  2334. * @private
  2335. */
  2336. var _prepClip = function(elements) {
  2337. if (typeof elements === "string") {
  2338. elements = [];
  2339. }
  2340. return typeof elements.length !== "number" ? [ elements ] : elements;
  2341. };
  2342. /**
  2343. * Add a `mouseover` handler function for a clipped element.
  2344. *
  2345. * @returns `undefined`
  2346. * @private
  2347. */
  2348. var _addMouseHandlers = function(element) {
  2349. if (!(element && element.nodeType === 1)) {
  2350. return;
  2351. }
  2352. var _suppressMouseEvents = function(event) {
  2353. if (!(event || (event = _window.event))) {
  2354. return;
  2355. }
  2356. if (event._source !== "js") {
  2357. event.stopImmediatePropagation();
  2358. event.preventDefault();
  2359. }
  2360. delete event._source;
  2361. };
  2362. var _elementMouseOver = function(event) {
  2363. if (!(event || (event = _window.event))) {
  2364. return;
  2365. }
  2366. _suppressMouseEvents(event);
  2367. ZeroClipboard.focus(element);
  2368. };
  2369. element.addEventListener("mouseover", _elementMouseOver, false);
  2370. element.addEventListener("mouseout", _suppressMouseEvents, false);
  2371. element.addEventListener("mouseenter", _suppressMouseEvents, false);
  2372. element.addEventListener("mouseleave", _suppressMouseEvents, false);
  2373. element.addEventListener("mousemove", _suppressMouseEvents, false);
  2374. _mouseHandlers[element.zcClippingId] = {
  2375. mouseover: _elementMouseOver,
  2376. mouseout: _suppressMouseEvents,
  2377. mouseenter: _suppressMouseEvents,
  2378. mouseleave: _suppressMouseEvents,
  2379. mousemove: _suppressMouseEvents
  2380. };
  2381. };
  2382. /**
  2383. * Remove a `mouseover` handler function for a clipped element.
  2384. *
  2385. * @returns `undefined`
  2386. * @private
  2387. */
  2388. var _removeMouseHandlers = function(element) {
  2389. if (!(element && element.nodeType === 1)) {
  2390. return;
  2391. }
  2392. var mouseHandlers = _mouseHandlers[element.zcClippingId];
  2393. if (!(typeof mouseHandlers === "object" && mouseHandlers)) {
  2394. return;
  2395. }
  2396. var key, val, mouseEvents = [ "move", "leave", "enter", "out", "over" ];
  2397. for (var i = 0, len = mouseEvents.length; i < len; i++) {
  2398. key = "mouse" + mouseEvents[i];
  2399. val = mouseHandlers[key];
  2400. if (typeof val === "function") {
  2401. element.removeEventListener(key, val, false);
  2402. }
  2403. }
  2404. delete _mouseHandlers[element.zcClippingId];
  2405. };
  2406. /**
  2407. * Creates a new ZeroClipboard client instance.
  2408. * Optionally, auto-`clip` an element or collection of elements.
  2409. *
  2410. * @constructor
  2411. */
  2412. ZeroClipboard._createClient = function() {
  2413. _clientConstructor.apply(this, _args(arguments));
  2414. };
  2415. /**
  2416. * Register an event listener to the client.
  2417. *
  2418. * @returns `this`
  2419. */
  2420. ZeroClipboard.prototype.on = function() {
  2421. return _clientOn.apply(this, _args(arguments));
  2422. };
  2423. /**
  2424. * Unregister an event handler from the client.
  2425. * If no `listener` function/object is provided, it will unregister all handlers for the provided `eventType`.
  2426. * If no `eventType` is provided, it will unregister all handlers for every event type.
  2427. *
  2428. * @returns `this`
  2429. */
  2430. ZeroClipboard.prototype.off = function() {
  2431. return _clientOff.apply(this, _args(arguments));
  2432. };
  2433. /**
  2434. * Retrieve event listeners for an `eventType` from the client.
  2435. * If no `eventType` is provided, it will retrieve all listeners for every event type.
  2436. *
  2437. * @returns array of listeners for the `eventType`; if no `eventType`, then a map/hash object of listeners for all event types; or `null`
  2438. */
  2439. ZeroClipboard.prototype.handlers = function() {
  2440. return _clientListeners.apply(this, _args(arguments));
  2441. };
  2442. /**
  2443. * Event emission receiver from the Flash object for this client's registered JavaScript event listeners.
  2444. *
  2445. * @returns For the "copy" event, returns the Flash-friendly "clipData" object; otherwise `undefined`.
  2446. */
  2447. ZeroClipboard.prototype.emit = function() {
  2448. return _clientEmit.apply(this, _args(arguments));
  2449. };
  2450. /**
  2451. * Register clipboard actions for new element(s) to the client.
  2452. *
  2453. * @returns `this`
  2454. */
  2455. ZeroClipboard.prototype.clip = function() {
  2456. return _clientClip.apply(this, _args(arguments));
  2457. };
  2458. /**
  2459. * Unregister the clipboard actions of previously registered element(s) on the page.
  2460. * If no elements are provided, ALL registered elements will be unregistered.
  2461. *
  2462. * @returns `this`
  2463. */
  2464. ZeroClipboard.prototype.unclip = function() {
  2465. return _clientUnclip.apply(this, _args(arguments));
  2466. };
  2467. /**
  2468. * Get all of the elements to which this client is clipped.
  2469. *
  2470. * @returns array of clipped elements
  2471. */
  2472. ZeroClipboard.prototype.elements = function() {
  2473. return _clientElements.apply(this, _args(arguments));
  2474. };
  2475. /**
  2476. * Self-destruct and clean up everything for a single client.
  2477. * This will NOT destroy the embedded Flash object.
  2478. *
  2479. * @returns `undefined`
  2480. */
  2481. ZeroClipboard.prototype.destroy = function() {
  2482. return _clientDestroy.apply(this, _args(arguments));
  2483. };
  2484. /**
  2485. * Stores the pending plain text to inject into the clipboard.
  2486. *
  2487. * @returns `this`
  2488. */
  2489. ZeroClipboard.prototype.setText = function(text) {
  2490. if (!_clientMeta[this.id]) {
  2491. throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance");
  2492. }
  2493. ZeroClipboard.setData("text/plain", text);
  2494. return this;
  2495. };
  2496. /**
  2497. * Stores the pending HTML text to inject into the clipboard.
  2498. *
  2499. * @returns `this`
  2500. */
  2501. ZeroClipboard.prototype.setHtml = function(html) {
  2502. if (!_clientMeta[this.id]) {
  2503. throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance");
  2504. }
  2505. ZeroClipboard.setData("text/html", html);
  2506. return this;
  2507. };
  2508. /**
  2509. * Stores the pending rich text (RTF) to inject into the clipboard.
  2510. *
  2511. * @returns `this`
  2512. */
  2513. ZeroClipboard.prototype.setRichText = function(richText) {
  2514. if (!_clientMeta[this.id]) {
  2515. throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance");
  2516. }
  2517. ZeroClipboard.setData("application/rtf", richText);
  2518. return this;
  2519. };
  2520. /**
  2521. * Stores the pending data to inject into the clipboard.
  2522. *
  2523. * @returns `this`
  2524. */
  2525. ZeroClipboard.prototype.setData = function() {
  2526. if (!_clientMeta[this.id]) {
  2527. throw new Error("Attempted to set pending clipboard data from a destroyed ZeroClipboard client instance");
  2528. }
  2529. ZeroClipboard.setData.apply(this, _args(arguments));
  2530. return this;
  2531. };
  2532. /**
  2533. * Clears the pending data to inject into the clipboard.
  2534. * If no `format` is provided, all pending data formats will be cleared.
  2535. *
  2536. * @returns `this`
  2537. */
  2538. ZeroClipboard.prototype.clearData = function() {
  2539. if (!_clientMeta[this.id]) {
  2540. throw new Error("Attempted to clear pending clipboard data from a destroyed ZeroClipboard client instance");
  2541. }
  2542. ZeroClipboard.clearData.apply(this, _args(arguments));
  2543. return this;
  2544. };
  2545. /**
  2546. * Gets a copy of the pending data to inject into the clipboard.
  2547. * If no `format` is provided, a copy of ALL pending data formats will be returned.
  2548. *
  2549. * @returns `String` or `Object`
  2550. */
  2551. ZeroClipboard.prototype.getData = function() {
  2552. if (!_clientMeta[this.id]) {
  2553. throw new Error("Attempted to get pending clipboard data from a destroyed ZeroClipboard client instance");
  2554. }
  2555. return ZeroClipboard.getData.apply(this, _args(arguments));
  2556. };
  2557. if (typeof define === "function" && define.amd) {
  2558. define(function() {
  2559. return ZeroClipboard;
  2560. });
  2561. } else if (typeof module === "object" && module && typeof module.exports === "object" && module.exports) {
  2562. module.exports = ZeroClipboard;
  2563. } else {
  2564. window.ZeroClipboard = ZeroClipboard;
  2565. }
  2566. })(function() {
  2567. return this || window;
  2568. }());