first commit

This commit is contained in:
@s.roertgen 2025-04-29 20:29:45 +02:00
commit def118101d
34 changed files with 4625 additions and 0 deletions

23
.gitignore vendored Normal file
View file

@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*

1
.npmrc Normal file
View file

@ -0,0 +1 @@
engine-strict=true

6
.prettierignore Normal file
View file

@ -0,0 +1,6 @@
# Package Managers
package-lock.json
pnpm-lock.yaml
yarn.lock
bun.lock
bun.lockb

15
.prettierrc Normal file
View file

@ -0,0 +1,15 @@
{
"useTabs": true,
"singleQuote": true,
"trailingComma": "none",
"printWidth": 100,
"plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
"overrides": [
{
"files": "*.svelte",
"options": {
"parser": "svelte"
}
}
]
}

38
README.md Normal file
View file

@ -0,0 +1,38 @@
# sv
Everything you need to build a Svelte project, powered by [`sv`](https://github.com/sveltejs/cli).
## Creating a project
If you're seeing this, you've probably already done this step. Congrats!
```bash
# create a new project in the current directory
npx sv create
# create a new project in my-app
npx sv create my-app
```
## Developing
Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:
```bash
npm run dev
# or start the server and open the app in a new browser tab
npm run dev -- --open
```
## Building
To create a production version of your app:
```bash
npm run build
```
You can preview the production build with `npm run preview`.
> To deploy your app, you may need to install an [adapter](https://svelte.dev/docs/kit/adapters) for your target environment.

26
eslint.config.js Normal file
View file

@ -0,0 +1,26 @@
import prettier from 'eslint-config-prettier';
import js from '@eslint/js';
import { includeIgnoreFile } from '@eslint/compat';
import svelte from 'eslint-plugin-svelte';
import globals from 'globals';
import { fileURLToPath } from 'node:url';
import svelteConfig from './svelte.config.js';
const gitignorePath = fileURLToPath(new URL('./.gitignore', import.meta.url));
export default [
includeIgnoreFile(gitignorePath),
js.configs.recommended,
...svelte.configs.recommended,
prettier,
...svelte.configs.prettier,
{
languageOptions: {
globals: { ...globals.browser, ...globals.node }
}
},
{
files: ['**/*.svelte', '**/*.svelte.js'],
languageOptions: { parserOptions: { svelteConfig } }
}
];

19
jsconfig.json Normal file
View file

@ -0,0 +1,19 @@
{
"extends": "./.svelte-kit/tsconfig.json",
"compilerOptions": {
"allowJs": true,
"checkJs": true,
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"sourceMap": true,
"strict": true,
"moduleResolution": "bundler"
}
// Path aliases are handled by https://svelte.dev/docs/kit/configuration#alias
// except $lib which is handled by https://svelte.dev/docs/kit/configuration#files
//
// If you want to overwrite includes/excludes, make sure to copy over the relevant includes/excludes
// from the referenced tsconfig.json - TypeScript does not merge them in
}

3819
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

42
package.json Normal file
View file

@ -0,0 +1,42 @@
{
"name": "edufeed2",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
"format": "prettier --write .",
"lint": "prettier --check . && eslint ."
},
"devDependencies": {
"@eslint/compat": "^1.2.5",
"@eslint/js": "^9.18.0",
"@sveltejs/adapter-auto": "^6.0.0",
"@sveltejs/kit": "^2.16.0",
"@sveltejs/vite-plugin-svelte": "^5.0.0",
"@tailwindcss/vite": "^4.0.0",
"eslint": "^9.18.0",
"eslint-config-prettier": "^10.0.1",
"eslint-plugin-svelte": "^3.0.0",
"globals": "^16.0.0",
"prettier": "^3.4.2",
"prettier-plugin-svelte": "^3.3.3",
"prettier-plugin-tailwindcss": "^0.6.11",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"tailwindcss": "^4.0.0",
"typescript": "^5.0.0",
"vite": "^6.2.6"
},
"dependencies": {
"@nostr-dev-kit/ndk": "^2.14.5",
"@nostr-dev-kit/ndk-svelte": "^2.4.10",
"daisyui": "^5.0.28",
"qrcode": "^1.5.4"
}
}

6
src/app.css Normal file
View file

@ -0,0 +1,6 @@
@import 'tailwindcss';
@plugin "daisyui";
html, body {
height: 100%;
}

13
src/app.d.ts vendored Normal file
View file

@ -0,0 +1,13 @@
// See https://svelte.dev/docs/kit/types#app.d.ts
// for information about these interfaces
declare global {
namespace App {
// interface Error {}
// interface Locals {}
// interface PageData {}
// interface PageState {}
// interface Platform {}
}
}
export {};

12
src/app.html Normal file
View file

@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>

View file

@ -0,0 +1,7 @@
<script>
export let event;
</script>
<div>
<p>{event.content}</p>
</div>

1
src/lib/index.js Normal file
View file

@ -0,0 +1 @@
// place files you want to import through the `$lib` alias in this folder.

25
src/lib/stores.js Normal file
View file

@ -0,0 +1,25 @@
import NDKSvelte from "@nostr-dev-kit/ndk-svelte";
import { writable, derived } from "svelte/store";
import { NDKNip07Signer } from "@nostr-dev-kit/ndk";
export let connected = writable(false);
export const ndk = writable(new NDKSvelte);
export const ndkReady = derived(ndk, $ndk => $ndk !== null);
export async function initializeNDK() {
const signer = new NDKNip07Signer
const ndkInstance = new NDKSvelte({
explicitRelayUrls: [
'wss://relay-rpi.edufeed.org'
],
});
await ndkInstance.connect();
// ndkInstance.signer = signer;
ndk.set(ndkInstance);
return ndkInstance;
}

27
src/routes/+layout.svelte Normal file
View file

@ -0,0 +1,27 @@
<script>
import '../app.css';
import { onMount } from 'svelte';
import { NDKNip07Signer } from '@nostr-dev-kit/ndk';
import NDKSvelte from '@nostr-dev-kit/ndk-svelte/svelte5';
import { ndk, connected, initializeNDK } from '$lib/stores';
import { browser } from '$app/environment';
let { children } = $props();
onMount(async () => {
const nip07signer = new NDKNip07Signer();
if (browser) {
try {
await initializeNDK();
console.log('NDK initialized successfully');
connected.set(true);
} catch (error) {
console.error('Failed to initialize NDK:', error);
}
}
});
</script>
{@render children()}

163
src/routes/+page.svelte Normal file
View file

@ -0,0 +1,163 @@
<script>
import { goto } from '$app/navigation';
import { ndk, connected } from '$lib/stores';
import { NDKEvent, NDKNip07Signer, NDKPrivateKeySigner } from '@nostr-dev-kit/ndk';
import { writable } from 'svelte/store';
import QRCode from 'qrcode';
let question = '';
let questionId = '';
let questionShortId = 0;
let qrCodeUrl = '';
let timer = 0;
let comments = writable([]);
let votingEnabled = false;
let sessionId = '';
async function joinSession() {
console.log('join ' + questionShortId);
const filter = {
kinds: [2222],
'#d': [questionShortId + ''], // filter by `d` tag
limit: 1
};
const question = await $ndk.fetchEvent(filter);
goto('/q/' + question.id);
}
async function postQuestion() {
questionShortId = 10000000 + Math.floor(Math.random() * 90000000);
const event = new NDKEvent($ndk, {
kind: 1342,
content: question,
tags: [['d', questionShortId + '']]
});
await event.publish();
questionId = event.id;
qrCodeUrl = await QRCode.toDataURL(`${window.location.origin}/q/${questionId}`);
}
function startTimer() {
const interval = setInterval(() => {
if (timer > 0) {
timer--;
} else {
clearInterval(interval);
votingEnabled = true;
}
}, 1000);
}
function login() {
if (window.nostr) {
const signer = new NDKNip07Signer();
$ndk.signer = signer;
} else {
const signer = new NDKPrivateKeySigner();
const privateKey = signer.generatePrivateKey(); // Generates a new private key
console.log('Generated Private Key:', privateKey);
}
}
</script>
<div class="main-layout">
<button class="btn btn-success" onclick={() => login()}>Login</button>
{#if !questionId}
<div class="mx-auto p-4">
<h1 class="mb-4 text-2xl font-bold">Join a session!</h1>
{#if $connected}
<div class="join">
<input type="number" class="border p-2" placeholder="Session id" bind:value={sessionId} />
<button class="btn btn-primary rounded" onclick={joinSession}> Join </button>
</div>
{/if}
</div>
<div class="divider" />
{/if}
<div class="mx-auto p-4">
<h1 class="mb-4 text-2xl font-bold">Ask a Question</h1>
{#if $connected}
{#if !questionId}
<div>
<textarea
class="mb-4 w-full rounded border p-2"
placeholder="Type your question here..."
bind:value={question}
></textarea>
<button class="btn btn-primary rounded" onclick={postQuestion}> Post Question </button>
</div>
{/if}
{#if questionId}
<div class="qr-share mt-4">
<h2 class="text-xl font-bold">Share Your Question</h2>
<img src={qrCodeUrl} alt="QR Code" class="mt-2" />
<p class="mb-5 text-center">Share this QR code or link:</p>
<p class="text-center">
<a href={`/q/${questionId}`}>{`/q/`}<span class="font-bold">{questionShortId}</span></a>
</p>
<h3 class="text-center text-xl">{questionShortId}</h3>
<div class="mt-4">
<label for="timer" class="mb-2 block">Set Timer (seconds):</label>
<input type="number" id="timer" class="rounded border p-2" bind:value={timer} />
<button class="ml-2 rounded bg-green-500 px-4 py-2 text-white" onclick={startTimer}>
Start Timer
</button>
</div>
</div>
{/if}
{#if votingEnabled}
<div class="mt-4">
<h2 class="text-xl font-bold">Voting is now enabled!</h2>
<p>Users can now vote on the question.</p>
</div>
{/if}
{:else}
<p>Connecting to Nostr relay...</p>
{/if}
</div>
</div>
<style>
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
:root {
display: grid;
place-items: center; /* shorthand for both horizontal and vertical centering */
height: 100%;
}
.qr-share img {
width: 100%;
border: 3px solid #eee;
aspect-ratio: 4 / 3;
}
.main-layout {
margin: auto;
width: 100vw;
max-width: 600px;
display: flex;
justify-content: center;
flex-direction: column;
gap: 5%;
height: 100%;
}
.main-layout > div {
width: 100%;
}
.divider {
background-color: #eee;
height: 1px;
}
.join {
display: flex;
gap: 10px;
width: 100%;
}
.join input {
flex-grow: 1;
}
</style>

View file

@ -0,0 +1,12 @@
import { error } from '@sveltejs/kit';
/** @type {import('./$types').PageLoad} */
export function load({ params }) {
if (params.id) {
return {
id: params.id,
};
}
error(404, 'Not found');
}

View file

@ -0,0 +1,63 @@
<script>
/** @type {import('./$types').PageProps} */
let { data } = $props();
import Comment from '$lib/components/Comment.svelte';
import { ndk, connected, ndkReady } from '$lib/stores';
import { NDKEvent } from '@nostr-dev-kit/ndk';
import { writable } from 'svelte/store';
function submitComment() {
const commentEvent = new NDKEvent($ndk, {
kind: 2222,
content: comment,
tags: [["E", data.id]]
});
commentEvent.publish();
}
let comment = ""
let comments = writable([]);
let question = writable("")
$effect(() => {
if ($ndkReady) {
const sub = $ndk.subscribe({ kinds: [2222], "#E": [data.id] });
sub.on('event', (event) => {
$comments = [...$comments, event];
console.log(`${event.content}`);
});
}
});
</script>
<div class="w-full flex flex-col justify-center mx-auto items-center">
<h1 class="">Identifier: {data.id}</h1>
<div>{@html data.id}</div>
{#await $ndk.fetchEvent(data.id) then question}
{#if question}
<div class="mb-4 w-full rounded border p-2">
<h2>Question: {question.content}</h2>
<p>Tags: {question.tags}</p>
<p>Created At: {new Date(question.created_at * 1000).toLocaleString()}</p>
</div>
<div>
<h1 class="text-xl">Ideensammlung</h1>
<textarea bind:value={comment} placeholder="Mein Kommentar"></textarea>
<button class="btn btn-error" onclick={() => submitComment()}>Absenden</button>
</div>
{:else}
<p>Loading...</p>
{/if}
{:catch error}
<p>Error fetching question: {error.message}</p>
{/await}
{#each $comments as event}
<Comment {event} />
{/each}
</div>

BIN
static/favicon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

13
svelte.config.js Normal file
View file

@ -0,0 +1,13 @@
import adapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const config = {
kit: {
// adapter-auto only supports some environments, see https://svelte.dev/docs/kit/adapter-auto for a list.
// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
// See https://svelte.dev/docs/kit/adapters for more information about adapters.
adapter: adapter()
}
};
export default config;

View file

@ -0,0 +1,69 @@
# SvelteKit NDK App
This project is a SvelteKit application that utilizes the NDK (Nostr Development Kit) library for building decentralized applications. It incorporates Tailwind CSS for styling, providing a modern and responsive UI.
## Features
- User authentication via browser extension or key pair creation.
- Ability to submit questions and receive comments.
- Voting mechanism after a timer expires.
- Real-time event handling using Nostr protocol.
## Project Structure
```
sveltekit-ndk-app
├── src
│ ├── lib
│ │ └── components
│ │ └── ExampleComponent.svelte
│ ├── routes
│ │ ├── +layout.svelte
│ │ ├── +page.svelte
│ │ └── api
│ │ └── +server.js
│ ├── app.css
│ └── app.html
├── static
│ └── favicon.ico
├── tailwind.config.cjs
├── postcss.config.cjs
├── package.json
├── svelte.config.js
├── tsconfig.json
└── README.md
```
## Installation
1. Clone the repository:
```
git clone <repository-url>
cd sveltekit-ndk-app
```
2. Install dependencies:
```
npm install
```
3. Run the development server:
```
npm run dev
```
4. Open your browser and navigate to `http://localhost:3000`.
## Usage
- Users can log in using a browser extension or create a new key pair.
- After logging in, users can submit questions and view responses.
- Comments can be made until the timer expires, after which users can vote on the questions.
## Contributing
Contributions are welcome! Please open an issue or submit a pull request for any enhancements or bug fixes.
## License
This project is licensed under the MIT License. See the LICENSE file for more details.

View file

@ -0,0 +1,24 @@
{
"name": "sveltekit-ndk-app",
"version": "1.0.0",
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
},
"dependencies": {
"svelte": "^3.44.0",
"sveltekit": "latest",
"@nostr-dev-kit/ndk-svelte": "^0.1.0",
"tailwindcss": "^2.2.19",
"postcss": "^8.4.6",
"autoprefixer": "^10.4.0"
},
"devDependencies": {
"vite": "^2.6.14",
"svelte-preprocess": "^4.9.4"
},
"keywords": [],
"author": "",
"license": "MIT"
}

View file

@ -0,0 +1,6 @@
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};

View file

@ -0,0 +1,5 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
/* Custom styles can be added below this line */

View file

@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SvelteKit NDK App</title>
<link rel="stylesheet" href="/app.css">
</head>
<body>
<div id="svelte"></div>
</body>
</html>

View file

@ -0,0 +1,22 @@
<!-- filepath: /sveltekit-ndk-app/sveltekit-ndk-app/src/routes/+layout.svelte -->
<script>
export let segment;
</script>
<div class="min-h-screen flex flex-col">
<header class="bg-blue-600 text-white p-4">
<h1 class="text-xl">Nostr Event App</h1>
</header>
<main class="flex-grow p-4">
<slot />
</main>
<footer class="bg-gray-800 text-white p-4 text-center">
<p>&copy; 2023 Nostr Event App</p>
</footer>
</div>
<style>
/* Additional styles can be added here */
</style>

View file

@ -0,0 +1,84 @@
<script>
import { onMount } from 'svelte';
import NDKSvelte from '@nostr-dev-kit/ndk-svelte';
import { writable, derived } from 'svelte/store';
const ndk = new NDKSvelte({
explicitRelayUrls: ['wss://relay-rpi.edufeed.org']
});
const connected = writable(false);
let events = writable([]);
let liascriptEvents = writable([]);
const count = derived(events, ($events) => $events.length);
onMount(async () => {
try {
await ndk.connect();
connected.set(true);
events = ndk.storeSubscribe({ kinds: [30142] }, { closeOnEose: false });
liascriptEvents = ndk.storeSubscribe({ kinds: [30143] }, { closeOnEose: false });
console.log('Subscription created and store initialized');
} catch (error) {
console.error('Error connecting to Nostr relay:', error);
}
});
</script>
{#if $connected}
<p class="status connected">Connected to Nostr relay</p>
{:else}
<p class="status connecting">Connecting to Nostr relay...</p>
{/if}
<h1>Nostr Events</h1>
<p>
{$count} events seen
</p>
{#if $events && $events.length > 0}
<h2>Recent events</h2>
<ul>
{#each $events as event}
<li>
Event ID: {event.id.substring(0, 8)}...
{#if event.content}
<p>Content: {event.content}</p>
{/if}
</li>
{/each}
</ul>
{:else}
<p>No events received yet. Waiting for events...</p>
{/if}
<style>
.status {
padding: 8px;
border-radius: 4px;
margin-bottom: 16px;
}
.connecting {
background-color: #fff3cd;
color: #856404;
}
.connected {
background-color: #d4edda;
color: #155724;
}
h1 {
margin-bottom: 16px;
}
ul {
list-style-type: none;
padding: 0;
}
li {
border: 1px solid #eee;
padding: 12px;
margin-bottom: 8px;
border-radius: 4px;
}
</style>

View file

@ -0,0 +1,25 @@
import { json } from '@sveltejs/kit';
export async function POST({ request }) {
const data = await request.json();
// Here you would handle the data, e.g., save it to a database or process it
// For demonstration, we'll just return the received data
return json({
status: 'success',
data: data
});
}
export async function GET({ url }) {
// Here you could fetch data from a database or another API
// For demonstration, we'll return a static response
const exampleData = {
message: 'Hello from the API!',
timestamp: new Date().toISOString()
};
return json(exampleData);
}

View file

@ -0,0 +1 @@
<!-- This file is intentionally left blank. -->

View file

@ -0,0 +1,14 @@
import adapter from '@sveltejs/adapter-auto';
import preprocess from 'svelte-preprocess';
export default {
preprocess: preprocess(),
kit: {
adapter: adapter(),
vite: {
css: {
postcss: true
}
}
}
};

View file

@ -0,0 +1,11 @@
module.exports = {
content: [
'./src/**/*.{svelte,js,ts}',
'./src/lib/**/*.{svelte,js,ts}',
'./src/routes/**/*.{svelte,js,ts}',
],
theme: {
extend: {},
},
plugins: [],
};

View file

@ -0,0 +1,11 @@
{
"extends": "@sveltejs/tsconfig",
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}

10
vite.config.js Normal file
View file

@ -0,0 +1,10 @@
import tailwindcss from '@tailwindcss/vite';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
server: {
host: true
},
plugins: [tailwindcss(), sveltekit()]
});