This is an automated email from the ASF dual-hosted git repository.
snoopdave pushed a commit to branch roller-6.1.x
in repository https://gitbox.apache.org/repos/asf/roller.git
The following commit(s) were added to refs/heads/roller-6.1.x by this push:
new e0c82f4da Open entries with active HTML in the textarea instead of the
rich editor (#331)
e0c82f4da is described below
commit e0c82f4daf414246872ef10c869581fca447065e
Author: Matt Raible <[email protected]>
AuthorDate: Sat Nov 21 11:17:33 2026 -0700
Open entries with active HTML in the textarea instead of the rich editor
(#331)
* Open entries with active HTML in the textarea instead of the rich editor
Before Summernote starts, EntryEditor.jsp checks the entry's HTML with the
new rich-editor-content.js, which parses it in an inert DOMParser document and
looks for scripts, frames, plugins, document-level elements, noscript, SVG set
and animate, on* attributes, and javascript: or vbscript: URLs in any
attribute. When it finds any, the entry opens in the plain HTML textarea with a
short notice, and media files are inserted into the textarea, since Summernote
would start itself on any c [...]
* Check table parts the way the rich editor parses them, and flag style
elements
jQuery's html(), which Summernote uses to load an entry, keeps table cells,
rows and captions found outside a table, while a full document parse drops them
and their attributes. rich-editor-content.js now also checks the entry parsed
as template contents, which keeps them, and treats <style> elements as active
since they apply to the whole page. Media files inserted into the textarea
fallback go at the cursor, or at the end when it has none.
* Check only URL attributes for script URLs, keep a cursor at the start of
the textarea, and test the rich editor check in a browser
rich-editor-content.js now looks for javascript: and vbscript: URLs only at
the start of URL attributes (href, src, action, formaction, xlink:href, data,
poster, background, cite and each srcset candidate), so text such as
title="JavaScript: The Good Parts" no longer opens an entry in the textarea.
Entries with textarea, title, xmp, noembed, noframes or plaintext elements, or
with markup that parses differently once serialized and parsed again (as the
rich editor does for undo and cod [...]
The textarea fallback now remembers whether the cursor has been placed, so
a media file goes at the start when the cursor was put there, and at the end
only when it never was.
The new RichEditorContentIT in it-selenium loads the script into a blank
page in Firefox and checks entries that should open in the textarea, entries
that should stay in the rich editor, and where media files are inserted. It
needs no running Roller; to run it without the module's Jetty, use mvn
test-compile failsafe:integration-test failsafe:verify
-Dit.test=RichEditorContentIT from it-selenium.
* Compare element structure, not text, when checking whether an entry
parses the same way twice
The serialize-and-parse-again check in rich-editor-content.js compared
serialized HTML, so a <pre> starting with a blank line, which loses one leading
newline each time it is parsed, opened in the textarea. It now compares the
elements, their namespaces and attributes, and leaves text out.
RichEditorContentIT checks that case.
* Check entries the way the entry form parses them, and open forms and form
controls in the textarea
The rich editor loads an entry inside the entry form, where the parser
ignores the start tag of another form, so the content check now also parses and
re-parses the HTML inside a form and no longer misses markup that only becomes
an element with an event handler there.
Entries with a form, input, button or select element, or a formaction
attribute, now open in the HTML textarea. The rich editor dropped a form's own
tags on save, and such controls became part of the entry form, where they could
be submitted with the entry or send it to another address.
The check reads attributes and child nodes through the DOM prototypes, so a
form control named attributes or firstChild can no longer hide its form's
attributes from it.
The leave-page warning is now attached on the first rich editor change
only, instead of once more on every change, and the test that guards Summernote
command calls matches single-quoted command names too.
The check also reads the parsed document's body and calls its createElement
and querySelectorAll through the DOM prototypes. In Firefox an image named
body, createElement or querySelectorAll replaces that property on the parsed
document, which made a harmless image with such a name open in the textarea and
left the body comparison looking at the image instead of the body.
* Warn before leaving the HTML textarea as soon as the author types
The textarea fallback installed the leave-page warning on change, which
fires only after the field loses focus, so an author who typed and closed the
tab while still in the field got no warning. It now listens for the first input
event, and media insertion triggers input. InitialLoginTestIT switches its
weblog to the rich editor, opens an entry with a click handler in the textarea,
and checks the warning is armed after typing and after inserting a media file.
RichEditorContentIT also [...]
* Check entries the way jQuery's html() loads them, and as code view leaves
them
The content check parsed entries with DOMParser, a template and a div in a
form, which only approximate how the rich editor loads them. DOMParser also
parses without a doctype, in quirks mode, while the editor page is in standards
mode, so the same HTML could become a different tree there.
The check now builds what jQuery's html() builds, in an inert
standards-mode document: in place in the rich editor inside the entry form, or,
for HTML whose first tag is a table part or that has script, style or link
tags, in a detached element inside the table elements jQuery adds, the way both
jQuery 3 and 4 do it. It checks that tree and checks that loading its
serialized HTML again, as undo does, gives the same elements.
Summernote 0.9's code view removes some tags from the HTML when the author
leaves it, which can end a comment early. Summernote 0.8.12 doesn't by default,
but the check is the same file on both branches and also follows the serialized
HTML through that filter, and HTML with an iframe tag anywhere in it, even in a
comment, opens in the textarea.
RichEditorContentIT now loads entries with the jQuery webjar for its check
that what stays in the rich editor has no event handlers.
* Open entries with markup in a link's href or a URL, or Bootstrap data
attributes, in the textarea
Summernote 0.8.12 shows some text from the entry as HTML: its link popover
parses a link's href as HTML when the caret is in the link, and its autolink
does the same with a URL-like word when the author types a space after it.
Entries with an href that has a < in it, or a URL-like word that has a < in it,
now open in the HTML textarea. Other text with < in it, such as code samples,
stays in the rich editor.
Bootstrap 3's data API acts on clicks anywhere in the page, and loads a
link into the dialog it names, so entries with data-toggle, data-target,
data-dismiss, data-slide, data-slide-to or data-bs-* attributes open in the
textarea too.
* Keep entries with an SVG title or microdata meta in the rich editor
The check treated every element named title or meta as active, so an inline
SVG with a <title> tooltip, or schema.org microdata written as <meta itemprop
content>, opened in the HTML textarea. It now flags only an HTML <title>, and a
<meta> unless it has itemprop and none of name, http-equiv and charset.
* Word the HTML textarea notice without an apostrophe
The notice used a doubled apostrophe, which shows as two unless the message
goes through MessageFormat, and the page shows it without parameters. It now
says cannot, which reads the same either way.
* Warn before leaving again after a submit that keeps the page open
The leave-page warning was armed on the first edit only, and a submit
removed it for good, so after a submit that was stopped before the page
changed, later edits could be lost without a prompt. The submit handler now
arms the warning again for the next edit, in the rich editor and in the HTML
textarea.
* Check every Summernote call in the entry editor, not just calls with a
command name
The test that Summernote only starts after the content check matched calls
that pass a quoted command name, so a call that passes a variable, no arguments
or a second options object would not have been seen. It now matches every
.summernote( call and expects exactly the init after the check and the guarded
pasteHTML.
* Parse HTML without table parts as is in the content check's jQuery 3 path
When the HTML has a script, style or link tag but doesn't start with a
table part, jQuery 3 parses it without any wrapper, but the check added an
empty <> around it, which left stray text in its parse. RichEditorContentIT
covers an entry with a link tag in a comment.
* List in CHANGES the other entries that open in the HTML textarea
---
CHANGES.md | 6 +-
.../main/resources/ApplicationResources.properties | 1 +
.../webapp/WEB-INF/jsps/editor/EntryEditor.jsp | 73 ++++-
.../roller-ui/scripts/rich-editor-content.js | 328 +++++++++++++++++++++
.../struts2/editor/EntryEditorRichContentTest.java | 131 ++++++++
it-selenium/pom.xml | 9 +
.../apache/roller/selenium/InitialLoginTestIT.java | 70 +++++
.../selenium/editor/RichEditorContentIT.java | 299 +++++++++++++++++++
8 files changed, 900 insertions(+), 17 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index 3618fcaa6..8fc7e5782 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -30,7 +30,11 @@
- **Entries with scripts or embeds open as HTML.** If an entry contains
scripts, frames, embedded objects, event-handler attributes or
`javascript:` links, the rich-text editor opens it in the HTML textarea
- with a notice, and the stored HTML is kept as is (#331).
+ with a notice, and the stored HTML is kept as is. Entries with forms, some
+ Bootstrap data attributes (such as `data-toggle`), a link or URL-like word
+ containing `<`, as in some code samples, or an iframe or other tag that the
+ editor's code view removes, even inside an HTML comment, also open in the
+ textarea (#331).
- **Names are shown as text.** Screen and full names are HTML-escaped where
templates print them and written as plain text in feeds; commenter names
diff --git a/app/src/main/resources/ApplicationResources.properties
b/app/src/main/resources/ApplicationResources.properties
index 8426ced40..af58a7e8b 100644
--- a/app/src/main/resources/ApplicationResources.properties
+++ b/app/src/main/resources/ApplicationResources.properties
@@ -1566,6 +1566,7 @@ weblogEdit.draft=Draft
weblogEdit.draftEntries=Recent Drafts
weblogEdit.deleteEntry=Delete Entry
weblogEdit.insertMediaFile=Insert Media File
+weblogEdit.richEditorShowsHtml=This entry contains HTML the rich text editor
cannot show safely, so it opens as HTML.
weblogEdit.inlineImageInvalid=This entry contains an unsupported or invalid
embedded image. Use a PNG, JPEG or GIF image, or insert a media file.
weblogEdit.inlineImageTooLarge=This entry has too much embedded image data.
Resize the image or ask an administrator to enable media uploads.
error.postTooLarge=The form is too large to submit, so nothing was saved. Use
your browser's Back button to return to it. If it contains pasted images, use
smaller images or insert them as media files. An administrator can raise the
server's maximum POST size.
diff --git a/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
b/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
index fe63d7001..d653aef15 100644
--- a/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
+++ b/app/src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp
@@ -22,6 +22,11 @@
<%-- ********************************************************************* --%>
<%-- content --%>
+<s:if test="editor.id != 'editor-text.jsp'">
+<div id="edit_content_html_notice" class="alert alert-info" role="status"
style="display: none">
+ <s:text name="weblogEdit.richEditorShowsHtml"/>
+</div>
+</s:if>
<s:textarea id="edit_content" name="bean.text"
tabindex="5" rows="18" cssClass="col-sm-12" theme="simple"/>
@@ -88,6 +93,10 @@
</div>
+<s:if test="editor.id != 'editor-text.jsp'">
+<script src="<s:url value='/roller-ui/scripts/rich-editor-content.js'
/>"></script>
+</s:if>
+
<script>
<s:if test="editor.id == 'editor-text.jsp'">
@@ -146,7 +155,19 @@
<%-- Rich text editor functions --%>
+ // Entries with HTML that Summernote would run or drop open in the textarea
+ // as HTML; see rich-editor-content.js. Summernote starts the editor on any
+ // call, so every call checks this first.
+ var richEditorStarted = false;
+
$(document).ready(function () {
+ if
(RollerRichEditor.hasActiveHtml(document.getElementById('edit_content').value))
{
+ $('#edit_content_html_notice').show();
+
RollerRichEditor.trackCursor(document.getElementById('edit_content'));
+ armLeaveWarning();
+ return;
+ }
+ richEditorStarted = true;
$('#edit_content').summernote({
toolbar: [
// [groupName, [list of button]]
@@ -179,26 +200,46 @@
}
}
);
- // Added event listener to confirm once the editor content is changed
- $('#edit_content').on('summernote.change', function(we, contents,
$editable) {
- var confirmFunction = function(event) {
- // Chrome requires returnValue to be set and original event is
found as originalEvent
- // see
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example
- if (event.originalEvent)
- event.originalEvent.returnValue = "Are you sure you want
to leave?";
- return "Are you sure you want to leave?";
- }
- $(window).on("beforeunload", confirmFunction);
+ armLeaveWarning();
+ });
+
+ // Warns before leaving the page once the entry is edited. Input, not
+ // change, for the textarea: change waits for it to lose focus.
+ function armLeaveWarning() {
+ if (richEditorStarted) {
+ $('#edit_content').one('summernote.change', warnBeforeLeaving);
+ } else {
+ $("#edit_content").one("input", warnBeforeLeaving);
+ }
+ }
+
+ function warnBeforeLeaving() {
+ var confirmFunction = function(event) {
+ // Chrome requires returnValue to be set and original event is
found as originalEvent
+ // see
https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload#Example
+ if (event.originalEvent)
+ event.originalEvent.returnValue = "Are you sure you want to
leave?";
+ return "Are you sure you want to leave?";
+ }
+ $(window).on("beforeunload", confirmFunction);
- // Remove it if it is form submit
- $(this.form).on('submit', function() {
- $(window).off("beforeunload", confirmFunction);
- });
+ // Remove it if it is form submit, and warn again on the next edit if
+ // the page stays, as when the submit is stopped
+ $(this.form).one('submit', function() {
+ $(window).off("beforeunload", confirmFunction);
+ armLeaveWarning();
});
- });
+ }
function insertMediaFile(toInsert) {
- $('#edit_content').summernote("pasteHTML", toInsert);
+ if (richEditorStarted) {
+ $('#edit_content').summernote("pasteHTML", toInsert);
+ } else {
+ // at the cursor, or at the end if the textarea hasn't had one
+ var textArea = document.getElementById('edit_content');
+ RollerRichEditor.insertAtCursor(textArea, toInsert);
+ $(textArea).trigger("input");
+ }
}
</s:else>
diff --git a/app/src/main/webapp/roller-ui/scripts/rich-editor-content.js
b/app/src/main/webapp/roller-ui/scripts/rich-editor-content.js
new file mode 100644
index 000000000..cddab50a8
--- /dev/null
+++ b/app/src/main/webapp/roller-ui/scripts/rich-editor-content.js
@@ -0,0 +1,328 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+/*
+ * Summernote loads an entry's HTML into the live page, where event handler
+ * attributes, scripts and embedded frames run as the person editing it.
Entries
+ * can hold such HTML (videos, slide decks and other embeds), and Summernote
+ * would also drop some of it on save, so those entries open in the plain HTML
+ * textarea instead. The stored HTML is never changed.
+ *
+ * hasActiveHtml(html) parses the HTML the way the rich editor loads it, with
+ * jQuery's html(), but in an inert standards-mode document, and returns true
+ * if it contains anything the rich editor would run or can't keep: script,
+ * frame, plugin, style, raw text and document-level elements, forms and form
+ * controls, on* and formaction attributes, javascript: and vbscript: URLs in
+ * URL attributes, Bootstrap's data attributes, markup in a link's href or in a
+ * URL in the text, or markup that parses differently once serialized and
+ * parsed again, as the rich editor does for undo and code view. It returns
true
+ * if the HTML can't be parsed.
+ *
+ * insertAtCursor(textArea, text) inserts a media file into the textarea
+ * fallback at the cursor, or at the end when trackCursor(textArea) hasn't seen
+ * the cursor placed.
+ */
+var RollerRichEditor = (function () {
+
+ // jQuery runs <script> elements it inserts; <base>, <link> and <style>
+ // act on the whole page, as does a <meta> that isn't microdata (see
+ // isActiveElement); <noscript> parses differently in the inert document,
+ // which has scripting off, so its contents can't be checked; <textarea>,
+ // HTML <title>, <xmp>, <noembed>, <noframes> and <plaintext> hold raw text
+ // that reads as markup when moved elsewhere; SVG <set> and <animate> can
+ // change other attributes after loading. The rich editor is inside the
+ // entry form, so it drops a <form>'s own tags on save, and <input>,
+ // <button> and <select> would be submitted with the entry or submit it
+ // themselves.
+ var ACTIVE_ELEMENTS = "script, iframe, frame, frameset, object, embed,
applet, "
+ + "base, link, style, noscript, textarea, xmp, noembed, "
+ + "noframes, plaintext, set, animate, form, input, button, select";
+
+ var HTML_NAMESPACE = "http://www.w3.org/1999/xhtml";
+
+ // attributes whose value the browser loads or follows as a URL
+ var URL_ATTRIBUTES = ["href", "src", "action", "formaction", "xlink:href",
"data",
+ "poster", "background", "cite", "srcset"];
+
+ // Bootstrap's data API acts on clicks anywhere in the page; Bootstrap 3
+ // opens the dialog an element names and loads the element's link into it.
+ var BOOTSTRAP_ATTRIBUTES = ["data-toggle", "data-target", "data-dismiss",
"data-slide",
+ "data-slide-to"];
+
+ // When the author types a space after a word that starts like a URL,
+ // Summernote's autolink parses the word as HTML to make the link's text.
+ // Its words end at spaces and no-break spaces only.
+ var AUTOLINKED = /^(?:[a-z][a-z0-9+,.-]*:\/\/|tel:|mailto:|xmpp:|www\.)/i;
+ var WORD_BREAK = /[ \u00a0]/;
+
+ // control characters and whitespace that browsers ignore inside a URL
scheme
+ var IGNORED_IN_SCHEME = /[\s\u0000-\u001f\u007f- -]/g;
+
+ // jQuery's html() sets innerHTML in place, unless the HTML has one of
+ // these tags or its first tag, which can be inside a comment, is a table
+ // part. Then it parses the HTML in a detached element, inside the table
+ // elements that part needs.
+ var FIRST_TAG = /<([a-z][^\/\0>\x20\t\r\n\f]*)/i;
+ var NOT_IN_PLACE = /<script|<style|<link/i;
+ var TABLE_WRAPPERS = {
+ thead: ["table"], tbody: ["table"], tfoot: ["table"], colgroup:
["table"],
+ caption: ["table"], col: ["table", "colgroup"], tr: ["table", "tbody"],
+ td: ["table", "tbody", "tr"], th: ["table", "tbody", "tr"]
+ };
+
+ // Summernote 0.9 removes these tags from the HTML when the author leaves
+ // code view, and keeps an iframe only if it comes from one of a list of
+ // video sites.
+ var CODE_VIEW_FILTER =
/<\/*(?:applet|b(?:ase|gsound|link)|embed|frame(?:set)?|ilayer|l(?:ayer|ink)|meta|object|s(?:cript|tyle)|t(?:itle|extarea)|xml)[^>]*?>/gi;
+ var CODE_VIEW_IFRAME = /<iframe/i;
+
+ // how many trips through code view in a row the check follows
+ var CODE_VIEW_TRIPS = 3;
+
+ // A form control named "attributes" or "firstChild" replaces that property
+ // on its form, so these read the properties from the prototypes instead.
+ function getter(prototype, name) {
+ return Object.getOwnPropertyDescriptor(prototype, name).get;
+ }
+ var attributesOf = getter(Element.prototype, "attributes");
+ var firstChildOf = getter(Node.prototype, "firstChild");
+ var lastChildOf = getter(Node.prototype, "lastChild");
+ var nextSiblingOf = getter(Node.prototype, "nextSibling");
+ var innerHtmlOf = getter(Element.prototype, "innerHTML");
+ var contentOf = getter(HTMLTemplateElement.prototype, "content");
+
+ // the elements under a fragment or element that match a selector
+ function select(root, selector) {
+ var prototype = root instanceof DocumentFragment ?
DocumentFragment.prototype : Element.prototype;
+ return prototype.querySelectorAll.call(root, selector);
+ }
+
+ // a <template>'s contents, which are a separate fragment
+ function templateContent(element) {
+ return element instanceof HTMLTemplateElement ?
contentOf.call(element) : null;
+ }
+
+ function hasActiveScheme(url) {
+ var compact = url.replace(IGNORED_IN_SCHEME, "").toLowerCase();
+ return compact.indexOf("javascript:") === 0 ||
compact.indexOf("vbscript:") === 0;
+ }
+
+ function hasActiveUrl(name, value) {
+ if (URL_ATTRIBUTES.indexOf(name) === -1) {
+ return false;
+ }
+ if (name !== "srcset") {
+ return hasActiveScheme(value);
+ }
+ // each image candidate is a URL, then an optional width or density
+ var candidates = value.split(",");
+ for (var i = 0; i < candidates.length; i++) {
+ if (hasActiveScheme(candidates[i])) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // An SVG <title> is a tooltip, not raw text, and a <meta> with itemprop
+ // and none of name, http-equiv and charset is microdata.
+ function isActiveElement(element) {
+ if (element.namespaceURI !== HTML_NAMESPACE) {
+ return false;
+ }
+ var has = function (name) {
+ return Element.prototype.hasAttribute.call(element, name);
+ };
+ return element.localName === "title" || (element.localName === "meta"
+ && (!has("itemprop") || has("name") || has("http-equiv") ||
has("charset")));
+ }
+
+ function hasActiveNodes(root) {
+ if (select(root, ACTIVE_ELEMENTS).length) {
+ return true;
+ }
+ var elements = select(root, "*");
+ for (var i = 0; i < elements.length; i++) {
+ var element = elements[i];
+ if (isActiveElement(element)) {
+ return true;
+ }
+ var attributes = attributesOf.call(element);
+ for (var j = 0; j < attributes.length; j++) {
+ var name = attributes[j].name.toLowerCase();
+ var value = attributes[j].value;
+ // formaction sends the entry form somewhere else, and
+ // Summernote 0.8's link popover shows a link's href as HTML
+ if (name.indexOf("on") === 0 || name === "formaction" ||
hasActiveUrl(name, value)
+ || (name === "href" && value.indexOf("<") !== -1)
+ || BOOTSTRAP_ATTRIBUTES.indexOf(name) !== -1 ||
name.indexOf("data-bs-") === 0) {
+ return true;
+ }
+ }
+ // querySelector skips template contents
+ var content = templateContent(element);
+ if (content && hasActiveNodes(content)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // whether text under a node has a URL-like word with markup in it
+ function hasMarkupToAutolink(node) {
+ for (var child = firstChildOf.call(node); child; child =
nextSiblingOf.call(child)) {
+ if (child.nodeType === Node.TEXT_NODE) {
+ var words = child.nodeValue.split(WORD_BREAK);
+ for (var i = 0; i < words.length; i++) {
+ if (words[i].indexOf("<") !== -1 &&
AUTOLINKED.test(words[i])) {
+ return true;
+ }
+ }
+ } else if (hasMarkupToAutolink(child)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ // The elements under a node, with their namespaces and attributes, in
+ // order. Text is left out: a parser drops a newline at the start of a
+ // <pre> each time, which changes nothing that runs.
+ function shape(node) {
+ var out = "";
+ for (var child = firstChildOf.call(node); child; child =
nextSiblingOf.call(child)) {
+ if (!(child instanceof Element)) {
+ continue;
+ }
+ var attributes = attributesOf.call(child);
+ out += "<" + child.namespaceURI + " " + child.localName;
+ for (var i = 0; i < attributes.length; i++) {
+ out += " " + attributes[i].name + "=" +
JSON.stringify(attributes[i].value);
+ }
+ out += ">" + shape(templateContent(child) || child) + "</>";
+ }
+ return out;
+ }
+
+ // What jQuery's html() builds from the HTML, for jQuery 3 and 4: for each
+ // parse, a holder with every element the parser made, and the element
+ // whose children the rich editor gets, or null where jQuery would fail.
+ function parseAsEditor(doc, html) {
+ var tag = (FIRST_TAG.exec(html) || ["", ""])[1].toLowerCase();
+ var wrappers = TABLE_WRAPPERS.hasOwnProperty(tag) ?
TABLE_WRAPPERS[tag] : null;
+ if (!wrappers && !NOT_IN_PLACE.test(html)) {
+ // In place, in the rich editor inside the entry form, where the
+ // parser ignores the start tag of another <form>. Outside it, the
+ // same HTML shows the forms the rich editor would drop on save.
+ var form = doc.createElement("form");
+ var editor = form.appendChild(doc.createElement("div"));
+ editor.innerHTML = html;
+ var outside = doc.createElement("div");
+ outside.innerHTML = html;
+ return [{holder: editor, content: editor}, {holder: outside,
content: outside}];
+ }
+ wrappers = wrappers || [];
+ // jQuery 3 adds the wrappers' tags around the HTML, then takes the
+ // last child at each level
+ var asText = doc.createElement("div");
+ asText.innerHTML = wrappers.length ? "<" + wrappers.join("><") + ">" +
html
+ + "</" + wrappers.slice().reverse().join("></") + ">" : html;
+ var content = asText;
+ for (var i = 0; i < wrappers.length && content; i++) {
+ content = lastChildOf.call(content);
+ }
+ // jQuery 4 parses the HTML inside the wrapper elements
+ var asElements = doc.createElement("div");
+ var inner = asElements;
+ for (var j = 0; j < wrappers.length; j++) {
+ inner = inner.appendChild(doc.createElement(wrappers[j]));
+ }
+ inner.innerHTML = html;
+ return [{holder: asText, content: content}, {holder: asElements,
content: inner}];
+ }
+
+ // Whether the rich editor could run or lose something in the HTML as it
+ // loads it, and as it loads it again for undo and when leaving code view.
+ function isActive(doc, html, codeViewTrips) {
+ var parses = parseAsEditor(doc, html);
+ for (var i = 0; i < parses.length; i++) {
+ var content = parses[i].content;
+ if (!content || hasActiveNodes(parses[i].holder) ||
hasMarkupToAutolink(content)) {
+ return true;
+ }
+ // Summernote serializes its content and loads it again for undo;
+ // markup such as nested forms comes back as a different tree of
+ // elements, which this check hasn't seen.
+ var serialized = innerHtmlOf.call(content);
+ var again = parseAsEditor(doc, serialized);
+ for (var j = 0; j < again.length; j++) {
+ if (!again[j].content || shape(again[j].content) !==
shape(content)) {
+ return true;
+ }
+ }
+ // Leaving code view removes tags from the serialized HTML, which
+ // can turn text inside a comment or an attribute into markup.
+ if (CODE_VIEW_IFRAME.test(serialized)) {
+ return true;
+ }
+ var viewed = serialized.replace(CODE_VIEW_FILTER, "");
+ if (viewed !== serialized
+ && (codeViewTrips === 0 || isActive(doc, viewed,
codeViewTrips - 1))) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ function hasActiveHtml(html) {
+ if (!html) {
+ return false;
+ }
+ try {
+ // a standards-mode document, like the editor page, that runs
nothing
+ var doc = document.implementation.createHTMLDocument("");
+ return isActive(doc, html, CODE_VIEW_TRIPS);
+ } catch (e) {
+ return true;
+ }
+ }
+
+ // A textarea's cursor is at 0 both before anyone has placed it and when
+ // someone has put it at the very start, so this remembers which it is.
+ function trackCursor(textArea) {
+ var placed = function () {
+ textArea.rollerCursorPlaced = true;
+ };
+ textArea.addEventListener("focus", placed);
+ textArea.addEventListener("select", placed);
+ }
+
+ function insertAtCursor(textArea, text) {
+ var start = textArea.selectionStart;
+ var end = textArea.selectionEnd;
+ if (!textArea.rollerCursorPlaced) {
+ start = end = textArea.value.length;
+ }
+ textArea.value = textArea.value.substring(0, start) + text +
textArea.value.substring(end);
+ textArea.selectionStart = textArea.selectionEnd = start + text.length;
+ textArea.focus();
+ }
+
+ return {hasActiveHtml: hasActiveHtml, trackCursor: trackCursor,
insertAtCursor: insertAtCursor};
+}());
diff --git
a/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/EntryEditorRichContentTest.java
b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/EntryEditorRichContentTest.java
new file mode 100644
index 000000000..e37673f06
--- /dev/null
+++
b/app/src/test/java/org/apache/roller/weblogger/ui/struts2/editor/EntryEditorRichContentTest.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.roller.weblogger.ui.struts2.editor;
+
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * Summernote runs event handlers and scripts in the HTML it loads, so the rich
+ * editor in EntryEditor.jsp checks the entry with rich-editor-content.js first
+ * and opens entries that fail the check in the textarea. Summernote also
starts
+ * itself on any call, so each call must be behind the same check. The check
+ * itself runs in a browser in it-selenium's RichEditorContentIT; this keeps
+ * the page wired to it.
+ */
+class EntryEditorRichContentTest {
+
+ private static String read(String path) throws IOException {
+ return new String(Files.readAllBytes(Paths.get(path)),
StandardCharsets.UTF_8);
+ }
+
+ /** Every call to Summernote, whatever it passes. */
+ private static final Pattern SUMMERNOTE_CALL =
Pattern.compile("\\.summernote\\(");
+
+ @Test
+ void summernoteStartsOnlyAfterTheContentCheck() throws IOException {
+ String jsp =
read("src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp");
+ assertTrue(jsp.contains("/roller-ui/scripts/rich-editor-content.js"));
+
+ int check = jsp.indexOf("RollerRichEditor.hasActiveHtml(");
+ int start = jsp.indexOf("richEditorStarted = true;");
+ int init = jsp.indexOf("$('#edit_content').summernote({");
+ assertTrue(check > 0 && check < start && start < init, "check, then
start, then init");
+
+ // the only other call is guarded by the flag
+ Matcher call = SUMMERNOTE_CALL.matcher(jsp);
+ int calls = 0;
+ while (call.find()) {
+ calls++;
+ if (call.start() == init + "$('#edit_content')".length()) {
+ continue;
+ }
+ String before = jsp.substring(Math.max(0, call.start() - 120),
call.start());
+ assertTrue(before.contains("if (richEditorStarted)"), "unguarded
call near: " + before);
+ }
+ assertEquals(2, calls, "the init and the guarded pasteHTML");
+ }
+
+ @Test
+ void summernoteCallsAreFoundWhateverTheyPass() {
+
assertTrue(SUMMERNOTE_CALL.matcher("$('#edit_content').summernote(\"code\",
html);").find());
+
assertTrue(SUMMERNOTE_CALL.matcher("$('#edit_content').summernote('code',
html);").find());
+
assertTrue(SUMMERNOTE_CALL.matcher("$('#edit_content').summernote(command);").find());
+
assertTrue(SUMMERNOTE_CALL.matcher("$('#edit_content').summernote();").find());
+
assertTrue(SUMMERNOTE_CALL.matcher("$(\"#edit_content\").summernote({height:
400});").find());
+ }
+
+ @Test
+ void theLeaveWarningIsAddedOnce() throws IOException {
+ String jsp =
read("src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp");
+ // each change would otherwise add another beforeunload handler
+ assertTrue(jsp.contains(".one('summernote.change',
warnBeforeLeaving)"));
+ assertFalse(jsp.contains(".on('summernote.change'"));
+ }
+
+ @Test
+ void theLeaveWarningComesBackAfterASubmitThatStaysOnThePage() throws
IOException {
+ String jsp =
read("src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp");
+ int submit = jsp.indexOf("$(this.form).one('submit', function() {");
+ int off = jsp.indexOf("$(window).off(\"beforeunload\",
confirmFunction);", submit);
+ int rearm = jsp.indexOf("armLeaveWarning();", off);
+ int end = jsp.indexOf("});", off);
+ assertTrue(submit > 0 && off > submit && rearm > off && rearm < end,
+ "the submit handler removes the warning, then arms it for the
next edit");
+ // the rich editor and the textarea fallback both start through it
+ int check = jsp.indexOf("RollerRichEditor.hasActiveHtml(");
+ int start = jsp.indexOf("richEditorStarted = true;");
+ int fallback = jsp.indexOf("armLeaveWarning();", check);
+ int rich = jsp.indexOf("armLeaveWarning();", start);
+ assertTrue(fallback > check && fallback < start && rich > start);
+ }
+
+ @Test
+ void theTextareaFallbackWarnsWhileTheAuthorTypes() throws IOException {
+ String jsp =
read("src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp");
+ // change waits for the textarea to lose focus, so an author who types
+ // and closes the tab would not be warned
+ assertTrue(jsp.contains("$(\"#edit_content\").one(\"input\",
warnBeforeLeaving);"));
+ assertFalse(jsp.contains("one(\"change\", warnBeforeLeaving)"));
+ // a media file inserted into the textarea counts as an edit too
+ assertTrue(jsp.contains("$(textArea).trigger(\"input\");"));
+ }
+
+ @Test
+ void theTextareaFallbackInsertsMediaAtTheCursor() throws IOException {
+ String jsp =
read("src/main/webapp/WEB-INF/jsps/editor/EntryEditor.jsp");
+ int check = jsp.indexOf("RollerRichEditor.hasActiveHtml(");
+ int track = jsp.indexOf("RollerRichEditor.trackCursor(");
+ int start = jsp.indexOf("richEditorStarted = true;");
+ assertTrue(check > 0 && check < track && track < start,
+ "the fallback tracks the cursor before the rich editor would
start");
+ assertTrue(jsp.contains("RollerRichEditor.insertAtCursor(textArea,
toInsert);"));
+ }
+}
diff --git a/it-selenium/pom.xml b/it-selenium/pom.xml
index 63c1a60be..370eeaa3e 100644
--- a/it-selenium/pom.xml
+++ b/it-selenium/pom.xml
@@ -106,6 +106,15 @@
<scope>test</scope>
</dependency>
+ <!-- RichEditorContentIT loads entries with the jQuery the rich editor
+ uses; keep in step with app/pom.xml -->
+ <dependency>
+ <groupId>org.webjars</groupId>
+ <artifactId>jquery</artifactId>
+ <version>3.7.1</version>
+ <scope>test</scope>
+ </dependency>
+
<!--
Type "war" listed below makes this a WAR overlay (i.e.,
incorporating
another WAR into this project in making a new WAR, with any
additional
diff --git
a/it-selenium/src/test/java/org/apache/roller/selenium/InitialLoginTestIT.java
b/it-selenium/src/test/java/org/apache/roller/selenium/InitialLoginTestIT.java
index 692d1a025..adfb78adc 100644
---
a/it-selenium/src/test/java/org/apache/roller/selenium/InitialLoginTestIT.java
+++
b/it-selenium/src/test/java/org/apache/roller/selenium/InitialLoginTestIT.java
@@ -37,14 +37,19 @@ import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
+import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.firefox.FirefoxProfile;
+import org.openqa.selenium.support.ui.Select;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class InitialLoginTestIT {
@@ -104,6 +109,71 @@ public class InitialLoginTestIT {
System.out.println("title/text: " + sbep.getBlogTitle() + " / " +
sbep.getBlogText());
assertEquals(blogEntryTitle, sbep.getBlogTitle());
assertEquals(blogEntryContent, sbep.getBlogText());
+
+ editEntryInTheHtmlTextarea();
+ }
+
+ /**
+ * Publishes an entry with HTML the rich editor would run or drop, then
+ * switches the weblog to the rich editor, where the entry opens in the
+ * HTML textarea. Checks that the page warns before leaving once the
+ * textarea is edited: while the author is still typing in it, and after a
+ * media file is inserted.
+ */
+ private void editEntryInTheHtmlTextarea() {
+ driver.get(baseUrl +
"roller-ui/authoring/entryAdd.rol?weblog=bobsblog");
+ EntryAddPage eap = new EntryAddPage(driver);
+ eap.setTitle("An entry with a click handler");
+ eap.setText("<p onclick=\"void 0\">Click me</p>");
+ eap.postBlogEntry();
+ String editPage = baseUrl +
"roller-ui/authoring/entryEdit.rol?weblog=bobsblog&bean.id="
+ + driver.findElement(By.name("bean.id")).getAttribute("value");
+ // Summernote kept the id of the Xinha editor it replaced
+ setWeblogEditor("editor-xinha.jsp");
+
+ driver.get(editPage);
+
assertTrue(driver.findElement(By.id("edit_content_html_notice")).isDisplayed());
+ assertFalse("an unedited entry should not warn before leaving",
warnsBeforeLeaving());
+ WebElement text = driver.findElement(By.id("edit_content"));
+ text.click();
+ text.sendKeys(" more");
+ assertTrue("typing in the HTML textarea should warn before leaving",
warnsBeforeLeaving());
+ stopWarningBeforeLeaving();
+
+ // what the media file chooser calls with the chosen file
+ driver.get(editPage);
+ js("insertMediaFile('<a href=\"/x.png\">x.png</a>');");
+
assertTrue(driver.findElement(By.id("edit_content")).getAttribute("value").contains("x.png"));
+ assertTrue("inserting a media file in the HTML textarea should warn
before leaving",
+ warnsBeforeLeaving());
+ stopWarningBeforeLeaving();
+
+ setWeblogEditor("editor-text.jsp");
+ }
+
+ /** Picks the weblog's entry editor on its settings page. */
+ private void setWeblogEditor(String editor) {
+ driver.get(baseUrl +
"roller-ui/authoring/weblogConfig.rol?weblog=bobsblog");
+ new
Select(driver.findElement(By.name("bean.editorPage"))).selectByValue(editor);
+ driver.findElement(By.cssSelector("form[action*='weblogConfig']
input.btn-success")).click();
+ assertTrue(driver.findElement(By.id("messages")).isDisplayed());
+ }
+
+ private Object js(String code, Object... args) {
+ return ((JavascriptExecutor) driver).executeScript(code, args);
+ }
+
+ /** Whether leaving the page now would ask the author to confirm. */
+ private boolean warnsBeforeLeaving() {
+ return (Boolean) js("var event =
document.createEvent('BeforeUnloadEvent');"
+ + "event.initEvent('beforeunload', false, true);"
+ + "window.dispatchEvent(event);"
+ + "return event.defaultPrevented || !!event.returnValue;");
+ }
+
+ /** Removes the leave-page warning, so the next navigation isn't held up.
*/
+ private void stopWarningBeforeLeaving() {
+ js("$(window).off('beforeunload');");
}
diff --git
a/it-selenium/src/test/java/org/apache/roller/selenium/editor/RichEditorContentIT.java
b/it-selenium/src/test/java/org/apache/roller/selenium/editor/RichEditorContentIT.java
new file mode 100644
index 000000000..c0e2d8992
--- /dev/null
+++
b/it-selenium/src/test/java/org/apache/roller/selenium/editor/RichEditorContentIT.java
@@ -0,0 +1,299 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.roller.selenium.editor;
+
+import java.io.InputStream;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.openqa.selenium.JavascriptExecutor;
+import org.openqa.selenium.WebDriver;
+import org.openqa.selenium.firefox.FirefoxDriver;
+import org.openqa.selenium.firefox.FirefoxOptions;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Runs the entry editor's rich-editor-content.js in a blank page in Firefox,
+ * without a Roller server: which entries open in the HTML textarea instead of
+ * the rich editor, and where the textarea fallback inserts media files.
+ *
+ * <p>The module's verify phase starts Roller in Jetty first. To run just this
+ * class without it, from it-selenium:
+ * {@code mvn test-compile failsafe:integration-test failsafe:verify
-Dit.test=RichEditorContentIT}
+ */
+public class RichEditorContentIT {
+
+ private static final String[] OPEN_IN_THE_TEXTAREA = {
+ "<script>document.title = 'x'</script>",
+ "<p>text</p><img src=\"x.png\" onerror=\"document.title = 'x'\">",
+ "<p ONCLICK=\"go()\">text</p>",
+ "<a href=\"javascript:go()\">link</a>",
+ "<a href=\" JaVa	Script:go()\">link</a>",
+ "<a href=\"javascript:go()\">link</a>",
+ "<a href=\"vbscript:go\">link</a>",
+ "<img src=\"a.png\" srcset=\"a.png 1x, javascript:go() 2x\">",
+ "<svg><a xlink:href=\"javascript:go()\"><text>x</text></a></svg>",
+ "<form><button formaction=\"javascript:go()\">x</button></form>",
+ "<form action=\"javascript:go()\"></form>",
+ "<object data=\"x.swf\"></object>",
+ "<video poster=\"javascript:go()\"></video>",
+ "<table background=\"javascript:go()\"><tr><td>x</td></tr></table>",
+ "<blockquote cite=\"javascript:go()\">x</blockquote>",
+ "<iframe src=\"https://www.youtube.com/embed/x\"></iframe>",
+ "<style>body { display: none }</style>",
+ "<td onclick=\"go()\">cell outside a table</td>",
+ "<caption onmouseover=\"go()\">x</caption>",
+ "<template><img src=x onerror=\"go()\"></template>",
+ "<noscript><p title=\"</noscript><img src=x
onerror=go()>\"></noscript>",
+ "<textarea><img src=x onerror=go()></textarea>",
+ "<xmp><img src=x onerror=go()></xmp>",
+ "<noembed><img src=x onerror=go()></noembed>",
+ "<title><img src=x onerror=go()></title>",
+ "<form><math><mtext></form><form><mglyph><style></math><img src
onerror=go()>",
+ "<math><mtext><table><mglyph><style><img src=x
onerror=go()></style></mglyph></table></mtext></math>",
+ // markup that parses differently once serialized and parsed again,
+ // as the rich editor does for undo and code view
+ "<form><div></form><form><p>x</p>",
+ "<form><math><mtext></form><form><mglyph><b>x</b></mglyph></form>",
+ // inside the entry form a nested form's start tag is ignored, so the
+ // image is an element there
+ "<math><mtext><p><form></form><mglyph><![CDATA[><img src
onerror=go()>]]>",
+ // a control named "attributes" hides its form's attributes
+ "</form><form style=\"animation-name:spin;animation-duration:1ms\"
onanimationstart=\"go()\">"
+ + "<input name=\"attributes\">x</form>",
+ // the rich editor drops a form's wrapper on save
+ "<form action=\"https://example.com/subscribe\"><input
name=\"email\"></form>",
+ // controls join the entry form and are submitted with it
+ "<input type=\"hidden\" name=\"bean.status\" value=\"PUBLISHED\">",
+ "<button formaction=\"https://example.com/x\">Save</button>",
+ "<button>Save</button>",
+ "<select name=\"bean.categoryId\"><option>x</option></select>",
+ "<p formaction=\"https://example.com/x\">text</p>",
+ // an image's name replaces that property on its document
+ "<img name=body><img src onerror=go()>",
+ "<form name=body></form><img src onerror=go()>",
+ "<img name=documentElement><img src onerror=go()>",
+ "<img name=querySelectorAll><img src onerror=go()>",
+ "<img name=body><table><tr><td onclick=\"go()\">x</td></tr></table>",
+ // jQuery parses HTML that starts with a table part inside a table
+ "<col><td onclick=\"go()\">x</td>",
+ // leaving code view removes <meta> tags, which here ends the comment
+ "<!-- -<meta>-> <input> -->",
+ "<!-- <iframe src=\"https://example.com/\"></iframe> -->",
+ // the rich editor shows these as HTML: a link's href in its link
+ // popover, and a URL-like word when the author types a space after it
+ "<p><a href=\"<b>bold</b>\">text</a></p>",
+ "<p>See https://example.com/<b>bold</b></p>",
+ "<p>See www.example.com/<b>bold</b></p>",
+ // Bootstrap acts on clicks on these anywhere in the page
+ "<p><a data-toggle=\"modal\" data-target=\"#x\"
href=\"/x\">text</a></p>",
+ "<p><a data-bs-toggle=\"collapse\" href=\"#x\">text</a></p>",
+ "<meta name=\"referrer\" content=\"no-referrer\">",
+ "<meta itemprop=\"isbn\" http-equiv=\"refresh\" content=\"0\">",
+ };
+
+ // checked as the rich editor loads them, with jQuery inside the entry
+ // form; none of these handlers runs without a click
+ private static final String[] LOADED_IN_THE_ENTRY_FORM = {
+ "<form><div></form><form><p onclick=\"go()\">x</p>",
+ "</form><form onclick=\"go()\"><input name=\"attributes\">x</form>",
+ "<col><td onclick=\"go()\">x</td>",
+ "<caption onclick=\"go()\">x</caption>",
+ "<!--<tr>--><td onclick=\"go()\">x</td>",
+ "<p>Hello <b>world</b></p>",
+ "<table><caption>c</caption><tr><td>1</td><td>2</td></tr></table>",
+ };
+
+ private static final String[] STAY_IN_THE_RICH_EDITOR = {
+ "",
+ "<p>Hello <b>world</b> and <i>everyone</i></p>",
+ "<a href=\"https://example.com/\" title=\"JavaScript: The Good
Parts\">book</a>",
+ "<img src=\"/blog/mediaresource/x.png\" alt=\"javascript: is a URL
scheme\">",
+ "<p>Type javascript: into the address bar</p>",
+ "<p data-note=\"vbscript: old\">text</p>",
+ "<a href=\"/wiki/javascript:void\">article</a>",
+ "<a href=\"https://example.com/?q=javascript:\">search</a>",
+ "<img src=\"a.png\" srcset=\"a.png 1x, b.png 2x\" alt=\"\">",
+ "<table><caption>c</caption><tr><td>1</td><td>2</td></tr></table>",
+ "<ul><li>one</li><li>two</li></ul><blockquote
cite=\"https://example.com/\">q</blockquote>",
+ "<pre><code>if (a < b) { run(); }</code></pre>",
+ "<pre>\n\nfirst line after a blank one</pre>",
+ "<p>One</p>\n<p>Two</p>\n",
+ "<img name=\"body\" src=\"a.png\" alt=\"\"><p>text</p>",
+ "<img name=\"querySelector\" src=\"a.png\" alt=\"\">",
+ "<img name=\"querySelectorAll\" src=\"a.png\" alt=\"\">",
+ "<img name=\"createElement\" src=\"a.png\" alt=\"\">",
+ "<!-- more --><p>text</p>",
+ "<!-- <b>bold</b> and <meta> --><p>text</p>",
+ "<table><tr><td>1</td></tr></table><p>after the table</p>",
+ "<p>Use <b> for bold, as https://example.com/ shows</p>",
+ // an SVG tooltip, and microdata
+ "<svg width=\"10\" height=\"10\"><title>Chart</title><rect
width=\"10\" height=\"10\"></rect></svg>",
+ "<div itemscope itemtype=\"https://schema.org/Book\"><meta
itemprop=\"isbn\" content=\"123\"></div>",
+ // jQuery parses HTML with a link tag in it outside the page
+ "<!-- <link rel=\"stylesheet\" href=\"a.css\"> --><p>text</p>",
+ };
+
+ // the rich editor loads entries with jQuery's html()
+ private static final String JQUERY =
"META-INF/resources/webjars/jquery/3.7.1/jquery.js";
+
+ private static WebDriver driver;
+ private static String script;
+ private static String jquery;
+
+ @BeforeClass
+ public static void startBrowser() throws Exception {
+ script = new String(Files.readAllBytes(Paths.get(
+
"../app/src/main/webapp/roller-ui/scripts/rich-editor-content.js")),
+ StandardCharsets.UTF_8);
+ try (InputStream in =
RichEditorContentIT.class.getClassLoader().getResourceAsStream(JQUERY)) {
+ jquery = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ }
+ FirefoxOptions options = new FirefoxOptions();
+ options.addArguments("-headless");
+ driver = new FirefoxDriver(options);
+ }
+
+ @AfterClass
+ public static void stopBrowser() {
+ if (driver != null) {
+ driver.quit();
+ }
+ }
+
+ /** A blank page with the editor's textarea, in a form, and the script
loaded. */
+ @Before
+ public void openPage() {
+ driver.get("about:blank");
+ js("document.body.innerHTML = '<form id=\"entry\">"
+ + "<textarea id=\"edit_content\">Hello
world</textarea></form>';"
+ + "var s = document.createElement('script');"
+ + "s.textContent = arguments[0];"
+ + "document.head.appendChild(s);", script);
+ }
+
+ private static Object js(String code, Object... args) {
+ return ((JavascriptExecutor) driver).executeScript(code, args);
+ }
+
+ private static boolean hasActiveHtml(String html) {
+ return (Boolean) js("return
RollerRichEditor.hasActiveHtml(arguments[0]);", html);
+ }
+
+ @Test
+ public void entriesWithActiveHtmlOpenInTheTextarea() {
+ StringBuilder missed = new StringBuilder();
+ for (String html : OPEN_IN_THE_TEXTAREA) {
+ if (!hasActiveHtml(html)) {
+ missed.append("\n ").append(html);
+ }
+ }
+ assertEquals("should open in the textarea:", "", missed.toString());
+ }
+
+ @Test
+ public void otherEntriesStayInTheRichEditor() {
+ StringBuilder flagged = new StringBuilder();
+ for (String html : STAY_IN_THE_RICH_EDITOR) {
+ if (hasActiveHtml(html)) {
+ flagged.append("\n ").append(html);
+ }
+ }
+ assertEquals("should stay in the rich editor:", "",
flagged.toString());
+ }
+
+ /**
+ * The rich editor loads an entry with jQuery's html(), inside the entry
+ * form, where a nested form's start tag is ignored, so what the check lets
+ * through must not hold an event handler once jQuery has loaded it there.
+ * about:blank is in quirks mode and the editor page isn't, so jQuery loads
+ * the entry into a standards-mode document here.
+ */
+ @Test
+ public void whatStaysInTheRichEditorHasNoEventHandlersOnceJqueryLoadsIt() {
+ js("var s = document.createElement('script');"
+ + "s.textContent = arguments[0];"
+ + "document.head.appendChild(s);", jquery);
+ StringBuilder missed = new StringBuilder();
+ for (String html : LOADED_IN_THE_ENTRY_FORM) {
+ boolean handlers = (Boolean) js(
+ "var page =
document.implementation.createHTMLDocument('');"
+ + "var form =
page.body.appendChild(page.createElement('form'));"
+ + "var holder =
form.appendChild(page.createElement('div'));"
+ + "jQuery(holder).html(arguments[0]);"
+ + "return
Array.from(holder.querySelectorAll('*')).some(function (element) {"
+ + " return element.getAttributeNames().some(function
(name) {"
+ + " return name.indexOf('on') === 0;"
+ + " });"
+ + "});", html);
+ if (handlers && !hasActiveHtml(html)) {
+ missed.append("\n ").append(html);
+ }
+ }
+ assertEquals("should open in the textarea:", "", missed.toString());
+ }
+
+ private static String insert(String text) {
+
js("RollerRichEditor.insertAtCursor(document.getElementById('edit_content'),
arguments[0]);",
+ text);
+ return (String) js("return
document.getElementById('edit_content').value;");
+ }
+
+ private static void trackAndPlaceCursor(int start, int end) {
+ js("var t = document.getElementById('edit_content');"
+ + "RollerRichEditor.trackCursor(t);"
+ + "if (arguments[0] >= 0) { t.focus();
t.setSelectionRange(arguments[0], arguments[1]); }",
+ start, end);
+ }
+
+ @Test
+ public void insertsAtTheEndWhenTheCursorWasNeverPlaced() {
+ trackAndPlaceCursor(-1, -1);
+ assertEquals("Hello world[media]", insert("[media]"));
+ }
+
+ @Test
+ public void insertsAtTheStartWhenTheCursorWasPlacedThere() {
+ trackAndPlaceCursor(0, 0);
+ assertEquals("[media]Hello world", insert("[media]"));
+ // the cursor follows the inserted text
+ assertEquals("[media][more]Hello world", insert("[more]"));
+ }
+
+ @Test
+ public void replacesTheSelection() {
+ trackAndPlaceCursor(6, 11);
+ assertEquals("Hello [media]", insert("[media]"));
+ }
+
+ @Test
+ public void theScriptLoaded() {
+ assertTrue((Boolean) js("return typeof RollerRichEditor.hasActiveHtml
=== 'function';"));
+ assertFalse(hasActiveHtml("<p>x</p>"));
+ }
+}