Skip to content

Commit

Permalink
feat: add context.safe to mark a value as safe
Browse files Browse the repository at this point in the history
  • Loading branch information
thetutlage committed Feb 28, 2020
1 parent 227fb0a commit 0ca5991
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/Context/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ import { set } from 'lodash'
import { Macroable } from 'macroable'
import { ContextContract } from '../Contracts'

class SafeValue {
constructor (public value: any) {}
}

/**
* Context is used at runtime to resolve values for a given
* template.
Expand Down Expand Up @@ -105,12 +109,21 @@ export class Context extends Macroable implements ContextContract {
this._frames.shift()
}

/**
* Mark output as safe
*/
public safe <T extends any> (value: T) {
return new SafeValue(value)
}

/**
* Escapes the value to be HTML safe. Only strings are escaped
* and rest all values will be returned as it is.
*/
public escape <T> (input: T): T {
return typeof (input) === 'string' ? he.escape(input) : input
return typeof (input) === 'string'
? he.escape(input)
: (input instanceof SafeValue ? input.value : input)
}

/**
Expand Down
1 change: 1 addition & 0 deletions src/Contracts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ export interface LoaderContract {
export interface ContextContract {
presenter: { state: any },
sharedState: any,
safe <T extends any> (value: T): { value: T },
newFrame (): void,
setOnFrame (key: string, value: any): void,
removeFrame (): void,
Expand Down

0 comments on commit 0ca5991

Please sign in to comment.