rtf-stream-parser
Version:
Stream Transform class to tokenize RTF, and another to de-encapsulate text or HTML
87 lines (86 loc) • 3.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleDeEncapsulation = void 0;
function getModeError(global) {
if (global._options.mode === 'html') {
return new Error('Not encapsulated HTML file');
}
else if (global._options.mode === 'text') {
return new Error('Not encapsulated text file');
}
else {
return new Error('Not encapsulated HTML or text file');
}
}
const allTokenHandler = (global, token) => {
if (!global._fromhtml && !global._fromtext) {
if (token.type === 3 || global._count > 10) {
throw getModeError(global);
}
}
if (global._state.htmlrtf && global._options.outlookQuirksMode) {
if (token.type !== 2 || (token.word !== 'f' && token.word !== 'htmlrtf')) {
return true;
}
}
};
const deEncapsulationControlHandlers = {
fromhtml: global => {
if (global._state.destination !== 'rtf') {
throw new Error('\\fromhtml not at root group');
}
if (global._fromhtml !== false || global._fromtext !== false) {
throw new Error('\\fromhtml or \\fromtext already defined');
}
if (global._options.mode !== 'html' && global._options.mode !== 'either') {
throw getModeError(global);
}
global._fromhtml = true;
if (global._options.prefix) {
global._pushOutput('html:');
}
return true;
},
fromtext: global => {
if (global._state.destination !== 'rtf') {
throw new Error('\\fromtext not at root group');
}
if (global._fromhtml !== false || global._fromtext !== false) {
throw new Error('\\fromhtml or \\fromtext already defined');
}
if (global._options.mode !== 'text' && global._options.mode !== 'either') {
throw getModeError(global);
}
global._fromtext = true;
if (global._options.prefix) {
global._pushOutput('text:');
}
return true;
},
htmlrtf: (global, token) => {
const on = token.param !== 0;
global._state.htmlrtf = on;
}
};
exports.handleDeEncapsulation = {
allTokenHandler: allTokenHandler,
controlHandlers: deEncapsulationControlHandlers,
outputDataFilter: global => {
if (global._state.htmlrtf) {
return true;
}
const allDests = global._state.allDestinations || {};
const insideHtmltag = !!allDests['htmltag'];
if (!insideHtmltag && global._state.destIgnorable) {
return true;
}
if (!insideHtmltag && (allDests['fonttbl'] || allDests['colortbl'] || allDests['stylesheet'] || allDests['pntext'])) {
return true;
}
},
preStreamFlushHandler: global => {
if (!global._fromhtml && !global._fromtext) {
throw getModeError(global);
}
}
};