├── .babelrc
├── .eslintrc
├── .github
└── workflows
│ └── Release.yml
├── .gitignore
├── .npmrc
├── .travis.yml
├── CODE_OF_CONDUCT.md
├── LICENSE
├── README.md
├── jest.config.json
├── package.json
├── rollup.config.mjs
├── src
├── document.ts
├── element.ts
├── index.d.ts
├── index.ts
├── test
│ ├── __mock__.ts
│ ├── document.spec.ts
│ ├── element.spec.ts
│ ├── index.spec.ts
│ └── utils.spec.ts
└── utils.ts
├── tsconfig.json
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | ["@babel/typescript", { "allowNamespaces": true }],
4 | [
5 | "@babel/preset-env",
6 | {
7 | "targets": {
8 | "node": "current"
9 | }
10 | }
11 | ]
12 | ]
13 | }
14 |
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "parser": "@typescript-eslint/parser",
3 | "parserOptions": {
4 | "ecmaVersion": 2020,
5 | "sourceType": "module"
6 | },
7 | "extends": ["plugin:@typescript-eslint/recommended"],
8 | "rules": {
9 | "@typescript-eslint/explicit-module-boundary-types": "off",
10 | "@typescript-eslint/ban-ts-comment": "off"
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/.github/workflows/Release.yml:
--------------------------------------------------------------------------------
1 | name: Create Release
2 | on:
3 | workflow_dispatch:
4 | inputs:
5 | version:
6 | required: true
7 | type: choice
8 | description: Version type
9 | options:
10 | - patch
11 | - minor
12 | - major
13 | jobs:
14 | release:
15 | if: github.ref == 'refs/heads/master'
16 | runs-on: ubuntu-latest
17 | steps:
18 | - name: Checkout code
19 | uses: actions/checkout@v2
20 | - name: Setup Node.js
21 | uses: actions/setup-node@v2
22 | with:
23 | node-version: '20.x'
24 | registry-url: 'https://registry.npmjs.org'
25 | - name: Install, test and build
26 | run: yarn && yarn build
27 | - name: Update Package.json version and tag
28 | run: |
29 | git config user.name "Hargne"
30 | git config user.email "johan.hargne@gmail.com"
31 | versionType="${{ github.event.inputs.version }}"
32 | new_version=$(npm version "$versionType" --no-git-tag-version)
33 | git add .
34 | git commit -m "Released $new_version"
35 | git tag "$new_version"
36 | git push origin --tags
37 | - name: Publish to NPM
38 | run: npm publish
39 | env:
40 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
41 |
42 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 |
2 | node_modules
3 | lib
4 | coverage/
5 | test-report/
6 | dist/
7 | index.html
8 | npm-debug.log
--------------------------------------------------------------------------------
/.npmrc:
--------------------------------------------------------------------------------
1 | scripts-prepend-node-path=true
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - node
4 | - lts/*
5 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
6 |
7 | ## Our Standards
8 |
9 | Examples of behavior that contributes to creating a positive environment include:
10 |
11 | * Using welcoming and inclusive language
12 | * Being respectful of differing viewpoints and experiences
13 | * Gracefully accepting constructive criticism
14 | * Focusing on what is best for the community
15 | * Showing empathy towards other community members
16 |
17 | Examples of unacceptable behavior by participants include:
18 |
19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances
20 | * Trolling, insulting/derogatory comments, and personal or political attacks
21 | * Public or private harassment
22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission
23 | * Other conduct which could reasonably be considered inappropriate in a professional setting
24 |
25 | ## Our Responsibilities
26 |
27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
28 |
29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
30 |
31 | ## Scope
32 |
33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
34 |
35 | ## Enforcement
36 |
37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at johan.hargne@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
38 |
39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
40 |
41 | ## Attribution
42 |
43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
44 |
45 | [homepage]: http://contributor-covenant.org
46 | [version]: http://contributor-covenant.org/version/1/4/
47 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 Johan Hargne
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
⚙️ html-creator
3 |
4 |
5 | Generate HTML with NodeJS
6 |
7 | Documentation »
8 |
9 |
10 |
11 | ## Installation
12 |
13 | ```shell
14 | $ npm i html-creator
15 | ```
16 |
17 | ## Usage
18 |
19 | ```Javascript
20 | const htmlCreator = require("html-creator");
21 |
22 | const html = new htmlCreator([
23 | {
24 | type: "head",
25 | content: [
26 | {
27 | type: "title",
28 | content: "Generated HTML",
29 | },
30 | {
31 | type: "style",
32 | content: `
33 | #cool-text {
34 | color: red;
35 | }
36 | `,
37 | },
38 | ],
39 | },
40 | {
41 | type: "body",
42 | content: [
43 | {
44 | type: "div",
45 | content: [
46 | {
47 | type: "div",
48 | content: "This is a cool text 😎",
49 | attributes: { id: "cool-text" },
50 | },
51 | {
52 | type: "a",
53 | content: "Click here",
54 | attributes: { href: "/path-to-infinity", target: "_blank" },
55 | },
56 | ],
57 | },
58 | ],
59 | },
60 | ]);
61 | const result = html.renderHTML();
62 | ```
63 |
64 | The above code will result with the following HTML output:
65 |
66 | ```HTML
67 |
68 |
69 |
70 | Generated HTML
71 |
76 |
77 |
78 |
82 |
83 |
84 | ```
85 |
86 | Visit the **[wiki](https://github.com/Hargne/html-creator/wiki)** for more examples of usage, method reference and further reading.
87 |
88 | # Wanna Contribute?
89 |
90 | Do you believe that something is missing from this plugin or perhaps is not working as intended? Awesome-pants! Help is always appreciated.
91 | Just be sure to read through the [Contributing Handbook](https://github.com/Hargne/html-creator/wiki/Contributing-Handbook) (and remember to have a jolly good time).
92 |
--------------------------------------------------------------------------------
/jest.config.json:
--------------------------------------------------------------------------------
1 | {
2 | "collectCoverage": true,
3 | "collectCoverageFrom": [
4 | "src/**/*.{js,jsx,ts,tsx}",
5 | "!src/**/*.d.ts",
6 | "!**/lib/*.{js,jsx,ts,tsx}",
7 | "!**/test/*.{js,jsx,ts,tsx}",
8 | "!**/node_modules/**",
9 | "!**/coverage/**",
10 | "!**/vendor/**"
11 | ],
12 | "coverageDirectory": "./coverage",
13 | "coverageReporters": ["json", "html", "text", "text-summary"],
14 | "coverageThreshold": {
15 | "global": {
16 | "branches": 50,
17 | "functions": 50,
18 | "lines": 50,
19 | "statements": 50
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "html-creator",
3 | "version": "0.7.4",
4 | "description": "Generate HTML with node.js",
5 | "main": "dist/index.js",
6 | "unpkg": "dist/index.js",
7 | "scripts": {
8 | "jest": "jest --no-cache --config=jest.config.json",
9 | "jest:watch": "jest --watch --no-cache --config=jest.config.json",
10 | "lint": "eslint --ext ts,tsx src",
11 | "test": "npm run lint && npm run bundle && npm run jest",
12 | "bundle": "rollup -c",
13 | "build": "npm run test && npm run bundle"
14 | },
15 | "files": [
16 | "dist"
17 | ],
18 | "repository": {
19 | "type": "git",
20 | "url": "git+https://github.com/Hargne/html-creator.git"
21 | },
22 | "keywords": [
23 | "html",
24 | "build",
25 | "generate",
26 | "create",
27 | "html-creator",
28 | "node",
29 | "node.js"
30 | ],
31 | "author": "Johan Hargne",
32 | "license": "MIT",
33 | "bugs": {
34 | "url": "https://github.com/Hargne/html-creator/issues"
35 | },
36 | "homepage": "https://github.com/Hargne/html-creator#readme",
37 | "devDependencies": {
38 | "@babel/core": "^7.9.0",
39 | "@babel/preset-env": "^7.8.7",
40 | "@babel/preset-typescript": "^7.8.3",
41 | "@rollup/plugin-babel": "^6.0.3",
42 | "@rollup/plugin-commonjs": "^24.1.0",
43 | "@rollup/plugin-node-resolve": "^15.0.2",
44 | "@types/jest": "^29.5.5",
45 | "@typescript-eslint/eslint-plugin": "^5.59.2",
46 | "@typescript-eslint/parser": "^5.59.2",
47 | "babel-jest": "^29.5.0",
48 | "eslint": "^8.39.0",
49 | "eslint-config-prettier": "^8.3.0",
50 | "eslint-plugin-prettier": "^4.2.1",
51 | "jest": "^29.5.0",
52 | "rollup": "^3.21.4",
53 | "rollup-plugin-terser": "^7.0.2",
54 | "ts-jest": "^29.1.0",
55 | "typescript": "^5.0.4"
56 | },
57 | "dependencies": {
58 | "@types/node": "^18.16.3",
59 | "mkdirp": "^3.0.1",
60 | "prettier": "^2.4.1"
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/rollup.config.mjs:
--------------------------------------------------------------------------------
1 | import babel from "@rollup/plugin-babel";
2 | import resolve from "@rollup/plugin-node-resolve";
3 | import { terser } from "rollup-plugin-terser";
4 |
5 | const externalLibraries = ["fs", "path", "mkdirp", "prettier"];
6 | const extensions = [".ts", ".js"];
7 |
8 | const config = {
9 | input: "src/index.ts",
10 | output: [
11 | {
12 | dir: "dist",
13 | format: "cjs",
14 | exports: "default",
15 | },
16 | ],
17 | external: externalLibraries,
18 | plugins: [
19 | resolve({
20 | jsnext: true,
21 | extensions,
22 | }),
23 | babel({
24 | extensions,
25 | babelHelpers: "bundled",
26 | }),
27 | terser(),
28 | ],
29 | };
30 |
31 | export default config;
32 |
--------------------------------------------------------------------------------
/src/document.ts:
--------------------------------------------------------------------------------
1 | import Prettier from "prettier";
2 | import { generateElement } from "./element";
3 | import { HTMLCreatorConfig, HTMLCreatorElement } from "./index.d";
4 | import { pushOrConcat, searchForElement } from "./utils";
5 |
6 | class HTMLCreatorDocument {
7 | content: HTMLCreatorElement[];
8 |
9 | constructor(content?: HTMLCreatorElement[]) {
10 | this.content = content && Array.isArray(content) ? content : [];
11 | }
12 |
13 | // Parses the content and returns the elements in HTML
14 | renderContent() {
15 | let output = "";
16 | if (this.content) {
17 | this.content.forEach((element) => {
18 | output += `${generateElement(element)}`;
19 | });
20 | }
21 | return output;
22 | }
23 |
24 | // Returns the content in HTML as a string
25 | getHTML(options?: HTMLCreatorConfig) {
26 | const html = `${generateElement({
27 | type: "html",
28 | content: this.renderContent(),
29 | attributes: options?.htmlTagAttributes,
30 | })}`;
31 | return options?.disablePrettier
32 | ? html.replace(/(\r\n|\n|\r)/gm, "")
33 | : Prettier.format(html, { parser: "html" });
34 | }
35 |
36 | setTitle(newTitle: string) {
37 | // Begin by searching for an existing title tag
38 | const titleTag = this.findElementByType("title")[0];
39 | if (titleTag) {
40 | titleTag.content = newTitle;
41 | return newTitle;
42 | }
43 | // Next search for an existing head tag
44 | const headTag = this.findElementByType("head")[0];
45 | if (headTag) {
46 | if (headTag.content && headTag.content.constructor === Array) {
47 | headTag.content.push({
48 | type: "title",
49 | content: newTitle,
50 | });
51 | } else {
52 | headTag.content = [
53 | {
54 | type: "title",
55 | content: newTitle,
56 | },
57 | ];
58 | }
59 | return newTitle;
60 | }
61 | // If we passed to this point, we simply add a new head tag and a title tag
62 | this.content.push({
63 | type: "head",
64 | content: [
65 | {
66 | type: "title",
67 | content: newTitle,
68 | },
69 | ],
70 | });
71 | return this;
72 | }
73 |
74 | addElement(element: HTMLCreatorElement | HTMLCreatorElement[]) {
75 | this.content = pushOrConcat(this.content, element);
76 | return this;
77 | }
78 |
79 | addElementToTarget(
80 | element: HTMLCreatorElement,
81 | search: { id?: string; class?: string; type?: string }
82 | ) {
83 | if (!search) {
84 | return this;
85 | }
86 |
87 | let targetElementList: HTMLCreatorElement[] = [];
88 | if (search.id) {
89 | targetElementList = this.findElementById(search.id);
90 | } else if (search.class) {
91 | targetElementList = this.findElementByClassName(search.class);
92 | } else if (search.type) {
93 | targetElementList = this.findElementByType(search.type);
94 | }
95 |
96 | if (targetElementList.length > 0) {
97 | targetElementList.forEach((targetElement) => {
98 | if (!targetElement.content) {
99 | targetElement.content = [element];
100 | return;
101 | }
102 |
103 | if (Array.isArray(targetElement.content)) {
104 | targetElement.content.push(element);
105 | return;
106 | }
107 |
108 | if (
109 | typeof targetElement.content === "string" ||
110 | targetElement.constructor === String
111 | ) {
112 | targetElement.content = [
113 | {
114 | content: targetElement.content,
115 | },
116 | element,
117 | ];
118 | }
119 | });
120 | }
121 |
122 | return this;
123 | }
124 |
125 | addElementToClass(
126 | className: string,
127 | element: HTMLCreatorElement | HTMLCreatorElement[]
128 | ) {
129 | if (Array.isArray(element)) {
130 | for (const elementItem of element) {
131 | this.addElementToTarget(elementItem, { class: className });
132 | }
133 | return this;
134 | }
135 | return this.addElementToTarget(element, { class: className });
136 | }
137 |
138 | addElementToId(
139 | id: string,
140 | element: HTMLCreatorElement | HTMLCreatorElement[]
141 | ) {
142 | if (Array.isArray(element)) {
143 | for (const elementItem of element) {
144 | this.addElementToTarget(elementItem, { id });
145 | }
146 | return this;
147 | }
148 | return this.addElementToTarget(element, { id });
149 | }
150 |
151 | addElementToType(
152 | type: HTMLCreatorElement["type"],
153 | element: HTMLCreatorElement | HTMLCreatorElement[]
154 | ) {
155 | if (Array.isArray(element)) {
156 | for (const elementItem of element) {
157 | this.addElementToTarget(elementItem, { type });
158 | }
159 | return this;
160 | }
161 | return this.addElementToTarget(element, { type });
162 | }
163 |
164 | findElementByType(needle: HTMLCreatorElement["type"]) {
165 | return searchForElement({ stack: this.content, type: needle });
166 | }
167 |
168 | findElementById(needle: string) {
169 | return searchForElement({ stack: this.content, id: needle });
170 | }
171 |
172 | findElementByClassName(needle: string) {
173 | return searchForElement({ stack: this.content, className: needle });
174 | }
175 |
176 | withBoilerplate() {
177 | this.content = [
178 | {
179 | type: "head",
180 | content: [
181 | { type: "meta", attributes: { charset: "utf-8" } },
182 | {
183 | type: "meta",
184 | attributes: {
185 | name: "viewport",
186 | content: "width=device-width, initial-scale=1, shrink-to-fit=no",
187 | },
188 | },
189 | ],
190 | },
191 | {
192 | type: "body",
193 | content: this.content,
194 | },
195 | ];
196 | return this;
197 | }
198 | }
199 |
200 | export default HTMLCreatorDocument;
201 |
--------------------------------------------------------------------------------
/src/element.ts:
--------------------------------------------------------------------------------
1 | import { HTMLCreatorElement } from "./index.d";
2 |
3 | const VoidElements = [
4 | "area",
5 | "base",
6 | "br",
7 | "col",
8 | "command",
9 | "embed",
10 | "hr",
11 | "img",
12 | "input",
13 | "keygen",
14 | "link",
15 | "meta",
16 | "param",
17 | "source",
18 | "track",
19 | "wbr",
20 | ];
21 |
22 | export const applyElementAttributes = (
23 | attributes: HTMLCreatorElement["attributes"]
24 | ) => {
25 | if (attributes) {
26 | return Object.keys(attributes)
27 | .filter(
28 | (key) => attributes[key] !== undefined && attributes[key] !== null
29 | )
30 | .map(
31 | (key) =>
32 | ` ${key.replace(/([A-Z])/g, (g) => `-${g[0].toLowerCase()}`)}="${
33 | attributes[key]
34 | }"`
35 | )
36 | .join("");
37 | }
38 | return "";
39 | };
40 |
41 | export const parseElementContent = (
42 | content?: HTMLCreatorElement["content"]
43 | ) => {
44 | if (content && content.constructor === Array) {
45 | return content.map((element) => generateElement(element)).join("");
46 | }
47 | return content || "";
48 | };
49 |
50 | export const generateElement = (element: HTMLCreatorElement): string => {
51 | if (element.type) {
52 | if (VoidElements.includes(element.type)) {
53 | return `<${element.type}${applyElementAttributes(element.attributes)} />`;
54 | }
55 | return `<${element.type}${applyElementAttributes(
56 | element.attributes
57 | )}>${parseElementContent(element.content)}${element.type}>`;
58 | }
59 | return typeof element.content === "string" ||
60 | element.content instanceof String
61 | ? (element.content as string)
62 | : "";
63 | };
64 |
--------------------------------------------------------------------------------
/src/index.d.ts:
--------------------------------------------------------------------------------
1 | export interface HTMLCreatorConfig {
2 | excludeHTMLtag?: boolean;
3 | htmlTagAttributes?: HTMLCreatorElement["attributes"];
4 | disablePrettier?: boolean;
5 | }
6 |
7 | export interface HTMLCreatorElement {
8 | type?: string;
9 | attributes?: { [key: string]: string };
10 | content?: string | HTMLCreatorElement[];
11 | }
12 |
--------------------------------------------------------------------------------
/src/index.ts:
--------------------------------------------------------------------------------
1 | import HTMLCreatorDocument from "./document";
2 | import { HTMLCreatorConfig, HTMLCreatorElement } from "./index.d";
3 | import { writeFile, logMessage } from "./utils";
4 |
5 | class HtmlCreator {
6 | document: HTMLCreatorDocument;
7 |
8 | constructor(htmlContent?: HTMLCreatorElement[]) {
9 | this.document = new HTMLCreatorDocument(htmlContent);
10 | }
11 |
12 | withBoilerplate() {
13 | this.document.withBoilerplate();
14 | return this;
15 | }
16 |
17 | renderHTMLToFile(destination: string, config?: HTMLCreatorConfig) {
18 | if (!destination) {
19 | return Promise.reject(logMessage("A file path is required", "error"));
20 | }
21 | return writeFile(destination, this.renderHTML(config))
22 | .then(() => logMessage(`HTML generated (${destination})`, "success"))
23 | .catch((error) => logMessage(error, "error"));
24 | }
25 |
26 | renderHTML(config?: HTMLCreatorConfig) {
27 | if (config) {
28 | const { excludeHTMLtag } = config;
29 | if (excludeHTMLtag) {
30 | return this.document.renderContent();
31 | }
32 | }
33 | return this.document.getHTML(config);
34 | }
35 | }
36 |
37 | export default HtmlCreator;
38 |
--------------------------------------------------------------------------------
/src/test/__mock__.ts:
--------------------------------------------------------------------------------
1 | export default {
2 | contentObject: [
3 | {
4 | type: "body",
5 | attributes: {
6 | style: "padding: 1rem",
7 | },
8 | content: [
9 | {
10 | type: "div",
11 | attributes: {
12 | class: "first-div",
13 | },
14 | content: [
15 | {
16 | type: "span",
17 | attributes: {
18 | class: "button",
19 | style: "padding: 5px;background-color: #eee;",
20 | },
21 | content: "A Button Span Deluxe",
22 | },
23 | ],
24 | },
25 | {
26 | type: "table",
27 | content: [
28 | {
29 | type: "td",
30 | attributes: {
31 | id: "first",
32 | class: "button",
33 | },
34 | content: "I am in a table!",
35 | },
36 | {
37 | type: "td",
38 | content: "I am in a table too!",
39 | },
40 | ],
41 | },
42 | ],
43 | },
44 | ],
45 | singleElement: {
46 | type: "div",
47 | attributes: {
48 | class: "some-class",
49 | },
50 | content: "Single div",
51 | },
52 | boilerPlateHtml:
53 | 'hello there
', // eslint-disable-line
54 | };
55 |
--------------------------------------------------------------------------------
/src/test/document.spec.ts:
--------------------------------------------------------------------------------
1 | import Document from "../document";
2 | import mockData from "./__mock__";
3 |
4 | describe("Document", () => {
5 | describe("class constructor", () => {
6 | it("should be able to execute successfully", () => {
7 | const document = new Document();
8 | expect(document.content).toEqual([]);
9 | });
10 | });
11 |
12 | describe("getHTML", () => {
13 | it("should successfully return a string containing HTML", () => {
14 | const document = new Document(mockData.contentObject);
15 | const html = document.getHTML({ disablePrettier: true });
16 | expect(html).toEqual(
17 | 'A Button Span Deluxe
I am in a table! | I am in a table too! |
'
18 | );
19 | });
20 | });
21 |
22 | describe("renderContent", () => {
23 | it("should successfully create and return the content in HTML", () => {
24 | const document = new Document(mockData.contentObject);
25 | const content = document.renderContent();
26 | expect(content).toEqual(
27 | 'A Button Span Deluxe
I am in a table! | I am in a table too! |
'
28 | );
29 | });
30 | });
31 |
32 | describe("findElementByType", () => {
33 | it("should return a single object if there is only one match", () => {
34 | const document = new Document(mockData.contentObject);
35 | expect(document.findElementByType("span")[0]).toEqual({
36 | type: "span",
37 | attributes: {
38 | class: "button",
39 | style: "padding: 5px;background-color: #eee;",
40 | },
41 | content: "A Button Span Deluxe",
42 | });
43 | });
44 | it("should return an array if there are multiple matches", () => {
45 | const document = new Document(mockData.contentObject);
46 | expect(document.findElementByType("td")).toEqual([
47 | {
48 | type: "td",
49 | attributes: {
50 | id: "first",
51 | class: "button",
52 | },
53 | content: "I am in a table!",
54 | },
55 | {
56 | type: "td",
57 | content: "I am in a table too!",
58 | },
59 | ]);
60 | });
61 | it("should return an empty array if there were no matches", () => {
62 | const document = new Document(mockData.contentObject);
63 | expect(document.findElementByType("nothing").length).toBe(0);
64 | });
65 | });
66 |
67 | describe("findElementById", () => {
68 | it("should return a single object if there is only one match", () => {
69 | const document = new Document(mockData.contentObject);
70 | expect(document.findElementById("first")[0]).toEqual({
71 | type: "td",
72 | attributes: {
73 | id: "first",
74 | class: "button",
75 | },
76 | content: "I am in a table!",
77 | });
78 | });
79 | it("should return empty array if there were no matches", () => {
80 | const document = new Document(mockData.contentObject);
81 | expect(document.findElementById("nothing").length).toBe(0);
82 | });
83 | });
84 |
85 | describe("findElementByClassName", () => {
86 | it("should return a single object if there is only one match", () => {
87 | const document = new Document(mockData.contentObject);
88 | expect(document.findElementByClassName("first-div")[0]).toEqual({
89 | type: "div",
90 | attributes: {
91 | class: "first-div",
92 | },
93 | content: [
94 | {
95 | type: "span",
96 | attributes: {
97 | class: "button",
98 | style: "padding: 5px;background-color: #eee;",
99 | },
100 | content: "A Button Span Deluxe",
101 | },
102 | ],
103 | });
104 | });
105 | it("should return an array if there are multiple matches", () => {
106 | const document = new Document(mockData.contentObject);
107 | expect(document.findElementByClassName("button")).toEqual([
108 | {
109 | type: "span",
110 | attributes: {
111 | class: "button",
112 | style: "padding: 5px;background-color: #eee;",
113 | },
114 | content: "A Button Span Deluxe",
115 | },
116 | {
117 | type: "td",
118 | attributes: {
119 | id: "first",
120 | class: "button",
121 | },
122 | content: "I am in a table!",
123 | },
124 | ]);
125 | });
126 | it("should return an empty array if there were no matches", () => {
127 | const document = new Document(mockData.contentObject);
128 | expect(document.findElementByClassName("nothing").length).toBe(0);
129 | });
130 | });
131 |
132 | describe("setTitle", () => {
133 | it("should be able to set a title on a document with an existing title tag", () => {
134 | const document = new Document([
135 | {
136 | type: "head",
137 | content: [
138 | {
139 | type: "title",
140 | content: "Title",
141 | },
142 | ],
143 | },
144 | ]);
145 | document.setTitle("New title");
146 | expect(document.findElementByType("title")[0]).toEqual({
147 | type: "title",
148 | content: "New title",
149 | });
150 | });
151 | it("should be able to set a title on a document with a HEAD tag but no title tag", () => {
152 | const document = new Document([
153 | {
154 | type: "head",
155 | },
156 | ]);
157 | document.setTitle("New title");
158 | expect(document.findElementByType("title")[0]).toEqual({
159 | type: "title",
160 | content: "New title",
161 | });
162 | });
163 | it("should be able to set a title on a document with no HEAD tag", () => {
164 | const document = new Document([
165 | {
166 | type: "body",
167 | },
168 | ]);
169 | document.setTitle("New title");
170 | expect(document.findElementByType("title")[0]).toEqual({
171 | type: "title",
172 | content: "New title",
173 | });
174 | });
175 | });
176 |
177 | describe("withBoilerplate", () => {
178 | it("should set the content to the boilerplate", () => {
179 | const document = new Document([{ type: "div", content: "hello there" }]);
180 | document.withBoilerplate();
181 | const html = document.getHTML({ disablePrettier: true });
182 | expect(html).toEqual(
183 | mockData.boilerPlateHtml.replace(/(\r\n|\n|\r|\t| +)/gm, "")
184 | );
185 | });
186 | });
187 |
188 | describe("addElement", () => {
189 | it("should add element data to the content", () => {
190 | const document = new Document().addElement({
191 | type: "div",
192 | content: "hello there",
193 | });
194 | expect(document.content).toEqual([
195 | { type: "div", content: "hello there" },
196 | ]);
197 | });
198 | it("should be able to add an array of elements", () => {
199 | const document = new Document().addElement([
200 | { type: "div", content: "hello there" },
201 | { type: "div", content: "hello there again" },
202 | ]);
203 | expect(document.content).toEqual([
204 | { type: "div", content: "hello there" },
205 | { type: "div", content: "hello there again" },
206 | ]);
207 | });
208 | it("should be chainable", () => {
209 | const document = new Document()
210 | .addElement({ type: "div", content: "hello there" })
211 | .addElement({ type: "div", content: "hello there again" });
212 | expect(document.content).toEqual([
213 | { type: "div", content: "hello there" },
214 | { type: "div", content: "hello there again" },
215 | ]);
216 | });
217 | });
218 |
219 | describe("addElementToTarget", () => {
220 | it("should add element data to a specified element ID that has string content", () => {
221 | const document = new Document([
222 | { type: "div", attributes: { id: "anId" }, content: "hello there" },
223 | ]);
224 | document.addElementToTarget(
225 | {
226 | type: "span",
227 | content: "in here",
228 | },
229 | { id: "anId" }
230 | );
231 | expect(document.content).toEqual([
232 | {
233 | type: "div",
234 | attributes: { id: "anId" },
235 | content: [
236 | { content: "hello there" },
237 | { type: "span", content: "in here" },
238 | ],
239 | },
240 | ]);
241 | });
242 |
243 | it("should add element data to a specified element ID that has no content", () => {
244 | const document = new Document([
245 | { type: "div", attributes: { id: "anId" } },
246 | ]);
247 | document.addElementToTarget(
248 | {
249 | type: "span",
250 | content: "in here",
251 | },
252 | { id: "anId" }
253 | );
254 | expect(document.content).toEqual([
255 | {
256 | type: "div",
257 | attributes: { id: "anId" },
258 | content: [{ type: "span", content: "in here" }],
259 | },
260 | ]);
261 | });
262 |
263 | it("should add element data to a specified element ID that has content", () => {
264 | const document = new Document([
265 | {
266 | type: "div",
267 | attributes: { id: "anId" },
268 | content: [{ type: "div", content: "hello there" }],
269 | },
270 | ]);
271 | document.addElementToTarget(
272 | {
273 | type: "span",
274 | content: "in here",
275 | },
276 | { id: "anId" }
277 | );
278 | expect(document.content).toEqual([
279 | {
280 | type: "div",
281 | attributes: { id: "anId" },
282 | content: [
283 | { type: "div", content: "hello there" },
284 | { type: "span", content: "in here" },
285 | ],
286 | },
287 | ]);
288 | });
289 |
290 | it("should add element data to all elements of given Class", () => {
291 | const document = new Document([
292 | {
293 | type: "div",
294 | attributes: { class: "aClass" },
295 | content: [{ type: "div", content: "hello there" }],
296 | },
297 | {
298 | type: "div",
299 | attributes: { class: "aClass" },
300 | content: [{ type: "div", content: "hello there 2" }],
301 | },
302 | ]);
303 | document.addElementToTarget(
304 | {
305 | type: "span",
306 | content: "in here",
307 | },
308 | { class: "aClass" }
309 | );
310 | expect(document.content).toEqual([
311 | {
312 | type: "div",
313 | attributes: { class: "aClass" },
314 | content: [
315 | { type: "div", content: "hello there" },
316 | { type: "span", content: "in here" },
317 | ],
318 | },
319 | {
320 | type: "div",
321 | attributes: { class: "aClass" },
322 | content: [
323 | { type: "div", content: "hello there 2" },
324 | { type: "span", content: "in here" },
325 | ],
326 | },
327 | ]);
328 | });
329 | });
330 |
331 | describe("addElementToClass", () => {
332 | it("should add element data to all elements of given class", () => {
333 | const document = new Document([
334 | {
335 | type: "div",
336 | attributes: { class: "aClass" },
337 | content: [{ type: "div", content: "hello there" }],
338 | },
339 | {
340 | type: "div",
341 | attributes: { class: "aClass" },
342 | content: [{ type: "div", content: "hello there 2" }],
343 | },
344 | ]);
345 | document.addElementToClass("aClass", {
346 | type: "span",
347 | content: "in here",
348 | });
349 | expect(document.content).toEqual([
350 | {
351 | type: "div",
352 | attributes: { class: "aClass" },
353 | content: [
354 | { type: "div", content: "hello there" },
355 | { type: "span", content: "in here" },
356 | ],
357 | },
358 | {
359 | type: "div",
360 | attributes: { class: "aClass" },
361 | content: [
362 | { type: "div", content: "hello there 2" },
363 | { type: "span", content: "in here" },
364 | ],
365 | },
366 | ]);
367 | });
368 |
369 | it("should add an array of element data to all elements of given class", () => {
370 | const document = new Document([
371 | {
372 | type: "div",
373 | attributes: { class: "aClass" },
374 | content: [{ type: "div", content: "hello there" }],
375 | },
376 | {
377 | type: "div",
378 | attributes: { class: "aClass" },
379 | content: [{ type: "div", content: "hello there 2" }],
380 | },
381 | ]);
382 | document.addElementToClass("aClass", [
383 | {
384 | type: "span",
385 | content: "in here",
386 | },
387 | {
388 | type: "span",
389 | content: "another one",
390 | },
391 | ]);
392 | expect(document.content).toEqual([
393 | {
394 | type: "div",
395 | attributes: { class: "aClass" },
396 | content: [
397 | { type: "div", content: "hello there" },
398 | { type: "span", content: "in here" },
399 | {
400 | type: "span",
401 | content: "another one",
402 | },
403 | ],
404 | },
405 | {
406 | type: "div",
407 | attributes: { class: "aClass" },
408 | content: [
409 | { type: "div", content: "hello there 2" },
410 | { type: "span", content: "in here" },
411 | {
412 | type: "span",
413 | content: "another one",
414 | },
415 | ],
416 | },
417 | ]);
418 | });
419 | });
420 |
421 | describe("addElementToId", () => {
422 | it("should add element data to a specified element ID", () => {
423 | const document = new Document([
424 | { type: "div", attributes: { id: "anId" }, content: "hello there" },
425 | ]);
426 | document.addElementToId("anId", {
427 | type: "span",
428 | content: "in here",
429 | });
430 | expect(document.content).toEqual([
431 | {
432 | type: "div",
433 | attributes: { id: "anId" },
434 | content: [
435 | { content: "hello there" },
436 | { type: "span", content: "in here" },
437 | ],
438 | },
439 | ]);
440 | });
441 |
442 | it("should add an array of element data to a specified element ID", () => {
443 | const document = new Document([
444 | { type: "div", attributes: { id: "anId" }, content: "hello there" },
445 | ]);
446 | document.addElementToId("anId", [
447 | {
448 | type: "span",
449 | content: "in here",
450 | },
451 | {
452 | type: "span",
453 | content: "another one",
454 | },
455 | ]);
456 | expect(document.content).toEqual([
457 | {
458 | type: "div",
459 | attributes: { id: "anId" },
460 | content: [
461 | { content: "hello there" },
462 | { type: "span", content: "in here" },
463 | { type: "span", content: "another one" },
464 | ],
465 | },
466 | ]);
467 | });
468 | });
469 |
470 | describe("addElementToType", () => {
471 | it("should add element data to all elements of given HTML type", () => {
472 | const document = new Document([
473 | { type: "div", content: [{ type: "span", content: "hello there" }] },
474 | { type: "div", content: [{ type: "span", content: "hello there 2" }] },
475 | ]);
476 | document.addElementToType("div", { type: "span", content: "in here" });
477 | expect(document.content).toEqual([
478 | {
479 | type: "div",
480 | content: [
481 | { type: "span", content: "hello there" },
482 | { type: "span", content: "in here" },
483 | ],
484 | },
485 | {
486 | type: "div",
487 | content: [
488 | { type: "span", content: "hello there 2" },
489 | { type: "span", content: "in here" },
490 | ],
491 | },
492 | ]);
493 | });
494 |
495 | it("should add the given array of element data to all elements of given HTML type", () => {
496 | const document = new Document([
497 | { type: "div", content: [{ type: "span", content: "hello there" }] },
498 | { type: "div", content: [{ type: "span", content: "hello there 2" }] },
499 | ]);
500 | document.addElementToType("div", [
501 | { type: "span", content: "in here" },
502 | { type: "span", content: "another one" },
503 | ]);
504 | expect(document.content).toEqual([
505 | {
506 | type: "div",
507 | content: [
508 | { type: "span", content: "hello there" },
509 | { type: "span", content: "in here" },
510 | { type: "span", content: "another one" },
511 | ],
512 | },
513 | {
514 | type: "div",
515 | content: [
516 | { type: "span", content: "hello there 2" },
517 | { type: "span", content: "in here" },
518 | { type: "span", content: "another one" },
519 | ],
520 | },
521 | ]);
522 | });
523 | });
524 | });
525 |
--------------------------------------------------------------------------------
/src/test/element.spec.ts:
--------------------------------------------------------------------------------
1 | import * as Element from "../element";
2 | import mockData from "./__mock__";
3 |
4 | describe("Element", () => {
5 | describe("generateElement", () => {
6 | it("should return a rendered HTML element", () => {
7 | const element = Element.generateElement(mockData.singleElement);
8 | expect(element.replace(/(\r\n|\n|\r|\t| +)/gm, "")).toEqual(
9 | 'Single div
'
10 | );
11 | });
12 |
13 | it("should return a rendered string content if no type was provided", () => {
14 | const element = Element.generateElement({ content: "hey" });
15 | expect(element.replace(/(\r\n|\n|\r|\t| +)/gm, "")).toEqual("hey");
16 | });
17 |
18 | it("should return a an empty string if provided invalid content", () => {
19 | // @ts-ignore
20 | const numberElement = Element.generateElement({ content: 122 });
21 | // @ts-ignore
22 | const arrayElement = Element.generateElement({ content: ["1"] });
23 |
24 | expect(numberElement.replace(/(\r\n|\n|\r|\t| +)/gm, "")).toEqual("");
25 | expect(arrayElement.replace(/(\r\n|\n|\r|\t| +)/gm, "")).toEqual("");
26 | });
27 | });
28 |
29 | describe("applyElementAttributes", () => {
30 | it("should return a string with the HTML attributes", () => {
31 | const attributeString = Element.applyElementAttributes({
32 | class: "new",
33 | dataTest: "test",
34 | });
35 | expect(attributeString).toEqual(' class="new" data-test="test"');
36 | });
37 |
38 | it("should not include keys when their value is undefined in attributes", () => {
39 | const attributeString = Element.applyElementAttributes({
40 | class: "new",
41 | dataTest: undefined,
42 | });
43 | expect(attributeString).toEqual(' class="new"');
44 | });
45 |
46 | it("should not include keys when their value is null in attributes", () => {
47 | const attributeString = Element.applyElementAttributes({
48 | class: "new",
49 | dataTest: null,
50 | });
51 | expect(attributeString).toEqual(' class="new"');
52 | });
53 | });
54 | });
55 |
--------------------------------------------------------------------------------
/src/test/index.spec.ts:
--------------------------------------------------------------------------------
1 | import htmlCreator from "../index";
2 | import mockData from "./__mock__";
3 |
4 | describe("Index", () => {
5 | describe("withBoilerplate", () => {
6 | it("should be able to create a HTML boilerplate when initializing", () => {
7 | const html = new htmlCreator([
8 | { type: "div", content: "hello there" },
9 | ]).withBoilerplate();
10 | expect(html.renderHTML({ disablePrettier: true })).toEqual(
11 | mockData.boilerPlateHtml.replace(/(\r\n|\n|\r|\t| +)/gm, "")
12 | );
13 | });
14 | });
15 |
16 | describe("renderHTML", () => {
17 | it("should return the content with a surrounding HTML tag", () => {
18 | const html = new htmlCreator([{ type: "div", content: "hello there" }]);
19 | expect(html.renderHTML().replace(/(\r\n|\n|\r|\t| +)/gm, "")).toEqual(
20 | "hello there
"
21 | );
22 | });
23 |
24 | it("should return additional attributes to the HTML tag", () => {
25 | const html = new htmlCreator([{ type: "div", content: "hello there" }]);
26 | expect(
27 | html
28 | .renderHTML({ htmlTagAttributes: { lang: "EN" } })
29 | .replace(/(\r\n|\n|\r|\t| +)/gm, "")
30 | ).toEqual('hello there
');
31 | });
32 |
33 | it("should only return the content if excludeHTMLtag is set", () => {
34 | const html = new htmlCreator([{ type: "div", content: "hello there" }]);
35 | expect(
36 | html
37 | .renderHTML({ excludeHTMLtag: true })
38 | .replace(/(\r\n|\n|\r|\t| +)/gm, "")
39 | ).toEqual("hello there
");
40 | });
41 | });
42 |
43 | describe("renderHTMLToFile", () => {
44 | it("should be able to render HTML to a file", () => {
45 | const html = new htmlCreator([
46 | { type: "div", content: "hello there" },
47 | ]).withBoilerplate();
48 | return html.renderHTMLToFile("index.html").then((response) => {
49 | expect(response.logMsg).toEqual(
50 | "HTML-Creator >> HTML generated (index.html)"
51 | );
52 | });
53 | });
54 | it("should log errors", () => {
55 | const html = new htmlCreator([
56 | { type: "div", content: "hello there" },
57 | ]).withBoilerplate();
58 | // @ts-ignore
59 | return html.renderHTMLToFile().catch((response) => {
60 | expect(response.logMsg).toEqual(
61 | "HTML-Creator >> A file path is required"
62 | );
63 | });
64 | });
65 | });
66 | });
67 |
--------------------------------------------------------------------------------
/src/test/utils.spec.ts:
--------------------------------------------------------------------------------
1 | import * as Utils from "../utils";
2 |
3 | describe("utils", () => {
4 | describe("logMessage", () => {
5 | it("should log a given message of an existing log type", () => {
6 | // Given
7 | const log = Utils.logMessage("msg", "success");
8 | // Then
9 | expect(log.logColor).toEqual("\x1b[32m%s\x1b[0m");
10 | expect(log.logMsg).toEqual("HTML-Creator >> msg");
11 | });
12 | it("should set the log type to default if none or an invalid type was provided", () => {
13 | // Given
14 | // @ts-ignore
15 | const log1 = Utils.logMessage("msg");
16 | // @ts-ignore
17 | const log2 = Utils.logMessage("msg", "invalidType");
18 | // Then
19 | expect(log1.logColor).toEqual("\x1b[37m%s\x1b[0m");
20 | expect(log2.logColor).toEqual("\x1b[37m%s\x1b[0m");
21 | });
22 | });
23 | });
24 |
--------------------------------------------------------------------------------
/src/utils.ts:
--------------------------------------------------------------------------------
1 | import path from "path";
2 | import fs from "fs";
3 | import { mkdirp } from "mkdirp";
4 | import { HTMLCreatorElement } from "./index.d";
5 |
6 | export const logMessage = (
7 | message: string,
8 | type: "default" | "success" | "error" = "default"
9 | ) => {
10 | const logTypes = {
11 | default: "\x1b[37m%s\x1b[0m",
12 | success: "\x1b[32m%s\x1b[0m",
13 | error: "\x1b[31m%s\x1b[0m",
14 | };
15 | const logColor = !logTypes[type] ? logTypes.default : logTypes[type];
16 | const logMsg = `HTML-Creator >> ${message}`;
17 | // Let's log messages to the terminal only if we aren't testing this very module
18 | if (process.env.JEST_WORKER_ID === undefined) {
19 | console.log(logColor, logMsg);
20 | }
21 | return { logColor, logMsg };
22 | };
23 |
24 | export const writeFile = async (filePath: string, content: string) => {
25 | await mkdirp(path.dirname(filePath));
26 | fs.writeFileSync(filePath, content);
27 | };
28 |
29 | export const searchForElement = ({
30 | stack,
31 | type,
32 | id,
33 | className,
34 | }: {
35 | stack: HTMLCreatorElement["content"];
36 | type?: HTMLCreatorElement["type"];
37 | id?: string;
38 | className?: string;
39 | }): HTMLCreatorElement[] => {
40 | const result = [];
41 |
42 | if (stack && Array.isArray(stack)) {
43 | // Look for matches and push to the result
44 | result.push(
45 | stack.filter((element) => {
46 | if (type) {
47 | return element.type === type;
48 | }
49 | if (id) {
50 | return element.attributes && element.attributes.id === id;
51 | }
52 | if (className) {
53 | return element.attributes && element.attributes.class === className;
54 | }
55 | return null;
56 | })
57 | );
58 | // Loop through the content of the element and look for matches
59 | stack.forEach((element) => {
60 | if (element.content && element.content.constructor === Array) {
61 | const deepSearch = searchForElement({
62 | stack: element.content,
63 | type,
64 | id,
65 | className,
66 | });
67 | if (deepSearch) {
68 | result.push(deepSearch);
69 | }
70 | }
71 | });
72 | }
73 | // Flatten result array or just return a single object
74 | const flatResult = result.flat();
75 | return flatResult.length === 1 ? [flatResult[0]] : flatResult;
76 | };
77 |
78 | export const pushOrConcat = (
79 | targetArray: HTMLCreatorElement[],
80 | input: HTMLCreatorElement | HTMLCreatorElement[]
81 | ) => {
82 | if (Array.isArray(input)) {
83 | return targetArray.concat(input);
84 | }
85 | targetArray.push(input);
86 | return targetArray;
87 | };
88 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "esnext",
5 | "noImplicitAny": true,
6 | "moduleResolution": "node",
7 | "sourceMap": true,
8 | "outDir": "dist",
9 | "baseUrl": "./src",
10 | "lib": ["es2019"],
11 | "resolveJsonModule": true,
12 | "esModuleInterop": true,
13 | "forceConsistentCasingInFileNames": true,
14 | "preserveSymlinks": true,
15 | "rootDir": "src"
16 | },
17 | "include": ["src/**/*"],
18 | "exclude": ["node_modules/**"]
19 | }
20 |
--------------------------------------------------------------------------------