smartntml/ts/index.ts
2022-06-16 01:17:58 +02:00

53 lines
1.6 KiB
TypeScript

import * as plugins from './smartntml.plugins.js';
import type * as litTypes from 'lit';
import { unsafeHTML } from 'lit/directives/unsafe-html.js';
export type { TemplateResult } from 'lit';
export class Smartntml {
// STATIC
public static async createAndInit() {
const smartntml = new Smartntml();
await smartntml.init();
return smartntml;
}
private static smartntmlSingletonDeferred: plugins.smartpromise.Deferred<Smartntml>;
public static async createAndInitSingleton() {
if (this.smartntmlSingletonDeferred) {
return this.smartntmlSingletonDeferred.promise;
}
this.smartntmlSingletonDeferred = plugins.smartpromise.defer();
const smartntmlInstance = await this.createAndInit();
this.smartntmlSingletonDeferred.resolve(smartntmlInstance);
return this.smartntmlSingletonDeferred.promise;
}
// INSTANCE
private render: typeof litTypes.render;
public html: typeof litTypes.html;
public unsafeHTML: typeof unsafeHTML;
constructor() {
this.init();
}
public async init() {
const lit = await import('lit');
const litUnsafeHtmlDirective = await import('lit/directives/unsafe-html.js');
this.render = lit.render;
this.html = lit.html;
this.unsafeHTML = litUnsafeHtmlDirective.unsafeHTML;
}
public async renderTemplateResult(templateResult: litTypes.TemplateResult, stripCommentsArg = true) {
const element = document.createElement('div');
this.render(templateResult, element);
let stringResult = element.innerHTML;
if (stripCommentsArg) {
stringResult = stringResult.replace(/<!--(.*?)-->/g, '');
}
return stringResult;
}
}