123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import "@logseq/libs";
- import { BlockEntity } from "@logseq/libs/dist/LSPlugin.user";
- const endpoint = 'http://localhost:3000/quizzes';
- const uniqueIdentifier = () =>
- Math.random()
- .toString(36)
- .replace(/[^a-z]+/g, "");
- async function fetchQuizzes() {
- const { status: status, content: quizzes } = await fetch(endpoint).then(res => res.json())
- const ret = quizzes || []
- return ret.map((quiz, i) => {
- return `${i + 1}. ${quiz.Question.Text}`
- })
- }
- const main = () => {
- console.log("logseq-quizhub-plugin LOADED!");
- logseq.Editor.registerSlashCommand("Get All Quizzes", async () => {
- const currBlock = await logseq.Editor.getCurrentBlock();
- let blocks = await fetchQuizzes()
- blocks = blocks.map((it: BlockEntity) => ({ content: it }))
- await logseq.Editor.insertBatchBlock(currBlock.uuid, blocks, {
- sibling: false
- })
- });
- logseq.Editor.registerSlashCommand("Insert a batch of quizzes", async () => {
- await logseq.Editor.insertAtEditingCursor(
- `{{renderer :quizhub_${uniqueIdentifier()}}}`
- );
- const currBlock = await logseq.Editor.getCurrentBlock();
- await logseq.Editor.insertBlock(currBlock.uuid, 'Text of the question here...',
- {
- sibling: false,
- before: false,
- }
- );
- await logseq.Editor.exitEditingMode();
- });
- logseq.App.onMacroRendererSlotted(async ({ slot, payload }) => {
- const [type] = payload.arguments;
- const id = type.split("_")[1]?.trim();
- const quizhubId = `quizhub_${id}`;
- logseq.provideModel({
- async postQuiz() {
- const parentBlock = await logseq.Editor.getBlock(payload.uuid, { includeChildren: true });
- const quizzes = parentBlock.children.map((child: BlockEntity) => {
- const question = { text: child.content }
- const answers = child.children.map((answer: BlockEntity, i: number) => {
- return { text: answer.content, correct: (i == 0) ? true : false }
- })
- return { question: question, answers: answers }
- });
- quizzes.forEach(async quiz => {
- const res = await fetch(endpoint, { method: 'POST', body: JSON.stringify(quiz) })
- const data = await res.json();
- console.log(data)
- })
- }
- });
- logseq.provideStyle(`
- .renderBtn {
- border: 1px solid black;
- border-radius: 8px;
- padding: 3px;
- font-size: 80%;
- background-color: white;
- color: black;
- }
- .renderBtn:hover {
- background-color: black;
- color: white;
- }
- `);
- logseq.provideUI({
- key: `${quizhubId}`,
- slot,
- reset: true,
- template: `<button data-on-click="postQuiz" class="renderBtn">Save</button>`,
- });
- });
- };
- logseq.ready(main).catch(console.error);
|