Merge branch '22-integrate-api-and-frontend' into 'main'

Integrate API and frontend

See merge request padas/24ss-5430-web-and-data-eng/gruppe-3/datadash!28
This commit is contained in:
Elias Schriefer
2024-07-01 14:45:48 +02:00
18 changed files with 604 additions and 254 deletions

View File

@@ -0,0 +1,18 @@
package de.uni_passau.fim.PADAS.group3.DataDash.controler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import de.uni_passau.fim.PADAS.group3.DataDash.model.Category;
import org.springframework.web.bind.annotation.GetMapping;
@RestController
@RequestMapping("/api/v1/categories")
public class CategoryController {
@GetMapping
public Category[] getMethodName() {
return Category.values();
}
}

View File

@@ -4,6 +4,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import de.uni_passau.fim.PADAS.group3.DataDash.model.Category;
import de.uni_passau.fim.PADAS.group3.DataDash.model.Dataset; import de.uni_passau.fim.PADAS.group3.DataDash.model.Dataset;
import de.uni_passau.fim.PADAS.group3.DataDash.model.DatasetService; import de.uni_passau.fim.PADAS.group3.DataDash.model.DatasetService;
import de.uni_passau.fim.PADAS.group3.DataDash.model.Type; import de.uni_passau.fim.PADAS.group3.DataDash.model.Type;
@@ -51,42 +53,42 @@ public class DatasetController {
datasetService.deleteDataset(id); datasetService.deleteDataset(id);
} }
@PostMapping("/id/{id}/upvote") @PutMapping("/id/{id}/upvote")
public Dataset upvote(@PathVariable("id") UUID id) { public Dataset upvote(@PathVariable("id") UUID id) {
datasetService.upvoteDataset(id); datasetService.upvoteDataset(id);
return null; return datasetService.getDatasetById(id);
} }
@PostMapping("/id/{id}/downvote") @PutMapping("/id/{id}/downvote")
public Dataset downvote(@PathVariable("id") UUID id) { public Dataset downvote(@PathVariable("id") UUID id) {
datasetService.downvoteDataset(id); datasetService.downvoteDataset(id);
return null; // new ResponseEntity<>(null, HttpStatus.OK); return getDatasetById(id); // new ResponseEntity<>(null, HttpStatus.OK);
} }
@PostMapping("/id/{id}/vote") @PutMapping("/id/{id}/stars")
public String postMethodName(@PathVariable("id") UUID id, public Dataset postMethodName(@PathVariable("id") UUID id,
@RequestParam("stars") int stars) { @RequestParam("stars") int stars) {
if (stars > 0 && stars < 6) { if (stars > 0 && stars < 6) {
datasetService.voteDataset(id, stars); datasetService.voteDataset(id, stars);
return null;
} }
return "Invalid vote"; return datasetService.getDatasetById(id);
} }
@GetMapping @GetMapping
public Page<Dataset> getDatasetsByDateAfter(@RequestParam(value = "author", required = false) String author, public Page<Dataset> getDatasetsByDateAfter(@RequestParam(value = "author", required = false) String author,
@RequestParam(value = "title", required = false) String title, @RequestParam(value = "title", required = false) String title,
@RequestParam(value = "description", required = false) String description, @RequestParam(value = "description", required = false) String description,
@RequestParam(value = "abst", required = false) String abst, @RequestParam(value = "abst", required = false) String abst,
@RequestParam(value = "type", required = false) Type type, @RequestParam(value = "type", required = false) Type type,
@RequestParam(value = "min-raiting", required = false) Float raiting, @RequestParam(value = "min-rating", required = false) Float rating,
@RequestParam(value = "page", required = false, defaultValue = "0") int page, @RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "20") int size, @RequestParam(value = "size", required = false, defaultValue = "20") int size,
@RequestParam(value = "sort", required = false, defaultValue = "upvotes") String sort, @RequestParam(value = "sort", required = false, defaultValue = "upvotes") String sort,
@RequestParam(value = "direction", required = false, defaultValue = "desc") String direction) { @RequestParam(value = "direction", required = false, defaultValue = "desc") String direction,
@RequestParam(value = "category", required = false) Category category) {
Pageable pageable = PageRequest.of(page, size, Pageable pageable = PageRequest.of(page, size,
Sort.by(direction.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sort)); Sort.by(direction.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sort));
return datasetService.getDatasetsByOptionalCriteria(title, description, author, abst, type, raiting, pageable); return datasetService.getDatasetsByOptionalCriteria(title, description, author, abst, type, rating, category,pageable);
} }
@GetMapping("/search") @GetMapping("/search")
@@ -94,10 +96,12 @@ public class DatasetController {
@RequestParam(value = "page", required = false, defaultValue = "0") int page, @RequestParam(value = "page", required = false, defaultValue = "0") int page,
@RequestParam(value = "size", required = false, defaultValue = "20") int size, @RequestParam(value = "size", required = false, defaultValue = "20") int size,
@RequestParam(value = "sort", required = false, defaultValue = "upvotes") String sort, @RequestParam(value = "sort", required = false, defaultValue = "upvotes") String sort,
@RequestParam(value = "direction", required = false, defaultValue = "desc") String direction) { @RequestParam(value = "direction", required = false, defaultValue = "desc") String direction,
@RequestParam(value = "category", required = false, defaultValue = "%") String category,
@RequestParam(value = "type", required = false, defaultValue = "%") String type){
Pageable pageable = PageRequest.of(page, size, Pageable pageable = PageRequest.of(page, size,
Sort.by(direction.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sort)); Sort.by(direction.equals("asc") ? Sort.Direction.ASC : Sort.Direction.DESC, sort));
return datasetService.searchByOptionalCriteria(search, pageable); return datasetService.searchByOptionalCriteria(search, category, type, pageable);
} }
} }

View File

@@ -0,0 +1,12 @@
package de.uni_passau.fim.PADAS.group3.DataDash.controler;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class PageController {
@GetMapping("/add")
public String getAddPage() {
return "add";
}
}

View File

@@ -0,0 +1,14 @@
package de.uni_passau.fim.PADAS.group3.DataDash.model;
public enum Category {
HEALTH,
ENVIRONMENT,
ECONOMY,
POLITICS,
TECHNOLOGY,
SPORTS,
SCIENCE,
CULTURE,
EDUCATION,
OTHER
}

View File

@@ -3,6 +3,7 @@ package de.uni_passau.fim.PADAS.group3.DataDash.model;
import java.net.URL; import java.net.URL;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.UUID; import java.util.UUID;
import java.sql.Date;
import jakarta.persistence.Entity; import jakarta.persistence.Entity;
import jakarta.persistence.EnumType; import jakarta.persistence.EnumType;
@@ -29,7 +30,7 @@ public class Dataset {
private String author; private String author;
private LocalDate date; private Date date;
private float raiting; private float raiting;
@@ -38,10 +39,10 @@ public class Dataset {
private int upvotes; private int upvotes;
private URL url; private URL url;
@Enumerated(EnumType.STRING)
private Category categorie;
private String[] categories; public Dataset(String title, String abst, String description, String author, URL url, Category categories, Type type) {
public Dataset(String title, String abst, String description, String author, URL url, String[] categories, Type type) {
this.raiting = 0; this.raiting = 0;
this.votes = 0; this.votes = 0;
@@ -51,7 +52,7 @@ public class Dataset {
setDescription(description); setDescription(description);
setAuthor(author); setAuthor(author);
setDate(LocalDate.now()); setDate(LocalDate.now());
setCategories(categories); setCategorie(categories);
setType(type); setType(type);
setUrl(url); setUrl(url);
} }
@@ -68,12 +69,12 @@ public class Dataset {
return author; return author;
} }
public String[] getCategories() { public Category getCategorie() {
return categories; return categorie;
} }
public LocalDate getDate() { public LocalDate getDate() {
return date; return date.toLocalDate();
} }
public String getDescription() { public String getDescription() {
@@ -116,12 +117,12 @@ public class Dataset {
this.author = author; this.author = author;
} }
public void setCategories(String[] categories) { public void setCategorie(Category categories) {
this.categories = categories; this.categorie = categories;
} }
public void setDate(LocalDate localDate) { public void setDate(LocalDate localDate) {
this.date = localDate; this.date = Date.valueOf(localDate);
} }
public void setDescription(String description) { public void setDescription(String description) {

View File

@@ -1,5 +1,6 @@
package de.uni_passau.fim.PADAS.group3.DataDash.model; package de.uni_passau.fim.PADAS.group3.DataDash.model;
import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.UUID; import java.util.UUID;
@@ -26,6 +27,7 @@ public class DatasetService {
} }
public void addDataset(Dataset dataset) { public void addDataset(Dataset dataset) {
dataset.setDate(LocalDate.now());
datasetRepository.save(dataset); datasetRepository.save(dataset);
} }
@@ -85,18 +87,17 @@ public class DatasetService {
} }
public Page<Dataset> getDatasetsByOptionalCriteria(String title, String description, String author, String abst, public Page<Dataset> getDatasetsByOptionalCriteria(String title, String description, String author, String abst,
Type type, Float raiting, Pageable pageable) { Type type, Float raiting, Category category, Pageable pageable) {
String[] categories = null;
return datasetRepository.findByOptionalCriteria(Optional.ofNullable(title), Optional.ofNullable(description), return datasetRepository.findByOptionalCriteria(Optional.ofNullable(title), Optional.ofNullable(description),
Optional.ofNullable(author), Optional.ofNullable(abst), Optional.ofNullable(type), Optional.ofNullable(author), Optional.ofNullable(abst), Optional.ofNullable(type), Optional.ofNullable(category),
Optional.ofNullable(categories), Optional.ofNullable(raiting), pageable); Optional.ofNullable(raiting), pageable);
} }
public Page<Dataset> searchByOptionalCriteria(String search, Pageable pageable) { public Page<Dataset> searchByOptionalCriteria(String search, String categories, String type, Pageable pageable) {
if (search.equals("%")) { //TODO: make it not Crash
System.out.println("searching for all datasets"); Category category = categories.equals("%") ? null : Category.valueOf(categories);
return datasetRepository.findAll(pageable); Type t = type.equals("%") ? null : Type.valueOf(type);
}
return datasetRepository.searchByOptionalCriteria(Optional.ofNullable(search), pageable); return datasetRepository.searchByOptionalCriteria(Optional.ofNullable(search), Optional.ofNullable(category), Optional.ofNullable(t),pageable);
} }
} }

View File

@@ -1,8 +1,7 @@
package de.uni_passau.fim.PADAS.group3.DataDash.model; package de.uni_passau.fim.PADAS.group3.DataDash.model;
import java.net.URL;
import java.sql.Date;
import java.util.List; import java.util.List;
import java.util.Random;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.CommandLineRunner;
@@ -23,8 +22,10 @@ public class LoadDummyDatabase {
return args -> { return args -> {
for (int i = 0; i < 100; i++) { for (int i = 0; i < 100; i++) {
Dataset dataset = new Dataset("Title" + i, "Abst" + i, "Description" + i, "Author" + i,null, new String[]{"Category" + i}, Type.API); Dataset dataset = new Dataset("Title" + i, "Abst" + i, "Description" + i, "Author" + i,null, Category.EDUCATION, Type.API);
repository.save(dataset); for (int j = 0; j < new Random().nextInt(50); j++) {
dataset.upvote();
}
log.info("Preloading" + repository.save(dataset)); log.info("Preloading" + repository.save(dataset));
} }
List<Dataset> s = repository.findByTitleLike("%Title%"); List<Dataset> s = repository.findByTitleLike("%Title%");

View File

@@ -11,49 +11,64 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query; import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param; import org.springframework.data.repository.query.Param;
public interface dataRepository extends JpaRepository<Dataset, UUID> {
public interface dataRepository extends JpaRepository<Dataset, UUID>{ Dataset getDatasetById(UUID id);
Dataset getDatasetById(UUID id); List<Dataset> findByTitle(String title);
List<Dataset> findByTitle(String title);
List<Dataset> findByTitleLike(String title);
List<Dataset> findByAuthorLike(String author);
List<Dataset> findByType(Type type);
List<Dataset> findByAuthor(String author);
List<Dataset> findByAbstLike(String abst);
List<Dataset> findByDescriptionLike(String description);
List<Dataset> findByCategories(String[] categories);
List<Dataset> findByRaitingGreaterThan(float raiting);
List<Dataset> findByVotesGreaterThan(int votes);
List<Dataset> findByDateAfter(Date date);
List<Dataset> findByDateBefore(Date date);
List<Dataset> findByDateBetween(Date date1, Date date2);
@SuppressWarnings("null")
Page<Dataset> findAll(Pageable pageable);
@Query("SELECT d FROM Dataset d WHERE " + List<Dataset> findByTitleLike(String title);
"(COALESCE(:title, '') = '' OR d.title LIKE :title) AND " +
"(COALESCE(:description, '') = '' OR d.description LIKE :description) AND" +
"(COALESCE(:author, '') = '' OR d.author LIKE :author) AND" +
"(COALESCE(:abst, '') = '' OR d.abst LIKE :abst) AND" +
"(:type IS NULL OR d.type = :type) AND"+
"(:categories IS NULL OR d.categories = :categories) AND" +
"(:raiting IS NULL OR d.raiting > :raiting)")
Page<Dataset>findByOptionalCriteria(@Param("title") Optional<String> title,
@Param("description") Optional<String> description,
@Param("author") Optional<String> author,
@Param("abst") Optional<String> abst,
@Param("type") Optional<Type> type,
@Param("categories") Optional<String[]> categories,
@Param("raiting") Optional<Float> raiting,
Pageable pageable);
List<Dataset> findByAuthorLike(String author);
@Query("SELECT d FROM Dataset d WHERE " + List<Dataset> findByType(Type type);
"(LOWER(d.title) LIKE LOWER(:search)) OR " +
"(LOWER(d.description) LIKE LOWER(:search)) OR " +
"(LOWER(d.author) LIKE LOWER(:search))")
Page<Dataset>searchByOptionalCriteria(@Param("search") Optional<String> search,
Pageable pageable);
List<Dataset> findByAuthor(String author);
List<Dataset> findByAbstLike(String abst);
List<Dataset> findByDescriptionLike(String description);
List<Dataset> findByRaitingGreaterThan(float raiting);
List<Dataset> findByVotesGreaterThan(int votes);
List<Dataset> findByDateAfter(Date date);
List<Dataset> findByDateBefore(Date date);
List<Dataset> findByCategorie(Category categorie);
List<Dataset> findByDateBetween(Date date1, Date date2);
@SuppressWarnings("null")
Page<Dataset> findAll(Pageable pageable);
@Query("SELECT d FROM Dataset d WHERE " +
"(COALESCE(:title, '') = '' OR d.title LIKE :title) AND " +
"(COALESCE(:description, '') = '' OR d.description LIKE :description) AND" +
"(COALESCE(:author, '') = '' OR d.author LIKE :author) AND" +
"(COALESCE(:abst, '') = '' OR d.abst LIKE :abst) AND" +
"(:type IS NULL OR d.type = :type) AND" +
"(:categorie IS NULL OR d.categorie = :categorie) AND" +
"(:raiting IS NULL OR d.raiting > :raiting)")
Page<Dataset> findByOptionalCriteria(@Param("title") Optional<String> title,
@Param("description") Optional<String> description,
@Param("author") Optional<String> author,
@Param("abst") Optional<String> abst,
@Param("type") Optional<Type> type,
@Param("categorie") Optional<Category> categories,
@Param("raiting") Optional<Float> raiting,
Pageable pageable);
@Query("SELECT d FROM Dataset d WHERE " +
"((LOWER(d.title) LIKE LOWER(:search)) OR " +
"(LOWER(d.description) LIKE LOWER(:search)) OR " +
"(LOWER(d.author) LIKE LOWER(:search))) AND" +
"(:categorie IS NULL OR d.categorie = :categorie) AND" +
"(:type IS NULL OR d.type = :type)")
Page<Dataset> searchByOptionalCriteria(@Param("search") Optional<String> search,
@Param("categorie") Optional<Category> categories,
@Param("type") Optional<Type> type,
Pageable pageable);
} }

View File

@@ -4,20 +4,6 @@
--accent-color: oklch(65.33% 0.158 247.76); --accent-color: oklch(65.33% 0.158 247.76);
} }
form label:after {
content: ":";
}
form :is(input[type=text], textarea) {
background-color: var(--fg-color);
border: none;
border-radius: .25lh;
color: var(--text-color, white);
padding: .5em;
font-family: sans-serif;
}
/* quick info box */
form { form {
display: grid; display: grid;
grid-template-columns: 1fr 1fr auto; grid-template-columns: 1fr 1fr auto;
@@ -30,17 +16,57 @@ form > * {
gap: 1rem; gap: 1rem;
} }
form :is(input[type=text], textarea) { form label:after {
content: ":";
}
/* text entries */
form :is(input[type=text], input[type=url], textarea) {
background-color: var(--fg-color);
border: none;
border-radius: .25lh;
color: var(--text-color, white);
padding: .5em;
font-family: sans-serif;
flex-grow: 1; flex-grow: 1;
} }
/* focus outlines */
:is(form :is(input[type=text], input[type=url], textarea), .btn):focus-visible {
outline: 2px solid var(--accent-color);
}
.btn, #is-dataset-toggle {
transition: outline ease-in 100ms;
}
/* input validation */
form :is(input[type=text], input[type=url], textarea):user-valid {
--validation-color: lime;
}
form :is(input[type=text], input[type=url], textarea):user-invalid {
--validation-color: red;
outline-style: solid;
}
form :is(input[type=text], input[type=url], textarea):is(:user-valid, :user-invalid) {
outline-color: var(--validation-color);
}
form :is(input[type=text], input[type=url], textarea):is(:user-valid, :user-invalid):not(:focus-visible) {
outline-width: 1px;
}
/* switch */ /* switch */
label:has(#is-dataset) { label:has(#is-dataset) {
gap: 0; gap: 0;
} }
#is-dataset { #is-dataset {
display: none; top: -100vh;
left: -100vw;
position: absolute;
} }
#is-dataset-toggle { #is-dataset-toggle {
@@ -69,6 +95,10 @@ label:has(#is-dataset) {
filter: drop-shadow(rgba(0, 0, 0, .8) 0 0 .25rem); filter: drop-shadow(rgba(0, 0, 0, .8) 0 0 .25rem);
} }
#is-dataset:focus-visible + #is-dataset-toggle {
outline: 2px solid var(--accent-color);
}
#is-dataset:not(:checked) + #is-dataset-toggle::before { #is-dataset:not(:checked) + #is-dataset-toggle::before {
left: 0; left: 0;
} }
@@ -79,7 +109,11 @@ label:has(#is-dataset) {
/* short description box */ /* short description box */
form :has(#short-description) { form :has(#short-description) {
grid-column: 1 / 3; grid-column: 1 / 2;
}
form :has(#url) {
grid-column: 2 / 4;
} }
/* full description box */ /* full description box */
@@ -116,13 +150,18 @@ form :has(#short-description) {
--drop-shadow-opacity: .5; --drop-shadow-opacity: .5;
--drop-shadow-offset-y: 0; --drop-shadow-offset-y: 0;
--drop-shadow-blur: .25rem; --drop-shadow-blur: .25rem;
filter: drop-shadow( --drop-shadow: drop-shadow(
rgba(0, 0, 0, var(--drop-shadow-opacity)) rgba(0, 0, 0, var(--drop-shadow-opacity))
0 var(--drop-shadow-offset-y) var(--drop-shadow-blur) 0 var(--drop-shadow-offset-y) var(--drop-shadow-blur)
); );
filter: var(--drop-shadow);
} }
.btn:hover { .btn:focus-visible, #is-dataset:focus-visible + #is-dataset-toggle {
outline-offset: 2px;
}
.btn:not(:disabled):hover {
background-color: color-mix(in oklab, var(--btn-color) 80%, var(--bg-color)); background-color: color-mix(in oklab, var(--btn-color) 80%, var(--bg-color));
--drop-shadow-opacity: .8; --drop-shadow-opacity: .8;
--drop-shadow-offset-y: .25rem; --drop-shadow-offset-y: .25rem;
@@ -132,3 +171,7 @@ form :has(#short-description) {
.btn.suggested { .btn.suggested {
--btn-color: var(--accent-color); --btn-color: var(--accent-color);
} }
.btn:disabled {
filter: var(--drop-shadow) grayscale(.5) brightness(.5);
}

View File

@@ -0,0 +1,59 @@
const form = document.forms[0];
const {
title: titleEntry,
author: authorEntry,
["is-dataset"]: isDatasetSwitch,
["short-description"]: shortDescriptionEntry,
url: urlEntry,
["full-description"]: fullDescriptionEntry,
["btn-add"]: addBtn,
["btn-cancel"]: cancelBtn,
} = form.elements;
const validationListener = () => {
addBtn.disabled = !form.checkValidity();
};
// Register validationListener on all required inputs that must be valid
[
titleEntry,
authorEntry,
shortDescriptionEntry,
urlEntry,
fullDescriptionEntry,
].forEach(input => input.addEventListener("input", validationListener));
form.addEventListener("submit", e => {
e.preventDefault();
if (!form.reportValidity()) return;
// Create the request body
const newContent = {
title: titleEntry.value,
author: authorEntry.value,
abst: shortDescriptionEntry.value,
url: urlEntry.value,
description: fullDescriptionEntry.value,
type: isDatasetSwitch.checked ? "API" : "DATASET",
categories: [],
};
console.debug(newContent);
// Don't allow several requests to be sent at the same time
addBtn.disabled = true;
fetch("/api/v1/datasets", {
method: "POST",
body: JSON.stringify(newContent),
headers: {
"Content-Type": "application/json;charset=utf-8"
}
}).then(response => {
if (response.status == 200) {
location.assign("/");
} else {
addBtn.disabled = !form.checkValidity();
}
});
});

View File

@@ -1,4 +1,5 @@
import { searchBarTimeout } from "./main.js" import {searchBarTimeout, searchSection} from "./main.js"
import Dataset from "./dataset.js"
export function fetchQuery(fetchString) { export function fetchQuery(fetchString) {
clearTimeout(searchBarTimeout); clearTimeout(searchBarTimeout);
@@ -10,5 +11,15 @@ export function fetchQuery(fetchString) {
} }
function parseContent(content) { function parseContent(content) {
//TODO: method for parsing query results if (content.length === 0) {
searchSection.querySelector("#nothing-found ").classList.remove("hidden");
} else {
searchSection.querySelector("#nothing-found").classList.add("hidden");
const datasets = content.map(dataset => new Dataset(dataset));
Array.from(searchSection.querySelectorAll(".datasets .dataset")).forEach(e => e.remove());
for (const dataset of datasets) {
searchSection.querySelector(".datasets").appendChild(dataset.createDatasetHTMLElement());
}
}
} }

View File

@@ -0,0 +1,51 @@
import { vote } from "./main.js";
export default class Dataset {
#abstract;
#author;
#categories;
#date;
#description;
#id;
#rating;
#title;
#type;
#upvotes;
#url;
#votes;
constructor({abst: shortDescription, author, categories, date, description, id, rating, title, type, upvotes, url, votes}) {
this.#abstract = shortDescription;
this.#author = author;
this.#categories = categories;
this.#date = date;
this.#description = description;
this.#id = id;
this.#rating = rating;
this.#title = title;
this.#type = type;
this.#upvotes = upvotes;
this.#url = url;
this.#votes = votes;
}
createDatasetHTMLElement() {
let template = document.querySelector("#dataset-template");
const clone = template.content.cloneNode(true);
clone.querySelector(".dataset").dataset.id = this.#id;
clone.querySelector("h3").innerText = this.#title;
clone.querySelector("p").innerText = this.#description;
clone.querySelector("span").innerText = this.#upvotes;
// Event Listeners
clone.querySelector(".upvote-btn").addEventListener("click", () => {
vote(this.#id, true);
});
clone.querySelector(".downvote-btn").addEventListener("click", () => {
vote(this.#id, false);
})
return clone;
}
}

View File

@@ -42,6 +42,7 @@ header {
left: 0; left: 0;
z-index: 1; z-index: 1;
} }
#tool-bar { #tool-bar {
display: flex; display: flex;
flex-direction: row; flex-direction: row;
@@ -61,6 +62,25 @@ header {
color: var(--text-color); color: var(--text-color);
} }
#nothing-found {
height: 60vh;
padding: 20vh 0;
}
#nothing-found-bg {
background: url("sad-looking-glass.svg") center no-repeat;
background-size: contain;
width: 100%;
height: 40vh;
}
#nothing-found-text {
text-align: center;
}
.hidden {
display: none;
}
#search-entry:focus-visible { #search-entry:focus-visible {
outline: none; outline: none;
} }
@@ -98,7 +118,7 @@ header {
gap: .5em; gap: .5em;
} }
/* Buttons */ /* Buttons */
.upvote-btn, .downvote-btn, #search-btn, #filter-btn, #sort-btn { .upvote-btn, .downvote-btn, #search-btn, #filter-btn, #sort-btn, #reset-tools-btn {
background: var(--icon-url) no-repeat; background: var(--icon-url) no-repeat;
background-size: contain; background-size: contain;
border: none; border: none;
@@ -128,6 +148,11 @@ header {
--icon-size: 1rem; --icon-size: 1rem;
} }
#reset-tools-btn {
--icon-url: url(reset.svg);
--icon-size: 1rem;
}
#sort-btn { #sort-btn {
--icon-url: url(sort.svg); --icon-url: url(sort.svg);
--icon-size: 1rem; --icon-size: 1rem;

View File

@@ -1,4 +1,5 @@
import { fetchQuery } from "./contentUtility.js"; import {fetchQuery} from "./contentUtility.js";
import Dataset from "./dataset.js";
const apiEndpoint = "/api/v1/datasets"; const apiEndpoint = "/api/v1/datasets";
const baseURL = location.origin; const baseURL = location.origin;
@@ -9,17 +10,22 @@ const lastQuery = {
currentPage: 0 currentPage: 0
}; };
// definition of all buttons // definition of all buttons & sections
const addButton = document.getElementById("add-btn"); const addButton = document.getElementById("add-btn");
const filterButton = document.getElementById("filter-btn"); const filterButton = document.getElementById("filter-btn");
const searchButton = document.getElementById("search-btn"); const searchButton = document.getElementById("search-btn");
const searchBar = document.getElementById("search-entry"); const searchBar = document.getElementById("search-entry");
const sortButton = document.getElementById("sort-btn"); const sortButton = document.getElementById("sort-btn");
const resetButton = document.getElementById("reset-tools-btn");
const upvoteButtons = document.getElementsByClassName("upvote-btn"); const upvoteButtons = document.getElementsByClassName("upvote-btn");
const downvoteButtons = document.getElementsByClassName("downvote-btn"); const downvoteButtons = document.getElementsByClassName("downvote-btn");
export const searchSection = document.getElementById("search");
const recentSection = document.getElementById("recents");
const mostLikedSection = document.getElementById("top");
// ID of the timeout, because we need to cancel it at some point // ID of the timeout, because we need to cancel it at some point
export let searchBarTimeout; export let searchBarTimeout;
const searchDelay = 500;
// Event listeners // Event listeners
addButton.addEventListener("click", () => { addButton.addEventListener("click", () => {
@@ -28,35 +34,43 @@ addButton.addEventListener("click", () => {
filterButton.addEventListener("change", () => { filterButton.addEventListener("change", () => {
const filterString = filterButton.value; const filterString = filterButton.value;
filter(filterString); if (filterString !== filterButton.querySelector("#default-filter").value) {
fetchQuery(createQuery());
}
}); });
searchButton.addEventListener("click", () => { searchButton.addEventListener("click", () => {
const searchString = searchBar.value; fetchQuery(createQuery());
search(searchString);
}); });
searchBar.addEventListener("input", () => { searchBar.addEventListener("input", () => {
updateSections();
clearTimeout(searchBarTimeout); clearTimeout(searchBarTimeout);
searchBarTimeout = setTimeout(() => { searchBarTimeout = setTimeout(() => {
const searchString = searchBar.value; fetchQuery(createQuery());
search(searchString); }, searchDelay);
}, 1000);
}); });
searchBar.addEventListener('keypress', function (e) { searchBar.addEventListener('keypress', function (e) {
if (e.key === 'Enter') { if (e.key === 'Enter') {
const searchString = searchBar.value; fetchQuery(createQuery());
search(searchString);
} }
})
sortButton.addEventListener("change", () => {
const sortString = sortButton.value;
sort(sortString);
}); });
const upvoteButtonClickListener = e => { sortButton.addEventListener("change", () => {
fetchQuery(createQuery());
});
resetButton.addEventListener("click", () => {
searchBar.value = "";
filterButton.value = filterButton.querySelector("#default-filter").value;
sortButton.value = sortButton.querySelector("#default-sort").value;
updateSections();
});
// Consider moving this to datasets.js completely
const upvoteButtonClickListener = e => {
const entryID = e.target.parentElement.parentElement.dataset.id; const entryID = e.target.parentElement.parentElement.dataset.id;
vote(entryID, true); vote(entryID, true);
}; };
@@ -64,6 +78,7 @@ for (const upvoteButton of upvoteButtons) {
upvoteButton.addEventListener("click", upvoteButtonClickListener); upvoteButton.addEventListener("click", upvoteButtonClickListener);
} }
// Consider moving this to datasets.js completely
const downvoteButtonClickListener = e => { const downvoteButtonClickListener = e => {
const entryID = e.target.parentElement.parentElement.dataset.id; const entryID = e.target.parentElement.parentElement.dataset.id;
vote(entryID, false); vote(entryID, false);
@@ -74,54 +89,134 @@ for (const downvoteButton of downvoteButtons) {
// functions of the main page // functions of the main page
function navigateToAdd() { function navigateToAdd() {
//TODO: url to add page not yet implemented, add here window.location.href = "/add";
} }
function filter(filterString) { function getFilterQuery() {
filterString = filterString.toUpperCase(); let filterString= filterButton.value.toUpperCase();
if (filterString === "NONE") {
let fetchURL = new URL(apiEndpoint, baseURL); return ["type", "%"]
fetchURL.searchParams.append("type", filterString); } else if (document.querySelector('#filter-btn option:checked').parentElement.label === "Standard categories") {
fetchURL.searchParams.append("size", defaultPagingValue); return ["type", filterString];
console.log(fetchURL); // TODO: remove
fetchQuery(fetchURL);
}
function search(searchString) {
let fetchURL = new URL(apiEndpoint + "/search", baseURL);
fetchURL.searchParams.append("search", searchString.length == 0 ? "%" : searchString);
console.log(fetchURL); // TODO: remove
fetchQuery(fetchURL);
}
function sort(sortString) {
let query = sortString.toLowerCase().split(" ");
if (query[1] === "a-z" || query[1] === "↑") {
query[1] = "asc";
} else { } else {
query[1] = "desc"; return ["category", filterString];
} }
let fetchURL = new URL(apiEndpoint, baseURL);
fetchURL.searchParams.append("sort", query[0]);
fetchURL.searchParams.append("direction", query[1]);
console.log(fetchURL); // TODO: remove
fetchQuery(fetchURL);
} }
function vote(entryID, up) { function getSearchQuery() {
let searchString = searchBar.value;
return (searchString.length === 0 ? "%" : ("%" + searchString + "%"));
}
function getSortQuery() {
let sortString = sortButton.value.toLowerCase().split(" ");
if (sortString[1] === "a-z" || sortString[1] === "↑" || sortString[1] === "oldest-newest") {
sortString[1] = "asc";
} else {
sortString[1] = "desc";
}
return sortString
}
// creates query for the whole toolbar, so that searching, sorting and filtering are always combined
function createQuery() {
updateSections();
let queryURL = new URL(apiEndpoint + "/search", baseURL);
queryURL.searchParams.append("search", getSearchQuery());
let filterQuery = getFilterQuery();
queryURL.searchParams.append(filterQuery[0], filterQuery[1]);
let sortQuery = getSortQuery();
queryURL.searchParams.append("sort", sortQuery[0]);
queryURL.searchParams.append("direction", sortQuery[1]);
queryURL.searchParams.append("size", defaultPagingValue.toString(10));
return queryURL;
}
export function vote(entryID, up) {
const fetchURL = new URL( const fetchURL = new URL(
`${apiEndpoint}/id/${entryID}/${up ? "up" : "down"}vote`, `${apiEndpoint}/id/${entryID}/${up ? "up" : "down"}vote`,
baseURL, baseURL,
); );
fetch(fetchURL, {
console.log(fetchURL); // TODO: remove method: "PUT",
fetch(fetchURL); headers: {
'Content-Type': 'application/json',
}})
.then(resp => resp.json())
.then((data) => {
console.log(data.upvotes); // TODO: remove, check einbauen: data.id === entryID?
let dataset = document.querySelector('[data-id= ' + CSS.escape(entryID) + ']')
dataset.querySelector("span").innerText = data.upvotes;
});
} }
function incrementPageCount() { function incrementPageCount() {
lastQuery.currentPage++; lastQuery.currentPage++;
} }
// updates the page display. If no query is present, the initial page is shown, otherwise the search results.
function updateSections() {
if (searchBar.value === "" && sortButton.value === sortButton.querySelector("#default-sort").value
&& filterButton.value === filterButton.querySelector("#default-filter").value) {
searchSection.classList.add("hidden");
recentSection.classList.remove("hidden");
mostLikedSection.classList.remove("hidden");
resetButton.classList.add("hidden");
} else {
searchSection.classList.remove("hidden");
recentSection.classList.add("hidden");
mostLikedSection.classList.add("hidden");
resetButton.classList.remove("hidden");
}
}
// fetches the further categories used in the filter function
function fetchCategories() {
const fetchURL = new URL(
"api/v1/categories" , baseURL);
fetch(fetchURL)
.then(resp => resp.json())
.then((data) => {
for (let i = 0; i < data.length; i++) {
let category = data[i].toLowerCase();
category = category.charAt(0).toUpperCase() + category.slice(1);
document.getElementById("other-categories").appendChild(new Option(category));
}
});
}
// fetches entries for the initial page
function fetchInitialEntries() {
let recentsQueryURL = new URL(apiEndpoint + "/search", baseURL);
recentsQueryURL.searchParams.append("sort", "date");
recentsQueryURL.searchParams.append("direction", "desc");
recentsQueryURL.searchParams.append("size", "6");
fetch(recentsQueryURL)
.then(resp => resp.json())
.then((data) => {
const datasets = data.content.map(dataset => new Dataset(dataset));
for (const dataset of datasets) {
document.querySelector("#recents .datasets").appendChild(dataset.createDatasetHTMLElement());
}
});
let topVotedQueryURL = new URL(apiEndpoint + "/search", baseURL);
topVotedQueryURL.searchParams.append("sort", "upvotes");
topVotedQueryURL.searchParams.append("direction", "desc");
topVotedQueryURL.searchParams.append("size", "1");
fetch(topVotedQueryURL)
.then(resp => resp.json())
.then((data) => {
document.querySelector("#top .datasets")
.appendChild(new Dataset(data.content[0]).createDatasetHTMLElement());
});
}
window.onload = function () {
fetchCategories();
fetchInitialEntries();
updateSections();
if (searchBar.value !== "") {
fetchQuery(createQuery());
}
}

View File

@@ -0,0 +1,52 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg xmlns="http://www.w3.org/2000/svg"
width="1.70667in" height="1.70667in"
viewBox="0 0 512 512">
<path id="Selection"
fill="#222" stroke="#222" stroke-width="1"
d="M 237.00,255.00
C 232.17,252.53 227.04,246.25 222.99,242.29
222.99,242.29 198.20,217.75 198.20,217.75
198.20,217.75 163.08,182.72 163.08,182.72
163.08,182.72 125.09,144.45 125.09,144.45
125.09,144.45 100.59,120.08 100.59,120.08
95.21,114.71 91.15,113.03 91.00,105.00
90.96,102.52 90.73,98.57 91.99,96.43
95.30,90.82 104.55,89.45 110.00,92.17
114.03,94.19 130.60,111.60 135.00,116.00
135.00,116.00 215.00,196.00 215.00,196.00
215.00,196.00 257.00,237.00 257.00,237.00
259.56,232.22 265.16,227.50 269.08,223.59
269.08,223.59 290.92,201.92 290.92,201.92
290.92,201.92 367.41,125.08 367.41,125.08
367.41,125.08 391.85,101.05 391.85,101.05
396.75,96.08 399.44,91.44 407.00,91.04
416.65,90.54 421.50,95.35 420.96,105.00
420.60,111.25 417.19,113.79 413.00,118.00
413.00,118.00 397.00,134.00 397.00,134.00
397.00,134.00 307.00,224.00 307.00,224.00
307.00,224.00 284.00,247.00 284.00,247.00
282.10,248.90 277.04,253.27 277.04,256.00
277.04,258.73 282.10,263.10 284.00,265.00
284.00,265.00 307.00,288.00 307.00,288.00
307.00,288.00 397.00,378.00 397.00,378.00
397.00,378.00 412.00,393.00 412.00,393.00
414.67,395.67 418.93,399.50 420.26,403.00
420.95,404.81 421.00,407.07 420.99,409.00
420.95,417.91 415.37,421.34 407.00,420.96
399.20,420.61 397.05,416.34 391.92,411.26
391.92,411.26 368.25,387.75 368.25,387.75
368.25,387.75 291.75,311.25 291.75,311.25
291.75,311.25 269.08,288.42 269.08,288.42
265.10,284.40 259.51,279.96 257.00,275.00
257.00,275.00 219.83,311.28 219.83,311.28
219.83,311.28 135.00,396.00 135.00,396.00
135.00,396.00 119.08,412.08 119.08,412.08
116.77,414.39 112.71,418.94 109.83,420.13
104.28,422.42 95.26,421.12 91.99,415.57
90.73,413.43 90.96,409.48 91.00,407.00
91.14,399.23 95.36,397.16 100.59,391.92
100.59,391.92 127.56,365.29 127.56,365.29
127.56,365.29 202.25,290.25 202.25,290.25
202.25,290.25 237.00,255.00 237.00,255.00 Z" />
</svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@@ -1,2 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?> <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg width="16" height="16" viewBox="0 0 16 16" version="1.1" id="sad-looking-glass" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg"><g id="main-layer"><path id="looking-glass" style="fill:none;stroke:#222222;stroke-width:1.5;stroke-linecap:round" d="M 11.22141,6 A 5.2214103,5.2214103 0 0 1 6,11.22141 5.2214103,5.2214103 0 0 1 0.77858973,6 5.2214103,5.2214103 0 0 1 6,0.77858973 5.2214103,5.2214103 0 0 1 11.22141,6 Z M 15.25,15.25 10,10" /><circle style="fill:#222222" id="left-eye" cx="4" cy="4.75" r="0.75" /><circle style="fill:#222222" id="right-eye" cx="8" cy="4.75" r="0.75" /><path style="fill:none;stroke:#222222;stroke-width:1.5;stroke-linecap:round" d="M 4,8 C 6,6.5 8,8 8,8" id="mouth" /></g></svg> <svg width="16" height="16" viewBox="0 0 16 16" version="1.1" id="sad-looking-glass" xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
<g id="main-layer">
<path id="looking-glass" style="fill:none;stroke:#aaa;stroke-width:1;stroke-linecap:round" d="M 11.22141,6 A 5.2214103,5.2214103 0 0 1 6,11.22141 5.2214103,5.2214103 0 0 1 0.77858973,6 5.2214103,5.2214103 0 0 1 6,0.77858973 5.2214103,5.2214103 0 0 1 11.22141,6 Z M 15.25,15.25 10,10" />
<circle style="fill:#aaa" id="left-eye" cx="4" cy="4.75" r="0.75" />
<circle style="fill:#aaa" id="right-eye" cx="8" cy="4.75" r="0.75" />
<path style="fill:none;stroke:#aaa;stroke-width:1;stroke-linecap:round" d="M 4,8 C 6,6.5 8,8 8,8" id="mouth" /></g></svg>

Before

Width:  |  Height:  |  Size: 794 B

After

Width:  |  Height:  |  Size: 819 B

View File

@@ -5,6 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>DataDash Add dataset/API</title> <title>DataDash Add dataset/API</title>
<link rel="stylesheet" href="add.css"> <link rel="stylesheet" href="add.css">
<script type="module" src="add.js"></script>
</head> </head>
<body> <body>
<main> <main>
@@ -19,15 +20,15 @@
how to use it. how to use it.
</p> </p>
<form action="/api/add" method="post"> <form>
<span> <span>
<label for="text">Title</label> <label for="title">Title</label>
<input type="text" name="title" id="title"> <input type="text" name="title" id="title" minlength="1" maxlength="50" required>
</span> </span>
<span id="author-box"> <span id="author-box">
<label for="author">Author</label> <label for="author">Author</label>
<input type="text" name="author" id="author"> <input type="text" name="author" id="author" required>
</span> </span>
<label> <label>
@@ -39,16 +40,21 @@
<span> <span>
<label for="short-description">Short description</label> <label for="short-description">Short description</label>
<input type="text" name="short-description" id="short-description"> <input type="text" name="short-description" id="short-description" maxlength="100" required spellcheck="true">
</span>
<span>
<label for="url">URL</label>
<input type="url" name="url" id="url" required>
</span> </span>
<span id="full-description-box"> <span id="full-description-box">
<label for="full-description">Full description</label> <label for="full-description">Full description</label>
<textarea name="full-description" id="full-description"></textarea> <textarea name="full-description" id="full-description" spellcheck="true"></textarea>
</span> </span>
<span id="btn-bar"> <span id="btn-bar">
<input type="submit" value="Add" id="btn-add" class="btn suggested"> <input type="submit" value="Add" id="btn-add" class="btn suggested" disabled>
<input type="reset" value="Cancel" id="btn-cancel" class="btn"> <input type="reset" value="Cancel" id="btn-cancel" class="btn">
</span> </span>
</form> </form>

View File

@@ -15,25 +15,44 @@
<p>The place to launch and discover datasets and API endpoints.</p> <p>The place to launch and discover datasets and API endpoints.</p>
</header> </header>
<template id="dataset-template">
<li class="dataset" data-id="id">
<div class="dataset-info">
<div class="details">
<h3>title</h3>
<p>Simply daily accountability phone call, powered by AI</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
</template>
<section id="tool-bar"> <section id="tool-bar">
<button class="btn flat" id="reset-tools-btn" title="Reset search results">Reset</button>
<select id="sort-btn" class="btn flat" title="Sort entries">Sort by <select id="sort-btn" class="btn flat" title="Sort entries">Sort by
<option id="default-sort">Date newest-oldest</option>
<option>Date oldest-newest</option>
<option>Author A-Z</option> <option>Author A-Z</option>
<option>Author Z-A</option> <option>Author Z-A</option>
<option>Title A-Z</option> <option>Title A-Z</option>
<option>Title Z-A</option> <option>Title Z-A</option>
<option>Stars ↑</option> <option>Stars ↑</option>
<option>Stars ↓</option> <option>Stars ↓</option>
<option>Votes ↑</option> <option>Upvotes ↑</option>
<option>Votes ↓</option> <option>Upvotes ↓</option>
</select> </select>
<div class="divider"></div> <div class="divider"></div>
<select class="btn flat" id="filter-btn" title="Filter entries">Filter <select class="btn flat" id="filter-btn" title="Filter entries">Filter
<option id="default-filter">None</option>
<optgroup label="Standard categories"> <optgroup label="Standard categories">
<option>Dataset</option> <option>Dataset</option>
<option>API</option> <option>API</option>
</optgroup> </optgroup>
<optgroup label="Other categories"> <optgroup id="other-categories" label="Other categories">
<option>a category</option>
</optgroup> </optgroup>
</select> </select>
<input type="search" name="query" id="search-entry" placeholder="Search"> <input type="search" name="query" id="search-entry" placeholder="Search">
@@ -43,103 +62,21 @@
<section id="recents"> <section id="recents">
<h2>Recently added:</h2> <h2>Recently added:</h2>
<ul class="datasets"> <ul class="datasets">
<!-- Preliminary content to be replaced by data from our server: -->
<li class="dataset" data-id="">
<div class="dataset-info">
<div class="icon standup"></div>
<div class="details">
<h3>Standup</h3>
<p>Simply daily accountability phone call, powered by AI</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
<li class="dataset">
<div class="dataset-info">
<div class="icon tori"></div>
<div class="details">
<h3>Tori</h3>
<p>The simple mobile crypto wallet even your grandparents can use</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
<li class="dataset">
<div class="dataset-info">
<div class="icon tyms"></div>
<div class="details">
<h3>Tyms</h3>
<p>Modern accounting ERP for ambitious businesses</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
<li class="dataset">
<div class="dataset-info">
<div class="icon zapcardz"></div>
<div class="details">
<h3>ZapCardz</h3>
<p>Remember what you learn forever with AI powered flashcards</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
<li class="dataset">
<div class="dataset-info">
<div class="icon peek"></div>
<div class="details">
<h3>Peek</h3>
<p>AI organizer and workspace for your browser tabs</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
</ul> </ul>
</section> </section>
<section id="top"> <section id="top">
<h2>Most Liked:</h2> <h2>Most Liked:</h2>
<ul class="datasets"> <ul class="datasets">
<li class="dataset">
<div class="dataset-info">
<div class="icon standup"></div>
<div class="details">
<h3>Standup</h3>
<p>Simply daily accountability phone call, powered by AI</p>
</div>
</div>
<aside class="upvote">
<button class="upvote-btn btn flat">Upvote</button>
<span class="upvote-count">0</span>
<button class="downvote-btn btn flat">Downvote</button>
</aside>
</li>
</ul> </ul>
</section> </section>
<section id="search"> <section id="search" class="hidden">
<h2>Search results:</h2> <h2>Search results:</h2>
<div id="nothing-found">
<div id="nothing-found-bg"></div>
<h3 id="nothing-found-text">Nothing found</h3>
</div>
<ul class="datasets"> <ul class="datasets">
</ul> </ul>
</section> </section>
</main> </main>