From 6efce3c4bb45a50841139927a47ee1d40846aadd Mon Sep 17 00:00:00 2001 From: Methapon Metanipat <162551568+Methapon-Frappet@users.noreply.github.com> Date: Mon, 11 Nov 2024 14:55:36 +0700 Subject: [PATCH] feat: rich text template (#68) * feat: add file * feat: add template convert function * refactor: update function --- src/utils/string-template.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/utils/string-template.ts diff --git a/src/utils/string-template.ts b/src/utils/string-template.ts new file mode 100644 index 00000000..5858a844 --- /dev/null +++ b/src/utils/string-template.ts @@ -0,0 +1,34 @@ +const templates = { + 'my-template': { + converter: (context?: number[]) => { + return context?.join(', ') || ''; + }, + }, +} as const; + +type Template = typeof templates; +type TemplateName = keyof Template; +type TemplateContext = { + [key in TemplateName]: Parameters[0]; +}; + +export function convertTemplate( + text: string, + context?: TemplateContext, + templateUse?: TemplateName[], +) { + let ret = text; + + for (const [name, template] of Object.entries(templates)) { + if (templateUse && !templateUse.includes(name as TemplateName)) continue; + + ret = text.replace( + new RegExp('\\#\\[' + name.replaceAll('-', '\\-') + '\\]', 'g'), + typeof template.converter === 'function' + ? template.converter(context?.[name as TemplateName]) + : template.converter, + ); + } + + return ret; +}