From 95d5a50f8838a4eb8a54fe0a6429b84a01c44f98 Mon Sep 17 00:00:00 2001 From: Sheldon Guo Date: Sun, 2 Mar 2025 12:23:58 +0800 Subject: [PATCH] feat: add template extraction and composition utilities in json-templates --- .../core/json-templates/src/utils/index.ts | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 packages/core/json-templates/src/utils/index.ts diff --git a/packages/core/json-templates/src/utils/index.ts b/packages/core/json-templates/src/utils/index.ts new file mode 100644 index 0000000000..db116079ed --- /dev/null +++ b/packages/core/json-templates/src/utils/index.ts @@ -0,0 +1,44 @@ +/** + * This file is part of the NocoBase (R) project. + * Copyright (c) 2020-2024 NocoBase Co., Ltd. + * Authors: NocoBase Team. + * + * This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License. + * For more information, please refer to: https://www.nocobase.com/agreement. + */ + +import { escapeSpecialChars, escape, revertEscape } from '../escape'; +import engine from '../engine'; + +type Filter = { + name: string; + handler: any; + args: string[]; +}; + +export function extractTemplateElements(template: string) { + const escapedTemplate = escape(template ?? ''); + const fullVariable = engine.fullVariablesSync(escapeSpecialChars(escapedTemplate))[0] ?? ''; + const variableSegments = engine.variableSegmentsSync(escapedTemplate)[0] ?? []; + const parsedTemplate = engine.parse(escapedTemplate)[0] ?? {}; + + const filters = + //@ts-ignore + parsedTemplate?.value?.filters?.map(({ name, handler, args }) => ({ + name, + handler, + args: args.map((arg) => arg.content), + })) ?? []; + + return revertEscape({ fullVariable, variableSegments, filters }); +} + +const composeFilterTemplate = (filter: Filter) => { + return `${filter.name}${filter.args.length ? `:${filter.args.join(',')}` : ''}`; +}; + +export const composeTemplate = ({ fullVariable, filters }: { fullVariable: string; filters: any[] }) => { + const filtersTemplate = filters.map(composeFilterTemplate).join(' | '); + const innerTemplateStr = [fullVariable, filtersTemplate].filter(Boolean).join(' | '); + return `{{${innerTemplateStr}}}`; +};