From e1c36e3cffa67f8a8f0cec1e87060aca38c88ee5 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Sat, 21 Nov 2020 14:44:48 +0100 Subject: [PATCH] tweak mechanism for auto-attaching project images --- gatsby-node.js | 28 +++++++++++++++++----------- src/pages/{ProjectsYaml.slug}.jsx | 4 ++-- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/gatsby-node.js b/gatsby-node.js index 3a3f6b6..0a50597 100644 --- a/gatsby-node.js +++ b/gatsby-node.js @@ -1,6 +1,5 @@ /* eslint-disable no-console */ -// const path = require('path') const remark = require('remark') const parse = require('remark-parse') const html = require('remark-html') @@ -84,19 +83,26 @@ exports.onPreBootstrap = async () => { } // -// Add repos to front page's context +// Add pageContext // exports.onCreatePage = async ({ page, actions }) => { - const { createPage } = actions + const { createPage, deletePage } = actions - if (page.path === '/') - createPage({ - ...page, - context: { - ...page.context, - repos - } - }) + // Regex for auto-attaching project images to pages based on slug. + // Image file names follow the pattern slug-01.png. + // Regex inspiration from https://stackoverflow.com/a/7124976 + const imageRegex = `/${page.path.replaceAll('/', '')}+?(?=-\\d)/` + + deletePage(page) + createPage({ + ...page, + context: { + ...page.context, + imageRegex, + // Add repos only to front page's context + ...(page.path === '/' && { repos }) + } + }) } exports.onCreateNode = ({ node, actions }) => { diff --git a/src/pages/{ProjectsYaml.slug}.jsx b/src/pages/{ProjectsYaml.slug}.jsx index 109270b..499efe6 100644 --- a/src/pages/{ProjectsYaml.slug}.jsx +++ b/src/pages/{ProjectsYaml.slug}.jsx @@ -82,7 +82,7 @@ export default class Project extends PureComponent { } export const projectQuery = graphql` - query($slug: String!) { + query($slug: String!, $imageRegex: String!) { projectsYaml(slug: { eq: $slug }) { title slug @@ -106,7 +106,7 @@ export const projectQuery = graphql` } projectImages: allImageSharp( - filter: { fluid: { originalName: { regex: $slug } } } + filter: { fluid: { originalName: { regex: $imageRegex } } } sort: { fields: [fluid___originalName], order: ASC } ) { edges {