Enhancement: Date format in preview path #593

This commit is contained in:
Elio Struyf
2023-06-29 11:43:40 +02:00
parent 1be87875d6
commit c1410de12e
2 changed files with 40 additions and 5 deletions
+1
View File
@@ -15,6 +15,7 @@
- [#586](https://github.com/estruyf/vscode-front-matter/issues/586): Allow to specify the content card fields
- [#588](https://github.com/estruyf/vscode-front-matter/issues/588): Added extensibility support to override card fields
- [#591](https://github.com/estruyf/vscode-front-matter/issues/591): Support for date format in the `datetime` field
- [#593](https://github.com/estruyf/vscode-front-matter/issues/593): Add support for date formatting in the preview path
### ⚡️ Optimizations
+39 -5
View File
@@ -1,15 +1,49 @@
import { format } from 'date-fns';
export const processFmPlaceholders = (value: string, fmData: any) => {
// Example: {{fm.date}} or {{fm.date | dateFormat 'DD.MM.YYYY'}}
if (value && value.includes('{{fm.')) {
const regex = new RegExp('{{fm.(\\w+)}}', 'g');
const regex = /{{fm.[^}]*}}/g;
const matches = value.match(regex);
if (matches) {
for (const match of matches) {
const field = match.replace('{{fm.', '').replace('}}', '');
const fieldValue = fmData[field];
const placeholderParts = match.split('|');
if (fieldValue) {
value = value.replace(match, fieldValue);
if (placeholderParts.length > 1) {
const field = placeholderParts[0].replace('{{fm.', '').trim();
const formatting = placeholderParts[1].trim().replace('}}', '');
// Get the field value
const fieldValue = fmData[field];
if (formatting.startsWith('format')) {
let dateFormat = formatting.replace('format:', '').trim();
// Strip the single quotes
if (dateFormat.startsWith("'") && dateFormat.endsWith("'")) {
dateFormat = dateFormat.substring(1, dateFormat.length - 1);
}
// Parse the date value and format it
if (fieldValue) {
const formattedDate = format(new Date(fieldValue), dateFormat);
value = value.replace(match, formattedDate);
}
} else if (fieldValue) {
value = value.replace(match, fieldValue);
}
} else {
// Get the field name
const field = match.replace('{{fm.', '').replace('}}', '');
// Get the field value
const fieldValue = fmData[field];
// Replace the placeholder with the field value
if (fieldValue) {
value = value.replace(match, fieldValue);
}
}
}
}