LinkEntryFactory.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. var escapeHTML = require('../Utils').escapeHTML;
  3. var entryFieldDescription = require('./EntryFieldDescription');
  4. var bind = require('lodash/bind');
  5. /**
  6. * An entry that renders a clickable link.
  7. *
  8. * A passed {@link options#handleClick} handler is responsible
  9. * to process the click.
  10. *
  11. * The link may be conditionally shown or hidden. This can be
  12. * controlled via the {@link options.showLink}.
  13. *
  14. * @param {Object} options
  15. * @param {String} options.id
  16. * @param {String} [options.label]
  17. * @param {Function} options.handleClick
  18. * @param {Function} [options.showLink] returning false to hide link
  19. * @param {String} [options.description]
  20. *
  21. * @example
  22. *
  23. * var linkEntry = link({
  24. * id: 'foo',
  25. * description: 'Some Description',
  26. * handleClick: function(element, node, event) { ... },
  27. * showLink: function(element, node) { ... }
  28. * });
  29. *
  30. * @return {Entry} the newly created entry
  31. */
  32. function link(options) {
  33. var id = options.id,
  34. label = options.label || id,
  35. showLink = options.showLink,
  36. handleClick = options.handleClick,
  37. description = options.description;
  38. if (showLink && typeof showLink !== 'function') {
  39. throw new Error('options.showLink must be a function');
  40. }
  41. if (typeof handleClick !== 'function') {
  42. throw new Error('options.handleClick must be a function');
  43. }
  44. var resource = {
  45. id: id
  46. };
  47. resource.html =
  48. '<a data-action="handleClick" ' +
  49. (showLink ? 'data-show="showLink" ' : '') +
  50. 'class="bpp-entry-link' + (options.cssClasses ? ' ' + escapeHTML(options.cssClasses) : '') +
  51. '">' + escapeHTML(label) + '</a>';
  52. // add description below link entry field
  53. if (description) {
  54. resource.html += entryFieldDescription(description);
  55. }
  56. resource.handleClick = bind(handleClick, resource);
  57. if (typeof showLink === 'function') {
  58. resource.showLink = function() {
  59. return showLink.apply(resource, arguments);
  60. };
  61. }
  62. return resource;
  63. }
  64. module.exports = link;