Coder Social home page Coder Social logo

gatsby-wpgraphql-inline-images's People

Contributors

pehaa avatar progital avatar rburgst avatar sarutole avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

gatsby-wpgraphql-inline-images's Issues

Package doesn't appear to be working with query hooks

import { useStaticQuery, graphql } from 'gatsby'

export const useContentPlaceholder = () => {
const { wpgraphql } = useStaticQuery(graphqlquery useContentPlaceholderQuery { wpgraphql { post(id: "cG9zdDoxMzM=") { content } } })

return wpgraphql.post.content

}

import React from 'react'
import contentParser from 'gatsby-wpgraphql-inline-images'
import { useContentPlaceholder } from '../../hooks/useContent'

export default () => {
const content = useContentPlaceholder()

const pluginOptions = {
  wordPressUrl: `https://noh.progital.dev/`,
  uploadsUrl: `https://noh.progital.dev/wp-content/uploads/`,
}
return (
    <React.Fragment>
        {<div>{contentParser({ content }, pluginOptions)}</div>}
    </React.Fragment>
)

}

I test across multiple different wordpress domains and even the example domain provided and the inline images are not being saved locally and converted into gatsby images. Am I doing something wrong here?

Images are not downloaded due to permission with htpasswd: "URI not defined" error

It seems to me that the plugin is configured as expected, with the headers authorization in its place:

gatsby-config.js

{
  resolve: 'gatsby-wpgraphql-inline-images',
  options: {
    debugOutput: true,
    wordPressUrl: 'https://admin.my-wordpress-site.com/',
    uploadsUrl: 'https://admin.my-wordpress-site.com/wp/wp-content/uploads/',
    processPostTypes: ['Page', 'Post'],
    graphqlTypeName: 'WordPressGraphQl',
    httpHeaders: {
      Authorization: `Basic ${process.env.TOKEN_HTPASSWD}`,
    },
  },
},

After that I'm calling the plugin inside the template of the page:

templates/pageLayout.js

const pluginOptions = {
	wordPressUrl: `https://admin.my-wordpress-site.com/`,
	uploadsUrl: `https://admin.my-wordpress-site.com/wp/wp-content/uploads/`,
}

const content = data.wpGraphQl.page.content

[...]

<Layout>
<main>
  <div>
    <h1 dangerouslySetInnerHTML={{ __html: data.wpGraphQl.page.title }} />
    <div>{contentParser({ content }, pluginOptions)}</div> 

[...]

The content is well rendered but the image markups it the same as when I use dangerouslySetInnerHTML:

<img 
  class="aligncenter size-large wp-image-240" 
  src="https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-1024x768.jpg" 
  alt="" 
  srcset="https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-1024x768.jpg 1024w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-300x225.jpg 300w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003-768x576.jpg 768w, https://admin.my-wordpress-site.com/wp/wp-content/uploads/2018/10/Borgo00003.jpg 1200w" sizes="(max-width: 848px) 100vw, 848px" width="848" height="636">

(obviously the image is not displayed because the headless wordpress cms its protected by the htpasswd)

I presume that the images are not downloaded since I don't found them in the static folder.

This is the end part of the develop process in the shell when I activate debugOutput:

success run static queries - 1.296 s — 5/5 3.95 queries/second
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 1/1 - 0.461 s
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 4/4 - 1.383 s
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success Downloading remote files — 1/1 - 0.252 s
success run page queries - 3.981 s — 13/13 3.29 queries/second
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
>>> Entered contentResolver @ URI not defined, skipping
success start webpack server - 2.393 s — 1/1 2.45 pages/second
 DONE  Compiled successfully in 9911ms

Roadmap: write tests

Adding tests is something that I've been wanting to do for some time. This and re-organizing codebase to make it more testable is at the top of the list.

FeaturedImage implementation

Hi there!

I'm getting the following error message for all my image requests when firing up gatsby develop.

My local WP site is proxying the images from production, so not sure if that has anything to do with my issue. However, I was able to reproduce the issue on a fresh gatsby-hello-world and a fresh wp install with a local image.

Exception featured image TypeError: Cannot read property 'toLowerCase' of undefined
    at healOptions (/node_modules/gatsby-plugin-sharp/plugin-options.js:51:38)
    at fluid (/node_modules/gatsby-plugin-sharp/index.js:296:19)
    at convertFileNodeToFluid (/node_modules/gatsby-wpgraphql-inline-images/src/utils.js:78:27)
    at downloadImage (/node_modules/gatsby-wpgraphql-inline-images/src/utils.js:60:29)
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at async Object.featuredImageResolver [as resolve] (/node_modules/gatsby-wpgraphql-inline-images/gatsby-node.js:102:19)
    at async Promise.all (index 2)
    at async Promise.all (index 0)
    at async Promise.all (index 0)

query

query {
    wordpress {
      portfolios {
        nodes {
          title
          featuredImage {
            srcSet
            sizes
            sourceUrl
            content
          }
        }
      }
    }
  }

Anchors

Amazing plugin, but I did notice it doesn't work with anchor tags, any plans to incorporate?

Objects type error after upgrading to WPGraphql latest version 0.10.0

I've just updated WPGraphql to the latest version 0.10.0

I'm getting this error:

Fragment "GatsbyImageJobQuery" cannot be spread here as objects of type "NodeWithFeaturedImageToMediaItemConnectionEdge" can never be of type "MediaItem".

Here my fragment:

fragment GatsbyImageJobQuery on WPGraphQL_MediaItem {
    altText
    sourceUrl
    imageFile {
      childImageSharp {
        fixed(width: 120, height: 120) {
          srcSetWebp
          tracedSVG
          ...GatsbyImageSharpFixed
        }
      }
    }
  }

Mangled MenuItems urls

Before I had this plugin I was getting normal urls and string replacing "https://my.domain.com" with "".

The plugin seems to be mangling URLs on menu Items to be localhost:8000/https:/pwddev.kinsta.cloud/video-testimonials/

Notice the missing / on https://

URI in gatsby-node.js Empty - and createNodeId must be a String error

Hi,

I am using your plugin for my build, and am unable to swap images out using the contentParser. After tracing the issue back it seems that there is no URI key on the source object passed from WordPress:

const { uri } = source;

This means all the content is returned without being run through the sourceParser.

What is the reason for checking for a URI? Where is this set in WordPress?

When I remove the URI checker, I end up getting errors from createRemoteFileNode within the utils.js file:

fileNode = await createRemoteFileNode({

Error:

Parameter passed to createNodeId must be a String or Number (got undefined)

Any ideas what this could be?

Thanks

PNGs lose transparency

When managing in a standard Gatsby query, a key 'toFormat: PNG' would be added to ensure that PNGs do not lose their transparency. Otherwise this happens:

image

This is caused by a webp image being created - losing transparency, and loading over the transparent PNG image.

In this instance we cannot do that. However, I think we can conditionally stop the webp being generated.

I am guessing that a check on the file type needs to occur, and then stop here:

if (generateWebp) {

sourceParser turning &nbsp; into string

Hi,

After running some tests, I have found that the resolver seems to be turning &nbsp; entities into strings, meaning contentParser is making them visible to the end user.

I think this is due to Cheerio not decoding entities:

const $ = cheerio.load(content, { xmlMode: true });

I can understand the confusion as here: https://cheerio.js.org/ the documentation says that decodeEntitites defaults to true, however looking at the in-depth documentation shows it actually defaults to false: https://github.com/fb55/htmlparser2/wiki/Parser-options#option-decodeentities

I am happy to add a PR unless there is a reason you have not included this?

Thanks

QUESTION: data attributes in markup

Hey!

I notice in the contentParser it looks like it's looking for particular data attributes that I don't recognize.

For example here:

getByPath(domNode, 'attribs[data-gts-encfluid]', null);

It's looking for elements with: attribs[data-gts-swapped-href]

Is there a WordPress plugin that is affecting image markup as well? Or what's going on with these custom attributes.

Just curious if there's anything needed on the WordPress side to work with this.

Thanks!

Whitespace text nodes cannot appear as a child of <table>

When rendering a table using the parser, the console returns the following error: Whitespace text nodes cannot appear as a child of <table>. Make sure you don't have any extra whitespace between tags on each line of your source code..

This does not appear when using a standard dangerouslySetInnerHTML implementation.

This package came across the issue and seemed to fix it: aknuds1/html-to-react#79

Also seems to be the most up-to-date.

Issue when adding the plugin

Hello,
I'm trying to add the plugin to an install.

It tells me
error An unexpected error occurred: "could not find a copy of gatsby to link in /mnt/c/Users/USERSESSION/SITENAME/node_modules/gatsby-wpgraphql-inline-images/node_modules".

Adding other plugins works normally.

My repo is there if needed https://github.com/bonakor/nuuksby/

Let me know if I can give more infos :)

Same page anchor links being removed

Hi,

When content is parsed from the editor it is removing anchor links.

Within the WordPress I have content that is set up like:

<a href="#what-is-an-actor">What is an Actor?</a>

However, when this is run through the parser the content is returned as:

<a class=" css-0" href="/">What is an Actor?</a>

On top of this, it seems to be added unneeded CSS classes.

I think these issues are caused the following line:
https://github.com/progital/gatsby-wpgraphql-inline-images/blob/dev/src/contentParser.js#L84

What is the need for using theme-ui, will a plain Link component not do the job?

Thanks,
Rob

error An unexpected error occurred: "could not find a copy of gatsby to link in /[project folder]/node_modules/gatsby-wpgraphql-inline-images/node_modules"

Environment

Gatsby version >= 2.22.00
Rest of versions in package.json: https://github.com/louiechristie/newcrossities/blob/559b283e6f0e1a91d51639d7b0a47e37a1c689a1/package.json

Command

yarn

Gives error

error An unexpected error occurred: "could not find a copy of gatsby to link in /[project folder]/node_modules/gatsby-wpgraphql-inline-images/node_modules"

How to replicate

yarn

Feature Request: Headers in Download Image

The plugin is not able to download any images from WP sites behind basic auth, or that require specific header tokens to access files.

WpGraphQL currently does this by allowing a headers option to be passed in via the config file. This may be the best way of doing this?

This header variable can then be passed to the CreateRemoteFileNode function.

fileNode = await createRemoteFileNode({

See: HTTP Headers in the CreateRemoteFleNode documentation: https://www.gatsbyjs.org/packages/gatsby-source-filesystem/#createremotefilenode

Not honouring pathPrefix or assetPrefix config options

Inline images are displaying correctly in development environment, but inline images are missing when building and deploying to a sub-folder.

Gatsby allows this by setting the pathPrefix configuration option in gatsby-config.js.

My guess is the plugin isn't using the withPrefix function, which is explained in the following article Adding a Path Prefix.

I'm still investigating, where the /static path is being set...might not be in this plugin. Any advice is appreciated.

Images are not downloaded when called from src/pages

Hey,
for your information im new to Gatsby and trying to render a static site with static files.

I have problems handling images in Gutenberg Blocks.
I queried the content I need via graphql and passed it through the contentParser function. But it didn't download the images as static files and returns nothing + there's no error.

Here's an insight to my syntax

import contentParser from 'gatsby-wpgraphql-inline-images'
const pluginOptions = {
    wordPressUrl: 'http://cms-gatsby-project.local',
    uploadsUrl: 'https://cms-gatsby-project.local/wp-content/uploads/'
}
const IndexPage = ({ data }) => {
    return (
           <div>{contentParser(data.wordpress.pages.nodes[0].content,pluginOptions)}</div>
        )
 }

 export const pageQuery = graphql`
        query frontPageQ{
            wordpress {
                pages(where: {name: "Startseite"}) {
                        nodes {
                            id
                            content
                        }
                }
    }
`
export default IndexPage

Hopefully you can help me :)

How to write tests using Jest

Hello!

I'm using this awesome plugin to render content and when I try to test my component using gatsby-wpgraphql-inline-images - it throws an error. I'm wondering if you can give guidance on how to correctly setup my test? Thanks!

 FAIL  src/templates/__tests__/supportQuestionPage.test.tsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/en/configuration.html

    Details:

    /Users/me/Documents/github/etShop-gatsby/node_modules/gatsby-wpgraphql-inline-images/src/contentParser.js:2
    import { jsx } from "theme-ui"
           ^

    SyntaxError: Unexpected token {

      at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
      at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:579:25)
      at Object.<anonymous> (node_modules/gatsby-wpgraphql-inline-images/index.js:1:45)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total

Here is what my component looks like:

import React from 'react'
import { graphql } from 'gatsby'
import contentParser from 'gatsby-wpgraphql-inline-images'

const SupportItem = (props: any) => {
	const pluginOptions = {
		wordPressUrl: `${process.env.GATSBY_DB}`,
		uploadsUrl: `${process.env.GATSBY_DB}/wp-content/uploads/`
	}
	const {
		// location,
		pageContext: {
			content
		},
		data: {
			wpgraphql: { supportQuestion: { title } }
		}
	} = props

	return (
		<div>
			<h1 data-testid={'title'}>{title}</h1>
			<div data-testid={'content'}>
				{contentParser({ content }, pluginOptions)}
			</div>
		</div>
	)
}

export default SupportItem

And here is what the test looks like:


import React from 'react'
import {
	render,
	cleanup
} from 'react-testing-library'
import SupportItem from '../supportQuestion'
import { StaticQuery } from 'gatsby'
import { SupportQuestionOne, SupportQuestionPageQuery } from '@redux/reduxTestUtils'

beforeEach(() => {
	// @ts-ignore
	StaticQuery.mockImplementationOnce((mock) =>
		mock.render(SupportQuestionPageQuery)
	)
})
afterEach(cleanup)
describe('Support Question Page', () => {

	it('Should render 1 Category', () => {
		const modalRender = render(<SupportItem
			data={SupportQuestionPageQuery}
			pageContext={{ content: SupportQuestionOne.content }}
		/>)
		expect(modalRender.getByTestId('content').innerHTML).toBe(SupportQuestionOne.title)
	})
	
})

My IDE tells me that there is no declaration file for the module 'gatsby-wpgraphql-inline-images'

gatsby develop doesn't return errors but my template pages don't have any image.

I try the method explained on the readme:

const pluginOptions = {
	wordPressUrl: `https://admin.mywordpress.domain/`,
	uploadsUrl: `https://admin.mywordpress.domain/wp/wp-content/uploads/`,
};
const content = data.wpGraphQl.page.content

and then:

<div>{contentParser({ content }, pluginOptions)}</div>

In the content rendered the text is ok, but images are not rendered, only their at all.
The browser console neither returns errors.

The only strange error was noted on my IDE (vscode) that tells me this (in a message by the import contentParser):

import contentParser from 'gatsby-wpgraphql-inline-images';

Non è stato trovato alcun file di dichiarazione per il modulo 'gatsby-wpgraphql-inline-images'.
Try npm install @types/gatsby-wpgraphql-inline-images if it exists or add a new declaration (.d.ts) file containing declare module 'gatsby-wpgraphql-inline-images';ts(7016)


This is my config on gatsby-config:

{
	resolve: 'gatsby-wpgraphql-inline-images',
		options: {
		   wordPressUrl: 'https://admin.mywordpress.domain/',
			uploadsUrl: 'https://admin.mywordpress.domain/wp/wp-content/uploads/',
			processPostTypes: ['Page', 'Post'],
			graphqlTypeName: 'WordPressGraphQl',
			httpHeaders: {
			   Authorization: `Basic ${process.env.TOKEN_HTPASSWD}`,
			}
		},
},

TypeError: breakpoints.map is not a function

The content parser replaces WordPress <a /> with Gatsby's <Link />, uses Styled.a from theme-ui. theme-ui extends styled-system, which seems to expect a ThemeProvider to be configured. My project doesn't use or need theme-ui or styled-system, so when I call contentParser; I get a long, confusing stack trace.

<Styled.a as={Link} to={url} className={className}>
{domToReact(domNode.children, parserOptions)}
</Styled.a>
seems to be causing the trouble. I'm guessing these libraries (theme-ui, styled-system) are not really required for gatsby-wpgraphql-inline-images to operate correctly. Would you be interested in removing them as dependencies? I'm happy to open a pull request.

Edit: typo fix

ACF Flexible Content - Rich Content / WYSIWYG fields

Hi there, can you confirm that the scope of this utility is limited to the default "Content" field that comes with Wordpress Post and Page post types, including CPTs that utilize the built in Content field?

I did some brief testing on a CPT that I have that ignores the built-in Content field, but instead uses the ACF Flexible Content field to create a Layout that uses a WYSIWYG field.

For all intents and purposes, the functionality on the CMS side looks the same, but my graphql queries would be further nested such as:

fragment OneColumnContentFields on Wordpress_LandingPage_Landingpagefields_Content_OneColumnContent {
  background {
    ...
  }
  content
}

query GET_LANDING_PAGE($id: ID!) {
    wordpress {
      landingPage(id: $id) {
        id
        uri
        title
        landingPageFields {
          content {
            __typename
            ...OneColumnContentFields
          }
        }
      }
    }
  }

Doesn't appear that the plugin will pick up the ACF WYSIWYG field thats nested inside of Flexible Content. Not sure if this is a bug or simply not intended functionality.

Installing the plugin with Yarn fails on W10

Hi,
I'm trying to install the plugin with W10, and it fails saying An unexpected error occurred:

\\node_modules".```

When I install the plugin with npm, it works but then launching "gatsby develop" bugs, saying 

`Something went wrong installing the "sharp" module

Cannot find module '../build/Release/sharp.node'


Would you have an idea of what to do (but I'm guessing your plugin might be merged into the new version of GatsbyWp :/)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.