Merge pull request #1374 from matrix-org/dbkr/consolidate_code_copy_button

Consolidate the code copy button
This commit is contained in:
David Baker 2017-09-10 16:07:51 +01:00 committed by GitHub
commit cc6123b556
2 changed files with 15 additions and 26 deletions

View File

@ -393,7 +393,6 @@ export function bodyToHtml(content, highlights, opts) {
} }
safeBody = sanitizeHtml(body, sanitizeHtmlParams); safeBody = sanitizeHtml(body, sanitizeHtmlParams);
safeBody = unicodeToImage(safeBody); safeBody = unicodeToImage(safeBody);
if (isHtml) safeBody = addCodeCopyButton(safeBody);
} }
finally { finally {
delete sanitizeHtmlParams.textFilter; delete sanitizeHtmlParams.textFilter;
@ -412,23 +411,6 @@ export function bodyToHtml(content, highlights, opts) {
return <span className={className} dangerouslySetInnerHTML={{ __html: safeBody }} dir="auto" />; return <span className={className} dangerouslySetInnerHTML={{ __html: safeBody }} dir="auto" />;
} }
function addCodeCopyButton(safeBody) {
// Adds 'copy' buttons to pre blocks
// Note that this only manipulates the markup to add the buttons:
// we need to add the event handlers once the nodes are in the DOM
// since we can't save functions in the markup.
// This is done in TextualBody
const el = document.createElement("div");
el.innerHTML = safeBody;
const codeBlocks = Array.from(el.getElementsByTagName("pre"));
codeBlocks.forEach(p => {
const button = document.createElement("span");
button.className = "mx_EventTile_copyButton";
p.appendChild(button);
});
return el.innerHTML;
}
export function emojifyText(text) { export function emojifyText(text) {
return { return {
__html: unicodeToImage(escape(text)), __html: unicodeToImage(escape(text)),

View File

@ -113,14 +113,8 @@ module.exports = React.createClass({
} }
}, 10); }, 10);
} }
// add event handlers to the 'copy code' buttons
const buttons = ReactDOM.findDOMNode(this).getElementsByClassName("mx_EventTile_copyButton"); this._addCodeCopyButton();
for (let i = 0; i < buttons.length; i++) {
buttons[i].onclick = (e) => {
const copyCode = buttons[i].parentNode.getElementsByTagName("code")[0];
this.copyToClipboard(copyCode.textContent);
};
}
} }
}, },
@ -257,6 +251,19 @@ module.exports = React.createClass({
} }
}, },
_addCodeCopyButton() {
// Add 'copy' buttons to pre blocks
ReactDOM.findDOMNode(this).querySelectorAll('.mx_EventTile_body pre').forEach((p) => {
const button = document.createElement("span");
button.className = "mx_EventTile_copyButton";
button.onclick = (e) => {
const copyCode = button.parentNode.getElementsByTagName("code")[0];
this.copyToClipboard(copyCode.textContent);
};
p.appendChild(button);
});
},
onCancelClick: function(event) { onCancelClick: function(event) {
this.setState({ widgetHidden: true }); this.setState({ widgetHidden: true });
// FIXME: persist this somewhere smarter than local storage // FIXME: persist this somewhere smarter than local storage