Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue: Image preview on dashboard cards works only sporadically #908

Closed
davidsneighbour opened this issue Jan 11, 2025 · 6 comments
Closed
Labels
bug Something isn't working Released The task has been released v10.8.0 Project: v10.8.0

Comments

@davidsneighbour
Copy link
Contributor

Happy New Year ;)

Describe the bug

The image preview works only in some of my recent posts. I wonder if it has to do with my schema or some other frontmatter quirks. The images linked are available and (to my eyes) are identical configured in the frontmatter.

image

To Reproduce
Steps to reproduce the behavior:

  1. Check out my repository and have a look at the dashboard and the last three posts for instance
  2. I think after checkout you will need to run npm install

Expected behavior
I would expect all three posts to have image previews

Device:

  • OS: Ubuntu 24.10
  • Front Matter CMS Version 10.7.0
  • Browser Chrome ;)
@davidsneighbour davidsneighbour added the bug Something isn't working label Jan 11, 2025
@estruyf
Copy link
Owner

estruyf commented Jan 18, 2025

Thanks @davidsneighbour, happy new year for you too.

I'll have a look at it.

@estruyf estruyf moved this to Ready in v10.9.0 Jan 18, 2025
@estruyf estruyf added this to v10.9.0 Jan 18, 2025
@project-labels project-labels bot added v10.8.0 Project: v10.8.0 Ready This is ready to be picked up labels Jan 18, 2025
@estruyf
Copy link
Owner

estruyf commented Feb 6, 2025

@davidsneighbour, the type or fmContentType field is missing in the front matter section. For the files are working, the type was set to blog.

As there are multiple content types defined for your blog in the frontMatter.content.pageFolders setting, it won't do it automatically.

Here is the view of your articles when I added fmContentType: blog (type is the old property, but will still work).

Image

@davidsneighbour
Copy link
Contributor Author

davidsneighbour commented Feb 7, 2025

Ok, that makes sense, ... "but" ;)
If I understand that right, then I have to add fmContentType: blog to all frontmatter sections in the blog section. Is there a way to have it "cascading" from somewhere? The blog is a Hugo website, so I am very spoiled with that. The content type is automatically blog because the "section" (first folder name relative to the content root) is named blog. It would be nice if that could somewhere be added once for a folder or in some form of config file for a folder and all files below that root have the same type if not defined explicitly.

It also messes up the last modified stamps on all content (if I add it now) ;) Not complaining, just asking.

@estruyf
Copy link
Owner

estruyf commented Feb 7, 2025

If I understand that right, then I have to add fmContentType: blog to all frontmatter sections in the blog section.

At this moment, yes, that is indeed the case. Or have a frontMatter.content.pageFolders setting which has only one content type defined.

The blog is a Hugo website, so I am very spoiled with that.

Each SSG has its own implementation. That is why FM uses the frontMatter.content.pageFolders setting and content-types to support as many SSGs.

It also messes up the last modified stamps on all content (if I add it now)

To temporarily turn this off, you can set the frontMatter.content.autoUpdateDate to false.

@davidsneighbour
Copy link
Contributor Author

Got it.

For convenience sake, here is a little NodeJS script for anyone who got to change many markdown files in a folder. This one does what I did not want to do by hand (traverse through a directory and add/change one front matter value in every markdown file) ;)

#!/usr/bin/env node

import fs from 'fs';
import path from 'path';
import { execSync } from 'child_process';

// Function to show help message
const showHelp = () => {
  console.log(`
Usage:
  node manage-frontmatter.mjs --folder=content --key=PARAM --value=NEWVALUE

Options:
  --folder=<path>   Directory to scan for Markdown files (default: 'content')
  --key=<param>     Frontmatter key to add/update
  --value=<value>   New value for the frontmatter key
  --help            Show this help message

Examples:
  node manage-frontmatter.mjs --folder=content/blog --key=fmContentType --value=blog
  node manage-frontmatter.mjs --key=author --value="John Doe"
    `);
  process.exit(0);
};

// Parse CLI arguments
const args = process.argv.slice(2).reduce((acc, arg) => {
  const [key, value] = arg.split('=');
  acc[key.replace('--', '')] = value;
  return acc;
}, {});

// Show help if `--help` is passed or if no required parameters are given
if (args.help || !args.key || !args.value) {
  showHelp();
}

const baseFolder = args.folder || 'content';
const keyToUpdate = args.key;
const newValue = args.value;

// Function to check if a package is installed
const isPackageInstalled = async (packageName) => {
  try {
    await import(packageName);
    return true;
  } catch (e) {
    return false;
  }
};

// Ensure gray-matter is installed
const packageName = 'gray-matter';

isPackageInstalled(packageName).then(async (installed) => {
  if (!installed) {
    console.error(`\n⚠️  The package '${packageName}' is not installed.\n`);
    process.stdout.write("Would you like to install it now? (y/n) ");

    process.stdin.setEncoding('utf8');
    process.stdin.once('data', (answer) => {
      answer = answer.trim().toLowerCase();
      if (answer === 'y') {
        console.log(`\nInstalling ${packageName}...\n`);
        try {
          execSync(`npm install ${packageName}`, { stdio: 'inherit' });
          console.log(`\n✅ ${packageName} installed. Please run the script again.\n`);
        } catch (err) {
          console.error(`\n❌ Failed to install ${packageName}. Exiting.\n`);
        }
      } else {
        console.log(`\n❌ ${packageName} is required to run this script. Exiting.\n`);
      }
      process.exit();
    });

    process.stdin.resume();
  } else {
    const { default: matter } = await import(packageName);

    /**
     * Recursively traverses directories and updates Markdown frontmatter
     * @param {string} dir - Directory to start traversal
     */
    const processDirectory = (dir) => {
      fs.readdirSync(dir).forEach(file => {
        const fullPath = path.join(dir, file);
        if (fs.statSync(fullPath).isDirectory()) {
          processDirectory(fullPath);
        } else if (file.endsWith('.md')) {
          updateFrontmatter(fullPath);
        }
      });
    };

    /**
     * Reads a markdown file, updates its frontmatter, and saves changes.
     * @param {string} filePath - Path to the markdown file
     */
    const updateFrontmatter = (filePath) => {
      const content = fs.readFileSync(filePath, 'utf8');
      const parsed = matter(content);

      // Update the given key with the new value
      parsed.data[keyToUpdate] = newValue;

      // Convert back to markdown format
      const updatedContent = matter.stringify(parsed.content, parsed.data);
      fs.writeFileSync(filePath, updatedContent, 'utf8');

      console.log(`Updated ${filePath}: Set '${keyToUpdate}' to '${newValue}'`);
    };

    // Start processing
    console.log(`Scanning folder: ${baseFolder}`);
    processDirectory(baseFolder);
    console.log('Update complete.');
  }
});

call it like this and follow the instructions:

node manage-frontmatter.mjs # or, for instance
node manage-frontmatter.mjs --folder=content/blog --key=fmContentType --value=blog

@github-project-automation github-project-automation bot moved this from Ready to Released in v10.9.0 Feb 8, 2025
@project-labels project-labels bot added Released The task has been released and removed Ready This is ready to be picked up labels Feb 8, 2025
davidsneighbour added a commit to davidsneighbour/kollitsch.dev that referenced this issue Feb 8, 2025
davidsneighbour added a commit to davidsneighbour/kollitsch.dev that referenced this issue Feb 8, 2025
@estruyf
Copy link
Owner

estruyf commented Feb 10, 2025

@davidsneighbour, thank you for sharing your script 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working Released The task has been released v10.8.0 Project: v10.8.0
Projects
None yet
Development

No branches or pull requests

2 participants