Added basic quiztivity editor

This commit is contained in:
Mawoka
2023-05-05 21:16:57 +02:00
parent ceb6760b20
commit 2750e7539d
16 changed files with 1497 additions and 877 deletions
+3
View File
@@ -33,6 +33,7 @@ from classquiz.routers import (
results,
admin,
box_controller,
quiztivity,
)
from classquiz.socket_server import sio
from classquiz.helpers import meilisearch_init, telemetry_ping, bg_tasks
@@ -86,6 +87,8 @@ async def auth_middleware_wrapper(request: Request, call_next):
return await rememberme_middleware(request, call_next)
app.include_router(quiztivity.router, tags=["quiztivity"], prefix="/api/v1/quiztivity", include_in_schema=True)
app.include_router(
box_controller.router, tags=["boxcontroller"], prefix="/api/v1/box-controller", include_in_schema=True
)
+20
View File
@@ -11,7 +11,9 @@ import ormar
from pydantic import BaseModel, Json, validator
from enum import Enum
from . import metadata, database
from .quiztivity import QuizTivityPage
from ..config import server_regex
from sqlalchemy import func
class UserAuthTypes(Enum):
@@ -318,3 +320,21 @@ class GameResults(ormar.Model):
tablename = "game_results"
metadata = metadata
database = database
class QuizTivityInput(BaseModel):
title: str
pages: list[QuizTivityPage]
class QuizTivity(ormar.Model):
id: uuid.UUID = ormar.UUID(primary_key=True)
title: str = ormar.Text(nullable=False)
created_at: datetime = ormar.DateTime(nullable=False, server_default=func.now())
user: User | None = ormar.ForeignKey(User)
pages: list[QuizTivityPage] = ormar.JSON(nullable=False)
class Meta:
tablename = "quiztivitys"
metadata = metadata
database = database
+50
View File
@@ -0,0 +1,50 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from pydantic import BaseModel
import enum
class Pdf(BaseModel):
url: str
class _MemoryCard(BaseModel):
image: str | None
text: str | None
id: str
class Memory(BaseModel):
cards: list[list[_MemoryCard]]
class Markdown(BaseModel):
markdown: str
class QuizTivityTypes(str, enum.Enum):
SLIDE = "SLIDE"
PDF = "PDF"
MEMORY = "MEMORY"
MARKDOWN = "MARKDOWN"
TYPE_CLASS_LIST = {
QuizTivityTypes.PDF: type(Pdf),
QuizTivityTypes.MEMORY: type(Memory),
QuizTivityTypes.MARKDOWN: type(Markdown),
}
class QuizTivityPage(BaseModel):
title: str | None
type: QuizTivityTypes
data: Pdf | Memory | Markdown
# @validator("type")
# def match_type_to_data_type(cls, v, values, **kwargs):
# print(values)
# if TYPE_CLASS_LIST[v] != type(values["data"]):
# raise ValueError("Specified Type doesn't match real data type")
# pass
+44
View File
@@ -0,0 +1,44 @@
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from uuid import UUID, uuid4
from fastapi import APIRouter, Depends, HTTPException
from classquiz.auth import get_current_user
from datetime import datetime
from classquiz.db.models import User, QuizTivityInput, QuizTivity
router = APIRouter()
@router.post("/create")
async def create_quiztivity(data: QuizTivityInput, user: User = Depends(get_current_user)) -> QuizTivity:
quiztivity = QuizTivity.parse_obj({**data.dict(), "user": user, "id": uuid4(), "created_at": datetime.now()})
return await quiztivity.save()
@router.get("/{uuid}")
async def get_quiztivity(uuid: UUID) -> QuizTivity:
quiztivity = await QuizTivity.objects.get_or_none(id=uuid)
if quiztivity is None:
raise HTTPException(status_code=404, detail="QuizTivity not found")
return quiztivity
@router.put("/{uuid}")
async def put_quiztivity(data: QuizTivityInput, uuid: UUID, user: User = Depends(get_current_user)) -> QuizTivity:
quiztivity = await QuizTivity.objects.get_or_none(id=uuid, user=user)
if quiztivity is None:
raise HTTPException(status_code=404, detail="QuizTivity not found")
quiztivity.pages = data.dict()["pages"]
quiztivity.title = data.title
return await quiztivity.update()
@router.delete("/{uuid}")
async def delete_quiztivity(uuid: UUID):
quiztivity = await QuizTivity.objects.get_or_none(id=uuid)
if quiztivity is None:
raise HTTPException(status_code=404, detail="QuizTivity not found")
await quiztivity.delete()
+2
View File
@@ -35,6 +35,7 @@
"@types/cookie": "^0.5.1",
"@types/js-cookie": "^3.0.3",
"@types/luxon": "^3.3.0",
"@types/marked": "^4.3.0",
"@types/qrcode": "^1.5.0",
"@types/sortablejs": "^1.15.1",
"@types/ua-parser-js": "^0.7.36",
@@ -66,6 +67,7 @@
"jws": "^4.0.0",
"luxon": "^3.3.0",
"mapbox-gl": "^2.14.1",
"marked": "^5.0.0",
"mdsvex": "^0.10.6",
"minisearch": "^6.0.1",
"pikaso": "^2.7.6",
+820 -877
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,58 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import { QuizTivityTypes } from './types';
import { getLocalization } from '$lib/i18n';
import { fade } from 'svelte/transition';
const { t } = getLocalization();
export let type: QuizTivityTypes | undefined;
const PageTypes = [
{
name: 'Pdf',
description: 'Upload a PDF!',
type: QuizTivityTypes.PDF,
svg: undefined
},
{
name: 'Memory',
description: 'Matching Pairs game',
type: QuizTivityTypes.MEMORY,
svg: undefined
},
{
name: 'Markdown',
description: 'Add content in Markdown format!',
type: QuizTivityTypes.MARKDOWN,
svg: undefined
}
];
</script>
<div
class="fixed top-0 left-0 z-50 bg-black bg-opacity-50 flex w-screen h-screen"
transition:fade={{ duration: 100 }}
>
<div class="m-auto w-5/6 h-5/6">
<div class="rounded bg-white p-6 dark:bg-gray-600">
<h1 class="text-center text-3xl mb-6">{$t('quiztivity.editor.select_page_type')}</h1>
<div class="grid grid-cols-4 gap-4 overflow-y-scroll">
{#each PageTypes as pt}
<div class="rounded p-6 border-[#B07156] border">
<button
class="text-xl text-black dark:text-white"
on:click={() => {
type = pt.type;
}}>{pt.name}</button
>
<p class="text-sm">{pt.description}</p>
</div>
{/each}
</div>
</div>
</div>
</div>
@@ -0,0 +1,41 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { Markdown } from '../../types';
import { getLocalization } from '$lib/i18n';
import BrownButton from '$lib/components/buttons/brown.svelte';
import { marked } from 'marked';
import { browser } from '$app/environment';
const { t } = getLocalization();
export let data: Markdown | undefined;
if (!data) {
data = {
markdown: ''
};
}
let rendered_html = '';
$: rendered_html = browser ? marked.parse(data.markdown) : '';
</script>
<div class="w-full h-[70vh] flex flex-row p-4 gap-4">
<textarea
class="w-full resize-none border-[#B07156] border-2 rounded outline-none p-2 bg-opacity-30 bg-white dark:placeholder-gray-300"
bind:value={data.markdown}
placeholder="Enter your markdown here!"
/>
<div class="w-full">
<div
class="aspect-video prose max-w-none border-[#B07156] border-2 rounded p-2 dark:prose-invert"
>
{@html rendered_html}
</div>
</div>
</div>
@@ -0,0 +1,96 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { Memory } from '../../types';
import { getLocalization } from '$lib/i18n';
import BrownButton from '$lib/components/buttons/brown.svelte';
const { t } = getLocalization();
export let data: Memory | undefined;
let new_pair_data = {
text_1: '',
text_2: ''
};
if (!data) {
data = {
cards: []
};
}
const add_card = () => {
if (!new_pair_data.text_1 || !new_pair_data.text_2) {
return;
}
const id = (Math.random() + 1).toString(36).substring(7);
data.cards = [
...data.cards,
[
{ id, text: new_pair_data.text_1 },
{ id, text: new_pair_data.text_2 }
]
];
new_pair_data = {
text_1: '',
text_2: ''
};
};
// $: console.log(new_pair_data.text_1.replaceAll("\n", "7"))
</script>
<div class="flex justify-center">
<div class="grid grid-cols-4 w-11/12 gap-4">
<div class="border-[#B07156] border-2 rounded">
<h2 class="text-center">{$t('quiztivity.memory.editor.add_card')}</h2>
<div class="grid grid-cols-2 py-2">
<div class="px-2 flex flex-col gap-2">
<textarea
type="text"
class="h-auto resize-none bg-transparent outline-none rounded outline-[#B07156] outline"
rows="3"
contenteditable="true"
bind:value={new_pair_data.text_1}
/>
<div class="flex justify-center">
<span class="h-0.5 bg-black block w-11/12" />
</div>
<BrownButton>{$t('quiztivity.memory.editor.upload_image')}</BrownButton>
</div>
<div class="px-2 flex flex-col gap-2">
<textarea
type="text"
class="h-auto resize-none bg-transparent outline-none rounded outline-[#B07156] outline"
rows="3"
contenteditable="true"
bind:value={new_pair_data.text_2}
/>
<div class="flex justify-center">
<span class="h-0.5 bg-black block w-11/12" />
</div>
<BrownButton>{$t('quiztivity.memory.editor.upload_image')}</BrownButton>
</div>
</div>
<div class="flex justify-center p-2">
<BrownButton on:click={add_card}
>{$t('quiztivity.memory.editor.add_pair')}</BrownButton
>
</div>
</div>
{#each data.cards as card_pair}
<div class="border-[#B07156] border-2 rounded">
<div class="grid grid-cols-2 py-2 h-full">
{#each card_pair as card}
<div class="px-2 flex h-full">
<p class="m-auto">{card.text}</p>
</div>
{/each}
</div>
</div>
{/each}
</div>
</div>
@@ -0,0 +1,10 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
console.log('Hello World!');
</script>
<p>hkgfdasuvzfgdhagivk!</p>
+167
View File
@@ -0,0 +1,167 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { Data } from './types';
import { getLocalization } from '$lib/i18n';
import BrownButton from '$lib/components/buttons/brown.svelte';
import AddNewSlide from './add_new_slide.svelte';
import { QuizTivityTypes } from './types';
import PdfEdit from './components/pdf/edit.svelte';
import MemoryEdit from './components/memory/edit.svelte';
import MarkdownEdit from './components/markdown/edit.svelte';
import { flip } from 'svelte/animate';
import { createEventDispatcher } from 'svelte';
const { t } = getLocalization();
const dispatch = createEventDispatcher();
export let data: Data;
export let saving: boolean;
let selected_slide = null;
let opened_slide = null;
let selected_type = undefined;
for (let i = 0; i < data.pages.length; i++) {
const id = (Math.random() + 1).toString(36).substring(7);
const type: QuizTivityTypes = data.pages[i].type as QuizTivityTypes;
data.pages[i] = { ...data.pages[i], id, type };
}
const handle_slide_add = (type: QuizTivityTypes | undefined | null) => {
if (!type) {
return;
}
const id = (Math.random() + 1).toString(36).substring(7);
data.pages.push({ title: undefined, data: undefined, type, id });
opened_slide = data.pages.length - 1;
};
$: handle_slide_add(selected_type);
const delete_slide = () => {
data.pages.slice(selected_slide, 1);
data.pages = data.pages;
};
const arraymove = (arr: any[], fromI: number, toI: number) => {
const el = arr[fromI];
arr.splice(fromI, 1);
arr.splice(toI, 0, el);
};
const move_slide_left = () => {
arraymove(data.pages, selected_slide, selected_slide - 1);
selected_slide -= 1;
data.pages = data.pages;
};
const move_slide_right = () => {
arraymove(data.pages, selected_slide, selected_slide + 1);
selected_slide += 1;
data.pages = data.pages;
};
</script>
{#if opened_slide === null}
<div>
<div class="grid grid-cols-3">
<span />
<input
class="bg-transparent outline-none text-center mx-auto"
placeholder={$t('quiztivity.editor.title_placeholder')}
bind:value={data.title}
/>
<div class="self-end pr-2 w-full">
<div class="ml-auto w-fit">
<BrownButton
on:click={() => {
dispatch('save');
}}
disabled={!data.title}>{$t('words.save')}</BrownButton
>
</div>
</div>
</div>
<div class="flex justify-center">
<div>
<div class="flex flex-row gap-2">
<BrownButton
on:click={() => {
selected_type = null;
}}>{$t('quiztivity.editor.add_new')}</BrownButton
>
<BrownButton on:click={delete_slide} disabled={selected_slide === null}
>{$t('quiztivity.editor.delete')}</BrownButton
>
<BrownButton
on:click={move_slide_left}
disabled={selected_slide === null || selected_slide === 0}
>{$t('quiztivity.editor.move_left')}</BrownButton
>
<BrownButton
on:click={move_slide_right}
disabled={selected_slide === null ||
selected_slide === data.pages.length - 1}
>{$t('quiztivity.editor.move_right')}</BrownButton
>
</div>
</div>
</div>
<div class="flex justify-center mt-6">
<div class="grid grid-cols-6 gap-6 w-11/12">
{#each data.pages as page, i (page.id)}
<div
class="border-[#B07156] border-2 rounded aspect-square flex flex-col group"
animate:flip={{ duration: 200 }}
>
<p class="m-auto">{page.type}</p>
<div
class="grid grid-cols-2 gap-2 p-2 group-hover:opacity-100 transition-all"
class:opacity-0={selected_slide !== i}
>
<BrownButton
on:click={() => {
selected_slide = selected_slide === i ? null : i;
}}
>
{#if selected_slide === i}{$t('words.selected')}{:else}{$t(
'words.select'
)}{/if}
</BrownButton>
<BrownButton
on:click={() => {
opened_slide = i;
}}>{$t('words.edit')}</BrownButton
>
</div>
</div>
{/each}
</div>
</div>
</div>
{:else}
{@const sel_t = data.pages[opened_slide].type}
<div class="h-full">
<div class="mb-2">
<BrownButton
on:click={() => {
opened_slide = null;
}}>{$t('words.back')}</BrownButton
>
</div>
{#if sel_t === QuizTivityTypes.PDF}
<PdfEdit />
{:else if sel_t === QuizTivityTypes.MEMORY}
<MemoryEdit bind:data={data.pages[opened_slide].data} />
{:else if sel_t === QuizTivityTypes.MARKDOWN}
<MarkdownEdit bind:data={data.pages[opened_slide].data} />
{:else}
<h1 class="text-8xl">ERROR!</h1>
{/if}
</div>
{/if}
{#if selected_type === null}
<AddNewSlide bind:type={selected_type} />
{/if}
+46
View File
@@ -0,0 +1,46 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
export enum QuizTivityTypes {
// eslint-disable-next-line no-unused-vars
SLIDE = 'SLIDE',
// eslint-disable-next-line no-unused-vars
PDF = 'PDF',
// eslint-disable-next-line no-unused-vars
MEMORY = 'MEMORY',
// eslint-disable-next-line no-unused-vars
MARKDOWN = 'MARKDOWN'
}
export interface Pdf {
url: string;
}
interface MemoryCard {
image?: string;
text?: string;
id: string;
}
export interface Memory {
cards: MemoryCard[][];
}
export interface Markdown {
markdown: string;
}
export interface QuizTivityPage {
title?: string;
type: QuizTivityTypes;
data: Pdf | Memory | Markdown;
id?: string;
}
export interface Data {
id?: string;
title: string;
pages: QuizTivityPage[];
}
@@ -0,0 +1,38 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { Data } from '../../../lib/quiztivity/types';
import Editor from '../../../lib/quiztivity/editor.svelte';
import { goto } from '$app/navigation';
let data: Data = { pages: [], id: undefined, title: '' };
let saving = false;
const save_quiztivity = async () => {
saving = true;
console.log(data);
const stringification = JSON.stringify(data);
console.log(stringification);
const res = await fetch('/api/v1/quiztivity/create', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: stringification
});
if (res.ok) {
// await goto("/dashboard")
} else {
alert("Couldn't save");
}
saving = false;
};
</script>
<div class="h-full">
<Editor bind:data on:save={save_quiztivity} bind:saving />
</div>
@@ -0,0 +1,40 @@
<!--
- This Source Code Form is subject to the terms of the Mozilla Public
- License, v. 2.0. If a copy of the MPL was not distributed with this
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
-->
<script lang="ts">
import type { PageData } from './$types';
import type { Data } from '../../../lib/quiztivity/types';
import Editor from '../../../lib/quiztivity/editor.svelte';
import { goto } from '$app/navigation';
export let data: PageData;
let saving = false;
let quiztivity = data.quiztivity;
const save_quiztivity = async () => {
saving = true;
const stringification = JSON.stringify(quiztivity);
const res = await fetch(`/api/v1/quiztivity/${quiztivity.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: stringification
});
if (res.ok) {
// await goto("/dashboard")
} else {
alert("Couldn't save");
}
saving = false;
};
</script>
<div class="h-full">
<Editor bind:data={quiztivity} on:save={save_quiztivity} bind:saving />
</div>
@@ -0,0 +1,24 @@
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
import type { PageLoad } from './$types';
import { error } from '@sveltejs/kit';
import type { Data } from '../../../lib/quiztivity/types';
export const load = (async ({ url, fetch }) => {
const id = url.searchParams.get('id');
if (!id) {
throw error(400, 'id missing');
}
const resp = await fetch(`/api/v1/quiztivity/${id}`);
if (!resp.ok) {
throw error(404, 'quiztivity not found');
}
const data: Data = await resp.json();
return {
quiztivity: data
};
}) satisfies PageLoad;
@@ -0,0 +1,38 @@
"""Added #1
Revision ID: 4bbe1850b61a
Revises: 7afe98d04169
Create Date: 2023-04-29 21:33:22.657554
"""
from alembic import op
import sqlalchemy as sa
import ormar
# revision identifiers, used by Alembic.
revision = "4bbe1850b61a"
down_revision = "7afe98d04169"
branch_labels = None
depends_on = None
def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"quiztivitys",
sa.Column("id", ormar.fields.sqlalchemy_uuid.CHAR(32), nullable=False),
sa.Column("title", sa.Text(), nullable=False),
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False),
sa.Column("user", ormar.fields.sqlalchemy_uuid.CHAR(32), nullable=True),
sa.Column("pages", sa.JSON(), nullable=False),
sa.ForeignKeyConstraint(["user"], ["users.id"], name="fk_quiztivitys_users_id_user"),
sa.PrimaryKeyConstraint("id"),
)
# ### end Alembic commands ###
def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table("quiztivitys")
# ### end Alembic commands ###