Copy/paste of styled elements
See original GitHub issueI keep running into weird and somewhat unintuitive behavior regarding copied and pasted content with block-level style attributes. Specifically, most of this comes from the style attributes being maintained in a way that is somewhat out of line with the way Squire does formatting and styling. It makes me wonder if we can’t improve on how this is handled.
If we do, I’ll gladly put in the work (the amount of trouble we run into here justifies it and more), but I’d like to have an agreement on exactly what sort of behavior we want.
More detail, then: If you paste in styled HTML (such as from Wikipedia), the styling is (in several browsers, at least) included on the pasted elements. I.e. if you have a page which sets font styles and sizes, etc., those styles will be added to the style attribute of a pasted element copied from that page. Since Squire mostly uses element styling (B, I, U tags, etc.) and does not clean up this styling, you can get odd cases where if you take Squire content, part of which was copied and pasted within Squire and show it elsewhere with different style rules, it will look inconsistent.
Example extracted HTML:
<div>This is text written, copied, then pasted.</div>
<div style="font-family: helvetica, sans-serif; font-size: 13px; color: #ccc">This is text written, copied, then pasted.</div>
Showing this (e.g. if it’s the content of a mail body) with a style sheet might lead to the upper line being displayed in 14px black Verdana, while the lower line is shown in 13px dark grey Helvetica.
(This is also the kind of thing that will surface #153.)
Issue Analytics
- State:
- Created 8 years ago
- Comments:5 (4 by maintainers)
Yeh, hooking DOMPurify into the willPaste event is a great way to have complete control over how much styling is preserved. There’s probably not much more worth doing in Squire itself, as mostly this depends on the context the editor is being used in, so I think I’m going to close this. If you think something more widely applicable could still be done, make a comment and I’ll consider reopening. 😃
I’ve done this by using DOMPurify.
Just add an event listener for ‘willPaste’, and make the event handler call DOMPurify.sanitize:
Please refer to DOMPurify documents how to configure the sanitizer, however, it is very easy to configure the sanitizing rules.