Giter Site home page Giter Site logo

ngx-prism / core Goto Github PK

View Code? Open in Web Editor NEW
12.0 2.0 6.0 1.59 MB

Simple Angular 2+ Prism highlighter module.

Home Page: https://www.npmjs.com/package/@ngx-prism/core

License: MIT License

JavaScript 35.29% TypeScript 62.27% HTML 2.44%
angular ng2 ngx prismjs angular4 highlight syntax prism

core's Introduction

@ngx-prism/core

npm version GitHub version Build Status Known Vulnerabilities

GitHub issues GitHub forks GitHub stars GitHub license

Simple Angular 4+ Prism highlighter module. Click to get package with rxjs on board.
Next update will be available only on @angular-package with name @angular-package/prism/core.


Pros(+)

  • AOT (Ahead Of Time Compilation) package: faster rendering, fewer asynchronous requests, smaller Angular framework download size, detect template errors earlier, better security.
  • MIT License: it can be used commercially.
  • Component changeDetectionStrategy is set to OnPush, It gives better overall performance.
  • [New] Change detector status is initially Detached and detectChanges() is used in every component property declared in its own property __properties. This is because of using @angular-package/change-detection.
  • Setters instead of ngOnChanges() method to detect changes.
  • Dynamically changes highlight string with code input property, and dynamically changes properties for change detection by setting them true or false with input cd.
  • It uses prismjs highlightElement(element, async, callback) to higlight, so async and hooks internal prism features can be used.
  • Interpolates string to highlight with interpolation object.
  • Performs highlight depending on whether property change detection is active or is not (by checking cd property).
  • Live @angular/cli usage demonstration and inside repository.
  • No known vulnerabilities found by snyk.io.

Cons(-)

  • Hooks are defined globally.
  • You cannot use both ng-content and property code the same time.
  • Need to provide new instance of objects to get them changed.

Important!

  • By default all properties are sensitive to detection.
  • Instead of using ngOnChanges angular cycle hook, now, it base only on setters and getters.
  • It is designed to use ng-content and property code separately. You should NOT use both the same time.
  • In @angular/cli add --aot to ng serve in scripts to have script "start": "ng serve --aot".
  • Selector prism-highlight is changed to ngx-prism.

Demonstration

Live demonstration

Clone this repository:

git clone https://github.com/ngx-prism/core.git

Go to demo folder and with your command line write the following:

npm i && npm start

Open http://localhost:4200/ in your browser.

Example demonstration usage of both core and rxjs is in https://github.com/ngx-prism/demo repository. To install it, do the following:

git clone https://github.com/ngx-prism/demo.git
cd demo
npm i && npm start

Open http://localhost:4200/ in your browser.

Installation

First, install @ngx-prism/core package with command:

npm i --save @ngx-prism/core

Add peer dependencies:

Usage

  1. Now, import PrismModule into your module:
// example.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { PrismModule } from '@ngx-prism/core'; // <----- Here
import { ExampleComponent } from './example.component'; // your component

@NgModule({
  declarations: [ ExampleComponent ],
  imports: [
    CommonModule,
    PrismModule // <----- Here
  ],
  exports: [ ExampleComponent ]
})
export class ExampleModule { }
  1. Use <ngx-prism></ngx-prism> tag with content inside and specify its content with property [language] to highlight it:
// example.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'example-component',
  template: `
    <ngx-prism [language]="language">
      {{content}}
    </ngx-prism>
  `
})
export class ExampleComponent {
  language = 'html';
  content = '<p>test</p>';
  constructor() { }
}

or use <ngx-prism></ngx-prism> tag with [code] and [interpolation] attribute like in ExampleComponent below:

// example.component.ts
import { Component } from '@angular/core';

@Component({
  selector: 'example-component',
  template: `
    <ngx-prism
      [language] = "language"
      [hooks] = "hooks"
      [code] = "content"
      [interpolation] = "interpolate"
    ></ngx-prism>`
})
export class ExampleComponent {
  content = '<p>test {{language}}</p>';
  hooks = {
    'before-sanity-check': (env) => { console.log(`before-sanity-check`, env); },
    'before-highlight': (env) => { console.log(`before-highlight`, env); },
    'after-highlight': (env) => { console.log(`after-highlight`, env); },
    'complete': (env) => { console.log(`complete`, env); },
    'before-insert': (env) => { console.log(`before-insert`, env); }
  };
  interpolate = {
    language: 'language interpolated'
  };
  language = 'html';
  constructor() { }
}
  • It is possible to import themes files in @angular/cli:
@import '~prismjs/themes/prism-coy.css';
@import '~prismjs/themes/prism-dark.css';
@import '~prismjs/themes/prism-funky.css';
@import '~prismjs/themes/prism-okaidia.css';
@import '~prismjs/themes/prism-solarizedlight.css';
@import '~prismjs/themes/prism-tomorrow.css';
@import '~prismjs/themes/prism-twilight.css';
@import '~prismjs/themes/prism.css';

Inputs

name Type Description
async boolean "Whether to use Web Workers to improve performance and avoid blocking the UI when highlighting very large chunks of code." - prismjs
callback (element: Element) => void | undefined = undefined "An optional callback to be invoked after the highlighting is done. Mostly useful when async is true, since in that case, the highlighting is done asynchronously." - prismjs
cd
(ChangeDetection)
PropertiesInterface
{[index:string]:boolean}
Properties provided with index as name and value true will be sensitive for changes.
code string "A string with the code to be highlighted." - prismjs
hooks Object Callback with specific execute time and name: before-sanity-check, before-highlight, after-highlight, complete, before-insert.
interpolation Object | undefined Data property values to inject.
language string "Valid language identifier, for example 'javascript', 'css'." - prismjs

Lifecycle Hooks

Angular Lifecycle Hooks

PrismComponent

ngAfterViewInit():

  • Sets property ready to true which by default is false.
  • Property ready is used in highlightElement(result: { code: string, language: string }): void method to performs when ready is set to true - prismService.highlight() method to highlight code.

ngAfterContentInit():

  • Update __properties for change detection with inputted property cd.

Change detection

Angular source

Component changeDetectionStrategy is set to OnPush means that the change detector's mode will be initially set to CheckOnce, and status CheckOnce means that after calling detectChanges the status of the change detector will become Checked. Status Checked means that the change detector should be skipped until its mode changes to CheckOnce.

Change detector status is now manually set to Detached by default and it means that its sub tree is not a part of the main tree and should be skipped. However it will call detectChanges() in Setters with indicated properties.

Scripts

Clone repository:

git clone https://github.com/ngx-prism/core.git

Go to just created folder:

cd core

To build a clean package, means before that script removes node_modules, dist folder and install dependencies:

npm run clean:start

To build a package:

npm start

To run karma tests:

npm test

GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:
MAJOR version when you make incompatible API changes,
MINOR version when you add functionality in a backwards-compatible manner, and
PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © ngx-prism

Donate

Click to donate

core's People

Contributors

echonax avatar

Stargazers

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

Watchers

 avatar  avatar

core's Issues

Can't resolve 'lodash-es' in 'C:\..'

I just started tutorial but had some errors..

ERROR in ./node_modules/@angular-package/change-detection/decorator/src/setter-getter.class.js
Module not found: Error: Can't resolve 'lodash-es' in 'C:\Users\USER\workspace\study\portfolio\node_modules@angular-package\change-detection\decorator\src'
ERROR in ./node_modules/@angular-package/change-detection/decorator/src/change-detector.class.js
Module not found: Error: Can't resolve 'lodash-es' in 'C:\Users\USER\workspace\study\portfolio\node_modules@angular-package\change-detection\decorator\src'
ERROR in ./node_modules/@ngx-prism/core/dist/prism.class.js
Module not found: Error: Can't resolve 'lodash-es' in 'C:\Users\USER\workspace\study\portfolio\node_modules@ngx-prism\core\dist'
ERROR in ./node_modules/@ngx-prism/core/dist/prism.service.js
Module not found: Error: Can't resolve 'lodash-es' in 'C:\Users\USER\workspace\study\portfolio\node_modules@ngx-prism\core\dist'

Doesn't compile with Ivy

Seems a common thing: AzureAD/microsoft-authentication-library-for-js#855

I get this same error:

ERROR in Attempted to get members of a non-class: "export class PrismService {
constructor(sanitizer) {
this.sanitizer = sanitizer;
}
highlight(el, options) {
if (el instanceof ElementRef) {
if (options.code) {
el.nativeElement.innerHTML = this.sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(options.code));
}
if (options.interpolation) {
el.nativeElement.innerHTML = this.interpolate(el.nativeElement.innerHTML, options.interpolation);
}
Prism.highlightElement(el.nativeElement, options.async, options.callback);
}
}
hooks() {
return Prism.hooks;
}
escapeHtml(unsafe) {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
interpolate(string, interpolation) {
if (interpolation && typeof interpolation === 'object') {
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
return _.template(string)(interpolation);
}
return string;
}
}"
ERROR in ./src/styles.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--15-3!./src/styles.scss)
Module Error (from ./node_modules/postcss-loader/src/index.js):
(Emitted value instead of an instance of Error) CssSyntaxError: /home/peters1/p4/nwfjs/theme/dist/icons/icons.scss:93:4: Can't resolve '@netapp/nwfjs_theme/icons/png/icon-info-warning.png' in '/home/peters1/p4/nwfjs_scaffolding/src'

91 | display: inline-flex;
92 | background-repeat: no-repeat;

93 | background-image: url(9m"~@netapp/nwfjs_theme/icons/png/icon-info-warning.png");
| ^
94 | }
95 |

** Angular Live Development Server is listening on localhost:9000, open your browser on https://localhost:9000/ **
ℹ 「wdm」: Failed to compile.
ℹ 「wdm」: Compiling...
0% compiling
Compiling @ngx-prism/core : module as esm5

Date: 2019-11-27T01:16:51.059Z - Hash: 79a096000a5eeb015170
4 unchanged chunks
chunk {styles} styles.js, styles.js.map (styles) 3.19 MB [initial] [rendered]
Time: 12736ms

ERROR in Attempted to get members of a non-class: "export class PrismService {
constructor(sanitizer) {
this.sanitizer = sanitizer;
}
highlight(el, options) {
if (el instanceof ElementRef) {
if (options.code) {
el.nativeElement.innerHTML = this.sanitizer.sanitize(SecurityContext.HTML, this.escapeHtml(options.code));
}
if (options.interpolation) {
el.nativeElement.innerHTML = this.interpolate(el.nativeElement.innerHTML, options.interpolation);
}
Prism.highlightElement(el.nativeElement, options.async, options.callback);
}
}
hooks() {
return Prism.hooks;
}
escapeHtml(unsafe) {
return unsafe
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
interpolate(string, interpolation) {
if (interpolation && typeof interpolation === 'object') {
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
return _.template(string)(interpolation);
}
return string;
}
}"

JSON language doesn't highlight syntax

json object and bash command are not highlighted properly

<ngx-prism [language]="'json'" >
       {{content}}
</ngx-prism>

<ngx-prism [language]="'bash'" >
 ng add @angular/fire
</ngx-prism>

--------- Component

public content = `"deploy" : {
                  "builder" : "@angular/fire:deploy",
                  "options" : {} 
        }`;

image

But checking on prismjs.com/ test drive show it correct
image

different I noticed is test drive has "language-markup" in "pre" tag and "language-json" in "code" tag but with ngx-prism/core these bot tags are set as "language-json".

Am I missing anything?

Thanks

Angular 9: Compile error

WARNING in Invalid constructor parameter decorator in /Users/apple/projects/angular-material/node_modules/@ngx-prism/core/dist/prism.service.js:
() => [
{ type: DomSanitizer, },
]

ERROR in getInternalNameOfClass() called on a non-ES5 class: expected PrismService to have an inner class declaration

package.json

    "@angular/animations": "^9.0.1",
    "@angular/cdk": "^9.0.0",
    "@angular/common": "^9.0.1",
    "@angular/compiler": "^9.0.1",
    "@angular/core": "^9.0.1",
    "@angular/forms": "^9.0.1",
    "@angular/http": "^7.2.16",
    "@angular/material": "^9.0.0",
    "@angular/platform-browser": "^9.0.1",
    "@angular/platform-browser-dynamic": "^9.0.1",
    "@angular/router": "^9.0.1",
    "@ngx-prism/core": "^2.0.1",
    "@types/prismjs": "^1.9.0",
    "prismjs": "^1.9.0",
    "rxjs": "~6.5.4",
    "zone.js": "~0.10.2"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.900.2",
    "@angular/cli": "~9.0.2",
    "@angular/compiler-cli": "^9.0.1",
    "@angular/language-service": "^9.0.1",
    "@types/jasmine": "~3.5.4",
    "@types/jasminewd2": "~2.0.8",
    "@types/node": "~13.7.1",
    "codelyzer": "~5.2.1",
    "jasmine-core": "~3.5.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~4.4.1",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage-istanbul-reporter": "~2.1.1",
    "karma-jasmine": "~3.1.1",
    "karma-jasmine-html-reporter": "^1.5.2",
    "protractor": "~5.4.3",
    "ts-node": "~8.6.2",
    "tslint": "~6.0.0",
    "typescript": "~3.7.5"
  }```

Does not work in IE

Hi,
Library does not seem to be working in Edge. I am getting an syntax error , so probably I need a polyfill but not sure which one is needed.
Angular-Version : 5.2.10
Angular-cli: 1.7.3

@angular-package/prism: ^2.0.2
"@types/prismjs": "^1.9.0",
"prismjs": "^1.15.0",

Bundle code where it is throwing error , I am not sure how much it will help though

"use strict";
eval("/* harmony import / var WEBPACK_IMPORTED_MODULE_0__angular_common = webpack_require("./node_modules/@angular/common/esm5/common.js");\n/ harmony import / var WEBPACK_IMPORTED_MODULE_1__angular_core = webpack_require("./node_modules/@angular/core/esm5/core.js");\n/ harmony import / var WEBPACK_IMPORTED_MODULE_2__prism_component = webpack_require("./node_modules/@angular-package/prism/core/prism.component.js");\n\n\n\nconst COMMON_DECLARATIONS_EXPORTS = [WEBPACK_IMPORTED_MODULE_2__prism_component["a" / PrismComponent /]];\nclass ApPrismModule {\n}\n/ harmony export (immutable) */ webpack_exports["a"] = ApPrismModule;\n\nApPrismModule.decorators = [\n { type: WEBPACK_IMPORTED_MODULE_1__angular_core["NgModule"], args: [{\n declarations: COMMON_DECLARATIONS_EXPORTS,\n exports: COMMON_DECLARATIONS_EXPORTS,\n imports: [WEBPACK_IMPORTED_MODULE_0__angular_common["CommonModule"]]\n },] },\n];\nApPrismModule.ctorParameters = () => [];\n//# sourceMappingURL=prism.module.js.map//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4vbm9kZV9tb2R1bGVzL0Bhbmd1bGFyLXBhY2thZ2UvcHJpc20vY29yZS9wcmlzbS5tb2R1bGUuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7O0FBQXVCO0FBQ0o7QUFDTTtBQUN6QjtBQUNBO0FBQ0E7QUFBQTtBQUFBO0FBQ0E7QUFDQSxLQUFLO0FBQ0w7QUFDQTtBQUNBO0FBQ0EsYUFBYSxJQUFJO0FBQ2pCO0FBQ0E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tL2NvcmUvcHJpc20ubW9kdWxlLmpzXG4vLyBtb2R1bGUgY2h1bmtzID0gdmVuZG9yIl0sInNvdXJjZVJvb3QiOiJ3ZWJwYWNrOi8vLyJ9\n//# sourceURL=webpack-internal:///./node_modules/@angular-package/prism/core/prism.module.js\n");

ng5 compilation issues

Am getting the following while trying to ng-serve with angular 5.

ERROR in ./node_modules/@ngx-prism/core/dist/prism.component.ts
Module build failed: Error: [path...]/node_modules/@ngx-prism/core/dist/prism.component.ts is not part of the compilation output. Please check the other error messages for details.
    at AngularCompilerPlugin.getCompiledFile ([path].../node_modules/@ngtools/webpack/src/angular_compiler_plugin.js:629:23)
    at plugin.done.then ([path..]/node_modules/@ngtools/webpack/src/loader.js:467:39)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 @ ./node_modules/@ngx-prism/core/dist/index.js 2:0-51
 @ ./src/bits/app.module.ts
 @ ./src/bits/main.ts
 @ multi webpack-dev-server/client?http://0.0.0.0:0 ./src/bits/main.ts

I believe this to be related to angular/angular-cli#8284 namely

@rolaveric's case is slightly different. You have TS files in your node_modules. This really goes against how libraries should be packaged: libraries should never ship their source .ts files.

Any chance of getting a transpiled version of the lib we can use directly?

[awesome lib btw!!!]

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.