snippet-chooser.js 2.4 KB

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