Skip to content

Commit

Permalink
Enhancement: Date format in preview path #593
Browse files Browse the repository at this point in the history
  • Loading branch information
estruyf committed Jun 29, 2023
1 parent 1be8787 commit c1410de
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
44 changes: 39 additions & 5 deletions src/helpers/processFmPlaceholders.ts
Original file line number Diff line number Diff line change
@@ -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 (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];

if (fieldValue) {
value = value.replace(match, fieldValue);
// Replace the placeholder with the field value
if (fieldValue) {
value = value.replace(match, fieldValue);
}
}
}
}
Expand Down

0 comments on commit c1410de

Please sign in to comment.