gobengo / distbin

distributed social pastebin using Activitypub
https://distbin.com
Apache License 2.0
78 stars 8 forks source link

Add lines number for source code #28

Open yalh76 opened 5 years ago

yalh76 commented 5 years ago

distbin-read

gobengo commented 5 years ago

A decent enough solution might just be to write a fresh function that takes the result of highlighting the code (an input HTML string that is a <code> or its innerHTML, parses/rewrites it, then returns an HTML string that includes line numbers. Use it here. https://github.com/gobengo/distbin/blob/master/src/distbin-html/an-activity.ts#L45

starting point:

const highlightedHtmlToLines = (html: string): Array<string> => html.split('\n'); // will probably need a more html-aware implementation
type HtmlString = string
type HtmlRewriter = (in: HtmlString ) => HtmlString ;
const addLineNumbers: HtmlRewriter = (highlightedCode: HtmlString): HtmlString => {
  const lines = highlightedHtmlToLines(highlightedCode)
  // two-column table with cells: lineNumber, actualLineHtml
  return `
  <table>
  ${
    lines
    .map((lineStr, lineIndex) => `
      <tr>
        <td class="lineNumber">${lineIndex}</td>
        <td class="lineOfCode>${lineStr}</td>
      </tr>`
    .join('\n')
  }
  </table>
  `
}