2021-04-13 10:57:08 +02:00
|
|
|
// Copyright: Ankitects Pty Ltd and contributors
|
|
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
2021-02-09 04:38:04 +01:00
|
|
|
|
2022-11-28 00:33:04 +01:00
|
|
|
import { filterElementBasic, filterElementExtended, filterElementInternal } from "./element";
|
2021-03-25 00:43:01 +01:00
|
|
|
import { filterNode } from "./node";
|
2021-03-24 23:35:51 +01:00
|
|
|
|
|
|
|
enum FilterMode {
|
|
|
|
Basic,
|
|
|
|
Extended,
|
|
|
|
Internal,
|
|
|
|
}
|
|
|
|
|
|
|
|
const filters: Record<FilterMode, (element: Element) => void> = {
|
|
|
|
[FilterMode.Basic]: filterElementBasic,
|
|
|
|
[FilterMode.Extended]: filterElementExtended,
|
|
|
|
[FilterMode.Internal]: filterElementInternal,
|
|
|
|
};
|
2021-01-30 17:54:07 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
const whitespace = /[\n\t ]+/g;
|
2021-01-30 17:54:07 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
function collapseWhitespace(value: string): string {
|
|
|
|
return value.replace(whitespace, " ");
|
2021-01-30 17:54:07 +01:00
|
|
|
}
|
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
function trim(value: string): string {
|
|
|
|
return value.trim();
|
2021-03-24 18:40:13 +01:00
|
|
|
}
|
2021-01-30 17:54:07 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
const outputHTMLProcessors: Record<FilterMode, (outputHTML: string) => string> = {
|
2022-11-28 00:33:04 +01:00
|
|
|
[FilterMode.Basic]: (outputHTML: string): string => trim(collapseWhitespace(outputHTML)),
|
2021-03-24 23:35:51 +01:00
|
|
|
[FilterMode.Extended]: trim,
|
|
|
|
[FilterMode.Internal]: trim,
|
|
|
|
};
|
2021-01-30 17:54:07 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
export function filterHTML(html: string, internal: boolean, extended: boolean): string {
|
|
|
|
const template = document.createElement("template");
|
|
|
|
template.innerHTML = html;
|
2021-01-30 17:54:07 +01:00
|
|
|
|
2021-04-23 05:00:18 +02:00
|
|
|
const mode = getFilterMode(internal, extended);
|
2021-03-24 23:35:51 +01:00
|
|
|
const content = template.content;
|
|
|
|
const filter = filterNode(filters[mode]);
|
2021-03-24 21:18:16 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
filter(content);
|
2021-03-24 18:40:13 +01:00
|
|
|
|
2021-03-24 23:35:51 +01:00
|
|
|
return outputHTMLProcessors[mode](template.innerHTML);
|
2021-03-24 18:40:13 +01:00
|
|
|
}
|
2021-04-23 05:00:18 +02:00
|
|
|
|
|
|
|
function getFilterMode(internal: boolean, extended: boolean): FilterMode {
|
|
|
|
if (internal) {
|
|
|
|
return FilterMode.Internal;
|
|
|
|
} else if (extended) {
|
|
|
|
return FilterMode.Extended;
|
|
|
|
} else {
|
|
|
|
return FilterMode.Basic;
|
|
|
|
}
|
|
|
|
}
|