smartntml/ts/index.ts

49 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-05-28 15:29:36 +00:00
import * as plugins from './smartntml.plugins.js';
import type * as litTypes from 'lit';
2022-05-28 18:17:17 +00:00
export type { TemplateResult } from 'lit';
2022-05-28 15:29:36 +00:00
export class Smartntml {
// STATIC
public static async createAndInit() {
const smartntml = new Smartntml();
await smartntml.init();
return smartntml;
}
2022-05-28 18:03:13 +00:00
private static smartntmlSingletonDeferred: plugins.smartpromise.Deferred<Smartntml>;
public static async createAndInitSingleton() {
if (this.smartntmlSingletonDeferred) {
return this.smartntmlSingletonDeferred.promise;
}
2022-05-28 22:33:36 +00:00
this.smartntmlSingletonDeferred = plugins.smartpromise.defer();
2022-05-28 18:03:13 +00:00
const smartntmlInstance = await this.createAndInit();
this.smartntmlSingletonDeferred.resolve(smartntmlInstance);
return this.smartntmlSingletonDeferred.promise;
}
2022-05-28 15:29:36 +00:00
// INSTANCE
2022-05-28 21:52:46 +00:00
private render: typeof litTypes.render;
2022-05-28 15:29:36 +00:00
html: typeof litTypes.html;
constructor() {
this.init();
}
public async init() {
const lit = await import('lit');
this.render = lit.render;
this.html = lit.html;
}
2022-05-29 13:02:48 +00:00
public async renderTemplateResult(templateResult: litTypes.TemplateResult, stripCommentsArg = true) {
2022-05-28 15:29:36 +00:00
const element = document.createElement('div');
this.render(templateResult, element);
2022-05-29 13:02:48 +00:00
let stringResult = element.innerHTML;
if (stripCommentsArg) {
stringResult = stringResult.replace(/<!--(.*?)-->/g, '');
}
return stringResult;
2022-05-28 15:29:36 +00:00
}
}