Compare commits

...

4 Commits

30 changed files with 638 additions and 188 deletions

1
.gitignore vendored
View File

@@ -236,3 +236,4 @@ out
.pnp.* .pnp.*
/.trash/ /.trash/
/dist/*.LICENSE.txt

2
dist/app.19f5ee6c7563dd0839a8.js vendored Normal file

File diff suppressed because one or more lines are too long

1
dist/app.css vendored Normal file

File diff suppressed because one or more lines are too long

2
dist/faker.19f5ee6c7563dd0839a8.js vendored Normal file

File diff suppressed because one or more lines are too long

15
dist/index.html vendored Normal file
View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Notes in JS (Home task 1)</title>
<link href="app.css" rel="stylesheet"></head>
<body>
<div id="appConsole" class="uk-container uk-margin-remove uk-background-muted uk-text-small"></div>
<div id="app" class="uk-container"></div>
<script defer src="vendors-node_modules_faker_index_js.19f5ee6c7563dd0839a8.js"></script><script defer src="faker.19f5ee6c7563dd0839a8.js"></script><script defer src="app.19f5ee6c7563dd0839a8.js"></script></body>
</html>

File diff suppressed because one or more lines are too long

View File

@@ -7,6 +7,7 @@
"scripts": { "scripts": {
"start": "cross-env SOURCE_MAP_ENV=true webpack serve --open", "start": "cross-env SOURCE_MAP_ENV=true webpack serve --open",
"srv": "cross-env SOURCE_MAP_ENV=true webpack serve", "srv": "cross-env SOURCE_MAP_ENV=true webpack serve",
"srv-prod": "cross-env SOURCE_MAP_ENV=true NODE_ENV=production webpack serve",
"watch": "webpack --watch", "watch": "webpack --watch",
"build": "cross-env NODE_ENV=production webpack", "build": "cross-env NODE_ENV=production webpack",
"build-dev": "cross-env SOURCE_MAP_ENV=true NODE_ENV=production webpack" "build-dev": "cross-env SOURCE_MAP_ENV=true NODE_ENV=production webpack"
@@ -35,5 +36,8 @@
"webpack": "^5.56.1", "webpack": "^5.56.1",
"webpack-cli": "^4.8.0", "webpack-cli": "^4.8.0",
"webpack-dev-server": "^4.3.1" "webpack-dev-server": "^4.3.1"
},
"dependencies": {
"faker": "^5.5.3"
} }
} }

View File

@@ -1,6 +1,13 @@
{ {
"routes": {
"/all": "All Notes",
"/": "Recent Notes",
"/archive": "Archived Notes",
"/analytics": "Analytics"
},
"localStorageKey": "notes-home-task-1", "localStorageKey": "notes-home-task-1",
"prePopulateAmount": 7, "prePopulateAmount": 7,
"fakerAmount": 44,
"lists": { "lists": {
"monthsFull": ["January","February","March","April","May","June","July", "August","September","October","November","December"] "monthsFull": ["January","February","March","April","May","June","July", "August","September","October","November","December"]
}, },
@@ -8,11 +15,15 @@
"primary", "success", "warning", "danger" "primary", "success", "warning", "danger"
], ],
"querySelectors": { "querySelectors": {
"root": "#app",
"console": "#appConsole", "console": "#appConsole",
"navTabs": "#asSwitcher", "navTabs": "#asSwitcher",
"modal": ".modal", "modal": ".modal",
"analyticsGrid": "#analyticsGrid",
"notesGrid": "#notesGrid", "notesGrid": "#notesGrid",
"noteEditForm": "#noteEditForm", "noteEditForm": "#noteEditForm",
"btnPrepopulate": "#btnPrepopulate",
"selectPrepopulate": "#selectPrepopulate",
"btnCreateNote": "#btnCreateNote", "btnCreateNote": "#btnCreateNote",
"btnDestroyModal": "#btnDestroyModal", "btnDestroyModal": "#btnDestroyModal",
"saveNote": "#saveNote", "saveNote": "#saveNote",
@@ -36,10 +47,10 @@
"schemas": { "schemas": {
"note": { "note": {
"id": [ false, "^[0-9]{6}$" ], "id": [ false, "^[0-9]{6}$" ],
"title": [ true, "^(.{1,128})$" ], "title": [ true, 128 ],
"category": [ true, "^(task|random_thought|idea|quote)$" ], "category": [ true, "^(task|random_thought|idea|quote)$" ],
"content": [ false, "^(.{1,1024}$)" ], "content": [ false, 1024 ],
"archive": [ false, "^(on|)$" ], "archive": [ false, "^(on|true|)$" ],
"createdAt": [ false, "^202[1-9]-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" ], "createdAt": [ false, "^202[1-9]-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" ],
"updatedAt": [ false, "^202[1-9]-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" ] "updatedAt": [ false, "^202[1-9]-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$" ]
} }

45
src/faker.js Normal file
View File

@@ -0,0 +1,45 @@
import { env, randomID6n } from './helpers'
const faker = require('faker')
export const fakerDB = length => {
const dates = [
'1/1/11', '1.1.11', '1-1-11', '01/01/11', '01.01.11', '01-01-11',
'01/01/2011', '01.01.2011', '01-01-2011', '01/1/2011', '01.1.2011', '01-1-2011',
'1/11/2011', '1.11.2011', '1-11-2011', '1/11/11', '1.11.11', '1-11-11',
'11/1/11', '11.1.11', '11-1-11', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
]
const data = []
const cat = env.schemas.note.category[1].slice(2, -2).split('|')
//
for (let i = 0; i < length; i++) {
const up = faker.date.between('2021-07-01', '2021-10-07')
let pickedDates = []
for( let i = 0; i< 4; i++ ) {
pickedDates.push( dates[(Math.random() * dates.length) | 0] )
}
pickedDates = pickedDates.filter( el => el !== '' )
const rec = {
id: randomID6n(),
title: faker.animal.snake(),
category: cat[(Math.random() * cat.length) | 0],
archive: ['', 'on'][(Math.random() * 2) | 0],
content: faker.hacker.phrase() + (pickedDates.length > 0 ? "<br/><strong style='color: green'>Dates:</strong> [ " + pickedDates.join(', ') : '') + " ]",
createdAt: faker.date.between('2021-07-06', '2021-10-01'),
updatedAt: ['', up][(Math.random() * 2) | 0],
}
data.push(rec)
}
return data
}
//console.log( JSON.stringify( data, null, 2 ))

View File

@@ -7,6 +7,12 @@ export const msgBox = document.getElementById(env.querySelectors.console.slice(1
*/ */
const monthsNamesFull = env.lists.monthsFull const monthsNamesFull = env.lists.monthsFull
export const randomID6n = () => Math.floor(100000 + Math.random() * 900000)
export const parseURL = url => new URL(url)
/** /**
* *
* @param string * @param string

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#fcc343"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zm-8.89 11.92L6.5 12H10v-2h4v2h3.5l-5.15 5.15c-.19.19-.51.19-.7 0zM5.12 5l.81-1h12l.94 1H5.12z"/></svg>

After

Width:  |  Height:  |  Size: 418 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#999"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M20.54 5.23l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.16.55L3.46 5.23C3.17 5.57 3 6.02 3 6.5V19c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.48-.17-.93-.46-1.27zm-8.89 11.92L6.5 12H10v-2h4v2h3.5l-5.15 5.15c-.19.19-.51.19-.7 0zM5.12 5l.81-1h12l.94 1H5.12z"/></svg>

Before

Width:  |  Height:  |  Size: 415 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#d6676d"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v10zM18 4h-2.5l-.71-.71c-.18-.18-.44-.29-.7-.29H9.91c-.26 0-.52.11-.7.29L8.5 4H6c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1z"/></svg>

After

Width:  |  Height:  |  Size: 368 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#999"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2H8c-1.1 0-2 .9-2 2v10zM18 4h-2.5l-.71-.71c-.18-.18-.44-.29-.7-.29H9.91c-.26 0-.52.11-.7.29L8.5 4H6c-.55 0-1 .45-1 1s.45 1 1 1h12c.55 0 1-.45 1-1s-.45-1-1-1z"/></svg>

Before

Width:  |  Height:  |  Size: 365 B

1
src/images/edit_48dp.svg Normal file
View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#abcdef"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM21.41 6.34l-3.75-3.75-2.53 2.54 3.75 3.75 2.53-2.54z"/></svg>

After

Width:  |  Height:  |  Size: 259 B

View File

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#999"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM21.41 6.34l-3.75-3.75-2.53 2.54 3.75 3.75 2.53-2.54z"/></svg>

Before

Width:  |  Height:  |  Size: 256 B

View File

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" height="48px" viewBox="0 0 24 24" width="48px" fill="#bada55"><path d="M0 0h24v24H0V0z" fill="none"/><path d="M18.71 3H5.29L3 5.79V21h18V5.79L18.71 3zM14 15v2h-4v-2H6.5L12 9.5l5.5 5.5H14zM5.12 5l.81-1h12l.94 1H5.12z"/></svg>

After

Width:  |  Height:  |  Size: 264 B

View File

@@ -6,7 +6,10 @@
</head> </head>
<body> <body>
<div id="appConsole" class="uk-container"></div>
<div id="app" class="uk-container"></div> <div id="appConsole" class="uk-container uk-margin-remove uk-background-muted uk-text-small"></div>
<div id="app" class="uk-container"></div>
</body> </body>
</html> </html>

View File

@@ -2,23 +2,10 @@ import { env } from './helpers'
import './styles/uikit.min.css' import './styles/uikit.min.css'
import './styles/main.css' import './styles/main.css'
import DOMController from './modules/DOMController' import DOMController from './modules/DOMController'
import RouteController from './modules/RouteController'
const app = document.getElementById('app')
window.env = env window.env = env
new DOMController(app) const app = document.getElementById(env.querySelectors.root.slice(1))
/*NotesAPI.saveNote({ new DOMController(app, new RouteController())
//id: 441512,
title: 'Note 1234',
category: 'category 1234',
content: 'contents 1234',
updatedAt: null
})*/
//NotesAPI.deleteNote(441512)
//console.log(NotesAPI.getNotes())
/*
1/1/11 or 1.1.11 or 1-1-11 01/01/11 or 01.01.11 or 01-01-11 01/01/2011 or 01.01.2011 or 01-01-2011 : true 01/1/2011 or 01.1.2011 or 01-1-2011 : true 1/11/2011 or 1.11.2011 or 1-11-2011 1/11/11 or 1.11.11 or 1-11-11 11/1/11 or 11.1.11 or 11-1-11*/

View File

@@ -0,0 +1,28 @@
import { createNode, msgBox } from '../helpers'
export default class AlertController {
static showError () {
this.displayDialog('Error occurred :(', 3000, 3)
}
/**
*
* @param msg
* @param fadeOut
* @param type
* @param parent
*/
static displayDialog (msg = 'Alert without message', fadeOut = 0, type = 0, parent = null) {
const alertTypes = window.env.alertTypes
const dialog = createNode('div', { class: `uk-alert-${alertTypes[type]} uk-padding-small` }, msg)
parent instanceof Element ? parent.appendChild(alert) : msgBox.appendChild(dialog)
if (fadeOut > 0) {
setTimeout(() => {
dialog.remove()
}, fadeOut)
}
}
}

View File

@@ -1,62 +1,133 @@
import Templates from '../templates/Views' import Templates from '../templates/Views'
import { msgBox, createNode, destroyNode, findDates, formatDate, ucWords } from '../helpers' import { createNode, destroyNode, findDates, formatDate, parseURL, replaceURLPathname, ucWords } from '../helpers'
import NotesAPI from './NotesAPI' import NotesAPI from './NotesAPI'
import ValidationController from './ValidationController'
import Alert from './AlertController'
export default class DOMController { export default class DOMController {
constructor (root) { constructor (root, routes) {
this.routes = routes
this.root = root this.root = root
try { try {
this.root.innerHTML = Templates.grid this.root.innerHTML = Templates.grid
this.renderRoutes()
} catch (e) { } catch (e) {
DOMController.alert(e.toString(), 0, 3) Alert.displayDialog(e.toString(), 0, 3)
} }
this.btnCreateNote = this.root.querySelector(window.env.querySelectors.btnCreateNote) this.btnCreateNote = this.root.querySelector(window.env.querySelectors.btnCreateNote)
this.btnPrepopulate = this.root.querySelector(window.env.querySelectors.btnPrepopulate)
this.createNotesGrid(window.env.prePopulateAmount || 0) this.createNotesGrid(window.env.prePopulateAmount || 0)
this.listener([ this.listener([
[this.btnCreateNote, 'click', (this.btnCreateNote.dataset.action || 'showError'), { legend: 'Create Note' }], [this.btnCreateNote, 'click', (this.btnCreateNote.dataset.action || 'showError'), { legend: 'Create Note' }],
[this.btnPrepopulate, 'click', (this.btnPrepopulate.dataset.action || 'showError')],
]) ])
this.navTabs()
}
navTabs () {
const navTabs = document.querySelectorAll(window.env.querySelectors.navTabs + ' > li > a')
for (let i = 0; i < navTabs.length; ++i) {
this.listener([navTabs[i], 'click', 'createNotesGridByRoute', navTabs[i]])
}
} }
/** /**
* *
*/ */
showError () { renderRoutes () {
DOMController.alert('Error occurred :(', 3000, 3)
for (const [route, name] of Object.entries(this.routes.routes)) {
const tab = createNode('li')
tab.classList.add('nav-tab')
if (route === '/') {
tab.classList.add('initial')
tab.classList.add('uk-active')
}
tab.innerHTML = `<a href="${route}">${name}</a>`
const anchor = tab.querySelector('a')
this.routes.navbar.appendChild(tab)
this.listener([anchor, 'click', 'createNotesGridByRoute', anchor])
}
}
createNotesGridByRoute (navTab) {
const pathname = parseURL(navTab.href).pathname
const route = pathname.slice(1).split('\/')[0]
window.history.pushState('', navTab.innerText, pathname) //change url without reload
//history.pushState({}, null, pathname) //change url
this.routes.navbar.querySelector('.uk-active').classList.remove('uk-active')
navTab.closest('.nav-tab').classList.add('uk-active')
document.getElementById(window.env.querySelectors.analyticsGrid.slice(1)).classList.add('uk-hidden')
document.getElementById(window.env.querySelectors.notesGrid.slice(1)).classList.remove('uk-hidden')
switch (route) {
case 'all':
this.createNotesGrid(0, null)
break
case '':
this.createNotesGrid(window.env.prePopulateAmount || 0)
break
case 'archive':
this.createNotesGrid(window.env.prePopulateAmount || 0, true)
break
case 'analytics':
document.getElementById(window.env.querySelectors.notesGrid.slice(1)).classList.add('uk-hidden')
const analyticsGrid = document.getElementById(window.env.querySelectors.analyticsGrid.slice(1))
this.createAnalyticsGrid(analyticsGrid)
break
}
}
prePopulate () {
const fakerAmount = document.querySelector(env.querySelectors.selectPrepopulate)
if (+fakerAmount.value <= 0) {
return
}
env.fakerAmount = (+fakerAmount.value > 44) ? 44 : +fakerAmount.value
localStorage.removeItem(window.env.localStorageKey)
fakerAmount.selectedIndex = 0
document.querySelector('.nav-tab.uk-active > a').click()
}
/**
* The method is being called for typical DOM-event task inside the table row
* to manipulate with records: deleting, editing, archiving.
*
* @param node
* @param method
*/
noteToAction (node, method) {
const row = node.closest('tr')
NotesAPI[method](parseInt(row.dataset.id, 10))
row.classList.add('as-removing')
setTimeout(() => {
row.remove()
document.querySelector('.nav-tab.uk-active > a').click()
}, 1050)
} }
/** /**
* *
* @param msg * @param node
* @param fadeOut
* @param type
* @param womb
*/ */
static alert (msg = 'Alert without message', fadeOut = 0, type = 0, womb = null) { noteToArchive (node) {
const alertTypes = window.env.alertTypes this.noteToAction(node, 'archiveNote')
const alert = createNode('div', { class: `uk-alert-${alertTypes[type]} uk-padding-small`, 'uk-alert': null }, msg) }
alert.style.display = 'block'
womb instanceof Element ? womb.appendChild(alert) : msgBox.appendChild(alert)
if (fadeOut > 0) { /**
setTimeout(() => { *
alert.remove() * @param node
}, fadeOut) */
} noteFromArchive (node) {
this.noteToAction(node, 'unArchiveNote')
} }
/** /**
@@ -64,26 +135,26 @@ export default class DOMController {
* @param node * @param node
*/ */
noteToTrash (node) { noteToTrash (node) {
const row = node.closest('tr') this.noteToAction(node, 'deleteNote')
NotesAPI.deleteNote(parseInt(row.dataset.id, 10))
row.classList.add('as-removing')
setTimeout(() => {
row.remove()
this.createNotesGrid(window.env.prePopulateAmount || 0)
}, 3000)
} }
createNotesGridByRoute (navTab) { createAnalyticsGrid (grid) {
const route = new URL( navTab.href ).pathname.slice(1).split('\/')[0] grid.classList.remove('uk-hidden')
document.querySelector('li.nav-tab.uk-active').classList.remove('uk-active') const aGrid = grid.querySelector(' tbody')
navTab.closest('li').classList.add( 'uk-active' ) aGrid.innerHTML = ''
switch ( route ){ for (const [key, value] of Object.entries(NotesAPI.getAnalytics())) {
case 'all': this.createNotesGrid( 0, null ); break;
case '': this.createNotesGrid( window.env.prePopulateAmount || 0 ); break; const row = createNode('tr')
case 'archived': this.createNotesGrid( window.env.prePopulateAmount || 0, true ); break; const td = createNode('td', {}, ucWords(key))
default: console.log(route) row.appendChild(td)
for (const [key, val] of Object.entries( value ) ) {
const td = createNode('td', {}, val.toString())
row.appendChild(td)
}
aGrid.appendChild(row)
} }
} }
@@ -94,15 +165,12 @@ export default class DOMController {
*/ */
createNotesGrid (len = window.env.prePopulateAmount || 0, archived = false) { createNotesGrid (len = window.env.prePopulateAmount || 0, archived = false) {
const notes = NotesAPI.getNotesSanitized(len, archived)
if (notes.length === 0) { return }
const notesGrid = document.querySelector(window.env.querySelectors.notesGrid + ' tbody') const notesGrid = document.querySelector(window.env.querySelectors.notesGrid + ' tbody')
notesGrid.innerHTML = '' notesGrid.innerHTML = ''
const notes = NotesAPI.getNotesSanitized(len, archived)
if (notes.length === 0) { return }
notes.forEach(el => { notes.forEach(el => {
const row = createNode('tr') const row = createNode('tr')
@@ -117,29 +185,23 @@ export default class DOMController {
value = formatDate(value) value = formatDate(value)
break break
case 'category': case 'category':
value = ucWords( value ) value = ucWords(value)
break break
case 'title': case 'title':
//attrs.class = 'uk-text-truncate'
attrs.class = 'uk-text-bold' attrs.class = 'uk-text-bold'
break break
case 'content':
//attrs.class = 'uk-text-truncate'
//attrs.title = value
break
case 'dates': case 'dates':
attrs.style = 'font-size: 12px'
value = findDates(el.content).join(', ') value = findDates(el.content).join(', ')
//attrs.class = 'uk-text-truncate'
//attrs.title = value
break break
case 'edit' : case 'edit' :
attrs.class = 'icon icon-edit grid-control' attrs.class = 'grid-control icon icon-edit'
attrs['data-action'] = 'getEditForm' attrs['data-action'] = 'getEditForm'
break break
case 'archive' : case 'archive' :
attrs.class = 'icon icon-archive grid-control' attrs.class = 'grid-control icon ' + (value === 'on' ? 'icon-unarchive' : 'icon-archive')
attrs['data-action'] = 'toArchive' attrs['data-action'] = value === 'on' ? 'noteFromArchive' : 'noteToArchive'
value = ''
break break
case 'delete' : case 'delete' :
attrs.class = 'icon icon-delete grid-control' attrs.class = 'icon icon-delete grid-control'
@@ -172,11 +234,70 @@ export default class DOMController {
for (let key of formData.keys()) { for (let key of formData.keys()) {
data[key] = formData.get(key) data[key] = formData.get(key)
} }
return data return data
} }
/** /**
*
* @param args
*/
getEditForm (args = {}) {
const node = createNode('div', { class: window.env.querySelectors.modal.slice(1) },
Templates.templates.editForm)
if (args.legend) {
node.querySelector('legend').innerHTML = args.legend
} else {
DOMController.fillTheForm(node, args)
}
this.root.appendChild(node)
node.style.display = 'block'
const contentInput = node.querySelector('textarea[maxlength]')
const titleInput = node.querySelector('input[maxlength]')
this.listener([
[node.querySelector(window.env.querySelectors.btnDestroyModal), 'click', destroyNode, node], //Remove modal dialog
[node.querySelector('form'), 'submit', NotesAPI.saveNote],
[contentInput, 'keydown', ValidationController.lengthOnKeyUp, contentInput],
[titleInput, 'keydown', ValidationController.lengthOnKeyUp, titleInput],
])
}
/**
*
* @param $form
* @param $el
*/
static fillTheForm ($form, $el) {
if ($el instanceof Element) {
const note = NotesAPI.getNoteByID(+$el.closest('tr').dataset.id)
if (note.length === 1) {
for (const [key, value] of Object.entries(note[0])) {
const $input = $form.querySelector(`[name='${key}']`)
if ($input instanceof Element) {
if ($input.type === 'checkbox') {
if (value !== '') {
$input.click()
}
} else {
$input.value = value
}
}
}
}
}
}
/**
* The function takes single DOM element or list of them
* *
* @param els * @param els
* @returns {void|*} * @returns {void|*}
@@ -184,15 +305,16 @@ export default class DOMController {
listener (els) { return els[0] instanceof Element ? this.on(els) : els.forEach(el => this.on(el)) } listener (els) { return els[0] instanceof Element ? this.on(els) : els.forEach(el => this.on(el)) }
/** /**
* * TODO: guessed this should be rethought
* @param args //selector, event, method, params * @param args
*/ */
on (args) { on (args) {
const [selector, event, method] = args const [selector, event, method] = args
if (!(selector instanceof Element)) { if (!(selector instanceof Element)) {
return Alert.displayDialog(`Internal Error: Try reload a page`, 3000, 3)
return false
} }
try { try {
@@ -207,7 +329,7 @@ export default class DOMController {
evt.preventDefault() evt.preventDefault()
setTimeout(() => { setTimeout(() => {
this.createNotesGrid(window.env.prePopulateAmount || 0) document.querySelector('.nav-tab.uk-active > a').click()
}, 300) }, 300)
} }
@@ -218,26 +340,13 @@ export default class DOMController {
} }
}) })
return true
} catch (err) { } catch (err) {
console.error(err) Alert.displayDialog(`Error: ${err.toString()}`, 3000, 3)
return false
} }
} }
getEditForm (args = {}) {
const node = createNode('div', { class: window.env.querySelectors.modal.slice(1) },
Templates.templates.editForm)
if (args.legend) {
node.querySelector('legend').innerHTML = args.legend
}
this.root.appendChild(node)
node.style.display = 'block'
this.listener([
[node.querySelector(window.env.querySelectors.btnDestroyModal), 'click', destroyNode, node], //Remove modal dialog
[node.querySelector('form'), 'submit', NotesAPI.saveNote],
])
}
} }

View File

@@ -1,24 +1,41 @@
import DOMController from './DOMController' import DOMController from './DOMController'
import Validation from './ValidationController' import Validation from './ValidationController'
import { fakerDB } from '../faker'
import Alert from './AlertController'
export default class NotesAPI{ export default class NotesAPI {
/**
*
* @returns {any}
* @param save
*/
static getStorage (save = true) {
const key = window.env.localStorageKey
let storage = localStorage.getItem(key)
if (storage === null) {
storage = JSON.stringify(fakerDB(env.fakerAmount)) || '[]'
if (save) localStorage.setItem(key, storage)
}
return JSON.parse(storage)
}
/** /**
* *
* @param n * @param n
* @param archive * @param archive
* @param key
* @returns {*} * @returns {*}
*/ */
static getNotes (n, archive = false, key = (window.env.localStorageKey || '') ) { static getNotes (n = 0, archive = false) {
let notes = JSON.parse(localStorage.getItem(key) || '[]') let notes = NotesAPI.getStorage()
if( typeof archive === 'boolean' ){ if (typeof archive === 'boolean') {
notes = notes.filter( el => ( archive ? el.archive === 'on' : el.archive !== 'on' ) ) notes = notes.filter(el => (archive ? el.archive === 'on' : el.archive !== 'on'))
} }
notes.sort((a, b) => { notes.sort((a, b) => {
return new Date(a.createdAt) > new Date(b.createdAt) ? -1 : 1 return new Date(a.createdAt) > new Date(b.createdAt) ? -1 : 1
}) })
@@ -26,37 +43,46 @@ export default class NotesAPI{
return n > 0 ? notes.slice(0, n) : notes return n > 0 ? notes.slice(0, n) : notes
} }
/**
*
* @param id
* @returns {*}
*/
static getNoteByID (id) {
return NotesAPI.getStorage().filter(el => el.id === id)
}
/** /**
* *
* @param n * @param n
* @param archive * @param archive
* @returns {*[]|[]} * @returns {*[]|[]}
*/ */
static getNotesSanitized( n = 0, archive = false){ static getNotesSanitized (n = 0, archive = false) {
let notes = NotesAPI.getNotes(0, archive) let notes = NotesAPI.getNotes(0, archive)
notes = Validation.allAgainstSchema(notes, window.env.schemas.note ) notes = Validation.allAgainstSchema(notes, window.env.schemas.note)
return n > 0 ? notes.slice(0, n) : notes return n > 0 ? notes.slice(0, n) : notes
} }
/** /**
* *
* @param noteToStore * @param noteToStore
* @param action
*/ */
static saveNote (noteToStore = null) { static saveNote (noteToStore = null, action = 'modal') {
if( Object.keys(noteToStore).length === 0 ){ if (Object.keys(noteToStore).length === 0) {
noteToStore = DOMController.getFormData() noteToStore = DOMController.getFormData()
} }
const isValid = Validation.againstSchema( noteToStore, window.env.schemas.note ) const isValid = Validation.againstSchema(noteToStore, window.env.schemas.note)
if( isValid.status === true ){ if (isValid.status === true) {
noteToStore = isValid.data noteToStore = isValid.data
const notes = NotesAPI.getNotes(0, null)
const notes = NotesAPI.getNotes() const noteExists = notes.find(note => note.id === +noteToStore.id)
const noteExists = notes.find(note => note.id === noteToStore.id)
if (noteExists) { if (noteExists) {
noteExists.title = noteToStore.title noteExists.title = noteToStore.title
@@ -70,12 +96,16 @@ export default class NotesAPI{
noteToStore.createdAt = new Date().toISOString() noteToStore.createdAt = new Date().toISOString()
notes.push(noteToStore) notes.push(noteToStore)
} }
NotesAPI.saveNotesToStorage(notes) NotesAPI.saveNotesToStorage(notes)
document.querySelector( window.env.querySelectors.noteEditForm ).closest('.modal').remove() if (action === 'modal') {
//TODO: Need to implement in different way
document.querySelector(window.env.querySelectors.noteEditForm).closest('.modal').remove()
}
} else { } else {
DOMController.alert( 'Could save the note! ' + isValid.errors.join(', '),6666, 2 ) //, document.getElementById('modalMsgBox') Alert.displayDialog('Could save the note! ' + isValid.errors.join(', '), 6000, 2) //, document.getElementById('modalMsgBox')
} }
} }
@@ -85,11 +115,35 @@ export default class NotesAPI{
* @param id * @param id
*/ */
static deleteNote (id) { static deleteNote (id) {
const notes = NotesAPI.getNotes() const notes = NotesAPI.getStorage()
const filteredNotesByID = notes.filter(note => note.id !== id) const filteredNotesByID = notes.filter(note => note.id !== id)
NotesAPI.saveNotesToStorage(filteredNotesByID) NotesAPI.saveNotesToStorage(filteredNotesByID)
} }
static unArchiveNote (id) {
this.archiveNote(id, '')
}
/**
*
* @param id
* @param value
*/
static archiveNote (id, value = 'on') {
if (value !== '') value = 'on'
let note = NotesAPI.getNoteByID(id)
if (note.length > 0 && note[0].archive !== value) {
note[0].archive = value
NotesAPI.saveNote(note[0], 'archive')
return true
}
return false
}
/** /**
* *
* @param notes * @param notes
@@ -98,4 +152,32 @@ export default class NotesAPI{
static saveNotesToStorage (notes, key = window.env.localStorageKey) { static saveNotesToStorage (notes, key = window.env.localStorageKey) {
localStorage.setItem(key, JSON.stringify(notes, null, 2)) localStorage.setItem(key, JSON.stringify(notes, null, 2))
} }
/**
*
* @returns {{}}
*/
static getAnalytics () {
const analytics = {}
const data = NotesAPI.getStorage()
const cats = [...new Set(data.map(item => item.category))]
if (typeof cats[0] !== 'undefined') {
const isArchive = data.map(item => {
const container = {}
container[item.category] = item.archive
return container
})
cats.forEach((cat, i) => {
analytics[cat] = {
Active: isArchive.filter(el => el[cat] === 'on').length,
Archived: isArchive.filter(el => el[cat] == '').length,
}
})
}
return analytics
}
} }

View File

@@ -0,0 +1,55 @@
import Views from '../templates/Views'
export default class RouteController {
constructor () {
document.addEventListener('DOMContentLoaded', e => {
this._navigation()
this._history()
})
}
get routes () {
return window.env.routes
}
/**
*
* @returns {*}
*/
get navbar () {
return document.getElementById(window.env.querySelectors.navTabs.slice(1))
}
get page404(){
document.body.innerHTML = Views.templates.notFound
setTimeout( () => {
window.location.assign('/')
}, 5000)
}
/**
*
* @private
*/
_navigation(){
if( Object.keys(this.routes).filter( path => window.location.pathname === path ).length === 0 ){
this.page404
} else{
document.querySelector( `a[href='${window.location.pathname}']` ).click()
}
}
_history(){
window.addEventListener('popstate', event => {
try {
document.querySelector('.uk-active').classList.remove('uk-active')
document.querySelector(window.env.querySelectors.navTabs + ` a[href='${event.target.location.pathname}']`).closest('.nav-tab').classList.add('uk-active')
} catch (e) {}
})
}
}

View File

@@ -1,14 +1,21 @@
import { env } from '../helpers'
export default class ValidationController { export default class ValidationController {
/**
static allAgainstSchema(array, schema) { *
* @param array
* @param schema
* @returns {*[]}
*/
static allAgainstSchema (array, schema) {
const objs = [] const objs = []
array.forEach( obj => { array.forEach(obj => {
const res = this.againstSchema(obj, schema) const res = this.againstSchema(obj, schema)
if( res.status === true ){ if (res.status === true) {
objs.push( res.data ) objs.push(res.data)
} }
}) })
@@ -38,17 +45,22 @@ export default class ValidationController {
const field = (obj[key] || '').toString().trim() const field = (obj[key] || '').toString().trim()
if (field !== '') { if (field !== '') {
const regex = new RegExp(value[1].toString(), 'i')
if (regex.exec(field)) { if (typeof value[1] !== 'number') {
out.data[key] = field const regex = new RegExp(value[1].toString(), 'i')
} else { if (regex.exec(field)) {
out.data[key] = field
if (value[0]) { } else {
out.errors.push(key)
out.error_text.push(`${key} is required`) if (value[0]) {
out.errors.push(key)
out.error_text.push(`${key} is required`)
}
} }
} else if (field.length > 0) {
out.data[key] = field.slice(0, value[1])
} }
} else { } else {
@@ -61,9 +73,7 @@ export default class ValidationController {
} }
} catch (e) { } catch (e) {
out.error_text.push(`Critical error! ` + e.toString())
console.error(e.toString())
out.error_text.push(`Critical error! See console`)
} }
out.status = !(out.error_text.length > 0 && out.errors.length > 0) out.status = !(out.error_text.length > 0 && out.errors.length > 0)
@@ -71,4 +81,18 @@ export default class ValidationController {
return out return out
} }
/**
*
* @param node
*/
static lengthOnKeyUp (node) {
const logger = document.querySelector(`[for='${node.id}'] > span`)
logger.innerHTML = `${node.value.length}/${env.schemas.note[node.getAttribute('name')][1]}`
node.value.length > env.schemas.note[node.getAttribute('name')][1]
? logger.classList.add('uk-text-danger')
: logger.classList.remove(
'uk-text-danger')
}
} }

View File

@@ -1,5 +1,4 @@
body{ body{
background-color: ghostwhite;
margin-top: 100px; margin-top: 100px;
} }
@@ -19,8 +18,12 @@ tbody td{
display: flex; display: flex;
z-index: 2; z-index: 2;
position: fixed; position: fixed;
bottom: 2rem; bottom: 0;
right: 2rem; right: 0;
white-space: pre-wrap;
font-family: Consolas, monospace;
box-sizing: content-box;
overflow: hidden;
} }
.icon{ .icon{
@@ -31,12 +34,23 @@ tbody td{
.icon.grid-control{ .icon.grid-control{
cursor: pointer; cursor: pointer;
filter: opacity(.5);
transition: transform 250ms; transition: transform 250ms;
} }
.icon.grid-control:hover{ .icon.grid-control:hover{
filter: brightness(0.1) sepia(1) hue-rotate(90deg) saturate(1); filter: opacity(1);
transform: translateY(5%); }
.icon.grid-control:not(.icon-unarchive):hover{
transform: translateY(4px);
}
.icon.grid-control.icon-unarchive:hover{
transform: translateY(-4px);
}
.icon.as-gray{
filter: grayscale(1);
} }
@keyframes fadeInAnimation { @keyframes fadeInAnimation {
@@ -49,7 +63,7 @@ tbody td{
} }
.as-removing{ .as-removing{
animation: fadeInAnimation ease 3s; animation: fadeInAnimation ease 1s;
animation-iteration-count: 1; animation-iteration-count: 1;
animation-fill-mode: forwards; animation-fill-mode: forwards;
} }
@@ -60,17 +74,22 @@ tbody td{
} }
.icon-edit{ .icon-edit{
background-image: url(../images/edit_black_48dp.svg) background-image: url(../images/edit_48dp.svg)
} }
.icon-archive{ .icon-archive{
background-image: url(../images/archive_black_48dp.svg) background-image: url(../images/archive_48dp.svg)
}
.icon-unarchive{
background-image: url(../images/unarchive_48dp.svg)
} }
.icon-delete{ .icon-delete{
background-image: url(../images/delete_black_48dp.svg) background-image: url(../images/delete_48dp.svg)
} }
/* The Modal (background) */ /* The Modal (background) */
#noteEditFormModal, .modal { #noteEditFormModal, .modal {
display: none; /* Hidden by default */ display: none; /* Hidden by default */
@@ -112,3 +131,10 @@ tbody td{
text-decoration: none; text-decoration: none;
cursor: pointer; cursor: pointer;
} }
input[readonly]{
outline: none;
border: none;
background: transparent;
color: #666;
}

15
src/templates/404.js Normal file
View File

@@ -0,0 +1,15 @@
export default `<div class="uk-container uk-text-center">
<div class="uk-container">
<ul id="asSwitcher"
class="uk-subnav uk-subnav-divider uk-margin-large-bottom uk-flex-center">
<li class="nav-tab"><a href="/all">All Notes</a></li>
<li class="nav-tab initial uk-active"><a href="/">Recent Notes</a></li>
<li class="nav-tab"><a href="/archive">Archived Notes</a></li>
<li class="nav-tab"><a href="/analytics">Analytics</a></li>
</ul>
</div>
<h1 class=" uk-text-danger">404 - NOT FOUND</h1>
<div class="uk-text-large uk-text-muted uk-text-bold">U will be redirected soon</div>
</div>`

View File

@@ -1,12 +1,11 @@
import grid from './grid' import grid from './grid'
import editForm from './editForm' import editForm from './editForm'
//import gridRow from '../../.trash/gridRow' import _404 from './404'
export default { export default {
templates: { templates: {
notFound: _404,
editForm: editForm, editForm: editForm,
// gridRow: gridRow
}, },
grid: grid grid: grid
} }

View File

@@ -1,12 +1,20 @@
import { env } from '../helpers'
export default `<form id="noteEditForm" class="uk-form-horizontal uk-margin-large modal-content" style="background: ghostwhite"> export default `<form id="noteEditForm" class="uk-form-horizontal uk-margin-large modal-content" style="background: ghostwhite">
<fieldset class="uk-fieldset"> <fieldset class="uk-fieldset">
<legend class="uk-legend">Edit Note</legend> <legend class="uk-legend">
<span class="uk-float-right uk-text-small">
created: <input class="" type="text" name="createdAt" readonly="readonly" value="" placeholder="0000-00-00">
updated: <input type="text" name="updatedAt" readonly="readonly" value="" placeholder="0000-00-00">
</span>
<span>Edit Note #<input class="uk-text-large" type="text" name="id" readonly="readonly" value="" placeholder="0"></span>
</legend>
<div id="modalMsgBox"></div> <div id="modalMsgBox"></div>
<div class="uk-margin"> <div class="uk-margin">
<label class="uk-form-label" for="formTitle">Title</label> <label class="uk-form-label" for="formTitle">Title <span></span></label>
<div class="uk-form-controls"> <div class="uk-form-controls">
<input id="formTitle" name="title" class="uk-input" type="text" maxlength="127" placeholder="Add a title..."> <input id="formTitle" name="title" class="uk-input" type="text" maxlength="${env.schemas.note.title[1]}" placeholder="Add a title...">
</div> </div>
</div> </div>
@@ -25,13 +33,14 @@ export default `<form id="noteEditForm" class="uk-form-horizontal uk-margin-larg
</div> </div>
<div class="uk-margin"> <div class="uk-margin">
<textarea name="content" class="uk-textarea" rows="6" placeholder="Description..."></textarea> <label class="uk-form-label" for="noteContentInput">Description <span></span></label>
<textarea id="noteContentInput" name="content" class="uk-textarea" rows="6" maxlength="${env.schemas.note.content[1]}" placeholder="Description..."></textarea>
</div> </div>
<div class="uk-margin"> <div class="uk-margin">
<label class="uk-form-label uk-float-right" for="formArchived">Archived</label> <label class="uk-form-label uk-float-right" for="formArchived">Archived</label>
<div class="uk-form-controls"> <div class="uk-form-controls">
<input id="formArchived" name="archive" class="uk-checkbox" type="checkbox"> <input id="formArchived" name="archive" class="uk-checkbox" type="checkbox">
</div> </div>
</div> </div>

View File

@@ -1,20 +1,11 @@
export default ` export default `
<div id="as-navbar" class="uk-background-secondary"> <nav id="as-navbar" class="uk-background-secondary">
<div class="uk-container"> <div class="uk-container">
<div class="uk-float-right uk-margin-top uk-margin-right"> <ul id="asSwitcher" class="uk-subnav uk-subnav-pill uk-margin-small-top uk-margin-small-bottom uk-padding-small"></ul>
<button id="btnCreateNote" class="uk-button uk-button-primary" data-action="getEditForm">Create Note</button> </div>
</div> </nav>
<ul id="asSwitcher" class="uk-subnav uk-subnav-pill uk-margin-small-top uk-margin-small-bottom uk-padding-small"> <table id="notesGrid" class="uk-table uk-table-small uk-table-striped uk-table-hover uk-table-divider">
<li class="nav-tab"><a href="/all">All Notes</a></li> <col width="156">
<li class="nav-tab uk-active"><a href="/">Recent Notes</a></li>
<li class="nav-tab"><a href="/archived">Archived Notes</a></li>
<li class="nav-tab"><a href="/analytics">Analytics</a></li>
</ul>
</div>
</div>
<table id="notesGrid" class="uk-table uk-table-small uk-table-responsive1 uk-table-striped uk-table-hover uk-table-divider">
<col width="150">
<col width="250"> <col width="250">
<col width="150"> <col width="150">
<col> <col>
@@ -30,15 +21,40 @@ export default `
<th>Content</th> <th>Content</th>
<th>Dates</th> <th>Dates</th>
<th></th> <th></th>
<th class="icon icon-archive"></th> <th class="icon icon-archive as-gray"></th>
<th class="icon icon-delete"></th> <th class="icon icon-delete as-gray"></th>
</tr> </tr>
</thead> </thead>
<tbody> <tbody>
</tbody> </tbody>
<!--<tr> </table>
<td colspan="8" class="uk-margin uk-text-right">
<button id="btnCreateNote" class="uk-button uk-button-primary" data-action="getEditForm">Create Note</button> <table id="analyticsGrid" class="uk-table uk-table-small uk-table-striped uk-table-hover uk-table-divider uk-hidden">
</td> <col width="156">
</tr>--> <col width="250">
</table>` <col width="150">
<thead>
<tr>
<th>Note Category</th>
<th>Active</th>
<th>Archived</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div class="uk-margin" uk-margin>
<div class="uk-margin-large-top">
<button id="btnCreateNote" class="uk-button uk-button-primary uk-text-bold uk-border-rounded uk-float-right" data-action="getEditForm">Create Note</button>
<select id="selectPrepopulate" class="uk-input uk-form-width-medium">
<option value="" selected disabled>Select amount to...</option>
<option>7</option>
<option>15</option>
<option>25</option>
<option>44</option>
</select>
<button id="btnPrepopulate" class="uk-button uk-button-danger uk-text-bold uk-border-rounded" data-action="prePopulate">Pre-populate</button>
</div>
</div>
`

View File

@@ -102,13 +102,15 @@ module.exports = {
}, },
], ],
}, },
entry: { app: './src/index' }, //
entry: { faker: './src/faker', app: './src/index' },
output: { output: {
path: path.resolve(__dirname, 'dist'), path: path.resolve(__dirname, 'dist'),
filename: '[name].[hash].js', filename: '[name].[hash].js',
}, },
plugins: plugins, plugins: plugins,
devtool: mode === 'production' ? 'source-map' : (process.env.SOURCE_MAP_ENV ? 'eval-cheap-module-source-map' : false), devtool: mode !== 'production' ? (process.env.SOURCE_MAP_ENV ? 'eval-cheap-module-source-map' : false) : false,
// devtool: 'source-map',
optimization: { optimization: {
minimize: isProd, minimize: isProd,
splitChunks: { splitChunks: {
@@ -137,6 +139,11 @@ module.exports = {
static: path.resolve(__dirname, 'dist'), static: path.resolve(__dirname, 'dist'),
compress: true, compress: true,
port: 1976, port: 1976,
//disableHostCheck: true,
allowedHosts: [
'dev.amok.space',
],
liveReload: true, liveReload: true,
historyApiFallback: true,
}, },
} }