Skip to content

Commit

Permalink
Generic HTML encode util
Browse files Browse the repository at this point in the history
  • Loading branch information
JrMasterModelBuilder committed Oct 15, 2023
1 parent 46e698b commit 8490c0e
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 26 deletions.
40 changes: 14 additions & 26 deletions src/projector/html.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,7 @@
import {writeFile} from 'fs/promises';

import {Projector} from '../projector';

/**
* HTML encode.
*
* @param s Raw strings.
* @returns HTML strings.
*/
function he(s: string) {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}

/**
* HTML encode an attribute.
*
* @param s Raw strings.
* @returns HTML strings.
*/
function ha(s: string) {
return he(s).replace(/"/g, '&quot;');
}
import {htmlEncode} from '../util';

/**
* ProjectorHtml object.
Expand Down Expand Up @@ -301,7 +282,9 @@ export class ProjectorHtml extends Projector {
'<html>',
' <head>',
' <meta charset="UTF-8">',
...(title === null ? [] : [` <title>${he(title)}</title>`]),
...(title === null
? []
: [` <title>${htmlEncode(title)}</title>`]),
' <meta http-equiv="X-UA-Compatible" content="IE=Edge">',
' <style>',
' * {',
Expand All @@ -315,8 +298,8 @@ export class ProjectorHtml extends Projector {
' body {',
...(background === null
? []
: [` background: ${he(background)};`]),
...(color === null ? [] : [` color: ${he(color)};`]),
: [` background: ${htmlEncode(background)};`]),
...(color === null ? [] : [` color: ${htmlEncode(color)};`]),
' font-family: Verdana, Geneva, sans-serif;',
' }',
' object,',
Expand Down Expand Up @@ -347,13 +330,18 @@ export class ProjectorHtml extends Projector {
' <div class="main">',
' <div class="player">',
' <object',
...[...object.entries()].map(([a, v]) => ` ${a}="${ha(v)}"`),
...[...object.entries()].map(
([a, v]) => ` ${a}="${htmlEncode(v, true)}"`
),
' >',
...[...param.entries()].map(
([a, v]) => ` <param name="${a}" value="${ha(v)}">`
([a, v]) =>
` <param name="${a}" value="${htmlEncode(v, true)}">`
),
' <embed',
...[...embed.entries()].map(([a, v]) => ` ${a}="${ha(v)}"`),
...[...embed.entries()].map(
([a, v]) => ` ${a}="${htmlEncode(v, true)}"`
),
' >',
' </object>',
' </div>',
Expand Down
19 changes: 19 additions & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,25 @@ import {inflateRaw} from 'node:zlib';

import {LAUNCHERS} from './launchers';

/**
* HTML encode.
*
* @param s Raw strings.
* @param dq Double quotes.
* @param sq Single quotes.
* @returns Encoded strings.
*/
export function htmlEncode(s: string, dq = false, sq = false) {
s = s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
if (dq) {
s = s.replace(/"/g, '&quot;');
}
if (sq) {
s = s.replace(/'/g, '&#39;');
}
return s;
}

/**
* Trim dot flash from head of path.
*
Expand Down

0 comments on commit 8490c0e

Please sign in to comment.