Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

Commit

Permalink
fix: add sanitizer (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
splincode authored Oct 11, 2023
1 parent bfb47d1 commit 2dd59fe
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 15 deletions.
3 changes: 1 addition & 2 deletions angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,7 @@
"projects/demo/src/assets"
],
"styles": ["projects/demo/src/styles.css"],
"scripts": [],
"es5BrowserSupport": true
"scripts": []
},
"configurations": {
"production": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import {
Inject,
OnDestroy,
Renderer2,
SecurityContext,
} from '@angular/core';
import {ControlValueAccessor, NG_VALUE_ACCESSOR} from '@angular/forms';
import {DomSanitizer} from '@angular/platform-browser';

/*
* This is a barebones contenteditable {@link ControlValueAccessor} allowing you to use
Expand Down Expand Up @@ -39,11 +41,7 @@ export class ContenteditableValueAccessor
*/
private observer = new MutationObserver(() => {
setTimeout(() => {
this.onChange(
ContenteditableValueAccessor.processValue(
this.elementRef.nativeElement.innerHTML,
),
);
this.onChange(this.processValue(this.elementRef.nativeElement.innerHTML));
});
});

Expand All @@ -60,6 +58,7 @@ export class ContenteditableValueAccessor
constructor(
@Inject(ElementRef) private readonly elementRef: ElementRef,
@Inject(Renderer2) private readonly renderer: Renderer2,
@Inject(DomSanitizer) private readonly sanitizer: DomSanitizer,
) {}

/*
Expand Down Expand Up @@ -88,11 +87,7 @@ export class ContenteditableValueAccessor
@HostListener('input')
onInput() {
this.observer.disconnect();
this.onChange(
ContenteditableValueAccessor.processValue(
this.elementRef.nativeElement.innerHTML,
),
);
this.onChange(this.processValue(this.elementRef.nativeElement.innerHTML));
}

/*
Expand All @@ -112,7 +107,7 @@ export class ContenteditableValueAccessor
this.renderer.setProperty(
this.elementRef.nativeElement,
'innerHTML',
ContenteditableValueAccessor.processValue(value),
this.processValue(value),
);
}

Expand Down Expand Up @@ -151,9 +146,14 @@ export class ContenteditableValueAccessor
* null is treated as empty string to prevent IE11 outputting 'null',
* also single <br> is replaced with empty string when passed to the control
*/
private static processValue(value: unknown): string {
private processValue(value: unknown): string {
const processed = String(value === null || value === undefined ? '' : value);

return processed.trim() === '<br>' ? '' : processed;
return (
this.sanitizer.sanitize(
SecurityContext.HTML,
processed.trim() === '<br>' ? '' : processed,
) ?? ''
);
}
}

0 comments on commit 2dd59fe

Please sign in to comment.