Debian Codegraph @

extensions/MultimediaViewer/resources/mmv/mmv.HtmlUtils.js

raw symbols SCIP
1 /*
2 * This file is part of the MediaWiki extension MediaViewer.
3 *
4 * MediaViewer is free software: you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation, either version 2 of the License, or
7 * (at your option) any later version.
8 *
9 * MediaViewer is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with MediaViewer. If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 /**
19 * Shared cache between HtmlUtils instances to store the results of expensive text operations.
20 *
21 * @member HtmlUtils
22 * @private
23 * @static
24 * @type {{text: Object.<string, string>, textWithLinks: Object.<string, string>, textWithTags: Object.<string, string>}}
25 */
26 const cache = {
27 text: {},
28 textWithLinks: {},
29 textWithTags: {}
30 };
31
32 /**
33 * Helper class that does various HTML-to-text transformations
34 */
35 class HtmlUtils {
36 /**
37 * Returns a jQuery node which contains the given HTML (wrapped into a `<div>` - this is
38 * necessary since an arbitrary HTML string might not have a jQuery representation).
39 *
40 * @param {string|HTMLElement|jQuery} html
41 * @return {jQuery}
42 */
43 static wrapAndJquerify( html ) {
44 if ( HtmlUtils.isJQueryOrHTMLElement( html ) ) {
45 return $( '<div>' ).append( $( html ).clone() );
46 } else if ( typeof html === 'string' ) {
47 return $( '<div>' ).html( html );
48 } else {
49 mw.log.warn( 'wrapAndJquerify: unknown type', html );
50 throw new Error( 'wrapAndJquerify: unknown type' );
51 }
52 }
53
54 /**
55 * Returns true of the object is a jQuery object or an HTMLElement, false otherwise
56 *
57 * @param {string|HTMLElement|jQuery} html
58 * @return {boolean}
59 */
60 static isJQueryOrHTMLElement( html ) {
61 if ( html instanceof $ ) {
62 return true;
63 }
64
65 if ( window.HTMLElement ) {
66 if ( html instanceof HTMLElement ) {
67 return true;
68 }
69 }
70
71 return false;
72 }
73
74 /**
75 * Filters display:none and <style></style> children of a node.
76 * The root element is never filtered, and generally ignored (i.e. whether the root element is
77 * visible won't affect the filtering).
78 * Works in place.
79 *
80 * @param {jQuery} $jq
81 */
82 static filterInvisible( $jq ) {
83 // We are not using :visible because
84 // 1) it would require appending $jq to the document which makes things complicated;
85 // 2) the main difference is that it looks for CSS rules hiding the element;
86 // since this function is intended to be used on html originating from a different
87 // document, possibly a different site, that would probably have unexpected results.
88 $jq
89 .find( '[style]' )
90 .filter( ( i, el ) => el.style.display === 'none' )
91 .remove();
92
93 // TemplateStyles can generate inline style tags
94 $jq
95 .find( 'style' )
96 .remove();
97 }
98
99 /**
100 * Discards all nodes which do not match the allowlist,
101 * but keeps the text and allowlisted nodes inside them.
102 * Works in-place.
103 *
104 * @param {jQuery} $el
105 * @param {string} allowlist a jQuery selector string such as 'a, span, br'
106 */
107 static allowlistHtml( $el, allowlist ) {
108 let $prev;
109 let $child = $el.children().first();
110
111 while ( $child && $child.length ) {
112 const child = $child.get( 0 );
113
114 if ( child.nodeType !== child.ELEMENT_NODE ) {
115 return;
116 }
117
118 HtmlUtils.allowlistHtml( $child, allowlist );
119
120 if ( !$child.is( allowlist ) ) {
121 $prev = $child.prev();
122 $child.replaceWith( $child.contents() );
123 } else {
124 $prev = $child;
125 }
126
127 if ( $prev && $prev.length === 1 ) {
128 $child = $prev.next();
129 } else {
130 $child = $el.children().first();
131 }
132 }
133 }
134
135 /**
136 * Adds a whitespace to block elements. This is useful if you want to convert the contents
137 * to text and don't want words that are visually separate (e.g. table cells) to be fused.
138 * Works in-place.
139 *
140 * @param {jQuery} $el
141 */
142 static appendWhitespaceToBlockElements( $el ) {
143 // the list of what elements to add whitespace to is somewhat ad-hoc (not all of these
144 // are technically block-level elements, and a lot of block-level elements are missing)
145 // but will hopefully cover the common cases where text is fused together.
146 $el
147 .find( 'blockquote, dd, dl, dt, li, td' )
148 .before( ' ' )
149 .after( ' ' );
150 $el
151 .find( 'br, tr, p' )
152 .before( '\n' )
153 .after( '\n' );
154 }
155
156 /**
157 * Returns the HTML code for a jQuery element (only the first one if passed a set of elements).
158 * Unlike .html(), this includes HTML code for the outermost element; compare
159 * - `$('<div>').html() // ''`
160 * - `HtmlUtils.jqueryToHtml( $('<div>') ) // '<div></div>'`
161 *
162 * @param {jQuery} $el
163 * @return {string}
164 */
165 static jqueryToHtml( $el ) {
166 // There are two possible implementations for this:
167 // 1) load into a wrapper element and get its innerHTML;
168 // 2) use outerHTML.
169 // We go with 1) because it handles the case when a jQuery object contains something
170 // that is not an element (this can happen with e.g. $x.children() which returns text
171 // nodes as well).
172 return $( '<div>' ).append( $el ).html();
173 }
174
175 /**
176 * Cleans up superfluous whitespace.
177 * Given that the results will be displayed in a HTML environment, this doesn't have any real
178 * effect. It is mostly there to make testing easier.
179 *
180 * @protected
181 * @param {string} html a HTML (or plaintext) string
182 * @return {string}
183 */
184 static mergeWhitespace( html ) {
185 html = html.replace( /^\s+|\s+$/g, '' );
186 html = html.replace( /\s*\n\s*/g, '\n' );
187 html = html.replace( / {2,}/g, ' ' );
188 return html;
189 }
190
191 /**
192 * Returns the text content of a html string.
193 * Tries to give an approximation of what would be visible if the HTML would be displayed.
194 *
195 * @param {string} html
196 * @return {string}
197 */
198 static htmlToText( html ) {
199 if ( !cache.text[ html ] ) {
200 const $html = HtmlUtils.wrapAndJquerify( html );
201 HtmlUtils.filterInvisible( $html );
202 HtmlUtils.appendWhitespaceToBlockElements( $html );
203 cache.text[ html ] = HtmlUtils.mergeWhitespace( $html.text() );
204 }
205 return cache.text[ html ];
206 }
207
208 /**
209 * Returns the text content of a html string, with the `<a>`, `<i>`, `<b>` tags left intact.
210 * Tries to give an approximation of what would be visible if the HTML would be displayed.
211 *
212 * @param {string} html
213 * @return {string}
214 */
215 static htmlToTextWithTags( html ) {
216 if ( !cache.textWithTags[ html ] ) {
217 const $html = HtmlUtils.wrapAndJquerify( html );
218 HtmlUtils.filterInvisible( $html );
219 HtmlUtils.appendWhitespaceToBlockElements( $html );
220 HtmlUtils.allowlistHtml( $html, 'a, span, i, b, sup, sub, s' );
221 cache.textWithTags[ html ] = HtmlUtils.mergeWhitespace( $html.html() );
222 }
223 return cache.textWithTags[ html ];
224 }
225
226 /**
227 * Returns the text content of a html string, with the `<a>` tags left intact.
228 * Tries to give an approximation of what would be visible if the HTML would be displayed.
229 *
230 * @param {string} html
231 * @return {string}
232 */
233 static htmlToTextWithLinks( html ) {
234 if ( !cache.textWithLinks[ html ] ) {
235 const $html = HtmlUtils.wrapAndJquerify( html );
236 HtmlUtils.filterInvisible( $html );
237 HtmlUtils.appendWhitespaceToBlockElements( $html );
238 HtmlUtils.allowlistHtml( $html, 'a, span' );
239 cache.textWithLinks[ html ] = HtmlUtils.mergeWhitespace( $html.html() );
240 }
241 return cache.textWithLinks[ html ];
242 }
243
244 /**
245 * Generates HTML code for a link.
246 *
247 * @param {string} text Link text (plain text; will be sanitized)
248 * @param {Object} props Link attributes (should at a minimum include href; will be sanitized)
249 * @return {string}
250 */
251 static makeLinkText( text, props ) {
252 for ( const key in props ) {
253 if ( !Object.prototype.hasOwnProperty.call( props, key ) ) {
254 continue;
255 }
256 props[ key ] = HtmlUtils.htmlToText( props[ key ] );
257 }
258 return HtmlUtils.jqueryToHtml( $( '<a>' ).prop( props ).text( text ) );
259 }
260 }
261
262 module.exports = HtmlUtils;