# ch-router-js

> Your Security System Network Integrator. [Chicorycom][website] 👋

Latest version **1.1.0** (published 2022-06-01) · MIT license · 0 weekly downloads

## Install

```sh
npm install ch-router-js
pnpm add ch-router-js
yarn add ch-router-js
bun add ch-router-js
```

## Health

**Score 20/100 (F)** — status: abandoned.

Positive: esm support; no vulnerabilities.

Warnings: low downloads; no types.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.1.0 |
| Published | 2022-06-01 |
| First published | 2021-08-26 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | ESM + CommonJS |
| Dependencies | 0 |
| Unpacked size | 17.8 KB |
| Known vulnerabilities | 0 |
| Install scripts | no |
| Author | Chicorycom |
| Maintainers | chicorycom |
| Keywords | router-js, chicorycom-router-js, ch-router-js, front-router-js, frontend-router-js |

## Links

- npm: https://www.npmjs.com/package/ch-router-js
- Repository: https://github.com/chicorycom/ch-router-js
- Issues: https://github.com/chicorycom/ch-router-js/issues
- npm.io page: https://npm.io/package/ch-router-js

## Alternatives

- [express-promise-router](https://npm.io/package/express-promise-router.md) — 736.1K weekly downloads
- [next-usequerystate](https://npm.io/package/next-usequerystate.md) — 29.8K weekly downloads
- [@bitkyc08/opencodex](https://npm.io/package/@bitkyc08/opencodex.md) — 4.6K weekly downloads
- [lynkr](https://npm.io/package/lynkr.md) — 575 weekly downloads
- [baremetal.js](https://npm.io/package/baremetal.js.md) — 42 weekly downloads

## Recent versions

- 1.1.0 (latest) — 2022-06-01
- 1.0.9 — 2022-05-26
- 1.0.7 — 2021-08-29
- 1.0.6 — 2021-08-28
- 1.0.5 — 2021-08-27
- 1.0.4 — 2021-08-27
- 1.0.3 — 2021-08-26
- 1.0.2 — 2021-08-26
- 1.0.1 — 2021-08-26
- 1.0.0 — 2021-08-26

## README

Your Security System Network Integrator. [Chicorycom][website] 👋

# ch-router-js

🍭 Wow, such a lovely router frontend web site
    export NODE_OPTIONS=--openssl-legacy-provider 

## Installation

Using npm:

```
npm install ch-router-js --save
```

Using Yarn:

```
yarn add ch-router-js
```

Work with module bundler:

## Quick Start

```js
import {router, Controller} from 'ch-router-js'


class Dashboard extends Controller {
    /**
     *
     * @param params
     */
    constructor(params) {
        super(params);
        this.setTitle("Dashboard"); 
    }

    /**
     *
     * @returns {string<innerHTML>}
     */
    getHtml() {
        return this.view(`<template><h1>test</h1></template>`);
    }
}


class About extends Controller {
    /**
     *
     * @param params
     */
    constructor(params) {
        super(params);
        //default title: slug
    }

    /**
     * 
     * @returns {Promise<*>}
     */
  async  getHtml() {
        const response = await this.get('/pages/dashboard')
        return this.view(response);
    }
}


const routes = [
    { path: "/", view: Dashboard },
    { path: "/about", view: About },
    { path: "/post/:slug", view: About }
]

const el = document.createElement('div')
document.body.prepend(el)

or 

const el = document.querySelector(selected)

const options = {
    el: el || selected,
    routes
}

router(options)

```

## Options

Name | Default | Description
----|-------|----
el | document.querySelector('.ch-router-js') | binding element
routes | array object | route for page, [see more details](https://chicorycom.net)
save | `function` | selected html element attribute ch-save
edit | `function` | selected html element attribute ch-edit
destroy | `function` | selected html element attribute ch-destroy
logout | `function` | selected html element attribute ch-logout

For example:


### Template page html or blade or ejs or twig ...

`Template sent by the serve`

```html
<template>
    <div class="__card-shadow-heading">
        <span class="__card-shadow-heading-action">
            <a class="list-toolbar-btn" href="#" title="configure">
                <i class="fas fa-cog"></i>
            </a>
            <a class="list-toolbar-btn" href="#" title="refresh">
                <i class="fas fa-sync-alt"></i>
            </a>
        </span>
    </div>
</template>
<script >
    //TODO script 
</script>
<style>
    /** TODO style **/
</style>
```

### HTML page

```html
<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
<nav>
  <a href="/" ch-link> Home page </a><br>
  <a href="/about" ch-link> About </a><br>
  <a href="/post/title-post-1" ch-link> single post </a><br>
  
  <button  ch-save> Save form </button>
  <button  ch-edit> edit form </button>
  <button  ch-destroy> delete  </button>
  <br>
  <button  ch-logout>logout </button>
</nav>
<div id="app"></div>
<script  src="/main.js"></script>
</body>
</html>
```

### main.js | Javascript script
```js
const opt = {
  el,
  routes,
  /**
   *
   * @param e
   * @returns {Promise<void>}
   */
  async destroy(el) {
    const res = await fetch(el.dataset.action, {
      method: 'DELETE'
    })
    if(res.status === 204){
      Success('Deleted!')
    }
  },

  /**
   *
   * @param e
   * @returns {Promise<void>}
   */
  async logout(el){
    const auth = await JSON.parse(localStorage.getItem('auth')) || {}
    const headers = new Headers();
    headers.set('Authorization', 'Basic ' + auth.token)
    const response = await fetch('/logout', { method: 'POST', headers })

    if(response.status >= 200 && response.status < 300){
      location.href = '/'
    }
  }
}

opt.save = async (el) => {
  const parent = el.parentNode.parentNode
  const li = parent.querySelectorAll('.edited')
  const body = {}

  await li.forEach(  element => {
    body[element.dataset.collum] = element.textContent.trim()
    element.removeAttribute('contentEditable')
  })
  if(JSON.stringify(bodyOld) !== JSON.stringify(body)){
    const res = await fetch(el.dataset.action, {
      method: 'PUT',
      headers: {
        'Content-type': 'application/json; charset=UTF-8' // Indicates the content
      },
      body: JSON.stringify(body)
    })
    if(res.status >= 300){
      alert(`Internal Server Error... code: ${res.status}`, '', 'error')
    }
  }

  el.innerHTML = ` <i class="fa fa-edit"></i> edit`
  el.removeAttribute.remove('ch-save')
  el.setAttribute('ch-edit', '')
  return el
}

opt.edit =  (el) => {
  const parent = el.parentNode.parentNode

  const li = parent.querySelectorAll('.edited')

  li.forEach(element => {
    element.setAttribute('contentEditable', 'true')
    bodyOld[element.dataset.collum] = element.textContent.trim()
  })

  li[0].focus()

  el.innerHTML = `<i class="far fa-save"></i> Save`
  el.removeAttribute('ch-edit')
  el.setAttribute('ch-save', '')
  return el
}

router(opt)

```

## API

+ `opt.save()`: callback
+ `opt.edit()`: callback
+ `opt.destroy()`: callback
+ `opt.logout()`: callback

[website]: https://chicorycom.net

---
_Source: https://npm.io/package/ch-router-js · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
