Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Render Word cloud block editor in libraries [FC-0076] #36199

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cms/static/js/views/xblock_editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ function($, _, gettext, BaseView, XBlockView, MetadataView, MetadataCollection)
el: metadataEditor,
collection: new MetadataCollection(models)
});
if (xblock.setMetadataEditor) {
if (xblock && xblock.setMetadataEditor) {
xblock.setMetadataEditor(metadataView);
}
}
Expand Down
120 changes: 108 additions & 12 deletions common/templates/xblock_v2/xblock_iframe.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,23 +35,43 @@
<script type="text/javascript" src="{{ lms_root_url }}/static/common/js/vendor/require.js"></script>
<script type="text/javascript" src="{{ lms_root_url }}/static/js/RequireJS-namespace-undefine.js"></script>
<script>
// The minimal RequireJS configuration required for common LMS building XBlock types to work:
// The minimal RequireJS configuration required for common LMS and CMS building XBlock types to work:
require = require || RequireJS.require;
define = define || RequireJS.define;
(function (require, define) {
require.config({
baseUrl: "{{ lms_root_url }}/static/",
paths: {
accessibility: 'js/src/accessibility_tools',
draggabilly: 'js/vendor/draggabilly',
hls: 'common/js/vendor/hls',
moment: 'common/js/vendor/moment-with-locales',
HtmlUtils: 'edx-ui-toolkit/js/utils/html-utils',
},
});
if ('{{ view_name | safe }}' === 'studio_view') {
// Call `require-config.js` of the CMS
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = "{{ cms_root_url }}/static/studio/cms/js/require-config.js";
document.head.appendChild(script);

require.config({
baseUrl: "{{ cms_root_url }}/static/studio",
paths: {
accessibility: 'js/src/accessibility_tools',
draggabilly: 'js/vendor/draggabilly',
hls: 'common/js/vendor/hls',
moment: 'common/js/vendor/moment-with-locales',
},
});
} else {
require.config({
baseUrl: "{{ lms_root_url }}/static/",
paths: {
accessibility: 'js/src/accessibility_tools',
draggabilly: 'js/vendor/draggabilly',
hls: 'common/js/vendor/hls',
moment: 'common/js/vendor/moment-with-locales',
HtmlUtils: 'edx-ui-toolkit/js/utils/html-utils',
},
});
}
define('gettext', [], function() { return window.gettext; });
define('jquery', [], function() { return window.jQuery; });
define('jquery-migrate', [], function() { return window.jQuery; });
define('underscore', [], function() { return window._; });
}).call(this, require || RequireJS.require, define || RequireJS.define);
}).call(this, require, define);
</script>
<!-- edX HTML Utils requires GlobalLoader -->
<script type="text/javascript" src="{{ lms_root_url }}/static/edx-ui-toolkit/js/utils/global-loader.js"></script>
Expand Down Expand Up @@ -269,6 +289,82 @@
// const passElement = isStudioView && (window as any).$ ? (window as any).$(element) : element;
const blockJS = new InitFunction(runtime, element, data) || {};
blockJS.element = element;

if (['MetadataOnlyEditingDescriptor', 'SequenceDescriptor'].includes(data['xmodule-type'])) {
// The xmodule type `MetadataOnlyEditingDescriptor` and `SequenceDescriptor` renders a `<div>` with
// the block metadata in the `data-metadata` attribute. But is necessary
// to call `XBlockEditorView.xblockReady()` to run the scripts to build the
// editor using the metadata.
require(['{{ cms_root_url }}/static/studio/js/views/xblock_editor.js'], function(XBlockEditorView) {
var editorView = new XBlockEditorView({
el: element,
xblock: blockJS,
});
// To render block using metadata
editorView.xblockReady(blockJS);

// Adding cancel and save buttons
var xblockActions = `
<div class="xblock-actions">
<ul>
<li class="action-item">
<input id="poll-submit-options" type="submit" class="button action-primary save-button" value="Save" onclick="return false;">
</li>
<li class="action-item">
<a href="#" class="button cancel-button">Cancel</a>
</li>
</ul>
</div>
`;
element.innerHTML += xblockActions;

const views = editorView.getMetadataEditor().views;
Object.values(views).forEach(view => {
const uniqueId = view.uniqueId;
const input = element.querySelector(`#${uniqueId}`);
if (input) {
input.addEventListener("input", function(event) {
view.model.setValue(event.target.value);
});
}
});

// Adding cancel functionality
$('.cancel-button', element).bind('click', function() {
runtime.notify('cancel', {});
event.preventDefault();
});

// Adding save functionality
$('.save-button', element).bind('click', function() {
//event.preventDefault();
var error_message_div = $('.xblock-editor-error-message', element);
const modifiedData = editorView.getChangedMetadata();

error_message_div.html();
error_message_div.css('display', 'none');

var handlerUrl = runtime.handlerUrl(element, 'studio_submit');

runtime.notify('save', {state: 'start', message: gettext("Saving")});

$.post(handlerUrl, JSON.stringify(modifiedData)).done(function(response) {
if (response.result === 'success') {
runtime.notify('save', {state: 'end'})
window.location.reload(false);
} else {
runtime.notify('error', {
'title': 'Error saving changes',
'message': response.message,
});
error_message_div.html('Error: '+response.message);
error_message_div.css('display', 'block');
}
});
});
});
}

callback(blockJS);
} else {
const blockJS = { element };
Expand Down
22 changes: 22 additions & 0 deletions xmodule/conditional_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,6 +382,28 @@ def validate(self):
validation.summary = conditional_validation.messages[0]
return validation

@XBlock.json_handler
def studio_submit(self, submissions, suffix=''): # pylint: disable=unused-argument
"""
Change the settings for this XBlock given by the Studio user.
"""
if 'display_name' in submissions:
self.display_name = submissions['display_name']
if 'show_tag_list' in submissions:
self.show_tag_list = submissions['show_tag_list']
if 'sources_list' in submissions:
self.sources_list = submissions['sources_list']
if 'conditional_attr' in submissions:
self.conditional_attr = submissions['conditional_attr']
if 'conditional_value' in submissions:
self.conditional_value = submissions['conditional_value']
if 'conditional_message' in submissions:
self.conditional_message = submissions['conditional_message']

return {
'result': 'success',
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can add Conditional blocks to courses with no issue. 👍
But I'm unable to test pasting a Conditional block into a library due to this error during re-indexing:

cms-1  | 2025-02-04 00:27:28,772 INFO 1640 [openedx.core.djangoapps.content.search.tasks] [user 6] [ip 172.24.0.1] tasks.py:55 - Updating content index document for library block with id: lb:OpenCraft:FAL-4029:conditional:f021eaec-5964-4ce7-8f1c-89f1f2f2ab04
cms-1  | 2025-02-04 00:27:28,806 ERROR 1640 [celery_utils.logged_task] [user 6] [ip 172.24.0.1] logged_task.py:48 - [2f7df8e9-8d8d-4e3b-9989-8ffd2d575f77] failed due to Traceback (most recent call last):
cms-1  |   File "/openedx/edx-platform/xmodule/xml_block.py", line 399, in parse_xml_new_runtime
cms-1  |     return super().parse_xml_new_runtime(node, runtime, keys)
cms-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  | AttributeError: 'super' object has no attribute 'parse_xml_new_runtime'
cms-1  |
cms-1  | During handling of the above exception, another exception occurred:
cms-1  |
cms-1  | Traceback (most recent call last):
cms-1  |   File "/openedx/venv/lib/python3.11/site-packages/celery/app/trace.py", line 453, in trace_task
cms-1  |     R = retval = fun(*args, **kwargs)
cms-1  |                  ^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/venv/lib/python3.11/site-packages/celery/app/autoretry.py", line 38, in run
cms-1  |     return task._orig_run(*args, **kwargs)
cms-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/venv/lib/python3.11/site-packages/edx_django_utils/monitoring/internal/code_owner/utils.py", line 195, in new_function
cms-1  |     return wrapped_function(*args, **kwargs)
cms-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/content/search/tasks.py", line 57, in upsert_library_block_index_doc
cms-1  |     api.upsert_library_block_index_doc(usage_key)
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/content/search/api.py", line 639, in upsert_library_block_index_doc
cms-1  |     searchable_doc_for_library_block(library_block_metadata)
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/content/search/documents.py", line 381, in searchable_doc_for_library_block
cms-1  |     block = xblock_api.load_block(xblock_metadata.usage_key, user=None)
cms-1  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/xblock/api.py", line 117, in load_block
cms-1  |     return runtime.get_block(usage_key, version=version)
cms-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/xblock/runtime/learning_core_runtime.py", line 217, in get_block
cms-1  |     block = block_class.parse_xml_new_runtime(xml_node, runtime=self, keys=keys)
cms-1  |             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/openedx/edx-platform/xmodule/xml_block.py", line 401, in parse_xml_new_runtime
cms-1  |     return super().parse_xml(node, runtime, keys)
cms-1  |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
cms-1  |   File "/mnt/xblock/xblock/core.py", line 763, in parse_xml
cms-1  |     block.runtime.add_node_as_child(block, child)
cms-1  |   File "/openedx/edx-platform/openedx/core/djangoapps/xblock/runtime/runtime.py", line 267, in add_node_as_child
cms-1  |     raise NotImplementedError("XML Serialization is only supported with LearningCoreXBlockRuntime")
cms-1  | NotImplementedError: XML Serialization is only supported with LearningCoreXBlockRuntime

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pomegranited I can't reproduce this error. Copying creates the block without any problems. Maybe there is an additional context that I'm ignoring?

Copy link
Contributor

@pomegranited pomegranited Feb 4, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ok weird.. I'm still seeing this issue? I don't get an error in the frontend at all, but the pasted Conditional block never appears.

I tried:

  • checking all my mounted dependencies to make sure i'm running the platform required versions (esp XBlock)
  • reindexing studio -- edit these errors don't show up in the shell to, e.g. "Error indexing library component xblock.v1:conditional:33a7bf8b-bf02-4783-9e76-941097b53c36: XML Serialization is only supported with LearningCoreXBlockRuntime"
  • checking Django Admin -- the conditional blocks show up in the learning package's component list?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ChrisChV Could you share the course you used? Maybe there's something wrong with the configuration I chose... grasping at straws here :)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it seems strange. I have created a new course and it works fine. Here I attach the course: course.q8xomjt4.tar.gz

@rpenido Did you have any problems with it, suddenly we have some configurations that we forgot to mention?

Copy link
Contributor Author

@ChrisChV ChrisChV Feb 6, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @navinkarkera @pomegranited! I've seen the issue. We're not going to support multi-level blocks for now (ref), so I've removed this new code related to the conditional in 0be1cfe. Can you please review it again?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was able to reproduce this issue, if you try to copy and paste a conditional block that has children, it fails with above error that @pomegranited pasted.

Ohhh.. that makes sense. Thank you for confirming that I'm not crazy, @navinkarkera !

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ChrisChV Got it, but now save button for conditional block doesn't work as you removed studio_submit handler.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@navinkarkera I created openedx/frontend-app-authoring#1652 to avoid copy/edit multilevel blocks, it's ready for review

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@pomegranited @navinkarkera Following the comments in openedx/frontend-app-authoring#1652, I think this PR is ready to be merged. There is no point in adding more code to the conditional block since it will not be supported.

@property
def non_editable_metadata_fields(self):
non_editable_fields = super().non_editable_metadata_fields
Expand Down
27 changes: 27 additions & 0 deletions xmodule/tests/test_conditional.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from unittest.mock import Mock, patch

from django.conf import settings
from webob import Request
from fs.memoryfs import MemoryFS
from lxml import etree
from opaque_keys.edx.keys import CourseKey
Expand Down Expand Up @@ -402,3 +403,29 @@ def test_validation_messages(self):
assert validation.summary.type == StudioValidationMessage.NOT_CONFIGURED
assert validation.summary.action_class == 'edit-button'
assert validation.summary.action_label == 'Configure list of sources'

def test_studio_submit_handler(self):
"""
Test studio_submint handler
"""
TEST_SUBMIT_DATA = {
'display_name': "New Conditional",
'show_tag_list': ["1", "2"],
'sources_list': ["1", "2"],
'conditional_attr': "test",
'conditional_value': 'value',
'conditional_message': 'message',
}
body = json.dumps(TEST_SUBMIT_DATA)
request = Request.blank('/')
request.method = 'POST'
request.body = body.encode('utf-8')
res = self.conditional.handle('studio_submit', request)
assert json.loads(res.body.decode('utf8')) == {'result': 'success'}

assert self.conditional.display_name == TEST_SUBMIT_DATA['display_name']
assert self.conditional.show_tag_list == TEST_SUBMIT_DATA['show_tag_list']
assert self.conditional.sources_list == TEST_SUBMIT_DATA['sources_list']
assert self.conditional.conditional_attr == TEST_SUBMIT_DATA['conditional_attr']
assert self.conditional.conditional_value == TEST_SUBMIT_DATA['conditional_value']
assert self.conditional.conditional_message == TEST_SUBMIT_DATA['conditional_message']
27 changes: 27 additions & 0 deletions xmodule/tests/test_word_cloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from django.test import TestCase
from fs.memoryfs import MemoryFS
from lxml import etree
from webob import Request
from opaque_keys.edx.locator import BlockUsageLocator, CourseLocator
from webob.multidict import MultiDict
from xblock.field_data import DictFieldData
Expand Down Expand Up @@ -115,3 +116,29 @@ def test_indexibility(self):
{'content_type': 'Word Cloud',
'content': {'display_name': 'Word Cloud Block',
'instructions': 'Enter some random words that comes to your mind'}}

def test_studio_submit_handler(self):
"""
Test studio_submint handler
"""
TEST_SUBMIT_DATA = {
'display_name': "New Word Cloud",
'instructions': "This is a Test",
'num_inputs': 5,
'num_top_words': 10,
'display_student_percents': 'False',
}
module_system = get_test_system()
block = WordCloudBlock(module_system, DictFieldData(self.raw_field_data), Mock())
body = json.dumps(TEST_SUBMIT_DATA)
request = Request.blank('/')
request.method = 'POST'
request.body = body.encode('utf-8')
res = block.handle('studio_submit', request)
assert json.loads(res.body.decode('utf8')) == {'result': 'success'}

assert block.display_name == TEST_SUBMIT_DATA['display_name']
assert block.instructions == TEST_SUBMIT_DATA['instructions']
assert block.num_inputs == TEST_SUBMIT_DATA['num_inputs']
assert block.num_top_words == TEST_SUBMIT_DATA['num_top_words']
assert block.display_student_percents == (TEST_SUBMIT_DATA['display_student_percents'] == "True")
20 changes: 20 additions & 0 deletions xmodule/word_cloud_block.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,26 @@ def index_dictionary(self):

return xblock_body

@XBlock.json_handler
def studio_submit(self, submissions, suffix=''): # pylint: disable=unused-argument
"""
Change the settings for this XBlock given by the Studio user
"""
if 'display_name' in submissions:
self.display_name = submissions['display_name']
if 'instructions' in submissions:
self.instructions = submissions['instructions']
if 'num_inputs' in submissions:
self.num_inputs = submissions['num_inputs']
if 'num_top_words' in submissions:
self.num_top_words = submissions['num_top_words']
if 'display_student_percents' in submissions:
self.display_student_percents = submissions['display_student_percents'] == 'True'

return {
'result': 'success',
}

farhan marked this conversation as resolved.
Show resolved Hide resolved

WordCloudBlock = (
_ExtractedWordCloudBlock if settings.USE_EXTRACTED_WORD_CLOUD_BLOCK
Expand Down
Loading