Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
{
"name": "@wide/modulus",
"version": "2.1.2",
"version": "2.2.0",
"description": "Robust Web Component interface",
"license": "MIT",
"author": "Aymeric Assier (https://github.com/myeti)",
"contributors": [
"Aymeric Assier (https://github.com/myeti)",
"Julien Martins Da Costa (https://github.com/jdacosta)"
"Julien Martins Da Costa (https://github.com/jdacosta)",
"Sébastien Robillard (https://github.com/robiseb)",
"Kévin Poccard Soudard (https://github.com/kevpoccs)"
],
"repository": {
"type": "git",
Expand Down
81 changes: 73 additions & 8 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,44 @@ Use the `[data-call]` helper with a formatted value `name#id.method`:

will internally trigger:
```js
modulus.seek('modal', '#register').open()
modulus.seek('modal', '#register').open({ el, e, data })
```

#### Parameters
Use the `[data-call.params]` to pass some predefined values:

| Value | Description |
|---|---|---|---|
| `$event` | `Event` object of the event listener method callback |
| `$el` | Element object binded to the event |
|---|---|
| `el` | HTMLElement object binded to the event |
| `e` | `Event` object of the event listener method callback |
| `data` | Optional parameters defined in `[data-call.params]` |

#### Parameters
Use the `[data-call.params]` to pass custom values:

```html
<button data-call="modal#register.open" data-call.params="$event">do something</button>
<button data-call="modal#register.open" data-call.params='[{ "myAttr": "myValue" }]'>do something</button>
```

> ⚠️ Note: `data-call.params` is waiting a JSON format only

Exmple with the previous HTML code:
```js
modulus.component('modal', class extends Component {
run() {
// ...
}

/**
* Open modal and do some stuff
*
* @params {HTMLElement} el
* @params {Event} e
* @params {Object|null} [data]
*/
open({ el, e, data }) {
// el: <button ...>
// e: Event{ ... }
// data: { ... } | null
}
```

## Component class

Expand Down Expand Up @@ -171,11 +193,54 @@ modulus.component('foo-bar', class extends Component {
Every event listeners created using `this.on()` are automatically `off()`ed on component destruction.


## Config

### Log level

To keep only `warn` and `error` logs (for production usage), set `production` to `true`:
```js
import modulus from '@wide/modulus'

modulus.config({ production: true })
```

Or manually assign a log level:
```js
import modulus, { LOG_LEVELS } from '@wide/modulus'

modulus.config({
log: {
level: LOG_LEVELS.INFO // DEBUG (default), INFO, WARN, ERROR, NONE
}
})
```

> ⚠️ Note: assign a log level will override the `production` setting.

To disable logs, set `enabled` to `false`:
```js
import modulus from '@wide/modulus'

modulus.config({
log: {
enabled: false
}
})
```

The default config is setted to show all kind of logs.


## Authors

- **Aymeric Assier** - [github.com/myeti](https://github.com/myeti)
- **Julien Martins Da Costa** - [github.com/jdacosta](https://github.com/jdacosta)

### Contributors

- **Sébastien Robillard** - [github.com/robiseb](https://github.com/robiseb)
- **Kévin Poccard Soudard** - [github.com/kevpoccs](https://github.com/kevpoccs)


## License

Expand Down
24 changes: 17 additions & 7 deletions src/directives.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import observe from '@wide/dom-observer'
import { logger } from './logger'
import { seek } from './index'

const DEFAULT_TOGGLE_CLASS = '-active'


/**
* Run component's method from HTML
* Ex: [data-call="modal#register.open"] -> modulus.seek('modal', '#register').open()
* Ex with params: [data-call="modal#register.open"] [data-call.params="$el"] -> modulus.seek('modal', '#register').open(el)
* Ex: [data-call="modal#register.open"]
* Ex with params: [data-call="modal#register.open"] [data-call.params='[{ "myAttribute": "myValue" }]']
*
* -> modulus.seek('modal', '#register').open({ el, e, data })
*/
observe('[data-call]', {
bind(el) {
Expand All @@ -17,13 +20,20 @@ observe('[data-call]', {
const component = seek(name, id)
if(component) {
const params = el.dataset['call.params']
let data = null

if (params) {
try {
data = JSON.parse(params)?.[0]
} catch(e) {
logger.error('Invalid JSON format in `data-call.params`.', e)
}
}

if (params === '$el') component[method](el)
else if (params === '$event') component[method](e)
else component[method]()
} else console.error(`Unknown component "${str}"`)
component[method]({ el, e, data })
} else logger.error(`Unknown component "${str}"`)
}
else console.error(`Invalid call string "${str}"`)
else logger.error(`Invalid call string "${str}"`)
})
}
})
Expand Down
44 changes: 41 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,23 @@
import observe, { seek as _seek } from '@wide/dom-observer'
import { LOG_LEVELS, Logger, logger } from './logger'
import { bind, unbind } from './hooks'
import './directives'

export { LOG_LEVELS } from './logger'


/**
* Default internal config values
* @type {Object}
*/
const DEFAULT_CONFIG = {
production: false,
log: {
enabled: true,
level: null
}
}


/**
* Register many regular and custom elements
Expand Down Expand Up @@ -39,7 +55,7 @@ export function registerMany(many) {
* @param {Function} Klass
*/
export function registerComponent(name, Klass) {
console.debug(`# register component [is=${name}]`)
logger(`# register component [is=${name}]`)
observe(`[is="${name}"]`, {
bind: el => bind(el, name, Klass),
unbind: el => unbind(el)
Expand All @@ -64,7 +80,7 @@ export function registerComponents(collection) {
* @param {Function} Klass
*/
export function registerWebComponent(name, Klass) {
console.debug(`# register web component <${name}>`)
logger(`# register web component <${name}>`)
try {
window.customElements.define(name, class extends HTMLElement {
connectedCallback() {
Expand All @@ -76,7 +92,7 @@ export function registerWebComponent(name, Klass) {
})
}
catch(err) {
console.error(err)
logger.error(err)
}
}

Expand Down Expand Up @@ -131,6 +147,27 @@ export function seekAll(name, selector) {
}


/**
* Set internal config
* - assign log level
* @param {Object} values
*/
export function setConfig(values = {}) {
const config = Object.assign({}, DEFAULT_CONFIG, values)
const { enabled, level } = config.log

if (enabled) {
if (level) {
Logger.LEVEL = Object.values(LOG_LEVELS).includes(level) ? level : LOG_LEVELS.DEBUG
} else {
Logger.LEVEL = config.production ? LOG_LEVELS.WARN : LOG_LEVELS.DEBUG
}
} else {
Logger.LEVEL = LOG_LEVELS.NONE
}
}


/**
* Extend modulus instance
*/
Expand All @@ -143,6 +180,7 @@ modulus.webComponents = registerWebComponents
modulus.imports = registerImports
modulus.seek = seek
modulus.seekAll = seekAll
modulus.config = setConfig


/**
Expand Down
62 changes: 54 additions & 8 deletions src/logger.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,62 @@
/**
* All available log levels
* @type {Object<String, Number>}
*/
export const LOG_LEVELS = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
NONE: Infinity
}


/**
* Map levels to real console functions
* @type {Object<String, Function>}
*/
const LOG_METHODS = {
[LOG_LEVELS.DEBUG]: console.debug,
[LOG_LEVELS.INFO]: console.log,
[LOG_LEVELS.WARN]: console.warn,
[LOG_LEVELS.ERROR]: console.error
}


/**
* Write log depending on the level requested
* @param {Number} level
* @param {String} prefix
* @param {Array} args
*/
function writeLog(level, prefix, args) {
const method = LOG_METHODS[level]
if(method && Logger.LEVEL <= level) method(prefix, ...args)
}


/**
* Logger factory
* @param {String} prefix
*/
export default function Logger(prefix = '') {
const logger = (...args) => writeLog(LOG_LEVELS.DEBUG, prefix, args)
logger.info = (...args) => writeLog(LOG_LEVELS.INFO, prefix, args)
logger.warn = (...args) => writeLog(LOG_LEVELS.WARN, prefix, args)
logger.error = (...args) => writeLog(LOG_LEVELS.ERROR, prefix, args)
return logger
}


const logger = function(...args) {
console.debug(prefix, ...args)
}
/**
* Logger global level
* @type {Number}
*/
Logger.LEVEL = LOG_LEVELS.DEBUG

logger.info = (...args) => console.log(prefix, ...args)
logger.warn = (...args) => console.warn(prefix, ...args)
logger.error = (...args) => console.error(prefix, ...args)

return logger
}
/**
* Built-in instance
* @type {Logger}
*/
export const logger = new Logger()
4 changes: 2 additions & 2 deletions src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,6 @@ export function parseRefs(el, uid) {
* @param {String} str
* @return {String}
*/
export function camelize(str) {
export function camelize(str) {
return str.replace(/[\s-]+(\w)/g, (m, c) => c.toUpperCase())
}
}