soapbox/src/utils/html.ts

38 wiersze
1.1 KiB
TypeScript
Czysty Zwykły widok Historia

2022-04-24 19:28:07 +00:00
/** Convert HTML to a plaintext representation, preserving whitespace. */
2020-03-27 20:59:38 +00:00
// NB: This function can still return unsafe HTML
export const unescapeHTML = (html: string = ''): string => {
2020-03-27 20:59:38 +00:00
const wrapper = document.createElement('div');
2022-01-28 20:52:22 +00:00
wrapper.innerHTML = html.replace(/<br\s*\/?>/g, '\n').replace(/<\/p><[^>]*>/g, '\n\n').replace(/<[^>]*>/g, '');
2022-04-24 19:28:07 +00:00
return wrapper.textContent || '';
2020-03-27 20:59:38 +00:00
};
2022-04-24 19:28:07 +00:00
/** Remove compatibility markup for features Soapbox supports. */
export const stripCompatibilityFeatures = (html: string): string => {
const node = document.createElement('div');
node.innerHTML = html;
const selectors = [
2022-04-24 19:28:07 +00:00
// Quote posting
'.quote-inline',
2022-04-24 19:28:07 +00:00
// Explicit mentions
'.recipients-inline',
];
// Remove all instances of all selectors
selectors.forEach(selector => {
node.querySelectorAll(selector).forEach(elem => {
elem.remove();
});
});
return node.innerHTML;
};
/** Convert HTML to plaintext. */
// https://stackoverflow.com/a/822486
export const stripHTML = (html: string) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.textContent || div.innerText || '';
};