Files
server-configs/siyuan/data/plugins/code-line-highlighter/index.js
2026-02-13 22:24:27 +08:00

1 line
26 KiB
JavaScript

(()=>{"use strict";var e={56(e,t,o){e.exports=function(e){var t=o.nc;t&&e.setAttribute("nonce",t)}},72(e){var t=[];function o(e){for(var o=-1,r=0;r<t.length;r++)if(t[r].identifier===e){o=r;break}return o}function r(e,r){for(var n={},s=[],l=0;l<e.length;l++){var a=e[l],c=r.base?a[0]+r.base:a[0],h=n[c]||0,u="".concat(c," ").concat(h);n[c]=h+1;var d=o(u),g={css:a[1],media:a[2],sourceMap:a[3],supports:a[4],layer:a[5]};if(-1!==d)t[d].references++,t[d].updater(g);else{var p=i(g,r);r.byIndex=l,t.splice(l,0,{identifier:u,updater:p,references:1})}s.push(u)}return s}function i(e,t){var o=t.domAPI(t);return o.update(e),function(t){if(t){if(t.css===e.css&&t.media===e.media&&t.sourceMap===e.sourceMap&&t.supports===e.supports&&t.layer===e.layer)return;o.update(e=t)}else o.remove()}}e.exports=function(e,i){var n=r(e=e||[],i=i||{});return function(e){e=e||[];for(var s=0;s<n.length;s++){var l=o(n[s]);t[l].references--}for(var a=r(e,i),c=0;c<n.length;c++){var h=o(n[c]);0===t[h].references&&(t[h].updater(),t.splice(h,1))}n=a}}},113(e){e.exports=function(e,t){if(t.styleSheet)t.styleSheet.cssText=e;else{for(;t.firstChild;)t.removeChild(t.firstChild);t.appendChild(document.createTextNode(e))}}},216(e,t,o){o.r(t),o.d(t,{default:()=>f});var r=o(72),i=o.n(r),n=o(825),s=o.n(n),l=o(659),a=o.n(l),c=o(56),h=o.n(c),u=o(540),d=o.n(u),g=o(113),p=o.n(g),m=o(523),b={};b.styleTagTransform=p(),b.setAttributes=h(),b.insert=a().bind(null,"head"),b.domAPI=s(),b.insertStyleElement=d(),i()(m.A,b);const f=m.A&&m.A.locals?m.A.locals:void 0},314(e){e.exports=function(e){var t=[];return t.toString=function(){return this.map(function(t){var o="",r=void 0!==t[5];return t[4]&&(o+="@supports (".concat(t[4],") {")),t[2]&&(o+="@media ".concat(t[2]," {")),r&&(o+="@layer".concat(t[5].length>0?" ".concat(t[5]):""," {")),o+=e(t),r&&(o+="}"),t[2]&&(o+="}"),t[4]&&(o+="}"),o}).join("")},t.i=function(e,o,r,i,n){"string"==typeof e&&(e=[[null,e,void 0]]);var s={};if(r)for(var l=0;l<this.length;l++){var a=this[l][0];null!=a&&(s[a]=!0)}for(var c=0;c<e.length;c++){var h=[].concat(e[c]);r&&s[h[0]]||(void 0!==n&&(void 0===h[5]||(h[1]="@layer".concat(h[5].length>0?" ".concat(h[5]):""," {").concat(h[1],"}")),h[5]=n),o&&(h[2]?(h[1]="@media ".concat(h[2]," {").concat(h[1],"}"),h[2]=o):h[2]=o),i&&(h[4]?(h[1]="@supports (".concat(h[4],") {").concat(h[1],"}"),h[4]=i):h[4]="".concat(i)),t.push(h))}},t}},523(e,t,o){o.d(t,{A:()=>l});var r=o(601),i=o.n(r),n=o(314),s=o.n(n)()(i());s.push([e.id,"/* Code Line Highlighter Plugin Styles */\n\n/* Overlay styling */\n.code-line-highlighter-overlay {\n transition: opacity 0.2s ease;\n}\n\n/* Ensure proper z-index stacking */\n.hl-block .hljs {\n isolation: isolate;\n}\n\n/* Line number highlighting */\n.hl-block .protyle-linenumber__rows span {\n transition: background-color 0.2s ease;\n}\n",""]);const l=s},540(e){e.exports=function(e){var t=document.createElement("style");return e.setAttributes(t,e.attributes),e.insert(t,e.options),t}},601(e){e.exports=function(e){return e[1]}},659(e){var t={};e.exports=function(e,o){var r=function(e){if(void 0===t[e]){var o=document.querySelector(e);if(window.HTMLIFrameElement&&o instanceof window.HTMLIFrameElement)try{o=o.contentDocument.head}catch(e){o=null}t[e]=o}return t[e]}(e);if(!r)throw new Error("Couldn't find a style target. This probably means that the value for the 'insert' parameter is invalid.");r.appendChild(o)}},825(e){e.exports=function(e){if("undefined"==typeof document)return{update:function(){},remove:function(){}};var t=e.insertStyleElement(e);return{update:function(o){!function(e,t,o){var r="";o.supports&&(r+="@supports (".concat(o.supports,") {")),o.media&&(r+="@media ".concat(o.media," {"));var i=void 0!==o.layer;i&&(r+="@layer".concat(o.layer.length>0?" ".concat(o.layer):""," {")),r+=o.css,i&&(r+="}"),o.media&&(r+="}"),o.supports&&(r+="}");var n=o.sourceMap;n&&"undefined"!=typeof btoa&&(r+="\n/*# sourceMappingURL=data:application/json;base64,".concat(btoa(unescape(encodeURIComponent(JSON.stringify(n))))," */")),t.styleTagTransform(r,e,t.options)}(t,e,o)},remove:function(){!function(e){if(null===e.parentNode)return!1;e.parentNode.removeChild(e)}(t)}}}},971(e){e.exports=require("siyuan")}},t={};function o(r){var i=t[r];if(void 0!==i)return i.exports;var n=t[r]={id:r,exports:{}};return e[r](n,n.exports,o),n.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),o.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},o.nc=void 0;var r={};(()=>{var e=r;const t=o(971);o(216);const i=["yellow","red","green","blue","custom1","custom2","custom3"];class n extends t.Plugin{constructor(){super(...arguments),this.observer=null,this.processingTimeouts=new Map,this.cleanupObserver=null,this.resizeObserver=null,this.inputListeners=new WeakMap,this.colorToAttr={yellow:"custom-hl",red:"custom-hlr",green:"custom-hlg",blue:"custom-hlb",custom1:"custom-hl-c1",custom2:"custom-hl-c2",custom3:"custom-hl-c3"},this.defaultColors={yellow:{background:"rgba(255, 193, 7, 0.2)",border:"#ffc107",visible:!0,label:"Yellow"},red:{background:"rgba(244, 67, 54, 0.2)",border:"#f44336",visible:!0,label:"Red"},green:{background:"rgba(76, 175, 80, 0.2)",border:"#4caf50",visible:!0,label:"Green"},blue:{background:"rgba(33, 150, 243, 0.2)",border:"#2196f3",visible:!0,label:"Blue"},custom1:{background:"rgba(156, 39, 176, 0.2)",border:"#9c27b0",visible:!1,label:"Custom 1"},custom2:{background:"rgba(0, 188, 212, 0.2)",border:"#00bcd4",visible:!1,label:"Custom 2"},custom3:{background:"rgba(233, 30, 99, 0.2)",border:"#e91e63",visible:!1,label:"Custom 3"}},this.colors={},this.config={autoEnableLineNumber:!0,defaultColor:"yellow",useCommentStyle:!1}}async onload(){console.log("LineHighlightPlugin: onload"),await this.loadConfig(),await this.loadCustomColors(),this.startCleanupObserver(),setTimeout(()=>this.processAllCodeBlocks(),500),setTimeout(()=>this.attachAllInputListeners(),600),setTimeout(()=>this.startResizeObserver(),700),setTimeout(()=>this.observeCodeBlocks(),600),this.eventBus.on("open-menu-content",this.handleContextMenu.bind(this))}onLayoutReady(){console.log("LineHighlightPlugin: onLayoutReady"),this.setupSettings()}async loadConfig(){try{const e=await this.loadData("config.json");e&&(this.config={...this.config,...e})}catch(e){console.error("Error loading config:",e)}}async saveConfig(){await this.saveData("config.json",this.config)}async loadCustomColors(){console.log("LineHighlightPlugin: loadCustomColors");try{const e=await this.loadData("colors.json");this.colors={...this.defaultColors,...e}}catch(e){console.error("Error loading custom colors:",e),this.colors={...this.defaultColors}}}async saveCustomColors(){console.log("LineHighlightPlugin: saveCustomColors"),await this.saveData("colors.json",this.colors),this.processAllCodeBlocks()}createElement(e,t={},o={},r=[]){const i=document.createElement(e);return Object.assign(i.style,t),Object.entries(o).forEach(([e,t])=>{e.startsWith("on")&&"function"==typeof t?i.addEventListener(e.substring(2).toLowerCase(),t):i.setAttribute(e,t)}),r.forEach(e=>"string"==typeof e?i.textContent=e:i.appendChild(e)),i}setupSettings(){this.setting||(this.setting=new t.Setting({confirmCallback:()=>{},height:"850px",width:"800px"})),this.setting.addItem({title:"",description:"",direction:"column",createActionElement:()=>{const e=this.createElement("div",{display:"flex",flexDirection:"column",width:"100%",marginBottom:"10px"});e.appendChild(this.createElement("div",{fontWeight:"bold",marginBottom:"5px"},{},["Auto Enable Line Numbers"]));const t=this.createElement("div",{display:"flex",alignItems:"center",width:"100%"}),o=this.createElement("input",{cursor:"pointer"},{type:"checkbox"});this.config.autoEnableLineNumber&&(o.checked=!0),o.addEventListener("change",async()=>{this.config.autoEnableLineNumber=o.checked,await this.saveConfig()}),t.appendChild(o),t.appendChild(this.createElement("span",{marginLeft:"8px"},{},["Automatically enable line numbers when adding highlights (Required for highlights to show properly)"])),e.appendChild(t);const r=this.createElement("div",{display:"flex",alignItems:"center",width:"100%",marginTop:"10px"}),i=this.createElement("input",{cursor:"pointer"},{type:"checkbox"});return this.config.useCommentStyle&&(i.checked=!0),i.addEventListener("change",async()=>{this.config.useCommentStyle=i.checked,await this.saveConfig()}),r.appendChild(i),r.appendChild(this.createElement("span",{marginLeft:"8px"},{},["Use legacy comment style (`// hl:1`) instead of attributes for context menu highlights"])),e.appendChild(r),e}}),this.setting.addItem({title:"",description:"",direction:"column",createActionElement:()=>{const e=this.createElement("div",{display:"flex",flexDirection:"column",width:"100%"});e.appendChild(this.createElement("div",{fontWeight:"bold",marginBottom:"5px"},{},["Highlight Colors"])),e.appendChild(this.createElement("div",{marginBottom:"10px"},{},["Customize the colors used for code line highlighting"]));const t=this.createElement("div",{display:"flex",flexDirection:"column",gap:"16px",width:"100%"});return i.forEach(e=>{const o=this.createElement("div",{display:"flex",alignItems:"center",gap:"12px",padding:"8px",border:"1px solid var(--b3-border-color)",borderRadius:"4px"},{"data-color-name":e}),r=this.createElement("input",{cursor:"pointer"},{type:"radio",name:"hl-default-color"});this.config.defaultColor===e&&(r.checked=!0),r.addEventListener("change",async()=>{r.checked&&(this.config.defaultColor=e,await this.saveConfig())});const i=this.createElement("input",{cursor:"pointer"},{type:"checkbox"});!1!==this.colors[e].visible&&(i.checked=!0),i.addEventListener("change",async()=>{this.colors[e].visible=i.checked,await this.saveCustomColors()});const n=this.createElement("input",{width:"80px",height:"24px",border:"1px solid var(--b3-border-color)",padding:"0 4px",borderRadius:"4px"},{type:"text",value:this.colors[e].label||e.charAt(0).toUpperCase()+e.slice(1)});n.addEventListener("change",async()=>{this.colors[e].label=n.value,await this.saveCustomColors()});const s=this.createElement("input",{width:"40px",height:"26px",border:"none",cursor:"pointer"},{type:"color",value:this.rgbaToHex(this.colors[e].background)}),l=this.createElement("input",{width:"80px"},{type:"range",min:"0",max:"100",value:String(100*this.extractOpacity(this.colors[e].background))}),a=this.createElement("input",{width:"40px",height:"26px",border:"none",cursor:"pointer"},{type:"color",value:this.colors[e].border});s.addEventListener("change",async()=>{const t=this.extractOpacity(this.colors[e].background);this.colors[e].background=this.hexToRgba(s.value,t),await this.saveCustomColors()}),l.addEventListener("input",async()=>{const t=this.rgbaToHex(this.colors[e].background);this.colors[e].background=this.hexToRgba(t,parseFloat(l.value)/100),await this.saveCustomColors()}),a.addEventListener("change",async()=>{this.colors[e].border=a.value,await this.saveCustomColors()});const c=this.createElement("button",{padding:"4px 8px",marginLeft:"auto",cursor:"pointer",border:"1px solid var(--b3-border-color)",borderRadius:"4px",background:"var(--b3-theme-background)"},{title:"Reset to default",onclick:async()=>{this.colors[e]={...this.defaultColors[e]},s.value=this.rgbaToHex(this.colors[e].background),l.value=String(100*this.extractOpacity(this.colors[e].background)),a.value=this.colors[e].border,n.value=this.colors[e].label||e,i.checked=!1!==this.colors[e].visible,await this.saveCustomColors()}},["↺"]);o.append(this.createElement("div",{display:"flex",flexDirection:"column",alignItems:"center",marginRight:"8px"},{},[this.createElement("span",{fontSize:"9px",color:"var(--b3-theme-on-surface)"},{},["Default"]),r]),this.createElement("div",{display:"flex",flexDirection:"column",alignItems:"center",marginRight:"8px"},{},[this.createElement("span",{fontSize:"9px",color:"var(--b3-theme-on-surface)"},{},["Visible"]),i]),n,this.createElement("span",{fontSize:"11px",color:"var(--b3-theme-on-surface)"},{},["Background"]),s,this.createElement("span",{fontSize:"11px",color:"var(--b3-theme-on-surface)",marginLeft:"4px"},{},["Opacity"]),l,this.createElement("span",{fontSize:"11px",color:"var(--b3-theme-on-surface)",marginLeft:"4px"},{},["Border"]),a,c),t.appendChild(o)}),t.appendChild(this.createElement("button",{padding:"8px 16px",cursor:"pointer",border:"1px solid var(--b3-border-color)",borderRadius:"4px",background:"var(--b3-theme-background)",marginTop:"8px"},{onclick:async()=>{this.colors={...this.defaultColors},await this.saveCustomColors(),this.setupSettings()}},["Reset All Colors to Default"])),e.appendChild(t),e}})}rgbaToHex(e){const t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);return t?"#"+[t[1],t[2],t[3]].map(e=>parseInt(e).toString(16).padStart(2,"0")).join(""):"#000000"}hexToRgba(e,t){return`rgba(${parseInt(e.slice(1,3),16)}, ${parseInt(e.slice(3,5),16)}, ${parseInt(e.slice(5,7),16)}, ${t})`}extractOpacity(e){const t=e.match(/rgba\([^,]+,[^,]+,[^,]+,\s*([\d.]+)/);return t?parseFloat(t[1]):.2}handleContextMenu(e){console.log("LineHighlightPlugin: handleContextMenu");const{menu:t,element:o,range:r}=e.detail,n=o?.closest(".code-block");if(!n)return;const s=this.getLineRangeFromSelection(n,r);if(!s)return;const{startLine:l,endLine:a}=s,c=l!==a?`lines ${l}-${a}`:`line ${l}`;t.addSeparator();const h=this.config.defaultColor||"yellow",u=this.colors[h]?.label||h.charAt(0).toUpperCase()+h.slice(1);t.addItem({label:`Highlight ${c} (${u})`,iconHTML:`<span style="color: ${this.colors[h].border};">●&nbsp;&nbsp;</span>`,click:()=>this.modifyBlockHighlights(n,e=>{let t=e.find(e=>e.color===h);t||(t={lines:[],color:h},e.push(t));for(let e=l;e<=a;e++)t.lines.includes(e)||t.lines.push(e);return t.lines.sort((e,t)=>e-t),e},`${c} highlighted in ${u}`)});const d=[];i.forEach(e=>{if(!1===this.colors[e].visible)return;const t=this.colors[e].label||e.charAt(0).toUpperCase()+e.slice(1);d.push({label:" "+t,iconHTML:`<span style="color: ${this.colors[e].border};">●&nbsp;&nbsp;</span>`,click:()=>this.modifyBlockHighlights(n,t=>{let o=t.find(t=>t.color===e);o||(o={lines:[],color:e},t.push(o));for(let e=l;e<=a;e++)o.lines.includes(e)||o.lines.push(e);return o.lines.sort((e,t)=>e-t),t},`${c} highlighted in ${t}`)})}),t.addItem({label:"All Colors",icon:"iconTheme",type:"submenu",submenu:d}),t.addItem({label:` Remove highlight from ${c}`,iconHTML:"🚫&nbsp;&nbsp;",click:()=>this.modifyBlockHighlights(n,e=>{let t=!1;for(let o=l;o<=a;o++)e.forEach(e=>{const r=e.lines.indexOf(o);-1!==r&&(e.lines.splice(r,1),t=!0)});return t?e.filter(e=>e.lines.length>0):e},`Highlight removed from ${c}`)})}getLineRangeFromSelection(e,t){if(!t)return null;const o=e.querySelector('.hljs div[contenteditable="true"]');if(!o)return null;const r=(o.textContent||"").split("\n"),i=(e,t)=>{let i=this.calculateOffset(e,t,o);if(null===i)return null;let n=0;for(let e=0;e<r.length;e++)if(n+=r[e].length+1,i<n)return e+1;return r.length},n=i(t.startContainer,t.startOffset),s=i(t.endContainer,t.endOffset);return n&&s?{startLine:n,endLine:s}:null}calculateOffset(e,t,o){let r=e;if(r.nodeType!==Node.TEXT_NODE&&(r=document.createTreeWalker(r,NodeFilter.SHOW_TEXT,null).nextNode(),!r))return null;let i=t;for(;r&&r!==o;)r.previousSibling?(i+=r.previousSibling.textContent?.length||0,r=r.previousSibling):r=r.parentNode;return i}async modifyBlockHighlights(e,o,r){console.log("LineHighlightPlugin: modifyBlockHighlights");const i=e.closest("[data-node-id]"),n=i?.getAttribute("data-node-id");if(!n)return void(0,t.showMessage)("Cannot find block ID",3e3,"error");let s=[];s=this.config.useCommentStyle?await this.getHighlightGroupsFromCommentSource(e):await this.getHighlightGroupsFromAttributes(n),s=o(s),this.config.useCommentStyle?await this.saveHighlightGroupsToCommentSource(n,s,e):await this.saveHighlightGroupsToAttributes(n,s,e),this.processCodeBlock(e),r&&(0,t.showMessage)(r,2e3,"info")}async getHighlightGroupsFromCommentSource(e){const t=(e.querySelector(".hljs")?.textContent||"").split("\n")[0]||"",o=this.parseHighlightMarker(t);return o?o.groups:[]}async saveHighlightGroupsToCommentSource(e,o,r){console.log("LineHighlightPlugin: saveHighlightGroupsToCommentSource",e,o);const i=await(0,t.fetchSyncPost)("/api/block/getBlockKramdown",{id:e});if(!i.data||!i.data.kramdown)return;const n=i.data.kramdown.match(/^(\s*```)(\w+)?(\s*\n)([\s\S]*?)(\s*```)([\s\S]*)$/);if(!n)return;const s=n[1],l=n[2]||"",a=n[3],c=n[4],h=n[5];let u=n[6],d=c.split("\n");d.length>0&&c.endsWith("\n")&&""===d[d.length-1]&&d.pop();const g=d[0]||"",p=this.parseHighlightMarker(g),m=o.length>0,b=this.getCommentSyntax(l);p?m?d[0]=this.generateMarkerString(o,b):d.shift():m&&(o.forEach(e=>e.lines=e.lines.map(e=>e+1)),d.unshift(this.generateMarkerString(o,b))),m&&this.config.autoEnableLineNumber&&(u?u.includes('linenumber="true"')||(u.includes("}")?u=u.replace("}",' linenumber="true"}'):u+=' {: linenumber="true"}'):u='\n{: linenumber="true"}');const f=`${s}${l}${a}${d.join("\n")}${/^\s*[\r\n]/.test(h)?"":"\n"}${h}${u}`;if(await(0,t.fetchSyncPost)("/api/block/updateBlock",{id:e,dataType:"markdown",data:f}),m&&this.config.autoEnableLineNumber){const o=await(0,t.fetchSyncPost)("/api/attr/getBlockAttrs",{id:e});if(o.data?.linenumber||await(0,t.fetchSyncPost)("/api/attr/setBlockAttrs",{id:e,attrs:{linenumber:"true"}}),r){const e=r.closest("[data-node-id]");if(e){e.setAttribute("linenumber","true");const t=r.querySelector('.hljs div[contenteditable="true"]');t&&t.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!0})),r.querySelector(".hljs")?.removeAttribute("data-render")}}}}getCommentSyntax(e){const t=e.toLowerCase().trim();return["html","xml","svg","markdown","md"].includes(t)?{start:"\x3c!--",end:"--\x3e"}:["css","less","scss","c"].includes(t)?{start:"/*",end:"*/"}:["python","py","ruby","rb","perl","bash","sh","shell","yaml","yml","dockerfile","r","elixir"].includes(t)?{start:"#",end:""}:["lua","sql"].includes(t)?{start:"--",end:""}:["erlang","latex","tex"].includes(t)?{start:"%",end:""}:["clojure","lisp","scheme"].includes(t)?{start:";",end:""}:["vim"].includes(t)?{start:'"',end:""}:{start:"//",end:""}}generateMarkerString(e,t){const o=[];e.forEach(e=>{let t="hl";"red"===e.color?t="hlr":"green"===e.color?t="hlg":"blue"===e.color?t="hlb":"custom1"===e.color?t="hl5":"custom2"===e.color?t="hl6":"custom3"===e.color&&(t="hl7"),o.push(`${t}:${this.formatLineSpec(e.lines)}`)});const r=o.join(";");return`${t.start} ${r} ${t.end}`.trim()}async getHighlightGroupsFromAttributes(e){console.log("LineHighlightPlugin: getHighlightGroupsFromAttributes",e);const o=(await(0,t.fetchSyncPost)("/api/attr/getBlockAttrs",{id:e})).data||{},r=[];return Object.entries(this.colorToAttr).forEach(([e,t])=>{const i=o[t];if(i){const t=this.parseLineSpec(i);t.length&&r.push({lines:t,color:e})}}),r}async saveHighlightGroupsToAttributes(e,o,r){console.log("LineHighlightPlugin: saveHighlightGroupsToAttributes",e,o);const i={},n=o.length>0;if(o.forEach(e=>{e.lines.length&&(i[this.colorToAttr[e.color]]=this.formatLineSpec(e.lines))}),Object.keys(this.colorToAttr).forEach(e=>{const t=this.colorToAttr[e];i[t]||(i[t]="")}),n&&this.config.autoEnableLineNumber&&(i.linenumber="true"),await(0,t.fetchSyncPost)("/api/attr/setBlockAttrs",{id:e,attrs:i}),n&&r&&this.config.autoEnableLineNumber){const e=r.closest("[data-node-id]");if(e){e.setAttribute("linenumber","true");const t=r.querySelector('.hljs div[contenteditable="true"]');t&&t.dispatchEvent(new Event("input",{bubbles:!0,cancelable:!0})),r.querySelector(".hljs")?.removeAttribute("data-render")}}}formatLineSpec(e){if(!e.length)return"";const t=[...e].sort((e,t)=>e-t),o=[];let r=t[0],i=t[0];for(let e=1;e<=t.length;e++)e<t.length&&t[e]===i+1?i=t[e]:(o.push(r===i?`${r}`:i===r+1?`${r},${i}`:`${r}-${i}`),e<t.length&&(r=i=t[e]));return o.join(",")}startCleanupObserver(){this.cleanupObserver=new MutationObserver(e=>{e.forEach(e=>e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE&&e.classList?.contains("code-line-highlighter-overlay-wrapper")){const t=e.parentElement;if(t?.classList?.contains("protyle-linenumber__rows"))return;t&&(t.classList?.contains("code-block")||t.classList?.contains("hljs")||t.closest(".hljs"))&&e.remove()}}))}),this.cleanupObserver.observe(document.body,{childList:!0,subtree:!0})}startResizeObserver(){this.resizeObserver=new ResizeObserver(e=>{e.forEach(e=>{const t=e.target;t.getAttribute("data-hl-active")&&this.updateHighlightDimensions(t)})}),document.querySelectorAll(".code-block").forEach(e=>this.resizeObserver?.observe(e))}updateHighlightDimensions(e){const t=e.querySelector(".protyle-linenumber__rows"),o=t?.querySelector(".code-line-highlighter-overlay-wrapper"),r=e.querySelector('.hljs div[contenteditable="true"]');if(!o||!t||!r)return;const i=t.getBoundingClientRect(),n=r.getBoundingClientRect(),s=parseFloat(window.getComputedStyle(r).paddingLeft)||0,l=n.left-i.left-s,a=i.width+Math.abs(l)+n.width-20;o.style.width="0px",o.querySelectorAll(".code-line-highlighter-overlay").forEach(e=>{e.style.width=`${a}px`})}processAllCodeBlocks(){console.log("LineHighlightPlugin: processAllCodeBlocks"),document.querySelectorAll(".code-block").forEach(e=>this.processCodeBlock(e))}scheduleProcessing(e,t){this.processingTimeouts.has(e)&&clearTimeout(this.processingTimeouts.get(e)),this.processingTimeouts.set(e,window.setTimeout(()=>{this.processCodeBlock(e),this.processingTimeouts.delete(e),this.resizeObserver&&!e.dataset.resizeObserved&&(this.resizeObserver.observe(e),e.dataset.resizeObserved="true")},t))}observeCodeBlocks(){console.log("LineHighlightPlugin: observeCodeBlocks"),this.observer=new MutationObserver(e=>{e.forEach(e=>{if("attributes"===e.type&&"data-render"===e.attributeName){const t=e.target.closest(".code-block");t&&this.scheduleProcessing(t,150)}else"childList"===e.type&&e.addedNodes.forEach(e=>{if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e;if(t.classList?.contains("code-block")&&(this.scheduleProcessing(t,150),this.attachInputListener(t)),t.querySelectorAll?.(".code-block").forEach(e=>{this.scheduleProcessing(e,150),this.attachInputListener(e)}),t.classList?.contains("protyle-linenumber__rows")){const e=t.closest(".code-block");e?.getAttribute("data-hl-active")&&this.scheduleProcessing(e,100)}})})}),this.observer.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["data-render"]})}attachInputListener(e){const t=e.querySelector('.hljs div[contenteditable="true"]');if(!t||this.inputListeners.has(t))return;const o=()=>{e.getAttribute("data-hl-active")&&setTimeout(()=>this.processCodeBlock(e),300)};t.addEventListener("input",o),this.inputListeners.set(t,o)}attachAllInputListeners(){document.querySelectorAll(".code-block").forEach(e=>this.attachInputListener(e))}async processCodeBlock(e){console.log("LineHighlightPlugin: processCodeBlock");const t=e.closest("[data-node-id]"),o=t?.getAttribute("data-node-id");let r=[],i="";if(o&&(r=await this.getHighlightGroupsFromAttributes(o),r.length&&(i=r.map(e=>`${e.color}:${this.formatLineSpec(e.lines)}`).join(";"))),!r.length){const t=(e.querySelector(".hljs")?.textContent||"").split("\n")[0]||"",o=this.parseHighlightMarker(t);o&&(r=o.groups,i=o.rawSpec)}const n=e.getAttribute("data-hl-active"),s=e.querySelector(".protyle-linenumber__rows .code-line-highlighter-overlay-wrapper");r.length>0?n&&n===i&&s||(this.removeHighlights(e),this.enableLineNumbers(e),setTimeout(()=>this.applyHighlight(e,r,i),100)):n&&this.removeHighlights(e)}enableLineNumbers(e){if(!this.config.autoEnableLineNumber)return;if(console.log("LineHighlightPlugin: enableLineNumbers"),e.querySelector(".protyle-linenumber__rows"))return;const t=e.closest("[data-node-id]");t&&(t.setAttribute("linenumber","true"),e.querySelector(".hljs")?.removeAttribute("data-render"))}removeHighlights(e){console.log("LineHighlightPlugin: removeHighlights"),e.querySelectorAll(".code-line-highlighter-overlay-wrapper, .code-line-highlighter-container").forEach(e=>e.remove());const t=this.getCodeBlockId(e);e.closest(".protyle-wysiwyg")?.querySelectorAll(`.code-line-highlighter-overlay-wrapper[data-code-block-id="${t}"]`).forEach(e=>e.remove()),e.removeAttribute("data-hl-active")}getCodeBlockId(e){return e.closest("[data-node-id]")?.getAttribute("data-node-id")||"unknown"}applyHighlight(e,t,o){console.log("LineHighlightPlugin: applyHighlight");const r=e.querySelector(".protyle-linenumber__rows"),i=e.querySelector('.hljs div[contenteditable="true"]');if(!r||!i)return;if(r.querySelector(".code-line-highlighter-overlay-wrapper"))return;const n=r.querySelectorAll("span");if(!n.length)return;e.setAttribute("data-hl-active",o);const s=r.getBoundingClientRect(),l=i.getBoundingClientRect(),a=parseFloat(window.getComputedStyle(i).paddingLeft)||0,c=l.left-s.left-a,h=s.width+Math.abs(c)+l.width-20,u=this.createElement("div",{position:"absolute",left:"-10px",top:"0",width:"0px",height:"100%",pointerEvents:"none",zIndex:"1",overflow:"visible"},{class:"code-line-highlighter-overlay-wrapper","data-code-block-id":this.getCodeBlockId(e),"data-hl-spec":o});t.forEach(e=>{const t=this.colors[e.color];e.lines.forEach(o=>{const r=o-1;if(n[r]){const o=n[r];u.appendChild(this.createElement("div",{position:"absolute",left:"0",top:`${o.offsetTop}px`,width:`${h}px`,height:`${o.offsetHeight}px`,backgroundColor:t.background,boxShadow:`inset 3px 0 0 ${t.border}`,pointerEvents:"none"},{class:"code-line-highlighter-overlay","data-color":e.color}))}})}),r.appendChild(u)}parseHighlightMarker(e){const t=e.trim().match(/^\s*(?:\/\/|#|<!--|\/\*|--|%|;|")\s*(.+?)(?:\s*(?:\*\/|-->))?$/);if(!t)return null;const o=t[1].trim(),r=[];let i,n=!1;const s=/hl([rgby]|1-7|c[1-3])?:([0-9,\-]+)/g;for(;null!==(i=s.exec(o));){n=!0;let e=i[1]||"y";r.push({lines:this.parseLineSpec(i[2]),color:this.getColorFromCode(e)})}return n?{groups:r,rawSpec:o}:null}getColorFromCode(e){return{y:"yellow",1:"yellow","":"yellow",r:"red",2:"red",g:"green",3:"green",b:"blue",4:"blue",5:"custom1",c1:"custom1",6:"custom2",c2:"custom2",7:"custom3",c3:"custom3"}[e.toLowerCase()]||"yellow"}parseLineSpec(e){const t=new Set;return e.split(",").forEach(e=>{const[o,r]=e.trim().split("-").map(e=>parseInt(e));if(!isNaN(o))if(isNaN(r))t.add(o);else for(let e=o;e<=r;e++)t.add(e)}),Array.from(t).sort((e,t)=>e-t)}onunload(){console.log("LineHighlightPlugin: onunload"),this.observer?.disconnect(),this.cleanupObserver?.disconnect(),this.resizeObserver?.disconnect(),this.processingTimeouts.forEach(e=>clearTimeout(e)),document.querySelectorAll(".code-line-highlighter-overlay-wrapper, .code-line-highlighter-container").forEach(e=>e.remove())}}e.default=n})(),module.exports=r.default})();