document-chooser.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import $ from 'jquery';
  2. function createDocumentChooser(id) {
  3. const chooserElement = $('#' + id + '-chooser');
  4. const docTitle = chooserElement.find('.title');
  5. const input = $('#' + id);
  6. const editLink = chooserElement.find('.edit-link');
  7. const chooserBaseUrl = chooserElement.data('chooserUrl');
  8. /*
  9. Construct initial state of the chooser from the rendered (static) HTML and arguments passed to
  10. createDocumentChooser. State is either null (= no document chosen) or a dict of id, title and
  11. edit_link.
  12. The result returned from the document chooser modal (see get_document_result_data in
  13. wagtail.documents.views.chooser) is a superset of this, and can therefore be passed directly to
  14. chooser.setState.
  15. */
  16. let state = null;
  17. if (input.val()) {
  18. state = {
  19. id: input.val(),
  20. edit_link: editLink.attr('href'),
  21. title: docTitle.text(),
  22. };
  23. }
  24. /* define public API functions for the chooser */
  25. const chooser = {
  26. getState: () => state,
  27. getValue: () => state && state.id,
  28. setState: (newState) => {
  29. if (newState) {
  30. input.val(newState.id);
  31. docTitle.text(newState.title);
  32. chooserElement.removeClass('blank');
  33. editLink.attr('href', newState.edit_link);
  34. } else {
  35. input.val('');
  36. chooserElement.addClass('blank');
  37. }
  38. state = newState;
  39. },
  40. getTextLabel: (opts) => {
  41. if (!state) return null;
  42. const result = state.title;
  43. if (opts && opts.maxLength && result.length > opts.maxLength) {
  44. return result.substring(0, opts.maxLength - 1) + '…';
  45. }
  46. return result;
  47. },
  48. focus: () => {
  49. $('.action-choose', chooserElement).focus();
  50. },
  51. openChooserModal: () => {
  52. // eslint-disable-next-line no-undef, new-cap
  53. ModalWorkflow({
  54. url: chooserBaseUrl,
  55. // eslint-disable-next-line no-undef
  56. onload: DOCUMENT_CHOOSER_MODAL_ONLOAD_HANDLERS,
  57. responses: {
  58. documentChosen: (result) => {
  59. chooser.setState(result);
  60. }
  61. }
  62. });
  63. },
  64. clear: () => {
  65. chooser.setState(null);
  66. },
  67. };
  68. $('.action-choose', chooserElement).on('click', () => {
  69. chooser.openChooserModal();
  70. });
  71. $('.action-clear', chooserElement).on('click', () => {
  72. chooser.clear();
  73. });
  74. if (window.comments) {
  75. window.comments.initFieldLevelCommentWidget(chooserElement[0]);
  76. }
  77. return chooser;
  78. }
  79. window.createDocumentChooser = createDocumentChooser;