filepond-plugin-file-poster.esm.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. /*!
  2. * FilePondPluginFilePoster 2.5.1
  3. * Licensed under MIT, https://opensource.org/licenses/MIT/
  4. * Please visit https://pqina.nl/filepond/ for details.
  5. */
  6. /* eslint-disable */
  7. const IMAGE_SCALE_SPRING_PROPS = {
  8. type: 'spring',
  9. stiffness: 0.5,
  10. damping: 0.45,
  11. mass: 10
  12. };
  13. const createPosterView = _ =>
  14. _.utils.createView({
  15. name: 'file-poster',
  16. tag: 'div',
  17. ignoreRect: true,
  18. create: ({ root }) => {
  19. root.ref.image = document.createElement('img');
  20. root.element.appendChild(root.ref.image);
  21. },
  22. write: _.utils.createRoute({
  23. DID_FILE_POSTER_LOAD: ({ root, props }) => {
  24. const { id } = props;
  25. // get item
  26. const item = root.query('GET_ITEM', { id: props.id });
  27. if (!item) return;
  28. // get poster
  29. const poster = item.getMetadata('poster');
  30. root.ref.image.src = poster;
  31. // let others know of our fabulous achievement (so the image can be faded in)
  32. root.dispatch('DID_FILE_POSTER_DRAW', { id });
  33. }
  34. }),
  35. mixins: {
  36. styles: ['scaleX', 'scaleY', 'opacity'],
  37. animations: {
  38. scaleX: IMAGE_SCALE_SPRING_PROPS,
  39. scaleY: IMAGE_SCALE_SPRING_PROPS,
  40. opacity: { type: 'tween', duration: 750 }
  41. }
  42. }
  43. });
  44. const applyTemplate = (source, target) => {
  45. // copy width and height
  46. target.width = source.width;
  47. target.height = source.height;
  48. // draw the template
  49. const ctx = target.getContext('2d');
  50. ctx.drawImage(source, 0, 0);
  51. };
  52. const createPosterOverlayView = fpAPI =>
  53. fpAPI.utils.createView({
  54. name: 'file-poster-overlay',
  55. tag: 'canvas',
  56. ignoreRect: true,
  57. create: ({ root, props }) => {
  58. applyTemplate(props.template, root.element);
  59. },
  60. mixins: {
  61. styles: ['opacity'],
  62. animations: {
  63. opacity: { type: 'spring', mass: 25 }
  64. }
  65. }
  66. });
  67. const getImageSize = (url, cb) => {
  68. let image = new Image();
  69. image.onload = () => {
  70. const width = image.naturalWidth;
  71. const height = image.naturalHeight;
  72. image = null;
  73. cb(width, height);
  74. };
  75. image.src = url;
  76. };
  77. const easeInOutSine = t => -0.5 * (Math.cos(Math.PI * t) - 1);
  78. const addGradientSteps = (
  79. gradient,
  80. color,
  81. alpha = 1,
  82. easeFn = easeInOutSine,
  83. steps = 10,
  84. offset = 0
  85. ) => {
  86. const range = 1 - offset;
  87. const rgb = color.join(',');
  88. for (let i = 0; i <= steps; i++) {
  89. const p = i / steps;
  90. const stop = offset + range * p;
  91. gradient.addColorStop(stop, `rgba(${rgb}, ${easeFn(p) * alpha})`);
  92. }
  93. };
  94. const MAX_WIDTH = 10;
  95. const MAX_HEIGHT = 10;
  96. const calculateAverageColor = image => {
  97. const scalar = Math.min(MAX_WIDTH / image.width, MAX_HEIGHT / image.height);
  98. const canvas = document.createElement('canvas');
  99. const ctx = canvas.getContext('2d');
  100. const width = (canvas.width = Math.ceil(image.width * scalar));
  101. const height = (canvas.height = Math.ceil(image.height * scalar));
  102. ctx.drawImage(image, 0, 0, width, height);
  103. let data = null;
  104. try {
  105. data = ctx.getImageData(0, 0, width, height).data;
  106. } catch (e) {
  107. return null;
  108. }
  109. const l = data.length;
  110. let r = 0;
  111. let g = 0;
  112. let b = 0;
  113. let i = 0;
  114. for (; i < l; i += 4) {
  115. r += data[i] * data[i];
  116. g += data[i + 1] * data[i + 1];
  117. b += data[i + 2] * data[i + 2];
  118. }
  119. r = averageColor(r, l);
  120. g = averageColor(g, l);
  121. b = averageColor(b, l);
  122. return { r, g, b };
  123. };
  124. const averageColor = (c, l) => Math.floor(Math.sqrt(c / (l / 4)));
  125. const drawTemplate = (canvas, width, height, color, alphaTarget) => {
  126. canvas.width = width;
  127. canvas.height = height;
  128. const ctx = canvas.getContext('2d');
  129. const horizontalCenter = width * 0.5;
  130. const grad = ctx.createRadialGradient(
  131. horizontalCenter,
  132. height + 110,
  133. height - 100,
  134. horizontalCenter,
  135. height + 110,
  136. height + 100
  137. );
  138. addGradientSteps(grad, color, alphaTarget, undefined, 8, 0.4);
  139. ctx.save();
  140. ctx.translate(-width * 0.5, 0);
  141. ctx.scale(2, 1);
  142. ctx.fillStyle = grad;
  143. ctx.fillRect(0, 0, width, height);
  144. ctx.restore();
  145. };
  146. const hasNavigator = typeof navigator !== 'undefined';
  147. const width = 500;
  148. const height = 200;
  149. const overlayTemplateShadow = hasNavigator && document.createElement('canvas');
  150. const overlayTemplateError = hasNavigator && document.createElement('canvas');
  151. const overlayTemplateSuccess = hasNavigator && document.createElement('canvas');
  152. let itemShadowColor = [40, 40, 40];
  153. let itemErrorColor = [196, 78, 71];
  154. let itemSuccessColor = [54, 151, 99];
  155. if (hasNavigator) {
  156. drawTemplate(overlayTemplateShadow, width, height, itemShadowColor, 0.85);
  157. drawTemplate(overlayTemplateError, width, height, itemErrorColor, 1);
  158. drawTemplate(overlayTemplateSuccess, width, height, itemSuccessColor, 1);
  159. }
  160. const loadImage = (url, crossOriginValue) =>
  161. new Promise((resolve, reject) => {
  162. const img = new Image();
  163. if (typeof crossOrigin === 'string') {
  164. img.crossOrigin = crossOriginValue;
  165. }
  166. img.onload = () => {
  167. resolve(img);
  168. };
  169. img.onerror = e => {
  170. reject(e);
  171. };
  172. img.src = url;
  173. });
  174. const createPosterWrapperView = _ => {
  175. // create overlay view
  176. const overlay = createPosterOverlayView(_);
  177. /**
  178. * Write handler for when preview container has been created
  179. */
  180. const didCreatePreviewContainer = ({ root, props }) => {
  181. const { id } = props;
  182. // we need to get the file data to determine the eventual image size
  183. const item = root.query('GET_ITEM', id);
  184. if (!item) return;
  185. // get url to file
  186. const fileURL = item.getMetadata('poster');
  187. // image is now ready
  188. const previewImageLoaded = data => {
  189. // calculate average image color, is in try catch to circumvent any cors errors
  190. const averageColor = root.query(
  191. 'GET_FILE_POSTER_CALCULATE_AVERAGE_IMAGE_COLOR'
  192. )
  193. ? calculateAverageColor(data)
  194. : null;
  195. item.setMetadata('color', averageColor, true);
  196. // the preview is now ready to be drawn
  197. root.dispatch('DID_FILE_POSTER_LOAD', {
  198. id,
  199. data
  200. });
  201. };
  202. // determine image size of this item
  203. getImageSize(fileURL, (width, height) => {
  204. // we can now scale the panel to the final size
  205. root.dispatch('DID_FILE_POSTER_CALCULATE_SIZE', {
  206. id,
  207. width,
  208. height
  209. });
  210. // create fallback preview
  211. loadImage(
  212. fileURL,
  213. root.query('GET_FILE_POSTER_CROSS_ORIGIN_ATTRIBUTE_VALUE')
  214. ).then(previewImageLoaded);
  215. });
  216. };
  217. /**
  218. * Write handler for when the preview has been loaded
  219. */
  220. const didLoadPreview = ({ root }) => {
  221. root.ref.overlayShadow.opacity = 1;
  222. };
  223. /**
  224. * Write handler for when the preview image is ready to be animated
  225. */
  226. const didDrawPreview = ({ root }) => {
  227. const { image } = root.ref;
  228. // reveal image
  229. image.scaleX = 1.0;
  230. image.scaleY = 1.0;
  231. image.opacity = 1;
  232. };
  233. /**
  234. * Write handler for when the preview has been loaded
  235. */
  236. const restoreOverlay = ({ root }) => {
  237. root.ref.overlayShadow.opacity = 1;
  238. root.ref.overlayError.opacity = 0;
  239. root.ref.overlaySuccess.opacity = 0;
  240. };
  241. const didThrowError = ({ root }) => {
  242. root.ref.overlayShadow.opacity = 0.25;
  243. root.ref.overlayError.opacity = 1;
  244. };
  245. const didCompleteProcessing = ({ root }) => {
  246. root.ref.overlayShadow.opacity = 0.25;
  247. root.ref.overlaySuccess.opacity = 1;
  248. };
  249. /**
  250. * Constructor
  251. */
  252. const create = ({ root, props }) => {
  253. // test if colors aren't default item overlay colors
  254. const itemShadowColorProp = root.query(
  255. 'GET_FILE_POSTER_ITEM_OVERLAY_SHADOW_COLOR'
  256. );
  257. const itemErrorColorProp = root.query(
  258. 'GET_FILE_POSTER_ITEM_OVERLAY_ERROR_COLOR'
  259. );
  260. const itemSuccessColorProp = root.query(
  261. 'GET_FILE_POSTER_ITEM_OVERLAY_SUCCESS_COLOR'
  262. );
  263. if (itemShadowColorProp && itemShadowColorProp !== itemShadowColor) {
  264. itemShadowColor = itemShadowColorProp;
  265. drawTemplate(overlayTemplateShadow, width, height, itemShadowColor, 0.85);
  266. }
  267. if (itemErrorColorProp && itemErrorColorProp !== itemErrorColor) {
  268. itemErrorColor = itemErrorColorProp;
  269. drawTemplate(overlayTemplateError, width, height, itemErrorColor, 1);
  270. }
  271. if (itemSuccessColorProp && itemSuccessColorProp !== itemSuccessColor) {
  272. itemSuccessColor = itemSuccessColorProp;
  273. drawTemplate(overlayTemplateSuccess, width, height, itemSuccessColor, 1);
  274. }
  275. // image view
  276. const image = createPosterView(_);
  277. // append image presenter
  278. root.ref.image = root.appendChildView(
  279. root.createChildView(image, {
  280. id: props.id,
  281. scaleX: 1.25,
  282. scaleY: 1.25,
  283. opacity: 0
  284. })
  285. );
  286. // image overlays
  287. root.ref.overlayShadow = root.appendChildView(
  288. root.createChildView(overlay, {
  289. template: overlayTemplateShadow,
  290. opacity: 0
  291. })
  292. );
  293. root.ref.overlaySuccess = root.appendChildView(
  294. root.createChildView(overlay, {
  295. template: overlayTemplateSuccess,
  296. opacity: 0
  297. })
  298. );
  299. root.ref.overlayError = root.appendChildView(
  300. root.createChildView(overlay, {
  301. template: overlayTemplateError,
  302. opacity: 0
  303. })
  304. );
  305. };
  306. return _.utils.createView({
  307. name: 'file-poster-wrapper',
  308. create,
  309. write: _.utils.createRoute({
  310. // image preview stated
  311. DID_FILE_POSTER_LOAD: didLoadPreview,
  312. DID_FILE_POSTER_DRAW: didDrawPreview,
  313. DID_FILE_POSTER_CONTAINER_CREATE: didCreatePreviewContainer,
  314. // file states
  315. DID_THROW_ITEM_LOAD_ERROR: didThrowError,
  316. DID_THROW_ITEM_PROCESSING_ERROR: didThrowError,
  317. DID_THROW_ITEM_INVALID: didThrowError,
  318. DID_COMPLETE_ITEM_PROCESSING: didCompleteProcessing,
  319. DID_START_ITEM_PROCESSING: restoreOverlay,
  320. DID_REVERT_ITEM_PROCESSING: restoreOverlay
  321. })
  322. });
  323. };
  324. /**
  325. * File Poster Plugin
  326. */
  327. const plugin = fpAPI => {
  328. const { addFilter, utils } = fpAPI;
  329. const { Type, createRoute } = utils;
  330. // filePosterView
  331. const filePosterView = createPosterWrapperView(fpAPI);
  332. // called for each view that is created right after the 'create' method
  333. addFilter('CREATE_VIEW', viewAPI => {
  334. // get reference to created view
  335. const { is, view, query } = viewAPI;
  336. // only hook up to item view and only if is enabled for this cropper
  337. if (!is('file') || !query('GET_ALLOW_FILE_POSTER')) return;
  338. // create the file poster plugin, but only do so if the item is an image
  339. const didLoadItem = ({ root, props }) => {
  340. updateItemPoster(root, props);
  341. };
  342. const didUpdateItemMetadata = ({ root, props, action }) => {
  343. if (!/poster/.test(action.change.key)) return;
  344. updateItemPoster(root, props);
  345. };
  346. const updateItemPoster = (root, props) => {
  347. const { id } = props;
  348. const item = query('GET_ITEM', id);
  349. // item could theoretically have been removed in the mean time
  350. if (!item || !item.getMetadata('poster') || item.archived) return;
  351. // don't update if is the same poster
  352. if (root.ref.previousPoster === item.getMetadata('poster')) return;
  353. root.ref.previousPoster = item.getMetadata('poster');
  354. // test if is filtered
  355. if (!query('GET_FILE_POSTER_FILTER_ITEM')(item)) return;
  356. if (root.ref.filePoster) {
  357. view.removeChildView(root.ref.filePoster);
  358. }
  359. // set preview view
  360. root.ref.filePoster = view.appendChildView(
  361. view.createChildView(filePosterView, { id })
  362. );
  363. // now ready
  364. root.dispatch('DID_FILE_POSTER_CONTAINER_CREATE', { id });
  365. };
  366. const didCalculatePreviewSize = ({ root, action }) => {
  367. // no poster set
  368. if (!root.ref.filePoster) return;
  369. // remember dimensions
  370. root.ref.imageWidth = action.width;
  371. root.ref.imageHeight = action.height;
  372. root.ref.shouldUpdatePanelHeight = true;
  373. root.dispatch('KICK');
  374. };
  375. const getPosterHeight = ({ root }) => {
  376. let fixedPosterHeight = root.query('GET_FILE_POSTER_HEIGHT');
  377. // if fixed height: return fixed immediately
  378. if (fixedPosterHeight) {
  379. return fixedPosterHeight;
  380. }
  381. const minPosterHeight = root.query('GET_FILE_POSTER_MIN_HEIGHT');
  382. const maxPosterHeight = root.query('GET_FILE_POSTER_MAX_HEIGHT');
  383. // if natural height is smaller than minHeight: return min height
  384. if (minPosterHeight && root.ref.imageHeight < minPosterHeight) {
  385. return minPosterHeight;
  386. }
  387. let height =
  388. root.rect.element.width * (root.ref.imageHeight / root.ref.imageWidth);
  389. if (minPosterHeight && height < minPosterHeight) {
  390. return minPosterHeight;
  391. }
  392. if (maxPosterHeight && height > maxPosterHeight) {
  393. return maxPosterHeight;
  394. }
  395. return height;
  396. };
  397. // start writing
  398. view.registerWriter(
  399. createRoute(
  400. {
  401. DID_LOAD_ITEM: didLoadItem,
  402. DID_FILE_POSTER_CALCULATE_SIZE: didCalculatePreviewSize,
  403. DID_UPDATE_ITEM_METADATA: didUpdateItemMetadata
  404. },
  405. ({ root, props }) => {
  406. // don't run without poster
  407. if (!root.ref.filePoster) return;
  408. // don't do anything while hidden
  409. if (root.rect.element.hidden) return;
  410. // should we redraw
  411. if (root.ref.shouldUpdatePanelHeight) {
  412. // time to resize the parent panel
  413. root.dispatch('DID_UPDATE_PANEL_HEIGHT', {
  414. id: props.id,
  415. height: getPosterHeight({ root })
  416. });
  417. // done!
  418. root.ref.shouldUpdatePanelHeight = false;
  419. }
  420. }
  421. )
  422. );
  423. });
  424. // expose plugin
  425. return {
  426. options: {
  427. // Enable or disable file poster
  428. allowFilePoster: [true, Type.BOOLEAN],
  429. // Fixed preview height
  430. filePosterHeight: [null, Type.INT],
  431. // Min image height
  432. filePosterMinHeight: [null, Type.INT],
  433. // Max image height
  434. filePosterMaxHeight: [null, Type.INT],
  435. // filters file items to determine which are shown as poster
  436. filePosterFilterItem: [() => true, Type.FUNCTION],
  437. // Enables or disables reading average image color
  438. filePosterCalculateAverageImageColor: [false, Type.BOOLEAN],
  439. // Allows setting the value of the CORS attribute (null is don't set attribute)
  440. filePosterCrossOriginAttributeValue: ['Anonymous', Type.STRING],
  441. // Colors used for item overlay gradient
  442. filePosterItemOverlayShadowColor: [null, Type.ARRAY],
  443. filePosterItemOverlayErrorColor: [null, Type.ARRAY],
  444. filePosterItemOverlaySuccessColor: [null, Type.ARRAY]
  445. }
  446. };
  447. };
  448. // fire pluginloaded event if running in browser, this allows registering the plugin when using async script tags
  449. const isBrowser =
  450. typeof window !== 'undefined' && typeof window.document !== 'undefined';
  451. if (isBrowser) {
  452. document.dispatchEvent(
  453. new CustomEvent('FilePond:pluginloaded', { detail: plugin })
  454. );
  455. }
  456. export default plugin;