-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
index.js
204 lines (173 loc) · 6.49 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
/**
* External dependencies
*/
import { flatMap, filter, compact } from 'lodash';
// Also polyfills Element#matches.
import 'element-closest';
/**
* Internal dependencies
*/
import { createBlock, getBlockTransforms, findTransform } from '../factory';
import { getBlockType } from '../registration';
import { getBlockAttributes, parseWithGrammar } from '../parser';
import normaliseBlocks from './normalise-blocks';
import specialCommentConverter from './special-comment-converter';
import isInlineContent from './is-inline-content';
import phrasingContentReducer from './phrasing-content-reducer';
import msListConverter from './ms-list-converter';
import listReducer from './list-reducer';
import imageCorrector from './image-corrector';
import blockquoteNormaliser from './blockquote-normaliser';
import figureContentReducer from './figure-content-reducer';
import shortcodeConverter from './shortcode-converter';
import markdownConverter from './markdown-converter';
import iframeRemover from './iframe-remover';
import {
deepFilterHTML,
isPlain,
removeInvalidHTML,
getPhrasingContentSchema,
getBlockContentSchema,
} from './utils';
/**
* Browser dependencies
*/
const { log, warn } = window.console;
export { getPhrasingContentSchema };
/**
* Filters HTML to only contain phrasing content.
*
* @param {string} HTML The HTML to filter.
*
* @return {string} HTML only containing phrasing content.
*/
function filterInlineHTML( HTML ) {
HTML = deepFilterHTML( HTML, [ phrasingContentReducer ] );
HTML = removeInvalidHTML( HTML, getPhrasingContentSchema(), { inline: true } );
// Allows us to ask for this information when we get a report.
log( 'Processed inline HTML:\n\n', HTML );
return HTML;
}
function getRawTransformations() {
return filter( getBlockTransforms( 'from' ), { type: 'raw' } )
.map( ( transform ) => {
return transform.isMatch ? transform : {
...transform,
isMatch: ( node ) => transform.selector && node.matches( transform.selector ),
};
} );
}
/**
* Converts an HTML string to known blocks. Strips everything else.
*
* @param {string} [options.HTML] The HTML to convert.
* @param {string} [options.plainText] Plain text version.
* @param {string} [options.mode] Handle content as blocks or inline content.
* * 'AUTO': Decide based on the content passed.
* * 'INLINE': Always handle as inline content, and return string.
* * 'BLOCKS': Always handle as blocks, and return array of blocks.
* @param {Array} [options.tagName] The tag into which content will be inserted.
* @param {boolean} [options.canUserUseUnfilteredHTML] Whether or not the user can use unfiltered HTML.
*
* @return {Array|string} A list of blocks or a string, depending on `handlerMode`.
*/
export default function rawHandler( { HTML = '', plainText = '', mode = 'AUTO', tagName, canUserUseUnfilteredHTML = false } ) {
// First of all, strip any meta tags.
HTML = HTML.replace( /<meta[^>]+>/, '' );
// If we detect block delimiters, parse entirely as blocks.
if ( mode !== 'INLINE' && HTML.indexOf( '<!-- wp:' ) !== -1 ) {
return parseWithGrammar( HTML );
}
// Normalize unicode to use composed characters.
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
// See https://core.trac.wordpress.org/ticket/30130
HTML = HTML.normalize();
// Parse Markdown (and encoded HTML) if:
// * There is a plain text version.
// * There is no HTML version, or it has no formatting.
if ( plainText && ( ! HTML || isPlain( HTML ) ) ) {
HTML = markdownConverter( plainText );
// Switch to inline mode if:
// * The current mode is AUTO.
// * The original plain text had no line breaks.
// * The original plain text was not an HTML paragraph.
// * The converted text is just a paragraph.
if (
mode === 'AUTO' &&
plainText.indexOf( '\n' ) === -1 &&
plainText.indexOf( '<p>' ) !== 0 &&
HTML.indexOf( '<p>' ) === 0
) {
mode = 'INLINE';
}
}
if ( mode === 'INLINE' ) {
return filterInlineHTML( HTML );
}
// An array of HTML strings and block objects. The blocks replace matched
// shortcodes.
const pieces = shortcodeConverter( HTML );
// The call to shortcodeConverter will always return more than one element
// if shortcodes are matched. The reason is when shortcodes are matched
// empty HTML strings are included.
const hasShortcodes = pieces.length > 1;
if ( mode === 'AUTO' && ! hasShortcodes && isInlineContent( HTML, tagName ) ) {
return filterInlineHTML( HTML );
}
const rawTransformations = getRawTransformations();
const phrasingContentSchema = getPhrasingContentSchema();
const blockContentSchema = getBlockContentSchema( rawTransformations );
return compact( flatMap( pieces, ( piece ) => {
// Already a block from shortcode.
if ( typeof piece !== 'string' ) {
return piece;
}
const filters = [
msListConverter,
listReducer,
imageCorrector,
phrasingContentReducer,
specialCommentConverter,
figureContentReducer,
blockquoteNormaliser,
];
if ( ! canUserUseUnfilteredHTML ) {
// Should run before `figureContentReducer`.
filters.unshift( iframeRemover );
}
const schema = {
...blockContentSchema,
// Keep top-level phrasing content, normalised by `normaliseBlocks`.
...phrasingContentSchema,
};
piece = deepFilterHTML( piece, filters, blockContentSchema );
piece = removeInvalidHTML( piece, schema );
piece = normaliseBlocks( piece );
// Allows us to ask for this information when we get a report.
log( 'Processed HTML piece:\n\n', piece );
const doc = document.implementation.createHTMLDocument( '' );
doc.body.innerHTML = piece;
return Array.from( doc.body.children ).map( ( node ) => {
const rawTransformation = findTransform( rawTransformations, ( { isMatch } ) => isMatch( node ) );
if ( ! rawTransformation ) {
warn(
'A block registered a raw transformation schema for `' + node.nodeName + '` but did not match it. ' +
'Make sure there is a `selector` or `isMatch` property that can match the schema.\n' +
'Sanitized HTML: `' + node.outerHTML + '`'
);
return;
}
const { transform, blockName } = rawTransformation;
if ( transform ) {
return transform( node );
}
return createBlock(
blockName,
getBlockAttributes(
getBlockType( blockName ),
node.outerHTML
)
);
} );
} ) );
}