/**
 * @license MIT, see License.md for full text.
 */
import{LitElement as e,html as t,css as o,render as i}from"../../lit/index.js";import{oneDark as n}from"./lib/themes/one-dark.js";import{hljs as r,highlightjs_line_numbers as s}from"./lib/highlightjs/highlight.js";import{javascript as a}from"./lib/highlightjs/languages/javascript.js";import{yaml as h}from"./lib/highlightjs/languages/yaml.js";import{jsonLang as l}from"./lib/highlightjs/languages/json.js";import{cssLang as d}from"./lib/highlightjs/languages/css.js";import{phpLang as c}from"./lib/highlightjs/languages/php.js";import{xml as p}from"./lib/highlightjs/languages/xml.js";r.registerLanguage("javascript",a),r.registerLanguage("json",l),r.registerLanguage("css",d),r.registerLanguage("php",c),r.registerLanguage("yaml",h),r.registerLanguage("xml",p),r.registerLanguage("html",p),window.hljs=r,s();class CodeSample extends e{static get styles(){return[o`
        :host {
          display: block;
        }

        :host([hidden]),
        [hidden] {
          display: none;
        }

        pre {
          margin: 0;
        }

        pre,
        code {
          font-family: var(
            --code-sample-font-family,
            Operator Mono,
            Inconsolata,
            Roboto Mono,
            monaco,
            consolas,
            monospace
          );
          font-size: var(--code-sample-font-size, 0.875rem);
        }
        /** line ending highlight!!! */
        table {
          border-spacing: 0;
          width: 100%;
          padding: 0;
          margin: 0;
          border: 0;
        }
        td.hljs-ln-numbers {
          text-align: right;
          color: #ccc;
          border-right: 1px solid #999;
          vertical-align: top;
          padding-left: 8px;
          padding-right: 4px;

          -webkit-touch-callout: none;
          -webkit-user-select: none;
          -khtml-user-select: none;
          -moz-user-select: none;
          -ms-user-select: none;
          user-select: none;
        }
        tr {
          transition: background-color 0.3s ease-in-out;
        }
        tr:hover {
          background-color: var(--code-sample-line-hover-color, #3297fd11);
        }
        tr:hover .hljs-ln-n {
          font-weight: bold;
        }
        .hljs-ln-n:before {
          content: attr(data-line-number);
        }
        td.hljs-ln-code {
          padding-left: 16px;
        }
        .line-highlighted {
          background-color: var(
            --code-sample-line-highlighted-color,
            #3297fd22
          );
        }

        .hljs {
          padding: 0;
          line-height: var(--code-sample-line-height, 1.3);
        }

        .demo:not(:empty) {
          padding: var(--code-sample-demo-padding, 0);
        }

        #code-container {
          position: relative;
        }

        button {
          background: var(--code-sample-copy-button-bg-color, #e0e0e0);
          border: none;
          cursor: pointer;
          display: block;
          position: absolute;
          right: 0;
          top: 0;
          text-transform: uppercase;
        }
      `]}render(){return t` <div id="theme"></div>
      <div id="demo" class="demo"></div>
      <slot></slot>
      <div id="code-container">
        <button
          type="button"
          ?hidden="${!this.copyClipboardButton}"
          id="copyButton"
          title="Copy to clipboard"
          @click="${this._copyToClipboard}"
        >
          Copy
        </button>
        <pre id="code"></pre>
      </div>`}static get haxProperties(){return{type:"element",canScale:!0,canEditSource:!0,gizmo:{title:"Code sample",description:"A sample of code highlighted in the page",icon:"icons:code",color:"blue",tags:["Instructional","code","highlight","syntax","code-sample"],meta:{author:"HAXTheWeb core team"}},settings:{configure:[{property:"type",title:"Code highlighting",description:"Syntax highlighting to apply to the code area",inputMethod:"select",options:{javascript:"JavaScript",html:"HTML",css:"CSS",xml:"XML",json:"JSON data",yaml:"YAML",php:"PHP"}},{slot:"",slotWrapper:"template",slotAttributes:{"preserve-content":"preserve-content"},title:"Source",description:"Code to be presented in content area",inputMethod:"code-editor"},{property:"copyClipboardButton",title:"Copy to clipboard button",description:"button in top right that says copy to clipboard",inputMethod:"boolean"},{property:"highlightStart",title:"Highlight start",description:"Line number to start highlighting",inputMethod:"number"},{property:"highlightEnd",title:"Highlight end",description:"Line to finish highlighting on",inputMethod:"number"}],advanced:[]},saveOptions:{unsetAttributes:["theme"]},demoSchema:[{tag:"code-sample",content:'<template preserve-content="preserve-content">const great = "example";\n            const great = "example";\n            const great = "example";</template>',properties:{type:"javascript","copy-clipboard-button":"copy-clipboard-button"}}]}}static get properties(){return{...super.properties,copyClipboardButton:{type:Boolean,attribute:"copy-clipboard-button"},theme:{type:Object},type:{type:String,reflect:!0},highlightStart:{type:Number,reflect:!0,attribute:"highlight-start"},highlightEnd:{type:Number,reflect:!0,attribute:"highlight-end"}}}static get tag(){return"code-sample"}constructor(){super(),this.highlightStart=null,this.highlightEnd=null,this._observer=null,this.theme=n,this.type="html",this.copyClipboardButton=!1}haxHooks(){return{gizmoRegistration:"haxgizmoRegistration"}}haxgizmoRegistration(e){let t=["javascript","js","json","css","php","yaml","xml","html"];for(var o in t)e.keyboardShortcuts["```"+t[o]]={tag:"code-sample",properties:{type:"js"===t[o]?"javascript":t[o]},content:`<template preserve-content="preserve-content">${this.getExample(t[o])}</template>`};e.keyboardShortcuts["```"]=e.keyboardShortcuts["```html"]}getExample(e){switch(e){case"css":return'\n  .the-cheet[is="tothelimit"] {\n    padding: 8px;\n    margin: 4px;\n  }\n';case"html":return'\n  <blockquote>\n  Dear Strongbad,\n  In 5th grade I have to watch a <em>lame hygiene movie</em>. I was thinking\n  you could make a <strong id="bad">better movie about hygiene</strong> than the cruddy school version.\n  Your friend,\n  John\n  </blockquote>\n';case"javascript":case"js":return'const everyBody = "to the limit";\n  let theCheat = true;\n  if (theCheat) {\n    return `is ${everyBody}`;\n  }';case"xml":return"<IAmLike>\n  <ComeOn>fhqwhgads</ComeOn>\n</IAmLike>";case"yaml":return"- CaracterList:\n  - Homestar Runner\n  - Strongbad\n  - The Cheat";case"php":return'  $MrTheCheat = "wins the big race";\nif ($MrTheCheat) {\n  return "HaVe A tRoPhY";\n}';case"json":return'{\n  "mainMenu": [\n    "Characters",\n    "Games",\n    "Toons",\n    "Email",\n    "Store"\n  ]\n}'}}firstUpdated(e){super.firstUpdated&&super.firstUpdated(e),""==this.innerHTML&&(this.innerHTML='<template preserve-content="preserve-content">const great="example";</template>'),this._updateContent(),setTimeout((()=>{this._themeChanged(this.theme)}),0)}connectedCallback(){super.connectedCallback(),this.querySelector("template")?(this._observer=new MutationObserver((e=>{this.shadowRoot&&this._updateContent()})),this._observer.observe(this,{attributes:!0,childList:!0,subtree:!0})):this.childNodes.length&&console.error("<code-sample>:","content must be provided inside a <template> tag")}disconnectedCallback(){this._observer&&(this._observer.disconnect(),this._observer=null),super.disconnectedCallback()}updated(e){e.forEach(((e,t)=>{"theme"==t&&this.shadowRoot&&this._themeChanged(this[t]),"highlightStart"===t&&this.shadowRoot&&null!==this[t]&&null!==this.highlightEnd&&setTimeout((()=>{this.highlightLines(this.highlightStart,this.highlightEnd)}),100),"highlightEnd"===t&&this.shadowRoot&&null!==this[t]&&null!==this.highlightStart&&setTimeout((()=>{this.highlightLines(this.highlightStart,this.highlightEnd)}),100)}))}highlightLines(e,t){Array.from(this.shadowRoot.querySelector("code.hljs table tbody").children).map(((o,i)=>{i<e-1||i>t-1?(o.classList.remove("line-highlighted"),o.setAttribute("part","line")):(o.classList.add("line-highlighted"),o.setAttribute("part","line line-highlighted"))}))}_themeChanged(e){if(e){for(;this.shadowRoot.querySelector("#theme").childNodes>0;)this.shadowRoot.querySelector("#theme").removeChild(this.shadowRoot.querySelector("#theme").firstChild);i(e,this.shadowRoot.querySelector("#theme"))}}_updateContent(){this._code&&this._code.parentNode&&this._code.parentNode.removeChild(this._code);let e=this._getCodeTemplate();e||(e=globalThis.document.createElement("template"),e.setAttribute("preserve-content","preserve-content"),this.appendChild(e)),this._applyHighlightjs(e.innerHTML)}_getCodeTemplate(){const e=this.children;return[].filter.call(e,(e=>e.nodeType===Node.ELEMENT_NODE))[0]}_applyHighlightjs(e){this._code=globalThis.document.createElement("code"),this.type&&this._code.classList.add(this.type),this._code.innerHTML=this._entitize(this._cleanIndentation(e)),this.shadowRoot&&this.shadowRoot.querySelector("#code")&&(this.shadowRoot.querySelector("#code").appendChild(this._code),r.highlightBlock(this._code),r.initLineNumbersOnLoad({},this.shadowRoot.querySelector("code")))}_cleanIndentation(e){const t=e.match(/\s*\n[\t\s]*/);return e.replace(new RegExp(t,"g"),"\n")}_entitize(e){return String(e).replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/=""/g,"").replace(/=&gt;/g,"=>").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}_copyToClipboard(e){const t=e.target,o=this._textAreaWithClonedContent();o.select();try{globalThis.document.execCommand("copy",!1),t.textContent="Done"}catch(e){console.error(e),t.textContent="Error"}o.remove(),setTimeout((()=>{t.textContent="Copy"}),1e3)}_textAreaWithClonedContent(){const e=globalThis.document.createElement("textarea");return globalThis.document.body.appendChild(e),e.value=this._cleanIndentation(this._getCodeTemplate().innerHTML),e}}globalThis.customElements.define(CodeSample.tag,CodeSample);export{CodeSample};