ZeroClipboard.js 88 KB

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