mdn / yari

The platform code behind MDN Web Docs
Mozilla Public License 2.0
1.18k stars 503 forks source link

EmbedLiveSample do not load images with a relative path #3430

Open germain-gg opened 3 years ago

germain-gg commented 3 years ago

I stumbled upon the Using CSS Transforms page

The image screen_shot_2016-02-16_at_15.53.54.png lives in mdn/content content/files/en-us/web/css/css_transforms/using_css_transforms and can be embedded within the page. However there is a code example below

<pre class="brush: html">&lt;img style="transform: rotate(90deg);
            transform-origin: bottom left;"
     src="/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms/screen_shot_2016-02-16_at_15.53.54.png"&gt;
</pre>

That code example is loaded using the {{EmbedLiveSample}} macro which extracts the content of the <pre> tag above and displays it within an iframe. The issue is that the relative path does not work and therefore the image is broken

I can see two ways of dealing with this

I'd be happy to work on a fix for this one once a direction has been agreed upon (either modifying mdn/content or slightly tweaking live-sample.js in this repo)

peterbe commented 3 years ago
* Using a fully qualified URL when wanting to load an asset

You'll have to do this. Kinda. You can't do cheerio stuff after the live sample has been put together. The code the extracts and builds live sample (and ultimately generates the ./_samples/index.html file) happens before we load the whole fully rendered HTML into a cheerio instance.

So whatever code that copies the <img src=...> needs to be smarter about turning that src into an "absolute URL" before just copying it blindly.

If you can hack up a hack that solves it, please go ahead and make a PR, even if it's not perfect, and we can help you fix it or write tests or whatever needs doing.

One thing to keep in mind is that the img tag might be a fully-formed external absolute URL like <img src="https://placehold.er/500x500.gif"> or something and in those cases you don't want to inject the prefix /en-US/docs/Web/CSS/CSS_Transforms/Using_CSS_transforms for example.

caugner commented 1 year ago

FWIW Those live samples currently do load relative images, because live samples are published into the same directory as the file attachments from the build, and https://yari-demos.prod.mdn.mozit.cloud/ essentially serves the same content as https://developer.mozilla.org/.

The proper way to do this would be to determine the file attachments used in the live sample as part of buildLiveSamplePages():

https://github.com/mdn/yari/blob/9b885aad6cf481e4d64892a1b5d8c5976e7944ba/build/index.ts#L349-L354

Then we can copy them next to the live samples:

https://github.com/mdn/yari/blob/9b885aad6cf481e4d64892a1b5d8c5976e7944ba/build/cli.ts#L217-L220