Skip to content

Commit

Permalink
CRUD projetos funcionando
Browse files Browse the repository at this point in the history
  • Loading branch information
andreeluis committed Dec 1, 2023
1 parent c846935 commit 717409e
Show file tree
Hide file tree
Showing 5 changed files with 241 additions and 137 deletions.
84 changes: 10 additions & 74 deletions src/projetos/assets/css/projetos.css
Original file line number Diff line number Diff line change
@@ -1,84 +1,20 @@
.card-content {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-height: 3em;
}

.card img {
max-width: 100%;
max-height: 250px;
object-fit: cover;
}



main article {
background-color: var(--light-grey);
margin: 2em auto;
padding: 1.5em 2.5em;
width: 90%;
border-radius: 1.5vmax;
}

main article.autor {
border: 2px solid var(--principal-blue);
}

#projects {
display: inline-block;
}

#projects a {
color: inherit;
}

#projects article h3 {
color: var(--principal-blue);
display: inline;
margin: 0 1em 0 0;
vertical-align: middle;
}

#projects article p.categoria {
.itens-list article p.dificuldade {
display: inline-block;
padding: .3em .6em;
background-color: var(--grey);
padding: .3em .6em;
color: var(--white);
font-weight: bold;
border-radius: .5vmax;
}

#projects article .engajamento {
display: inline;
vertical-align: middle;
font-size: 1.2em;
float: right;
}

#projects article .engajamento span {
margin-right: 1em;
}

#projects article .engajamento button {
padding: 0;
border: none;
background: none;
font-size: 1em;
}

#projects article .engajamento button:hover {
cursor: pointer;
border-radius: .5vmax;
}

#projects article .engajamento .edit {
color: var(--blue);
.itens-list article p.easy {
background-color: var(--light-green);
}

#projects article .engajamento .delete {
color: var(--red);
.itens-list article p.medium {
background-color: var(--light-yellow);
color: var(--black);
}

#projects article .engajamento button i {
margin-left: .5em;
.itens-list article p.hard {
background-color: var(--light-red);
}
174 changes: 162 additions & 12 deletions src/projetos/assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,183 @@
let projectsList;

window.addEventListener('load', ShowProjects, false);
const Dificuldades = {
easy: 'Fácil',
medium: 'Médio',
hard: 'Difícil'
};

const form = document.querySelector('#modal form');

window.addEventListener('load', ShowProjects, false);
document.querySelector('#add-project').addEventListener('click', addProject, false);

// READ
async function LoadProjects() {
try { projectsList = await (await fetch(`${apiURL}/projetos`)).json() }
catch (error) { console.error('Falha ao carregar os projetos:', error) }
}

function generateHTML(project) {
const { id, titulo, categoria, dificuldade, conteudo, imagem, autor, usuario } = project;
const isAuthor = isLogged() && JSON.parse(sessionStorage.getItem('user')).id == usuario;

return `
<article ${isAuthor ? `class="autor"` : ''}>
<a href="projeto.html?id=0">
<h3 class="titulo">${titulo}</h3>
</a>
<p class="categoria">${categoria}</p>
<p class="dificuldade ${dificuldade}">${Dificuldades[dificuldade]}</p>
${isAuthor ? `
<div class="handle-item">
<span>
<button value="${id}" class="edit"><i class="fas fa-edit"></i></button>
<button value="${id}" class="delete"><i class="fas fa-trash-alt"></i></button>
</span>
</div>` :
'' }
<p id="conteudo">${conteudo}</p>
</article>
`;
}

async function ShowProjects() {
try {
await LoadProjects();

const textoHTML = projectsList.map(project => `
<article>
<a href="projeto.html?id=0">
<h3 class="titulo">${project.titulo}</h3>
</a>
<p class="categoria">${project.categoria}</p>
<p class="categoria">${project.dificuldade}</p>
<p id="conteudo">${project.conteudo}</p>
</article>
`).join('');
const textoHTML = projectsList.map(generateHTML).join('');

document.querySelector("#projects").innerHTML = textoHTML;

// Event listeners
document.querySelectorAll('.edit').forEach(button => {
button.addEventListener('click', editProject, false);
});
document.querySelectorAll('.delete').forEach(button => {
button.addEventListener('click', deleteProject, false);
});
}
catch (error) {
console.error('Falha ao exibir os projetos:', error);
}
}

// CREATE
function addProject() {
console.log('addPost()');
if (isLogged()) {
openAddModal();

form.removeEventListener('submit', handleEditSubmit, false);
form.removeEventListener('submit', handleAddSubmit, false);
form.addEventListener('submit', handleAddSubmit, false);
} else {
alert('Você precisa estar conectado para criar um novo projeto!');
window.location.href = '../login.html';
}
}

async function handleAddSubmit(event) {
event.preventDefault();

const newProject = {
id: generateUUID(8),
titulo: document.querySelector('#modal form #title').value,
categoria: document.querySelector('#modal form #category').value,
dificuldade: document.querySelector('#modal form #difficulty').value,
conteudo: document.querySelector('#modal form #content').value,
imagem: '',
autor: JSON.parse(sessionStorage.getItem('user')).name,
usuario: JSON.parse(sessionStorage.getItem('user')).id
};

try {
const response = await fetch(`${apiURL}/projetos`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(newProject),
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

ShowProjects();
closeModal();

} catch (error) { console.error('Falha ao adicionar o projeto:', error); }
}


// UPDATE
function editProject() {
id = this.value;
const project = projectsList.find(project => project.id == id);

openEditModal(project);

form.removeEventListener('submit', handleAddSubmit, false);
form.removeEventListener('submit', handleEditSubmit, false);
form.addEventListener('submit', handleEditSubmit, false);
}

async function handleEditSubmit(event) {
event.preventDefault();

const updatedProject = {
titulo: document.querySelector('#modal form #title').value,
categoria: document.querySelector('#modal form #category').value,
dificuldade: document.querySelector('#modal form #difficulty').value,
conteudo: document.querySelector('#modal form #content').value
};

try {
const response = await fetch(`${apiURL}/projetos/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updatedProject)
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

await ShowProjects();
closeModal();
} catch (error) {
console.error('Falha ao atualizar o projeto:', error);
}
}


// DELETE
async function deleteProject() {
const id = this.value;
const project = projectsList.find(project => project.id == id);

const confirmDelete = window.confirm(`Você realmente quer excluir ${project.titulo}?`);
if (confirmDelete) {
try {
const response = await fetch(`${apiURL}/projetos/${id}`, {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
}
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

ShowProjects();
}
catch (error) {
console.error('Falha ao deletar o projeto:', error);
}
}
}
40 changes: 40 additions & 0 deletions src/projetos/assets/js/modal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
const modal = document.querySelector("#modal");

document.querySelector('#close-modal').addEventListener('click', closeModal, false);
window.addEventListener('click', event => { event.target == modal ? closeModal() : null; }, false);

const modalTitle = document.querySelector('#modal h3');
const modalButton = document.querySelector('#modal form button');

const inputTitle = document.querySelector('#modal form #title');
const inputCategory = document.querySelector('#modal form #category');
const inputDifficulty = document.querySelector('#modal form #difficulty');
const inputContent = document.querySelector('#modal form #content');

function openAddModal() {
modalTitle.innerHTML = 'Adicionar post';
modalButton.innerHTML = 'Adicionar';

inputTitle.value = '';
inputCategory.value = '';
inputContent.value = '';

modal.style.display = "block";
}

function openEditModal(project) {
modalTitle.innerHTML = 'Editar post';
modalButton.innerHTML = 'Editar';

inputTitle.value = project.titulo;
inputCategory.value = project.categoria;
inputDifficulty.value = project.dificuldade;
inputContent.value = project.conteudo;

modal.style.display = "block";
}

function closeModal() {
modal.style.display = "none";
}

42 changes: 0 additions & 42 deletions src/projetos/assets/js/projeto.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,45 +22,3 @@ async function showProject() {
console.error('Falha ao carregar e exibir os posts:', error);
}
}

async function addComentario(event) {
event.preventDefault();

await loadPost();

const novoComentario = {
id: generateUUID(8),
autor: JSON.parse(sessionStorage.getItem('user')).name,
usuario: JSON.parse(sessionStorage.getItem('user')).id,
comentario: document.querySelector('#comentario').value,
};

fetch(`${apiURL}/posts/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
//body: JSON.stringify({ novoComentario }),
body: JSON.stringify({ comentarios: [...post.comentarios, novoComentario] }),
})
.then(() => showPost())
.catch(error => {
console.error('Erro ao inserir comentario via API JSONServer:', error);
});
}

async function addCurtida() {
await loadPost();

fetch(`${apiURL}/posts/${id}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ curtidas: post.curtidas + 1 }),
})
.then(() => showPost())
.catch(error => {
console.error('Erro ao inserir curtida via API JSONServer:', error);
});
}
Loading

0 comments on commit 717409e

Please sign in to comment.