|
1 | 1 | import {TemplateInstance, NodeTemplatePart} from '@github/template-parts' |
2 | 2 | import type {TemplateTypeInit} from '@github/template-parts' |
3 | | -import {getCSPTrustedTypesPolicy} from './trusted-types.js' |
4 | 3 |
|
5 | 4 | const templates = new WeakMap<TemplateStringsArray, HTMLTemplateElement>() |
6 | 5 | const renderedTemplates = new WeakMap<Node | NodeTemplatePart, HTMLTemplateElement>() |
7 | 6 | const renderedTemplateInstances = new WeakMap<Node | NodeTemplatePart, TemplateInstance>() |
8 | 7 |
|
| 8 | +interface CSPTrustedHTMLToStringable { |
| 9 | + toString: () => string |
| 10 | +} |
| 11 | + |
| 12 | +interface CSPTrustedTypesPolicy { |
| 13 | + createHTML: (s: string) => CSPTrustedHTMLToStringable |
| 14 | +} |
| 15 | + |
9 | 16 | export class TemplateResult { |
10 | 17 | constructor( |
11 | 18 | public readonly strings: TemplateStringsArray, |
12 | 19 | public readonly values: unknown[], |
13 | 20 | public processor: TemplateTypeInit |
14 | 21 | ) {} |
15 | 22 |
|
| 23 | + static cspTrustedTypesPolicy: CSPTrustedTypesPolicy | null = null |
| 24 | + |
| 25 | + static setCSPTrustedTypesPolicy(policy: CSPTrustedTypesPolicy | null) { |
| 26 | + TemplateResult.cspTrustedTypesPolicy = policy |
| 27 | + } |
| 28 | + |
16 | 29 | get template(): HTMLTemplateElement { |
17 | 30 | if (templates.has(this.strings)) { |
18 | 31 | return templates.get(this.strings)! |
19 | 32 | } else { |
20 | 33 | const template = document.createElement('template') |
21 | 34 | const end = this.strings.length - 1 |
22 | 35 | const html = this.strings.reduce((str, cur, i) => str + cur + (i < end ? `{{ ${i} }}` : ''), '') |
23 | | - const trustedHtml = getCSPTrustedTypesPolicy() ? (getCSPTrustedTypesPolicy()?.createHTML(html) as string) : html |
| 36 | + const trustedHtml = TemplateResult.cspTrustedTypesPolicy |
| 37 | + ? (TemplateResult.cspTrustedTypesPolicy.createHTML(html) as string) |
| 38 | + : html |
24 | 39 | template.innerHTML = trustedHtml |
25 | 40 | templates.set(this.strings, template) |
26 | 41 | return template |
|
0 commit comments