pngwn / MDsveX

A markdown preprocessor for Svelte.
https://mdsvex.pngwn.io
MIT License
2.27k stars 96 forks source link

`<style>` exported from layout instead of component? #10

Closed DavidPeicho closed 4 years ago

DavidPeicho commented 4 years ago

Hi,

This may be a tricky problem to solve, imagine this situation:

---
layout: './layouts/about.svelte'
---

<h1 class='noooes'>Test</h1>

<style>
  .noooes {
    color: white;
  }
</style>

The style will not get applied to the <h1> tag. When removing the layout, the still gets applied.

My guess is that at some poin the <style> tag may be exported for the Layout component but not for the file component? (I mean the svexy).

pngwn commented 4 years ago

The reason for this and the other style-related issue, is that I didn't consider using MDsveX files as actual components with styling etc. What is happening here is that the whole markdown file is wrapped with the layout component.

This:

---
layout: './layouts/about.svelte'
---

<h1 class='noooes'>Test</h1>

<style>
  .noooes {
    color: white;
  }
</style>

Becomes:

<Layout>
  <h1 class='noooes'>Test</h1>

  <style>
    .noooes {
      color: white;
    }
  </style>
</Layout>

<script>
  import Layout from './layouts/about.svelte';
</script>

Which is a problem because Svelte expects those style tags to be defined at the top level (not as a child of another element).

This isn't particularly difficult to fix but it could slow things down quite a bit if I need to do some more complex parsing of every single MDsveX file, which might be necessary to fix #11 as well (#11 is probably a trickier problem than this one).

Now, what I could do is what I've done with normal and context="module" scripts: use fenced code blocks to pull them out and inject them into the component, this way there would be no scoping issues. Something like:

---
layout: './layouts/about.svelte'
---

<h1 class='noooes'>Test</h1>

```css exec
  .noooes {
    color: white;
  }


This would mean that any CSS in a fenced block like this doesn't have to follow markdown rules and can be extracted and correctly scoped. I'm not 100% on this right now , but it might be a good solution, I'll need some time to consider it.
pngwn commented 4 years ago

I am going to add this, it seems the most pleasant solution and matches the pattern of the javascript tags. I will use the [lang] style syntax and hopefully I can make this support compile to css languages as well as plain css, which will give the same flexibility as using normal style tags but with none of the problems we are currently having.

DavidPeicho commented 4 years ago

This seems like a good idea for me! Thanks for investing time into that

pngwn commented 4 years ago

This was implemented in the latest version, so this issue should be resolved now. Let me know how you get on.