first commit

main
Laurin Weger 9 months ago
commit 1b83bedc2f
Signed by: laurin
GPG Key ID: C62769CE726A5F92
  1. 42
      .gitignore
  2. 176
      LICENSE-APACHE2
  3. 22
      LICENSE-MIT
  4. 125
      README.md
  5. 33
      index.html
  6. 29
      package.json
  7. 3124
      pnpm-lock.yaml
  8. 246
      src/components/ExpenseCard.svelte
  9. 54
      src/components/ExpenseCategories.svelte
  10. 101
      src/components/ExpenseCategoryCard.svelte
  11. 70
      src/components/Expenses.svelte
  12. 28
      src/components/Main.svelte
  13. 21
      src/components/useDocumentStore.svelte.ts
  14. 314
      src/expense-tracker.css
  15. 74
      src/types.ts
  16. 12
      src/utils/index.ts
  17. 66
      src/utils/loadStore.ts
  18. 62
      src/utils/ngSession.ts
  19. 17
      tsconfig.json
  20. 7
      vite.config.ts

42
.gitignore vendored

@ -0,0 +1,42 @@
# dependencies (bun install)
node_modules
# output
out
dist
*.tgz
# code coverage
coverage
*.lcov
# logs
logs
_.log
report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# caches
.eslintcache
.cache
*.tsbuildinfo
# IntelliJ based IDEs
.idea
# Finder (MacOS) folder config
.DS_Store
.astro
# Playwright
/test-results/
/playwright-report/
/blob-report/
/playwright/.cache/

@ -0,0 +1,176 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

@ -0,0 +1,125 @@
# NextGraph Svelte Expense Tracker Example with Discrete JSON Documents
A complete example app demonstrating the **NextGraph Discrete (Yjs/Automerge) ORM SDK** in Svelte. Changes are immediately persisted and synced with other devices. All data is encrypted.
This README walks you through the features of the SDK and how to build your own NextGraph-powered application.
You can find examples for Vue and React frontends and the RDF (graph) ORM [here](https://docs.nextgraph.org/en/framework/getting-started/).
---
## Table of Contents
- [NextGraph Svelte Expense Tracker Example with Discrete JSON Documents](#nextgraph-svelte-expense-tracker-example-with-discrete-json-documents)
- [Table of Contents](#table-of-contents)
- [Quick Start](#quick-start)
- [Project Structure](#project-structure)
- [Building Your Own App](#building-your-own-app)
- [Step 1: Install Dependencies](#step-1-install-dependencies)
- [Step 2: Initialization](#step-2-initialization)
- [Step 3: Use the Data in the Components](#step-3-use-the-data-in-the-components)
- [About NextGraph](#about-nextgraph)
- [License](#license)
---
## Quick Start
Create a wallet at https://nextgraph.eu and log in once with your password.
Clone this repo:
```bash
# Clone the repository
git clone https://git.nextgraph.org/NextGraph/expense-tracker-discrete-svelte.git
cd expense-tracker-discrete-svelte
# Install dependencies
pnpm install
# Run the development server:
pnpm dev
```
Open the URL displayed in the console. You'll be redirected to NextGraph to authenticate with your wallet, then your app loads inside NextGraph's secure iframe.
---
## Project Structure
```
src/
├── components/ # The app's components
│
├── utils/
│ ├── loadStore.ts # Creates or loads the CRDT document with your data
│ ├── ngSession.ts # NextGraph session initialization
│ └── useDocumentStore.ts # Hook that's used in the components to get the document data
└── types.ts # Types for the data store
```
---
## Building Your Own App
If you want to create your own app, clone this repo or walk through the following steps.
### Step 1: Install Dependencies
```bash
pnpm add @ng-org/web@latest @ng-org/orm@latest
# Or npm install / yarn add / ...
```
| Package | Purpose |
| -------------------- | --------------------------------------- |
| `@ng-org/web` | Core NextGraph SDK for web applications |
| `@ng-org/orm` | Core ORM utilities |
| `@ng-org/orm/svelte` | svelte framework-specific hooks |
### Step 2: Initialization
Your app will run inside a NextGraph-controlled iframe. To make things easier for you, we created a utility file that handles initialization, see [`src/utils/ngSession.ts`](src/utils/ngSession.ts).
The file exports an `init()` function. When it is called outside of an iframe, it will redirected you to authenticate with your wallet. **That's why you should call it as early as possible**, to prevent shortly rendered pages directly followed by the redirect. In this app, we call it in [`index.html`](./index.html).
Now we have a session and need to load (and possibly create) a document. The document contains the data that we use for our application and that we subscribe to.
You can see how this is done in [`src/utils/loadStore.ts`](src/utils/loadStore.ts).\
In `loadStore.ts`, you can see how a subscription to the document is created that the application uses. To find the document id, a SPARQL graph query is made: To every document, you can attach RDF data. We leverage that here by attaching an application-specific quad (e.g. `<documentId> <type> <did:ng:z:ExpenseTrackerDiscreteApp-Automerge>`), to find the document again. Once we have the document id, we can create an ORM subscription. Note that creating the subscription here is strictly speaking not necessary. The `useDiscrete` hook that is introduced next can create a subscription by itself. If a subscription is open however, the hook will use that one. In our case, the subscription remains open throughout the application's lifetime and we don't need to wait for the initialization of a subscription again and again.
### Step 3: Use the Data in the Components
In the hook [`useDocumentStore`](src/utils/useDocumentStore.ts), you can see how we subscribe to the document that stores expenses and expense categories.
Use the `useDiscrete` hook to create 2-way bindings between the engine and svelte.
You can see that modifications to values of the returned `doc` in the (child) components will immediately update them.
In addition to the component update, the modified data is immediately persisted and will be synchronized with other applications and devices as well. When changes are coming from the engine (e.g. a different device made a change), the components update too.
When the subscription isn't established yet, `doc` will be `undefined`
For an example, see [`src/components/Expenses.tsx`](src/components/Expenses.tsx) and the [`ExpenseCard`](src/components/ExpenseCard.tsx) children.
For more advanced data and subscription management, e.g. transactions or component-independent stores, see the TS docs of `@ng-org/orm` (especially DiscreteOrmSubscription) and the [reference](https://docs.nextgraph.org/en/reference/orm/#overview).
## About NextGraph
> **NextGraph** brings about the convergence of P2P and Semantic Web technologies, towards a decentralized, secure and privacy-preserving cloud, based on CRDTs.
>
> This open source ecosystem provides solutions for end-users (a platform) and software developers (a framework), wishing to use or create **decentralized** apps featuring: **live collaboration** on rich-text documents, peer to peer communication with **end-to-end encryption**, offline-first, **local-first**, portable and interoperable data, total ownership of data and software, security and privacy.
>
> Centered on repositories containing **semantic data** (RDF), **rich text**, and structured data formats like **JSON**, synced between peers belonging to permissioned groups of users, it offers strong eventual consistency, thanks to the use of **CRDTs**. Documents can be linked together, signed, shared securely, queried using the **SPARQL** language and organized into sites and containers.
>
> More info: [https://nextgraph.org](https://nextgraph.org)
## License
Licensed under either of
- Apache License, Version 2.0 ([LICENSE-APACHE2](LICENSE-APACHE2) or http://www.apache.org/licenses/LICENSE-2.0)
- MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
at your option.
`SPDX-License-Identifier: Apache-2.0 OR MIT`
---
NextGraph received funding through the [NGI Assure Fund](https://nlnet.nl/assure) and the [NGI Zero Commons Fund](https://nlnet.nl/commonsfund/), both funds established by [NLnet](https://nlnet.nl/) Foundation with financial support from the European Commission's [Next Generation Internet](https://ngi.eu/) programme, under the aegis of DG Communications Networks, Content and Technology under grant agreements No 957073 and No 101092990, respectively.

@ -0,0 +1,33 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script type="module">
// Initialize as early as possible to prevent rendering before redirect to auth.
import { init as initNg, sessionPromise } from "./src/utils/ngSession";
let crdt = import.meta.env.NG_CRDT;
initNg(crdt);
</script>
<link rel="stylesheet" href="./src/expense-tracker.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Expense Tracker in Svelte with Discrete ORM</title>
</head>
<body>
<div id="root"></div>
<script type="module" lang="ts">
import { mount } from "svelte";
import App from "./src/components/Main.svelte";
import { sessionPromise } from "./src/utils/ngSession";
await sessionPromise;
mount(App, { target: document.getElementById("root") });
</script>
</body>
</html>

@ -0,0 +1,29 @@
{
"name": "@ng-org/expense-tracker-discrete-svelte",
"version": "0.1.0",
"private": true,
"authors": [
"Laurin Weger"
],
"license": "MIT/Apache-2.0",
"type": "module",
"scripts": {
"dev-automerge": "cross-env NG_CRDT=Automerge vite dev",
"dev-yjs": "cross-env NG_CRDT=YMap vite dev",
"build-automerge": "cross-env NG_CRDT=Automerge vite build",
"build-yjs": "cross-env NG_CRDT=YMap vite build"
},
"dependencies": {
"@ng-org/orm": "0.1.2-alpha.11",
"@ng-org/web": "0.1.2-alpha.8",
"svelte": "^5.53.3"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^6.2.4",
"vite": "^7.1.3",
"cross-env": "^7.0.3"
},
"engines": {
"node": ">=22.18"
}
}

File diff suppressed because it is too large Load Diff

@ -0,0 +1,246 @@
<!--
// Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
-->
<script lang="ts">
import type { Expense, ExpenseCategory } from "../types.ts";
import type { DeepSignal } from "@ng-org/orm";
let {
expense = $bindable(),
availableCategories = $bindable(),
}: {
expense: DeepSignal<Expense>;
availableCategories: DeepSignal<ExpenseCategory[]>;
} = $props();
let isEditing = $state(false);
const paymentStatusLabels: Record<Expense["paymentStatus"], string> = {
Paid: "Paid",
Pending: "Pending",
Overdue: "Overdue",
Refunded: "Refunded",
};
const paymentStatusEntries = Object.entries(paymentStatusLabels);
const currencyFormatter = new Intl.NumberFormat("en-US", {
style: "currency",
currency: "EUR",
minimumFractionDigits: 2,
});
const purchaseDate = $derived(
expense.dateOfPurchase
? new Date(expense.dateOfPurchase).toLocaleDateString()
: "Date not set",
);
const totalPriceDisplay = $derived(
currencyFormatter.format(expense.totalPrice ?? 0),
);
const isCategorySelected = (category: ExpenseCategory) =>
!!expense.expenseCategories?.includes(category["@id"] ?? "");
const toggleCategory = (category: ExpenseCategory, checked: boolean) => {
const categoryId = category["@id"];
if (!categoryId) return;
if (checked) {
if (!expense.expenseCategories) {
expense.expenseCategories = [categoryId];
} else if (!expense.expenseCategories.includes(categoryId)) {
expense.expenseCategories.push(categoryId);
}
} else {
expense.expenseCategories = (expense.expenseCategories ?? []).filter(
(value) => value !== categoryId,
);
}
};
function nameOfCategory(categoryIri: string) {
return availableCategories.find((c) => c["@id"] === categoryIri)
?.categoryName;
}
</script>
<article class="expense-card">
<div class="expense-header">
<div class="header-text">
{#if isEditing}
<input
class="header-input"
value={expense.title ?? ""}
oninput={(event) =>
(expense.title = event.currentTarget?.value ?? "")}
placeholder="Expense title"
/>
{:else}
<h3 class="header-title">{expense.title || "New expense"}</h3>
{/if}
<p class="muted small-margin">{purchaseDate}</p>
</div>
<button
type="button"
class="icon-btn"
aria-label={isEditing ? "Close editing" : "Edit expense"}
onclick={() => (isEditing = !isEditing)}
>
{#if isEditing}
<svg
data-slot="icon"
fill="none"
stroke-width="1.5"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M6 18 18 6M6 6l12 12"
></path>
</svg>
{:else}
<svg
data-slot="icon"
fill="none"
stroke-width="1.5"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125"
></path>
</svg>
{/if}
</button>
</div>
<div class="info-grid">
<div class="field-group">
<span class="field-label">Description</span>
{#if isEditing}
<textarea
class="textarea"
value={expense.description ?? ""}
oninput={(event) =>
(expense.description = event.currentTarget?.value ?? "")}
placeholder="Add helpful context"
></textarea>
{:else}
<p class="value-text">{expense.description || "No description yet."}</p>
{/if}
</div>
<div class="field-group">
<span class="field-label">Total price (€)</span>
{#if isEditing}
<input
type="number"
class="input"
value={expense.totalPrice ?? 0}
oninput={(event) => {
const next = event.currentTarget?.valueAsNumber;
expense.totalPrice = Number.isFinite(next) ? (next ?? 0) : 0;
}}
/>
{:else}
<span class="value-text">{totalPriceDisplay}</span>
{/if}
</div>
<div class="field-group">
<span class="field-label">Quantity</span>
{#if isEditing}
<input
type="number"
min="1"
class="input"
value={expense.amount ?? 1}
oninput={(event) => {
const next = event.currentTarget?.valueAsNumber;
expense.amount = Number.isFinite(next) ? (next ?? 1) : 1;
}}
/>
{:else}
<span class="value-text">{expense.amount ?? 1}</span>
{/if}
</div>
<div class="field-group">
<span class="field-label">Payment status</span>
{#if isEditing}
<select
class="select"
value={expense.paymentStatus}
onchange={(event) => {
const selected = event.currentTarget?.value;
if (selected) {
expense.paymentStatus = selected as Expense["paymentStatus"];
}
}}
>
{#each paymentStatusEntries as [iri, label]}
<option value={iri}>{label}</option>
{/each}
</select>
{:else}
<span class="value-text">
{paymentStatusLabels[expense.paymentStatus] ?? "Unknown"}
</span>
{/if}
</div>
</div>
<div class="field-group">
<span class="field-label">Categories</span>
{#if isEditing}
{#if availableCategories.length}
<div class="category-picker">
{#each availableCategories as category}
<label class="category-option">
<input
type="checkbox"
class="checkbox"
checked={isCategorySelected(category)}
onchange={(event) =>
toggleCategory(
category,
event.currentTarget?.checked ?? false,
)}
/>
<span class="category-text">
<strong>{category.categoryName || "Unnamed"}</strong>
<small class="muted">
{category.description || "No description"}
</small>
</span>
</label>
{/each}
</div>
{:else}
<p class="muted">No categories available yet. Create one above.</p>
{/if}
{:else}
{#if expense.expenseCategories?.length}
<div class="chip-list">
{#each expense.expenseCategories as categoryIri}
<span class="chip">{nameOfCategory(categoryIri) || "Unnamed"}</span>
{/each}
</div>
{:else}
<p class="muted">No categories linked.</p>
{/if}
<small class="helper-text">Enter edit mode to link categories.</small>
{/if}
</div>
</article>

@ -0,0 +1,54 @@
<!--
// Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
-->
<script lang="ts">
import { useDocumentStore } from "./useDocumentStore.svelte";
import ExpenseCategoryCard from "./ExpenseCategoryCard.svelte";
const store = useDocumentStore();
const expenseCategories = $derived(store.doc?.expenseCategories);
function createCategory() {
if (!expenseCategories) return;
expenseCategories.push({
categoryName: "New category",
description: "",
});
}
</script>
<section class="panel">
<header class="panel-header">
<div>
<p class="label-accent">Categories</p>
<h2 class="title">
Expense Categories
<span class="badge">{expenseCategories?.length || ""} total</span>
</h2>
</div>
<div class="header-actions">
<button type="button" class="primary-btn" onclick={createCategory}>
+ New category
</button>
</div>
</header>
{#if !expenseCategories}
Loading...
{:else if !expenseCategories.length}
<p class="muted">No categories yet</p>
{:else}
<div class="cards-grid">
{#each expenseCategories as category (category["@id"])}
<ExpenseCategoryCard {category} />
{/each}
</div>
{/if}
</section>

@ -0,0 +1,101 @@
<!--
// Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
-->
<script lang="ts">
import type { ExpenseCategory } from "../types.ts";
import type { DeepSignal } from "@ng-org/orm";
let { category }: { category: DeepSignal<ExpenseCategory> } = $props();
let isEditing = $state(false);
const idBase = $derived(
category["@id"] ?? category.categoryName ?? "category",
);
</script>
<article class="category-card">
<div class="card-header">
<div>
<p class="label-accent">Category</p>
<h3 class="title">{category.categoryName || "Untitled category"}</h3>
</div>
<button
type="button"
class="icon-btn"
aria-label={isEditing ? "Close editing" : "Edit category"}
onclick={() => (isEditing = !isEditing)}
>
{#if isEditing}
<svg
data-slot="icon"
fill="none"
stroke-width="1.5"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M6 18 18 6M6 6l12 12"
></path>
</svg>
{:else}
<svg
data-slot="icon"
fill="none"
stroke-width="1.5"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="m16.862 4.487 1.687-1.688a1.875 1.875 0 1 1 2.652 2.652L6.832 19.82a4.5 4.5 0 0 1-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 0 1 1.13-1.897L16.863 4.487Zm0 0L19.5 7.125"
></path>
</svg>
{/if}
</button>
</div>
{#if isEditing}
<div class="edit-grid">
<div>
<label class="field-label" for={`${idBase}-name`}>Category name</label>
<input
id={`${idBase}-name`}
class="text-input"
value={category.categoryName ?? ""}
oninput={(event) =>
(category.categoryName = event.currentTarget?.value ?? "")}
placeholder="e.g. Groceries"
/>
</div>
<div>
<label class="field-label" for={`${idBase}-description`}
>Description</label
>
<textarea
id={`${idBase}-description`}
class="text-area"
value={category.description ?? ""}
oninput={(event) =>
(category.description = event.currentTarget?.value ?? "")}
placeholder="Optional context for this spend bucket"
></textarea>
</div>
</div>
{:else}
<p class="description">{category.description || "No description yet."}</p>
{/if}
</article>

@ -0,0 +1,70 @@
<!--
// Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
-->
<script lang="ts">
import type { Expense } from "../types.ts";
import { useDocumentStore } from "./useDocumentStore.svelte";
import ExpenseCard from "./ExpenseCard.svelte";
const store = useDocumentStore();
const expenses = $derived(store.doc?.expenses);
const expenseCategories = $derived(store.doc?.expenseCategories);
function createExpense(obj: Partial<Expense> = {}) {
if (!expenses) return;
expenses.push({
amount: obj.amount ?? 1,
recurrenceInterval: obj.recurrenceInterval ?? "",
description: obj.description ?? "",
totalPrice: obj.totalPrice ?? 0,
paymentStatus: obj.paymentStatus ?? "Paid",
isRecurring: obj.isRecurring ?? false,
expenseCategories: obj.expenseCategories ?? [],
dateOfPurchase: obj.dateOfPurchase ?? new Date().toISOString(),
title: obj.title ?? "New Expense",
});
}
const expensesSorted = $derived(
expenses &&
[...expenses].sort((a, b) =>
a.dateOfPurchase.localeCompare(b.dateOfPurchase),
),
);
</script>
<section class="panel">
<header class="panel-header">
<div>
<p class="label-accent">Expenses</p>
<h2 class="title">Recent activity</h2>
</div>
<button class="primary-btn" onclick={() => createExpense({})}>
+ Add expense
</button>
</header>
<div class="cards-stack">
{#if !expenses}
Loading...
{:else if expenses.length === 0}
<p class="muted">
Nothing tracked yet - log your first purchase to kick things off.
</p>
{:else}
{#each expensesSorted as expense, index (expense["@id"])}
<ExpenseCard
expense={expensesSorted![index]}
availableCategories={expenseCategories!}
/>
{/each}
{/if}
</div>
</section>

@ -0,0 +1,28 @@
<!--
// Copyright (c) 2025 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
-->
<script lang="ts">
import ExpenseCategories from "./ExpenseCategories.svelte";
import Expenses from "./Expenses.svelte";
</script>
<div id="svelte-main" class="expense-app-shell">
<div class="expense-app-content">
<header class="expense-hero">
<h1>Svelte Expense Tracker</h1>
<p>Organize categories, log purchases. Encrypted and local-first.</p>
</header>
<div class="section-stack">
<ExpenseCategories />
<Expenses />
</div>
</div>
</div>

@ -0,0 +1,21 @@
// Copyright (c) 2026 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
import type { DocumentStore } from "../types.ts";
import { ormSubscriptionPromise } from "../utils/ngSession.ts";
import { useDiscrete } from "@ng-org/orm/svelte";
export function useDocumentStore() {
const documentIdPromise = ormSubscriptionPromise.then(
(connection) => connection.documentId,
);
return useDiscrete<DocumentStore>(documentIdPromise);
}

@ -0,0 +1,314 @@
:root {
--panel-bg: #ffffff;
--panel-shadow: 0 25px 60px rgba(15, 23, 42, 0.08);
--panel-border: #e5e7eb;
--text-muted: #6b7280;
--text-accent: #4c1d95;
--chip-bg: #ede9fe;
--chip-text: #4c1d95;
--badge-bg: #eef2ff;
--badge-text: #4338ca;
--button-bg: #4f46e5;
--button-shadow: 0 15px 30px rgba(79, 70, 229, 0.2);
}
body {
margin: 0;
}
.framework-grid {
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.framework-card {
width: 100%;
}
.framework-card .box {
min-width: 0;
margin: 0;
height: 100%;
}
@media (min-width: 1400px) {
.framework-grid {
flex-direction: row;
align-items: stretch;
}
.framework-card {
flex: 1;
display: flex;
}
}
.expense-app-content {
max-width: 1200px;
margin: 0 auto;
display: grid;
gap: 1.75rem;
}
.expense-hero {
display: flex;
flex-direction: column;
gap: 0.5rem;
text-align: center;
}
.expense-hero h1 {
font-size: 2.5rem;
margin: 0;
}
.expense-hero p {
color: var(--text-muted);
max-width: 560px;
margin: 0 auto;
}
.section-stack {
display: grid;
gap: 1.5rem;
}
.panel {
background: var(--panel-bg);
border-radius: 1.25rem;
padding: 1.5rem;
margin: 1rem;
box-shadow: var(--panel-shadow);
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.panel-header {
display: flex;
justify-content: space-between;
align-items: center;
flex-wrap: wrap;
gap: 1rem;
}
.section-label,
.label-accent,
.badge-label {
text-transform: uppercase;
letter-spacing: 0.18em;
font-size: 0.75rem;
color: #9ca3af;
margin: 0;
}
.badge {
background: var(--badge-bg);
color: var(--badge-text);
border-radius: 999px;
padding: 0.25rem 1rem;
font-size: 0.85rem;
font-weight: 600;
margin-left: 0.75rem;
}
.primary-btn {
background: var(--button-bg);
color: white;
border: none;
border-radius: 999px;
padding: 0.65rem 1.4rem;
font-weight: 600;
cursor: pointer;
box-shadow: var(--button-shadow);
}
.cards-grid {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
}
.cards-stack {
display: grid;
gap: 1rem;
}
.category-card,
.expense-card {
border: 1px solid var(--panel-border);
border-radius: 18px;
background: #fbfbff;
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 1.25rem;
}
.category-card {
padding: 1.25rem;
gap: 0.85rem;
}
.card-header,
.expense-header {
display: flex;
justify-content: space-between;
gap: 1rem;
align-items: flex-start;
}
.header-text {
flex: 1;
margin-right: 1rem;
}
.icon-btn {
background: var(--badge-bg);
border: 1px solid #c7d2fe;
border-radius: 999px;
width: 2.25rem;
height: 2.25rem;
display: grid;
place-items: center;
cursor: pointer;
color: var(--text-accent);
font-size: 1rem;
}
.title,
.header-title {
margin: 0;
font-size: 1.3rem;
}
.muted {
color: var(--text-muted);
}
.small-margin {
margin: 0.2rem 0 0;
}
.badge-line {
display: flex;
align-items: center;
gap: 0.75rem;
}
.header-actions {
display: flex;
gap: 0.75rem;
align-items: center;
flex-wrap: wrap;
}
.field-group {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.field-label {
text-transform: uppercase;
letter-spacing: 0.12em;
font-size: 0.75rem;
color: #9ca3af;
}
.value-text {
font-size: 1rem;
color: #111827;
margin: 0;
}
.input,
.textarea,
.select,
.header-input,
.text-input,
.text-area {
border-radius: 10px;
border: 1px solid #d1d5db;
padding: 0.6rem 0.75rem;
font-size: 0.95rem;
font-family: inherit;
background: white;
}
.header-input {
width: 100%;
font-size: 1.35rem;
font-weight: 600;
}
.textarea,
.text-area {
min-height: 80px;
resize: vertical;
}
.info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(210px, 1fr));
gap: 1rem;
}
.chip-list {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}
.chip {
background: var(--chip-bg);
color: var(--chip-text);
border-radius: 999px;
padding: 0.3rem 0.85rem;
font-size: 0.85rem;
font-weight: 600;
}
.category-picker {
display: flex;
flex-direction: column;
gap: 0.65rem;
}
.category-option {
display: flex;
gap: 0.75rem;
align-items: flex-start;
padding: 0.65rem 0.75rem;
border-radius: 12px;
border: 1px solid var(--panel-border);
background: white;
}
.checkbox {
width: 1rem;
height: 1rem;
margin-top: 0.3rem;
}
.category-text {
display: flex;
flex-direction: column;
gap: 0.15rem;
}
.helper-text {
color: #9ca3af;
}
.description {
margin: 0;
color: #4b5563;
line-height: 1.5;
}
.edit-grid {
display: grid;
gap: 0.9rem;
}

@ -0,0 +1,74 @@
export type IRI = string;
/**
* Expense Type
*/
export interface Expense {
/**
* The subject IRI.
*/
readonly "@id"?: IRI;
/**
* The name of the expense
*/
title: string;
/**
* A readable description
*/
description?: string;
/**
* The total price
*/
totalPrice: number;
/**
* The number of items bought
*/
amount: number;
/**
* The (ISO8601) date of purchase
*/
dateOfPurchase: string;
/**
* The use category of the product
*
* Original IRI: http://example.org/expenseCategory
*/
expenseCategories: string[];
/**
* True, if this is a recurring expense (e.g. bus pass)
*/
isRecurring: boolean;
/**
* For recurring events, the interval of recurrence
*/
recurrenceInterval?: string;
/**
* The payment status of the expense
*/
paymentStatus: "Paid" | "Pending" | "Overdue" | "Refunded";
}
/**
* ExpenseCategory Type
*/
export interface ExpenseCategory {
readonly "@id"?: IRI;
/**
* Name of expense category
*/
categoryName: string;
/**
* Human-readable description of category
*/
description: string;
}
/**
* The structure of the discrete JSON (YJS or Automerge) document that all data is stored in.
*/
export interface DocumentStore {
expenses: Expense[];
expenseCategories: ExpenseCategory[];
}
export type AllowedCrdt = "YMap" | "Automerge";

@ -0,0 +1,12 @@
// Copyright (c) 2026 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
export * as ngSession from "./ngSession.ts";
export * from "./loadStore.ts";

@ -0,0 +1,66 @@
// Copyright (c) 2026 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
import { DiscreteOrmSubscription } from "@ng-org/orm";
import type { AllowedCrdt, DocumentStore } from "../types.ts";
import { sessionPromise } from "./ngSession.ts";
/**
* Establishes an ORM subscription and loads or creates
* the CRDT document store where all application data is stored as JSON.
*/
export async function loadStore(crdt: AllowedCrdt) {
/** The identifier that we use to find this application's store. */
const APPLICATION_CLASS_IRI = `did:ng:z:ExpenseTrackerDiscreteApp-${crdt}`;
// First, find or create the document that we use for this document.
// We find its document id / IRI with a sparql query.
const { ng, session_id } = await sessionPromise;
// If a document already exists, we have added an RDF triple with type APPLICATION_CLASS_IRI
const ret = await ng.sparql_query(
session_id,
`SELECT ?storeId WHERE { GRAPH ?storeId { ?s a <${APPLICATION_CLASS_IRI}> } }`,
undefined,
undefined,
);
let documentId = ret?.results.bindings?.[0]?.storeId?.value;
// Create a new document, if necessary.
if (!documentId) {
// Create document with the preferred CRDT.
documentId = await ng.doc_create(
session_id,
crdt,
crdt === "Automerge" ? "data:json" : "data:map", // Currently, the class name cannot be arbitrary due to a but in the ng interface. APPLICATION_CLASS_IRI,
"store",
undefined,
);
// Add class to RDF part of the document so we can find it again.
await ng.sparql_update(
session_id,
`INSERT DATA { GRAPH <${documentId}> {<${documentId}> a <${APPLICATION_CLASS_IRI}> } }`,
documentId,
);
}
const subscription = DiscreteOrmSubscription.getOrCreate(documentId);
await subscription.readyPromise;
const storeObject = subscription.signalObject as Partial<DocumentStore>;
// If the store is still empty, initialize it.
if (!storeObject.expenses) {
storeObject.expenses = [];
storeObject.expenseCategories = [];
}
return subscription;
}

@ -0,0 +1,62 @@
// Copyright (c) 2026 Laurin Weger, Par le Peuple, NextGraph.org developers
// All rights reserved.
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE2 or http://www.apache.org/licenses/LICENSE-2.0>
// or the MIT license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
// SPDX-License-Identifier: Apache-2.0 OR MIT
import { ng, init as initNgWeb } from "@ng-org/web";
import {
DiscreteOrmSubscription,
initNg as initNgSignals,
type Session as NextGraphSession,
} from "@ng-org/orm";
import { loadStore } from "./loadStore.ts";
import type { AllowedCrdt } from "../types.ts";
export let session: NextGraphSession | undefined;
let resolveSessionPromise: (
value: NextGraphSession | PromiseLike<NextGraphSession>,
) => void;
let rejectSessionPromise: (reason?: any) => void;
/** Resolves to the current NextGraph session. */
export let sessionPromise: Promise<NextGraphSession> = new Promise(
(resolve, reject) => {
resolveSessionPromise = resolve;
rejectSessionPromise = reject;
},
);
/** CRDT of the document, depending on the environment variable. */
export let PREFERRED_CRDT: AllowedCrdt;
/** Call as early in your app as possible so that the page is redirected to auth. */
export async function init(crdtIfNew: AllowedCrdt) {
PREFERRED_CRDT = crdtIfNew;
await initNgWeb(
async (event: any) => {
session = event.session;
session!.ng ??= ng;
resolveSessionPromise(session!);
initNgSignals(ng, session!);
},
true,
[],
).catch((error) => {
rejectSessionPromise(error);
});
}
/** Initializes and keeps open the orm subscription while the application is running. */
export let ormSubscriptionPromise = sessionPromise.then(async (session) => {
const subscription = await loadStore(PREFERRED_CRDT);
ormSubscription = subscription;
return subscription;
});
export let ormSubscription: DiscreteOrmSubscription | undefined = undefined;

@ -0,0 +1,17 @@
{
"compilerOptions": {
"rootDir": "src",
"outDir": "dist",
"target": "esnext",
"module": "esnext",
"moduleResolution": "bundler",
"declaration": true,
"declarationMap": true,
"strict": true,
"skipLibCheck": true,
"resolveJsonModule": true,
"allowImportingTsExtensions": true,
"rewriteRelativeImportExtensions": true
},
"include": ["src"]
}

@ -0,0 +1,7 @@
import { defineConfig } from "vite";
import { svelte } from "@sveltejs/vite-plugin-svelte";
export default defineConfig({
plugins: [svelte()],
envPrefix: ["NG_"],
});
Loading…
Cancel
Save