metonym / svelte-highlight

Syntax Highlighting for Svelte using highlight.js
https://svhe.onrender.com
MIT License
252 stars 13 forks source link

Feature Request: Header and/or footer slot(s) #297

Closed Jack-Barry closed 9 months ago

Jack-Barry commented 9 months ago

I'm trying to implement a "copy" button at the top of code snippets, but so far haven't found a good way to accomplish this

My first whack at it was to relatively position the bounding element, then absolutely position the button to the top right. This isn't great, because on smaller screens the button may overlap the text from the code snippet.

Screenshot 2023-11-18 at 1 36 43 PM

I'd rather have the button be a full width block so that all of the code text gets positioned underneath. I tried adding padding to the Highlight and/or the LineNumbers component, but it doesn't look like I'd expect it to

Screenshot 2023-11-18 at 1 40 18 PM

Am I missing a glaringly obvious way to do this, or would it be possible for this lib to allow for a header and/or footer slot so that something like this can be accomplished?

metonym commented 9 months ago

Hi @Jack-Barry, I think you are on the right track with the relative positioning. In my opinion, this can be accomplished without adding accessory slots to this library.

I believe the trick is to style the button to be a full width. Could you try the following?

StackBlitz source code

<div>
  <button type="button">Copy</button>
  <HighlightSvelte {code} let:highlighted>
    <LineNumbers {highlighted} />
  </HighlightSvelte>
</div>

<style>
  div {
    position: relative;
    outline: 2px solid red;
  }

  button {
    width: 100%;
    height: 40px;
  }
</style>
Screenshot 2023-11-18 at 1 16 35 PM
Jack-Barry commented 9 months ago

I probably communicated my goal poorly - wouldn't want the button to be full width, would want it to just be in the top right corner. Kinda like what shows up in the example you provided. Difference is, the full width section should match the background color/border/border-radius etc. of the code snippet. This is what I'm after:

copy-button-example

In this example screenshot, note how the code snippet has padding above it (a full width div as a header) that the button can sit inside of. That way the background color and border and whatnot matches the code snippet, but on a smaller screen the button won't obscure the text underneath

Jack-Barry commented 9 months ago

After taking a poke around the Highlight JS issues, looks like what I'm after is the ability to add a plugin, per this issue: https://github.com/highlightjs/highlight.js/issues/2946

Maybe instead of slots, the svelte-highlight lib could support the addPlugin/removePlugin features of HighlightJS?

metonym commented 9 months ago

In which case one solution is to match the div's background color with that of the code snippet to make it appear as one block:

Source

Screenshot 2023-11-18 at 7 55 01 PM