Skip to content

Commit

Permalink
Merge pull request #1203 from MoshiKoi/editor-improvements
Browse files Browse the repository at this point in the history
Add a notice when tags and attributes are rejected
  • Loading branch information
MoshiKoi authored Oct 23, 2023
2 parents ca4e6d2 + 7bbf18b commit be6f490
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
34 changes: 34 additions & 0 deletions app/assets/javascripts/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,19 @@ const ALLOWED_ATTR = ['id', 'class', 'href', 'title', 'src', 'height', 'width',
'start', 'dir'];

$(() => {
DOMPurify.addHook("uponSanitizeAttribute", (node, event) => {
const rowspan = node.getAttribute("rowspan");
const colspan = node.getAttribute("colspan");

if (rowspan && Number.isNaN(+rowspan)) {
event.keepAttr = false;
}

if (colspan && Number.isNaN(+colspan)) {
event.keepAttr = false;
}
});

const $uploadForm = $('.js-upload-form');

const stringInsert = (str, idx, insert) => str.slice(0, idx) + insert + str.slice(idx);
Expand Down Expand Up @@ -149,6 +162,27 @@ $(() => {
ALLOWED_TAGS,
ALLOWED_ATTR
});

const removedElements = [...new Set(DOMPurify.removed
.filter(entry => entry.element && !(entry.element instanceof HTMLBodyElement))
.map(entry => entry.element.localName))];

const removedAttributes = [...new Set(DOMPurify.removed
.filter(entry => entry.attribute)
.map(entry => [
entry.attribute.name + (entry.attribute.value ? `='${entry.attribute.value}'` : ''),
entry.from.localName
]))]

$tgt.parents('form')
.find('.rejected-elements')
.toggleClass('hide', removedElements.length === 0 && removedAttributes.length === 0)
.find('ul')
.empty()
.append(
removedElements.map(name => $(`<li><code>&lt;${name}&gt;</code></li>`)),
removedAttributes.map(([attr, elName]) => $(`<li><code>${attr}</code> (in <code>&lt;${elName}&gt;</code>)</li>`)));

$tgt.parents('.form-group').siblings('.post-preview').html(html);
$tgt.parents('form').find('.js-post-html[name="__html"]').val(html + '<!-- g: js, mdit -->');
}, 0);
Expand Down
8 changes: 8 additions & 0 deletions app/views/posts/_form.html.erb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,14 @@
<%= render 'shared/body_field', f: f, field_name: :body_markdown, field_label: t('posts.body_label'), post: post,
min_length: min_body_length(category), max_length: max_body_length(category) %>

<div class="rejected-elements notice is-warning hide">
<h3>Unsupported HTML detected</h3>
<p>The following HTML tags and attributes are unsupported and will be removed from the final post:</p>
<ul>
</ul>
<p>For a list of allowed HTML, see <a href="/help/advanced-formatting">this help article</a>.
If you meant to display the tags as code in the post, please enclose them in a code block.</p>
</div>
<div class="post-preview"></div>

<% unless post_type.has_parent? %>
Expand Down

0 comments on commit be6f490

Please sign in to comment.