Giter VIP home page Giter VIP logo

speed-highlight / core Goto Github PK

View Code? Open in Web Editor NEW
257.0 257.0 14.0 2.14 MB

A lightweight syntax highlighter written in JavaScript

Home Page: https://speed-highlight.github.io/core/examples/

License: Creative Commons Zero v1.0 Universal

JavaScript 88.67% CSS 11.33%
deno fast highlighter highlighting highlightjs javascript js language lightweight regex simple small syntax-highlighting ts

core's People

Contributors

aaronmyatt avatar beartocode avatar dependabot[bot] avatar gilbert avatar gutenfries avatar matubu avatar semantic-release-bot avatar speed-highlight-bot avatar techsin avatar vitalybaev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

core's Issues

[BUG] [class*=shj-lang-] color & background defined twice in github-* themes

Information

  • Speed-highlight.js version 1.2.6
  • Browser version n/a

Description

If we look at github-dark.css, for example, we see this at the top:

[class*='shj-lang-'] {
    white-space: pre;
    margin: 10px 0;
    border-radius: 10px;
    padding: 30px 20px;
    background: #fff;
    color: #112;
...

and this further down:

[class*='shj-lang-'] {
    color: #24292f;
    background: #fff;
}

This a bit redundant and also makes it slightly harder to update these styles, which is how I bumped into this.

Expected behavior
Just define the color & background once.

I just wanted to add that this project is awesome! Super lightweight and fast - the best lightweight highlighting library 0 thanks!

[FEATURE] Enhance types/docs to avoid relying on browser dynamic import for language files

Is your feature request related to a problem? Please describe.

I'm using this great small library to syntax highlight yaml. I'm working with Vite. It worked OK for me during pnpm run dev but I found out after deployment, built with pnpm run build, the library was trying to dynamic import the language file. Since the build didn't include the dynamic import anymore (not sure how dev and built versions differ), it was 404'ing on the yaml.js since it wasn't in the bundle.

I found this issue that mentioned a workaround for vite, using a plugin to help with dynamic imports. I wanted to avoid that step.

In short, my workaround solution is like this:

// ๐Ÿ”ฅ 1. import the syntax you need, use * as languageSyntax to import it and later use it
//       note: this is not using any special vite features!
import * as yamlSyntax from "../../node_modules/@speed-highlight/core/dist/languages/yaml";

// ๐Ÿ”ฅ 2. set language and the module syntax; the loadLanguage function has a bit of a misleading type; should also accept this module
loadLanguage("yaml", yamlSyntax as unknown as ShjLanguage);

I think this is intended, and I think it's worth documenting a little more explicitly.

I have a full example below too, for future readers.

Source code example
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import { Box, Button, useTheme } from "@mui/material";
import {
  ShjLanguage,
  highlightText,
  loadLanguage,
} from "@speed-highlight/core";
import jsYaml from "js-yaml";
import { useEffect, useState } from "react";
import darkTheme from "../../node_modules/@speed-highlight/core/dist/themes/github-dark.css?inline";
import lightTheme from "../../node_modules/@speed-highlight/core/dist/themes/github-light.css?inline";

// ๐Ÿ”ฅ 1. import the syntax you need, use * as languageSyntax to import it and later use it
//       note: this is not using any special vite features!
import * as yamlSyntax from "../../node_modules/@speed-highlight/core/dist/languages/yaml";

// ๐Ÿ”ฅ 2. set language and the module syntax; the loadLanguage function has a bit of a misleading type; should also accept this module
loadLanguage("yaml", yamlSyntax as unknown as ShjLanguage);

interface YamlDisplayProps {
  yaml: string;
}

export function YamlDisplay({ yaml }: YamlDisplayProps) {
  const [text, setText] = useState<string | null>(null);
  const [css, setCss] = useState<string | null>(null);
  const theme = useTheme();

  const mode = theme.palette.mode;

  const content = yaml
    ? jsYaml.dump(JSON.parse(JSON.stringify(yaml)))
    : "";

  useEffect(() => {
    // ๐Ÿ”ฅ 3. use highlightText, use the same key as before
    highlightText(content, "yaml", undefined, {
      hideLineNumbers: false,
    }).then((output) => {
      setText(output);
      if (mode === "light") {
        setCss(lightTheme);
      } else {
        setCss(darkTheme);
      }
    });
  }, [content, mode]);

  if (!yaml) {
    return <p>no yaml to display</p>;
  }

  return (
    <>
      {css && (
        <style type="text/css" dangerouslySetInnerHTML={{ __html: css }} />
      )}
      <Box sx={{ position: "relative" }}>
        <Box
          sx={{
            position: "absolute",
            top: 0,
            right: 0,
            p: 2,
            
          }}
        >
          <Button
            startIcon={<ContentCopyIcon />}
            onClick={() => {
              navigator.clipboard.writeText(content);
            }}
          >
            Copy
          </Button>
        </Box>

        {text && (
          <pre>
            <code>
              <Box

                component="div"
                // ๐Ÿ”ฅ 3. set the class name to match the language
                className="shj-lang-yaml"

                // ๐Ÿ”ฅ 4. set the text/html that was produced by the highlighter
                dangerouslySetInnerHTML={{ __html: text }}
              />
            </code>
          </pre>
        )}
      </Box>
    </>
  );
}

Describe the solution you'd like

I think the types could use an update to make it clearer at the typescript level level how to achieve this, and if the docs had an example of this it would also help too.

Describe alternatives you've considered

The alternative would have been to use the vite plugin mentioned in the issue.

Additional context

New languages plan for 1.1.0

  • bash/shell
  • brainfuck
  • css
  • csv
  • git
  • http
  • ini
  • js
  • jsdoc
  • json
  • log file
  • md
  • plain
  • regex
  • sql
  • TOML
  • typescript
  • yaml
  • TODO
  • uri
  • makefile
  • lua
  • perl
  • python
  • diff
  • html

[BUG] Deno: Cannot access 'theme' before initialization

Information

Description

Running the Deno example fails with an error:

error: Uncaught (in promise) ReferenceError: Cannot access 'theme' before initialization
        let res = '', theme = await theme;
                              ^
    at highlightText (file:///Users/tobias/code/speed-highlight--core/src/term.js:10:24)
    at printHighlight (file:///Users/tobias/code/speed-highlight--core/src/term.js:17:67)
    at file:///Users/tobias/code/speed-highlight--core/examples/deno.js:14:1

Example

$ git clone https://github.com/speed-highlight/core.git
$ cd core
$ deno run --allow-read examples/deno.js

Expected behavior

Just print the highlighted code.

Ability to hide line numbers

Sometimes we don't want to display line numbers.

Describe the solution you'd like
It seems that we should add another optional argument to highlightElement. It should be an object with parameters (more settings can be tweaked here in the future).

Describe alternatives you've considered
We don't have some solution with this package.

Additional context
I can create a PR with this feature. I only want to hear your approval.

[FEATURE] - Expanding syntax

Is your feature request related to a problem? Please describe.

I use Leanpub Markdown for authoring my books. It's a small extension on top of regular Markdown. One of the main features it supports are insertions and deletions like this:

// You might see insertions
leanpub-start-insert
const webpack = require("webpack");
leanpub-end-insert

// You might see deletions as well
leanpub-start-delete
const { MiniHtmlWebpackPlugin } = require("mini-html-webpack-plugin");
leanpub-end-delete

// Or combinations of both
leanpub-start-delete
const { MiniHtmlWebpackPlugin } = require("mini-html-webpack-plugin");
leanpub-end-delete
leanpub-start-insert
const webpack = require("webpack");
leanpub-end-insert

// If content has been omitted, then ellipsis is used
...

Note the Leanpub specific syntax that's sitting on top of the rest.

Describe the solution you'd like

It would be great to have a way to overlay an extension on top of a language in order to parse those custom sections. My current solution looks like this: https://github.com/survivejs/site/blob/master/utils/highlight.js .

Describe alternatives you've considered

As mentioned, I've implemented this in illuminate.js and thought to bring up the idea as there's value in having an API for extensions.

[BUG] Unable to import language when bundled by Vite.

Information

  • Speed-highlight.js version: 1.1.11
  • Browser version: n/a

Description

Unable to import language either dynamically or directly when bundled by Vite.

Example

import asm from "@speed-highlight/core/dist/langauges/asm.js";

const lang = await import(`./languages/${lang}.js`);

Expected behavior

Able to import without error.

Actual Behavior

Either, this when directly importing:

Missing "./dist/languages/log" specifier in "@speed-highlight/core" package

Or, this in the console when dynamically importing (which is done by tokenize when lang is of type string):

Loading module from โ€œhttp://localhost:5173/node_modules/.vite/deps/languages/log.jsโ€ was blocked because of a disallowed MIME type (โ€œโ€).

Create template system for string comment ...

Is your feature request related to a problem? Please describe.
Repetition for string match and basic things like that

Describe the solution you'd like
Have a filed expend: 'string-single'/'string'/'string-double'

Describe alternatives you've considered
No

[FEATURE] Sync version?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
Add any other context or screenshots about the feature request here.

[BUG] bash highlighting kinda broken

Information

  • Speed-highlight.js version: 1.2.6

Description
See the example. It's mostly just incomplete handling of the bash syntax.

Example
image

Expected behavior
Proper bash handling.

[FEATURE] Add typescript definitions

Hello, first of all I want to thank you for this awesome library!
My request is pretty simple: add typings definitions so that all typescript users can enjoy this library as well!

Github wiki

Create github pages and create better documentation

[FEATURE] Consider supporting prismjs language syntax rules

Is your feature request related to a problem? Please describe.
While this library is neat and fast, it has highlighting issues. Why re-invent the highlight rules when there's other projects out there that have already solved it.

Describe the solution you'd like
I think it makes sense to at least also support the well-established prismjs language files. It does require speed-highlight to adapt to their format. But given that you'd re-use their format + gain support for all the languages they have it might be a worthwile consideration?

Describe alternatives you've considered
I did use prismjs. Moved to this library because it's still maintained, fast and i like it's themes better :)

[FEATURE] Sync version

Is your feature request related to a problem? Please describe.
Trying to use this with Deno's Markdown. It doesn't work because this library is asynchronous and that library doesn't accept an asynchronous syntax highlighter.

Describe the solution you'd like
Expose highlightTextSync for example?

Describe alternatives you've considered
Not much I can do, this library always returns a promise and the markdown library doesn't know how to handle it.

Reproduction script

import { Marked } from 'https://deno.land/x/[email protected]/mod.ts';
import { highlightText } from 'https://deno.land/x/[email protected]/src/index.js';

Marked.setOptions({
  // prints `[object Promise]`
  highlight: (code, lang) => highlightText(code, lang),
});

I saw the only reason this is asynchronous is because tokenize imports the language if not loaded yet. Maybe I can import the languages in advance and pass them down to tokenizeSync?

[BUG] Online demo seems to be broken

Information

I tested both on Chromium 92 and Safari 15.1.

Description

https://matubu.github.io/speed_highlight_js/examples/ seems to be broken. The page is giving

TypeError: Cannot read property 'sub' of undefined
    at tokenize (index.js:36)
    at highlightText (index.js:89)
    at highlightElement (index.js:108)
    at (index):95

Maybe some recent change broke it?

Example

See above.

Expected behavior

I would expect the demo to work.

General feedback

Just came across this project and it looks really, really awesome!

I wanted to provide some constructive feedback and ask some questions that might help.

Suggestions

  • demo url is missing from the github repo settings (I usually skim new projects and this is one of the most important signals I look for)
  • demo should use more common defaults; asm => typescript or javascript; atom-dark => default or dark; disable line numbering by default
  • the API seems like it may be a drop-in replacement for prismjs which is awesome, but I don't see this mentioned anywhere. maybe add a "migrating from prism" section or a comparisons section w/ notes about other options?
  • the demo styling could use some love; on wide screens maybe set the content max-width to be centered at 1000px or something
  • would love to see a section on how to use w/ react, vue, etc. happy to contribute a minimal react demo or a react npm package wrapper it it helps

Questions

  • are there other planned packages outside of speed-highlight/core?
    const { setTheme, printHighlight } = require('@speed-highlight/core/dist/node/term.js');
  • what is term? any chance you could make this import a little more clean?

Note: I don't usually provide this level of feedback, but I really like what you've built (I've been struggling w/ prismjs recently), and I see it having the potential to become widely used.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.