Compare commits
450 Commits
codex/mobi
...
v0.2026030
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
97d2182c0e | ||
|
|
80baa74175 | ||
|
|
f71e6d07e7 | ||
|
|
b8a0702e3c | ||
|
|
c48f337c4d | ||
|
|
b32d46f482 | ||
|
|
fd100e1c3b | ||
|
|
249db95c9e | ||
|
|
3c27b63908 | ||
|
|
a246de4483 | ||
|
|
2793024904 | ||
|
|
f0ef9cacec | ||
|
|
d2538e121f | ||
|
|
531666b031 | ||
|
|
e239d71a48 | ||
|
|
e2f1fe239e | ||
|
|
8495f0e2e6 | ||
|
|
19bc3c67e3 | ||
|
|
628d97d909 | ||
|
|
aa6b31317c | ||
|
|
b24ba8a4c6 | ||
|
|
b3f47f4507 | ||
|
|
6fcd0552d0 | ||
|
|
8747a84453 | ||
|
|
2eb3080050 | ||
|
|
99b64c0fac | ||
|
|
b2a68a9a67 | ||
|
|
f5bbcb81a4 | ||
|
|
db5e53f77e | ||
|
|
90e67adc41 | ||
|
|
185feb5a2c | ||
|
|
f04dfdbd37 | ||
|
|
3c27403f86 | ||
|
|
276b3c1a37 | ||
|
|
cadb3500f1 | ||
|
|
ee8f0d6bcd | ||
|
|
41d43501a0 | ||
|
|
32b8e2ee57 | ||
|
|
b1110ead87 | ||
|
|
b75b917538 | ||
|
|
24bb64841e | ||
|
|
df2452dcaf | ||
|
|
89d0e39ad2 | ||
|
|
e3977a6042 | ||
|
|
4cdc534c01 | ||
|
|
1a93acdce7 | ||
|
|
9c8f7907b8 | ||
|
|
8d9862ffef | ||
|
|
a5e4efcf86 | ||
|
|
e4bab72952 | ||
|
|
f08b807a0c | ||
|
|
b521736102 | ||
|
|
4d13628d0b | ||
|
|
2b6000f5d4 | ||
|
|
894cb45779 | ||
|
|
2a1b17f8c6 | ||
|
|
47ca3cb13c | ||
|
|
5fb059d2e9 | ||
|
|
bd7feb94e7 | ||
|
|
de7b624902 | ||
|
|
7e1057482e | ||
|
|
7aa4bf7efe | ||
|
|
6e99bf7d03 | ||
|
|
669d473a64 | ||
|
|
ba1404b808 | ||
|
|
98314c5106 | ||
|
|
bac5a911c1 | ||
|
|
67155db9ab | ||
|
|
b42a4d3608 | ||
|
|
e29be460c3 | ||
|
|
bcfbc8e00e | ||
|
|
95bcf3b25a | ||
|
|
3fff794d9b | ||
|
|
de6023547f | ||
|
|
0effc563dc | ||
|
|
37ac70f720 | ||
|
|
222f697873 | ||
|
|
681554af58 | ||
|
|
87bce9d4cc | ||
|
|
248774ed13 | ||
|
|
6363e84402 | ||
|
|
8106eb86a8 | ||
|
|
7feae25d45 | ||
|
|
cc08055e0a | ||
|
|
c789b49bef | ||
|
|
bccc0ceed4 | ||
|
|
b924ec9b95 | ||
|
|
c56a8c0e7f | ||
|
|
c5bcbecf1f | ||
|
|
5ef4f2d642 | ||
|
|
f52ce5c618 | ||
|
|
d83fef67f0 | ||
|
|
8a91d25395 | ||
|
|
77f76a33a4 | ||
|
|
d8aa615ea3 | ||
|
|
82dafe9334 | ||
|
|
aff56af6aa | ||
|
|
4e2fa0d374 | ||
|
|
465a80d3e1 | ||
|
|
ce12e3cd6f | ||
|
|
e67eb5e85e | ||
|
|
c11184b24a | ||
|
|
ee42731ecc | ||
|
|
3c57b0ff1a | ||
|
|
bd0576c593 | ||
|
|
57f0378bab | ||
|
|
1ff342ae60 | ||
|
|
da55318979 | ||
|
|
384cffec48 | ||
|
|
c0ce5064d8 | ||
|
|
e9c869075a | ||
|
|
f881c13b62 | ||
|
|
92c7b003d9 | ||
|
|
cafdc84260 | ||
|
|
d87c80ece4 | ||
|
|
a67e0bd221 | ||
|
|
ed8a51aa8f | ||
|
|
fb763f5338 | ||
|
|
a18a19166b | ||
|
|
1efdbfb978 | ||
|
|
233497cb5c | ||
|
|
6ff3a1929a | ||
|
|
42b463e07a | ||
|
|
a6b92d5248 | ||
|
|
8c574882e5 | ||
|
|
bb0a5c5c98 | ||
|
|
cd1246d43c | ||
|
|
92c8dbd1bf | ||
|
|
4672fcb5c0 | ||
|
|
d962cd9eae | ||
|
|
88a8035c45 | ||
|
|
035bd7f630 | ||
|
|
9ce890576b | ||
|
|
f569750666 | ||
|
|
9cfa8a7ca2 | ||
|
|
918b204d3d | ||
|
|
177e593e90 | ||
|
|
959e4975e3 | ||
|
|
a2f1476b98 | ||
|
|
9d5c90f5c0 | ||
|
|
e91a7ae7f6 | ||
|
|
47e38ba6b0 | ||
|
|
cbb88b34b8 | ||
|
|
52b1693f43 | ||
|
|
3d784ce740 | ||
|
|
480d124a0e | ||
|
|
b15a4d143c | ||
|
|
baca6b1098 | ||
|
|
8a38dfc3c7 | ||
|
|
464d143313 | ||
|
|
990bcfc83a | ||
|
|
35c5e0f2c3 | ||
|
|
1e2ed97630 | ||
|
|
49b8e1d817 | ||
|
|
a6140fe277 | ||
|
|
4474e635fd | ||
|
|
375e370a9e | ||
|
|
25b01f9501 | ||
|
|
c44f5887ae | ||
|
|
9523bbdb54 | ||
|
|
347a8aa487 | ||
|
|
c33e89556d | ||
|
|
be420adace | ||
|
|
b7d1bb18cf | ||
|
|
b05992e2b1 | ||
|
|
0ebb5033fa | ||
|
|
31c30133bd | ||
|
|
ba9a720c4f | ||
|
|
d6d1b87d0c | ||
|
|
58692882f2 | ||
|
|
a312a6982f | ||
|
|
5ef59a8716 | ||
|
|
4664f3360e | ||
|
|
1c2f0ee193 | ||
|
|
fa5bc3fac2 | ||
|
|
ecc6734881 | ||
|
|
f2eaa5c842 | ||
|
|
81990214af | ||
|
|
f9fadf2763 | ||
|
|
aaf9c9a330 | ||
|
|
68a7518b51 | ||
|
|
e3f159a3f4 | ||
|
|
2bac6a117f | ||
|
|
d6b7343dac | ||
|
|
9c81caca46 | ||
|
|
60704dc37b | ||
|
|
9da7cf5182 | ||
|
|
17e9cb1a8e | ||
|
|
5b6bc64cd6 | ||
|
|
807a4904a2 | ||
|
|
ee663df4fe | ||
|
|
9184fadde0 | ||
|
|
7534b8f20c | ||
|
|
d6feccb91f | ||
|
|
8b48babcff | ||
|
|
53e9c60bb1 | ||
|
|
72d21f6482 | ||
|
|
021597566d | ||
|
|
15b2042081 | ||
|
|
9a185e5003 | ||
|
|
45237251c6 | ||
|
|
99b4098f48 | ||
|
|
12e2859946 | ||
|
|
58881640a5 | ||
|
|
1a6d6b3446 | ||
|
|
561ae2d656 | ||
|
|
edba920623 | ||
|
|
292f105fae | ||
|
|
a9166bb50b | ||
|
|
813ad22595 | ||
|
|
e95e85ceb1 | ||
|
|
19f35728e7 | ||
|
|
c5ede71439 | ||
|
|
0b2c7daac6 | ||
|
|
a6b8602fff | ||
|
|
57b30d2328 | ||
|
|
2fe473ebbd | ||
|
|
b5f69fa58c | ||
|
|
af2932c918 | ||
|
|
f047f8e3c9 | ||
|
|
d2cb395f65 | ||
|
|
1d23c1ac05 | ||
|
|
d79b677119 | ||
|
|
6e038a5310 | ||
|
|
a2ed06dcf6 | ||
|
|
ae3657d19c | ||
|
|
2b8e1a5967 | ||
|
|
0fd56da5d6 | ||
|
|
7ebaf464cb | ||
|
|
6e14996301 | ||
|
|
6ac505c8c9 | ||
|
|
f7c4e16be9 | ||
|
|
62c8d0f7a8 | ||
|
|
b5eb7e4098 | ||
|
|
08ce58b8e5 | ||
|
|
a8a72b54d2 | ||
|
|
a24a9735c4 | ||
|
|
db87806ffc | ||
|
|
75f7e4fa4f | ||
|
|
1d0e1284ed | ||
|
|
49704bc76d | ||
|
|
49ebc3e71e | ||
|
|
0f4484b28a | ||
|
|
a98b4c6aad | ||
|
|
873fb4d434 | ||
|
|
8a08fb67a3 | ||
|
|
5d09e32b08 | ||
|
|
7736d20b9f | ||
|
|
9bcc1776cc | ||
|
|
576ce1f294 | ||
|
|
9a5b37f602 | ||
|
|
8b44ebbc22 | ||
|
|
3ea175eec5 | ||
|
|
2e2224865c | ||
|
|
7e586eccb0 | ||
|
|
a7abcc21b3 | ||
|
|
d65eba8096 | ||
|
|
45a0098f5c | ||
|
|
99535cc0da | ||
|
|
31d8bfb843 | ||
|
|
e7e4dccd3f | ||
|
|
9a8b2d930a | ||
|
|
bacd4e17a2 | ||
|
|
8276e4225d | ||
|
|
6a63768892 | ||
|
|
49a4ba2491 | ||
|
|
e607859c5b | ||
|
|
b4201487ec | ||
|
|
4c031bdb8b | ||
|
|
45b48e654c | ||
|
|
f90bb1f701 | ||
|
|
8a7fb09a46 | ||
|
|
8911aad930 | ||
|
|
56ed81ccb0 | ||
|
|
d127ece50d | ||
|
|
be4e3c72ae | ||
|
|
7219c0799f | ||
|
|
5d73655875 | ||
|
|
8cbf30358d | ||
|
|
ab87c046c2 | ||
|
|
fe55f9253d | ||
|
|
5d833b4203 | ||
|
|
1a87036087 | ||
|
|
2a9a3dd2f6 | ||
|
|
323c8e3cc2 | ||
|
|
ab3221dc13 | ||
|
|
4612fe43e0 | ||
|
|
f0eb9e7f22 | ||
|
|
7352d056bc | ||
|
|
ed26463231 | ||
|
|
cdd33cf41f | ||
|
|
c53b919151 | ||
|
|
71e9ad364f | ||
|
|
de5154e5f1 | ||
|
|
c4f6de9f49 | ||
|
|
8b708f2c81 | ||
|
|
32fd3ca656 | ||
|
|
060a9cf0fb | ||
|
|
209821ffdd | ||
|
|
8d19731e13 | ||
|
|
1fba2a042e | ||
|
|
79fe2d9e6d | ||
|
|
2268350cca | ||
|
|
e288ccc905 | ||
|
|
ec01b46cbd | ||
|
|
6eb01ac598 | ||
|
|
ce5f48bfbf | ||
|
|
8454ce7be5 | ||
|
|
d40c1b28d7 | ||
|
|
e51bafd4b7 | ||
|
|
beaf946f7d | ||
|
|
76a0076909 | ||
|
|
0794d8f8ac | ||
|
|
d17739179a | ||
|
|
c67c4a267e | ||
|
|
8bc67774eb | ||
|
|
53cba9f88d | ||
|
|
381a82475e | ||
|
|
437a35420c | ||
|
|
75929dd420 | ||
|
|
30dba89c89 | ||
|
|
ba874013fd | ||
|
|
13da213168 | ||
|
|
1bfeb78868 | ||
|
|
45e6c33de5 | ||
|
|
57b42d233d | ||
|
|
65ec00ae33 | ||
|
|
058276c6f4 | ||
|
|
747265b5a6 | ||
|
|
995b20d084 | ||
|
|
6b22197161 | ||
|
|
40fa39ca67 | ||
|
|
e2bc3ef4c0 | ||
|
|
ad41fbb9cd | ||
|
|
c0426c84c8 | ||
|
|
5f624d111a | ||
|
|
472882eb21 | ||
|
|
066bef8eba | ||
|
|
1c064731fc | ||
|
|
889d06b717 | ||
|
|
19b53a6f3c | ||
|
|
4c7ed07fee | ||
|
|
211c7e5d41 | ||
|
|
bf549d5605 | ||
|
|
3eef1e76d4 | ||
|
|
a5e465d0f9 | ||
|
|
afaa22966d | ||
|
|
7a8b8bc618 | ||
|
|
5aac07f7e2 | ||
|
|
53cf2bc4d6 | ||
|
|
42b543992c | ||
|
|
36dc6d4416 | ||
|
|
55d9e733ea | ||
|
|
61d279ba9e | ||
|
|
0f3b6801d1 | ||
|
|
1e1c177a54 | ||
|
|
f1398133ee | ||
|
|
64de189db7 | ||
|
|
504bfa4907 | ||
|
|
da0a113eec | ||
|
|
866d6fea75 | ||
|
|
3c0bed651a | ||
|
|
c5a76ed03c | ||
|
|
59b697fd16 | ||
|
|
8c89b5d7fe | ||
|
|
9f9cf7cec1 | ||
|
|
d10fd6bb25 | ||
|
|
e02e61ae01 | ||
|
|
9ec46676f0 | ||
|
|
e9ad3ff5cc | ||
|
|
4c7838522d | ||
|
|
d6198e981b | ||
|
|
c446d4c321 | ||
|
|
64907b83c6 | ||
|
|
f0434b32aa | ||
|
|
a485ca49c7 | ||
|
|
57a13bb4fe | ||
|
|
1b3e1d2f67 | ||
|
|
a0e888dffb | ||
|
|
7c19817d6e | ||
|
|
d217607407 | ||
|
|
c180b6851a | ||
|
|
74db63f1c8 | ||
|
|
d793093249 | ||
|
|
7dc8b317af | ||
|
|
db5d5c98d5 | ||
|
|
bd58557a71 | ||
|
|
800a0df61b | ||
|
|
5b91b25713 | ||
|
|
964daea45e | ||
|
|
9cfd956940 | ||
|
|
7140bf052d | ||
|
|
ca8637b155 | ||
|
|
4511951e81 | ||
|
|
21a624b633 | ||
|
|
c8e87f0ab9 | ||
|
|
9b26969d2f | ||
|
|
4447a8a873 | ||
|
|
d54c956082 | ||
|
|
e5612d933e | ||
|
|
93aa709217 | ||
|
|
ffa93ea511 | ||
|
|
e608d1f412 | ||
|
|
785720b3dd | ||
|
|
36f4f5048a | ||
|
|
e174c782cb | ||
|
|
2720757620 | ||
|
|
23ca40c19a | ||
|
|
6527db10a2 | ||
|
|
67b8d1830c | ||
|
|
9b44f5d564 | ||
|
|
0d4dba2161 | ||
|
|
0053d3b985 | ||
|
|
0e7865c667 | ||
|
|
23c6a5d0d2 | ||
|
|
0fbebfbfaa | ||
|
|
e3a88db08a | ||
|
|
81f7b163e4 | ||
|
|
ff9b98e14e | ||
|
|
1cccfd70cd | ||
|
|
b87ebe59a6 | ||
|
|
369792f738 | ||
|
|
8533984508 | ||
|
|
731a2e5188 | ||
|
|
66b9518613 | ||
|
|
5ebcf41d47 | ||
|
|
197a1b2428 | ||
|
|
001f2e728e | ||
|
|
624271ffab | ||
|
|
e4c0fe6b36 | ||
|
|
362f6c67a5 | ||
|
|
649d1ce2e0 | ||
|
|
5268168abb | ||
|
|
cae6fced35 | ||
|
|
efd79e9a3d | ||
|
|
f476897d5e | ||
|
|
0fcda11cf1 | ||
|
|
20ce35bb44 | ||
|
|
7f1f4d859b | ||
|
|
434395d602 | ||
|
|
17613b5c4e | ||
|
|
486c0faa6f | ||
|
|
b4cd95f0b4 | ||
|
|
158c5a0089 | ||
|
|
d88b16357b | ||
|
|
8b91db3466 | ||
|
|
163a5606b6 | ||
|
|
1230cc4e77 | ||
|
|
53c881278e | ||
|
|
e54d7552d9 |
1
(HOME)/.tauri/laputa-v2.key
Normal file
1
(HOME)/.tauri/laputa-v2.key
Normal file
@@ -0,0 +1 @@
|
||||
dW50cnVzdGVkIGNvbW1lbnQ6IHJzaWduIGVuY3J5cHRlZCBzZWNyZXQga2V5ClJXUlRZMEl5V3BxWUNBZU1LZWxOK3ZEZTZkdGhzM2l6cnpVUmIvUEtTTWgzLzNEU1VoZ0FBQkFBQUFBQUFBQUFBQUlBQUFBQUFpN2xxclpGK3YzRERub1EvZFdsdVdORktuOHZYVlB0S2U2QkhNdlMreElkRVdabTh6UllNYzNFb2VWYTVCayszNUpyOC94Z0dJS2pVQ3NSKzdKNEszZHpDZll0aGdtV1J6bWFXODc4VWJpOVFYdUhEai9tNHQ2U3ZRbVd1NHBkR01YS2ZrUDlPRVU9Cg==
|
||||
1
(HOME)/.tauri/laputa-v2.key.pub
Normal file
1
(HOME)/.tauri/laputa-v2.key.pub
Normal file
@@ -0,0 +1 @@
|
||||
dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDVCQTVDRkIzNkFGRTYwQjUKUldTMVlQNXFzOCtsVzROZmJLR0JFVGw1a1UzKzViY3dUcWFoaUttRFhhVk8rVUhrc29QL1FPeXUK
|
||||
1
.claude-pid
Normal file
1
.claude-pid
Normal file
@@ -0,0 +1 @@
|
||||
21351
|
||||
@@ -1,133 +0,0 @@
|
||||
# Create Architecture Decision Record
|
||||
|
||||
Use this command when you need to document an architectural decision made during a task.
|
||||
|
||||
Inspired by [adr-tools](https://github.com/npryce/adr-tools) (Nygard format), adapted for Laputa's frontmatter-based note format.
|
||||
|
||||
## When to use this
|
||||
|
||||
Create an ADR when your work involves any of these:
|
||||
- Choosing a storage strategy (vault vs app settings vs database)
|
||||
- Adding or removing a major dependency
|
||||
- Supporting a new platform or target
|
||||
- Introducing or removing a core abstraction
|
||||
- Making a cross-cutting decision that affects how future code should be written
|
||||
|
||||
Do NOT create ADRs for: bug fixes, UI styling, refactors that preserve behavior, or test additions.
|
||||
|
||||
## Creating a new ADR
|
||||
|
||||
### 1. Find the next ID
|
||||
|
||||
```bash
|
||||
ls docs/adr/*.md | grep -oP '\d{4}' | sort -n | tail -1 | xargs -I{} printf '%04d\n' $(({} + 1))
|
||||
```
|
||||
|
||||
If no files exist yet, start at `0001`.
|
||||
|
||||
### 2. Create the file
|
||||
|
||||
Filename: `docs/adr/NNNN-short-kebab-title.md`
|
||||
|
||||
Template:
|
||||
|
||||
```markdown
|
||||
---
|
||||
type: ADR
|
||||
id: "NNNN"
|
||||
title: "Short decision title"
|
||||
status: active
|
||||
date: YYYY-MM-DD
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
The issue motivating this decision, and any context that influences or constrains it.
|
||||
|
||||
## Decision
|
||||
|
||||
**The change we're proposing or have agreed to implement.** State it clearly in one or two sentences — bold so it stands out.
|
||||
|
||||
## Options considered
|
||||
|
||||
- **Option A** (chosen): brief description — pros / cons
|
||||
- **Option B**: brief description — pros / cons
|
||||
- **Option C**: brief description — pros / cons
|
||||
|
||||
## Consequences
|
||||
|
||||
What becomes easier or harder as a result?
|
||||
What risks does this introduce that will need to be mitigated?
|
||||
What would trigger re-evaluation of this decision?
|
||||
|
||||
## Advice
|
||||
|
||||
*(optional)* Input received before making this decision — who was consulted, what they said.
|
||||
Omit this section if the decision was made without external input.
|
||||
```
|
||||
|
||||
### 3. Update the index
|
||||
|
||||
Add a row to `docs/adr/README.md`:
|
||||
|
||||
```markdown
|
||||
| [NNNN](NNNN-short-kebab-title.md) | Title | active |
|
||||
```
|
||||
|
||||
### 4. Include in the same commit as the feature
|
||||
|
||||
```bash
|
||||
git add docs/adr/NNNN-*.md docs/adr/README.md
|
||||
# fold into the feature commit — do not create a separate commit just for the ADR
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Superseding an existing ADR
|
||||
|
||||
Equivalent of `adr new -s <N>` from adr-tools — do this in two steps:
|
||||
|
||||
### Step 1: Mark the old ADR as superseded
|
||||
|
||||
Edit the existing file — add `superseded_by` and update `status`:
|
||||
|
||||
```yaml
|
||||
---
|
||||
type: ADR
|
||||
id: "000N"
|
||||
title: "Old decision title"
|
||||
status: superseded # ← change from active
|
||||
superseded_by: "NNNN" # ← add this
|
||||
date: YYYY-MM-DD
|
||||
---
|
||||
```
|
||||
|
||||
**Never edit the content sections** of an active ADR — only the status metadata.
|
||||
|
||||
### Step 2: Create the new ADR
|
||||
|
||||
Follow the steps above. In the **Context** section, reference the superseded ADR:
|
||||
|
||||
```markdown
|
||||
## Context
|
||||
|
||||
Supersedes [ADR-000N](000N-old-title.md).
|
||||
|
||||
[explain why the old decision no longer holds]
|
||||
```
|
||||
|
||||
### Step 3: Update the README index
|
||||
|
||||
Change the old row's status to `superseded`, add the new row.
|
||||
|
||||
---
|
||||
|
||||
## Best practices (from adr-tools / Nygard)
|
||||
|
||||
- **One decision per ADR** — if you find yourself writing "and also", split it
|
||||
- **Write Decision first** — if you can't state it in 1-2 sentences, the decision is too vague
|
||||
- **Context is the "why now"** — what forced this decision to be made today?
|
||||
- **Consequences should include negatives** — a one-sided ADR is a red flag
|
||||
- **Committed = immutable** — once pushed, the content doesn't change; only status metadata does
|
||||
- **If in doubt, create one** — cheaper to have an unnecessary ADR than to lose context
|
||||
- Date = today's date, `YYYY-MM-DD`
|
||||
@@ -1,42 +0,0 @@
|
||||
# /laputa-done <task_id>
|
||||
|
||||
Mark a Laputa task as done: add completion comment, move to In Review, then self-dispatch the next task.
|
||||
|
||||
Run this after Phase 1 (Playwright) and Phase 2 (native app QA) both pass **and `git push origin main` has succeeded**.
|
||||
|
||||
⚠️ A task is NOT done until the push succeeds. If the push is blocked by the pre-push hook (clippy, tests, CodeScene, build):
|
||||
- Read the error
|
||||
- Fix it (never use `--no-verify`)
|
||||
- Commit the fix and push again
|
||||
- Repeat until push exits with code 0
|
||||
|
||||
## Steps
|
||||
|
||||
**1. Add completion comment to the task**
|
||||
|
||||
Summarize what was done — this is the context Luca and Brian will read in Todoist:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "https://api.todoist.com/api/v1/comments" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"task_id": "$ARGUMENTS",
|
||||
"content": "✅ Implementation complete.\n\n**What changed:** [brief summary of the implementation]\n**ADR:** [if an ADR was created, reference it here; otherwise omit]\n**Playwright:** all tests pass\n**Native QA:** tested with pnpm tauri dev — [describe what was tested and what was observed]"
|
||||
}'
|
||||
```
|
||||
|
||||
**2. Move task to In Review**
|
||||
|
||||
```bash
|
||||
curl -s -X POST "https://api.todoist.com/api/v1/tasks/$ARGUMENTS/move" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"section_id": "6g3XjX33FF4Vj86M"}'
|
||||
```
|
||||
|
||||
**3. Pick the next task**
|
||||
|
||||
Run `/laputa-next-task` to get the next task and start working on it immediately.
|
||||
|
||||
If there are no tasks, `/laputa-next-task` will wait 10 minutes and retry automatically. Do NOT exit — stay alive and let it loop.
|
||||
@@ -1,60 +0,0 @@
|
||||
# /laputa-next-task
|
||||
|
||||
Pick the next Laputa task from Todoist and move it to In Progress.
|
||||
|
||||
Priority order: **To Rework** first, then **Open** (sorted by Todoist priority p1→p4).
|
||||
|
||||
## Steps
|
||||
|
||||
1. Fetch tasks from To Rework (`6g6QqvR9rRpvJWvv`), then Open (`6g3XjWR832hVHhCM`)
|
||||
2. **Sort by priority — this is mandatory.** Todoist returns tasks in arbitrary order. You must sort them yourself:
|
||||
- Todoist priority field: `4` = p1 (urgent), `3` = p2, `2` = p3, `1` = p4
|
||||
- Sort descending by `priority` field (4 first, 1 last)
|
||||
- To Rework tasks always come before Open tasks regardless of priority
|
||||
- **Never pick a p3/p4 task if a p1/p2 task exists in the same section**
|
||||
3. Take the first task from the sorted list
|
||||
4. Move it to In Progress (`6g3XjWjfmJFcGgHM`) via Todoist API:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "https://api.todoist.com/api/v1/tasks/<task_id>/move" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"section_id": "6g3XjWjfmJFcGgHM"}'
|
||||
```
|
||||
|
||||
5. Add a "started" comment to the task:
|
||||
|
||||
```bash
|
||||
curl -s -X POST "https://api.todoist.com/api/v1/comments" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"task_id": "<task_id>", "content": "🚀 Starting work. [Brief description of approach or what needs to be fixed]"}'
|
||||
```
|
||||
|
||||
6. Fetch the full task details (description, comments) from Todoist:
|
||||
|
||||
```bash
|
||||
curl -s "https://api.todoist.com/api/v1/tasks/<task_id>" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY"
|
||||
|
||||
curl -s "https://api.todoist.com/api/v1/comments?task_id=<task_id>" \
|
||||
-H "Authorization: Bearer $TODOIST_API_KEY"
|
||||
```
|
||||
|
||||
6. For To Rework tasks: read the ❌ QA failed comment — it tells you exactly what to fix
|
||||
7. Output: task ID, title, and full description so you can start working immediately
|
||||
|
||||
If no tasks are available in either section → wait 10 minutes and try again (loop forever):
|
||||
|
||||
```bash
|
||||
while true; do
|
||||
# ... check tasks ...
|
||||
if no_tasks; then
|
||||
sleep 600 # 10 minutes
|
||||
else
|
||||
break # got a task, proceed
|
||||
fi
|
||||
done
|
||||
```
|
||||
|
||||
Do NOT exit when there are no tasks. Keep looping until a task appears. This keeps Claude Code alive permanently — the watchdog is a safety net only, not the primary dispatcher.
|
||||
@@ -1,2 +0,0 @@
|
||||
HOTSPOT_THRESHOLD=10.0
|
||||
AVERAGE_THRESHOLD=9.92
|
||||
@@ -1,5 +0,0 @@
|
||||
# Exclude third-party tools and their dependencies from CodeScene analysis
|
||||
tools/
|
||||
e2e/
|
||||
tests/
|
||||
scripts/
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"exclude": [
|
||||
"tools/",
|
||||
"scripts/",
|
||||
"src-tauri/gen/",
|
||||
"coverage/",
|
||||
"dist/"
|
||||
]
|
||||
}
|
||||
18
.env.example
18
.env.example
@@ -1,18 +0,0 @@
|
||||
# Copy to .env.local and fill in real values.
|
||||
# These are never committed — .env.local is gitignored.
|
||||
# Release workflows must mirror these values into GitHub Actions secrets:
|
||||
# - VITE_SENTRY_DSN
|
||||
# - SENTRY_DSN (same value as VITE_SENTRY_DSN for Rust-side crash reporting)
|
||||
# - VITE_POSTHOG_KEY
|
||||
# - VITE_POSTHOG_HOST
|
||||
|
||||
# Sentry DSN (https://sentry.io → Project → Settings → Client Keys)
|
||||
VITE_SENTRY_DSN=
|
||||
|
||||
# PostHog (https://posthog.com → Project → Settings → Project API Key)
|
||||
VITE_POSTHOG_KEY=
|
||||
VITE_POSTHOG_HOST=https://eu.i.posthog.com
|
||||
|
||||
# Lara CLI (https://github.com/translated/lara-cli)
|
||||
LARA_ACCESS_KEY_ID=
|
||||
LARA_ACCESS_KEY_SECRET=
|
||||
3
.github/FUNDING.yml
vendored
3
.github/FUNDING.yml
vendored
@@ -1,3 +0,0 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
custom: https://refactoring.fm/
|
||||
275
.github/HOOKS.md
vendored
275
.github/HOOKS.md
vendored
@@ -1,64 +1,257 @@
|
||||
# Git Hooks
|
||||
|
||||
This repo uses Husky hooks from `.husky/`. Those files are the source of truth.
|
||||
## Pre-Commit Hook: CodeScene Check
|
||||
|
||||
## Installation
|
||||
Il repository ha un pre-commit hook che verifica la qualità del codice prima di ogni commit.
|
||||
|
||||
`pnpm install` runs the `prepare` script and installs the hooks into `.git/hooks`.
|
||||
## Post-Commit Hook: Auto-Implement Design Changes
|
||||
|
||||
If you need to reinstall them manually:
|
||||
Quando committi modifiche a `ui-design.pen`, il post-commit hook:
|
||||
1. Analizza automaticamente le modifiche (colori, typography, spacing, layout)
|
||||
2. Spawna Claude Code in background per implementare le modifiche
|
||||
3. Ti notifica quando l'implementazione è completa
|
||||
|
||||
---
|
||||
|
||||
## Pre-Commit Hook Details
|
||||
|
||||
### Cosa Fa
|
||||
|
||||
1. **Analizza file staged** — controlla solo TypeScript/Rust modificati
|
||||
2. **Confronta con base branch** — `origin/main` per branch, `HEAD~1` per main
|
||||
3. **Avvisa per file grandi** — >500 linee modificate
|
||||
4. **Suggerisce review** — con Claude Code + CodeScene MCP per analisi dettagliata
|
||||
|
||||
### Bypass Hook
|
||||
|
||||
Se sai cosa stai facendo:
|
||||
|
||||
```bash
|
||||
pnpm exec husky
|
||||
# Skip hook per questo commit
|
||||
git commit --no-verify -m "your message"
|
||||
|
||||
# O includi nel commit message
|
||||
git commit -m "your message [skip codescene]"
|
||||
```
|
||||
|
||||
The hooks expect `node` and `pnpm` to be available. If they are installed via `nvm`, the hooks will try to load `~/.nvm/nvm.sh` automatically.
|
||||
### Installazione (già fatto per questa repo)
|
||||
|
||||
## Policy
|
||||
L'hook è già installato in `.git/hooks/pre-commit`.
|
||||
|
||||
- Commit on `main` only.
|
||||
- Push from `main` to `origin/main` only.
|
||||
- Never use `--no-verify`.
|
||||
- `.codescene-thresholds` is a ratchet. It can only move up.
|
||||
Se cloni la repo altrove, copia l'hook:
|
||||
```bash
|
||||
cp .github/hooks/pre-commit .git/hooks/pre-commit
|
||||
chmod +x .git/hooks/pre-commit
|
||||
```
|
||||
|
||||
## Pre-commit
|
||||
### Esempio Output
|
||||
|
||||
`.husky/pre-commit` blocks commits unless all of the following are true:
|
||||
#### ✅ Commit Normale
|
||||
```
|
||||
🔍 Running CodeScene Code Health check...
|
||||
Comparing against: origin/main
|
||||
Analyzing code changes...
|
||||
✅ CodeScene check passed
|
||||
+42 -18 lines
|
||||
|
||||
- `HEAD` is attached to `main`
|
||||
- staged TypeScript files pass `pnpm lint --quiet`
|
||||
- TypeScript passes `npx tsc --noEmit`
|
||||
- frontend tests pass via `pnpm test --run --silent`
|
||||
- current CodeScene Hotspot and Average health are both at or above `.codescene-thresholds`
|
||||
💡 For detailed code health analysis, run:
|
||||
claude 'Check code health of this commit with CodeScene MCP'
|
||||
```
|
||||
|
||||
If `CODESCENE_PAT` or `CODESCENE_PROJECT_ID` is missing, the CodeScene portion is skipped, but the rest of the hook still runs.
|
||||
#### ⚠️ File Grandi
|
||||
```
|
||||
🔍 Running CodeScene Code Health check...
|
||||
Comparing against: origin/main
|
||||
Analyzing code changes...
|
||||
⚠️ Large file changes detected (>500 lines):
|
||||
- src/components/Editor.tsx
|
||||
- src-tauri/src/vault.rs
|
||||
|
||||
## Pre-push
|
||||
Consider:
|
||||
- Breaking into smaller commits
|
||||
- Reviewing with Claude Code + CodeScene MCP
|
||||
- Running: claude 'Review code health of staged changes'
|
||||
|
||||
`.husky/pre-push` blocks pushes unless all of the following are true:
|
||||
Continue anyway? (y/N)
|
||||
```
|
||||
|
||||
- the current branch is `main`
|
||||
- every pushed branch ref is `refs/heads/main -> refs/heads/main`
|
||||
- TypeScript and the Vite build pass
|
||||
- frontend coverage passes
|
||||
- Rust lint and Rust coverage pass when `src-tauri/` changed
|
||||
- the curated Playwright core smoke lane passes via `pnpm playwright:smoke`
|
||||
- current CodeScene Hotspot and Average health are both at or above `.codescene-thresholds`
|
||||
### CodeScene MCP Integration
|
||||
|
||||
If the remote CodeScene scores are better than the current thresholds, the hook updates `.codescene-thresholds`, stages it, and stops the push. Commit that file normally, then push again. The hook does not auto-commit or bypass itself.
|
||||
|
||||
## Legacy Files
|
||||
|
||||
The legacy `pre-commit` file under `.github/hooks/` is archival only. Do not copy it into `.git/hooks`; use Husky and `.husky/` instead. The old design `post-commit` auto-implementation hook was removed because it depended on obsolete one-off scripts. `install-hooks.sh` remains as a reinstall helper that runs Husky.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If a hook cannot find `node` or `pnpm`:
|
||||
Per analisi dettagliata del code health, usa Claude Code:
|
||||
|
||||
```bash
|
||||
export NVM_DIR="$HOME/.nvm"
|
||||
. "$NVM_DIR/nvm.sh"
|
||||
nvm use node
|
||||
# Analizza staged changes
|
||||
claude 'Check code health of staged changes with CodeScene MCP'
|
||||
|
||||
# Analizza file specifico
|
||||
claude 'What is the code health score of src/components/Editor.tsx?'
|
||||
|
||||
# Pre-commit safeguard
|
||||
claude 'Run pre_commit_code_health_safeguard on staged changes'
|
||||
```
|
||||
|
||||
Then retry the commit or push.
|
||||
### Troubleshooting
|
||||
|
||||
**Hook non si attiva:**
|
||||
- Verifica che `.git/hooks/pre-commit` esista ed sia eseguibile
|
||||
- `ls -la .git/hooks/pre-commit` — dovrebbe mostrare `-rwxr-xr-x`
|
||||
|
||||
**Vuoi disabilitare temporaneamente:**
|
||||
```bash
|
||||
mv .git/hooks/pre-commit .git/hooks/pre-commit.disabled
|
||||
```
|
||||
|
||||
**Vuoi riabilitare:**
|
||||
```bash
|
||||
mv .git/hooks/pre-commit.disabled .git/hooks/pre-commit
|
||||
```
|
||||
|
||||
### Future Improvements
|
||||
|
||||
Possibili miglioramenti:
|
||||
- [ ] Integrazione diretta API CodeScene per score numerico
|
||||
- [ ] Fail automatico se code health < soglia
|
||||
- [ ] Cache dei risultati per evitare re-analisi
|
||||
- [ ] Hook pre-push più pesante per analisi completa
|
||||
|
||||
---
|
||||
|
||||
## Post-Commit Hook: Auto-Implement Design Changes
|
||||
|
||||
### Cosa Fa
|
||||
|
||||
Quando committi modifiche a `ui-design.pen`, il hook:
|
||||
|
||||
1. **Analizza il diff** — usa `scripts/design-diff-analyzer.js`
|
||||
2. **Identifica modifiche significative:**
|
||||
- 🎨 Colori (fill, backgroundColor)
|
||||
- 📝 Typography (fontSize, fontFamily)
|
||||
- 📏 Spacing (padding, margin, gap)
|
||||
- 🔲 Layout (nuovi componenti, riorganizzazioni)
|
||||
3. **Spawna Claude Code** — in background via `openclaw sessions spawn`
|
||||
4. **Auto-notifica** — quando l'implementazione è completa
|
||||
|
||||
### Cosa Implementa
|
||||
|
||||
| Tipo Modifica | Azione |
|
||||
|--------------|--------|
|
||||
| Colori | Aggiorna `src/theme.json` o CSS variables |
|
||||
| Typography | Aggiorna `src/theme.json` typography |
|
||||
| Spacing | Aggiorna `src/theme.json` spacing |
|
||||
| Layout | Modifica/crea componenti React |
|
||||
| Testi mockup | Nessuna azione (solo design) |
|
||||
|
||||
### Esempio Output
|
||||
|
||||
```
|
||||
🎨 Design file changed - analyzing...
|
||||
|
||||
📋 Implementation tasks:
|
||||
|
||||
1. [HIGH] Update color palette
|
||||
- fill: $--muted-foreground → #666666
|
||||
- backgroundColor: #FFFFFF → #F5F5F5
|
||||
|
||||
Update src/theme.json or CSS variables to match the design.
|
||||
|
||||
2. [MEDIUM] Update typography
|
||||
- fontSize: 14px → 16px
|
||||
|
||||
Update src/theme.json typography settings.
|
||||
|
||||
🚀 Spawning Claude Code to implement changes...
|
||||
|
||||
✅ Claude Code spawned - you'll be notified when implementation is complete
|
||||
```
|
||||
|
||||
### Workflow Completo
|
||||
|
||||
```
|
||||
You Post-Commit Hook Claude Code Brian (AI)
|
||||
│ │ │ │
|
||||
├─ Modify ui-design.pen │ │ │
|
||||
├─ git add ui-design.pen │ │ │
|
||||
├─ git commit │ │ │
|
||||
│ │ │ │
|
||||
│ ├─ Analyze diff │ │
|
||||
│ ├─ Generate tasks │ │
|
||||
│ ├─ Spawn Claude Code ────────> │
|
||||
│ │ │ │
|
||||
│ │ ├─ Implement changes │
|
||||
│ │ ├─ Test visually │
|
||||
│ │ ├─ Run tests │
|
||||
│ │ ├─ Commit │
|
||||
│ │ ├─ openclaw system event ────>
|
||||
│ │ │ │
|
||||
│ │ │ ├─ Notify Telegram
|
||||
│ <─────────────────────────────────────────────────────────────────────────────┘
|
||||
│ "✅ Design changes implemented and tested"
|
||||
```
|
||||
|
||||
### Design Diff Analyzer
|
||||
|
||||
Lo script `scripts/design-diff-analyzer.js` rileva:
|
||||
|
||||
- **Color changes** — `"fill": "#OLD" → "#NEW"`
|
||||
- **Font changes** — `"fontSize": 14 → 16`
|
||||
- **Spacing** — `"padding": 8 → 12`
|
||||
- **Content** — testi mockup (no implementation)
|
||||
|
||||
Uso:
|
||||
```bash
|
||||
# Analizza ultimo commit
|
||||
node scripts/design-diff-analyzer.js
|
||||
|
||||
# Output JSON per automation
|
||||
node scripts/design-diff-analyzer.js --json
|
||||
```
|
||||
|
||||
### Disabilitare Temporaneamente
|
||||
|
||||
Se vuoi committare il design senza auto-implementazione:
|
||||
|
||||
```bash
|
||||
# Disabilita hook
|
||||
mv .git/hooks/post-commit .git/hooks/post-commit.disabled
|
||||
|
||||
# Commit
|
||||
git commit -m "design: update mockup"
|
||||
|
||||
# Riabilita hook
|
||||
mv .git/hooks/post-commit.disabled .git/hooks/post-commit
|
||||
```
|
||||
|
||||
### Monitorare Claude Code
|
||||
|
||||
Mentre Claude Code lavora in background:
|
||||
|
||||
```bash
|
||||
# Lista sub-agent attivi
|
||||
openclaw sessions list --kinds isolated
|
||||
|
||||
# Vedi log di un sub-agent
|
||||
openclaw sessions history --session-key <key>
|
||||
|
||||
# Ferma sub-agent (se necessario)
|
||||
openclaw subagents kill --target design-auto-implement
|
||||
```
|
||||
|
||||
### Troubleshooting
|
||||
|
||||
**Hook non parte:**
|
||||
- Verifica che `ui-design.pen` sia effettivamente cambiato: `git diff HEAD~1 ui-design.pen`
|
||||
- Verifica che lo script analyzer esista: `ls -la scripts/design-diff-analyzer.js`
|
||||
|
||||
**Nessuna notifica:**
|
||||
- Claude Code potrebbe essere ancora in esecuzione — controlla `openclaw sessions list`
|
||||
- Verifica che il prompt includa `openclaw system event` al termine
|
||||
|
||||
**Modifiche non implementate:**
|
||||
- Controlla i log di Claude Code: `openclaw sessions history --session-key <key>`
|
||||
- Il sub-agent viene auto-eliminato dopo completion (cleanup=delete)
|
||||
|
||||
### Limitazioni
|
||||
|
||||
- **Modifiche complesse** — layout completamente nuovi potrebbero richiedere intervento manuale
|
||||
- **Timeout** — 10 minuti max (configurabile in hook)
|
||||
- **Solo modifiche recenti** — analizza solo HEAD vs HEAD~1
|
||||
|
||||
26
.github/SETUP.md
vendored
26
.github/SETUP.md
vendored
@@ -14,26 +14,6 @@ Nel repository GitHub (Settings → Secrets and variables → Actions → New re
|
||||
**CODESCENE_PROJECT_ID**
|
||||
Trova l'ID del progetto nella dashboard CodeScene (URL: `https://codescene.io/projects/<PROJECT_ID>/...`)
|
||||
|
||||
**VITE_SENTRY_DSN**
|
||||
```
|
||||
<frontend Sentry DSN used by shipped Tolaria builds>
|
||||
```
|
||||
|
||||
**SENTRY_DSN**
|
||||
```
|
||||
<same DSN as VITE_SENTRY_DSN, passed to the Rust/Tauri build for native crash reporting>
|
||||
```
|
||||
|
||||
**VITE_POSTHOG_KEY**
|
||||
```
|
||||
<PostHog project API key used by shipped Tolaria builds>
|
||||
```
|
||||
|
||||
**VITE_POSTHOG_HOST**
|
||||
```
|
||||
https://eu.i.posthog.com
|
||||
```
|
||||
|
||||
### 2. Enable GitHub Actions
|
||||
|
||||
- Vai su Settings → Actions → General
|
||||
@@ -85,12 +65,6 @@ cargo fmt --manifest-path=src-tauri/Cargo.toml -- --check
|
||||
- **Fail se code health diminuisce**
|
||||
- Confronta HEAD vs base branch
|
||||
|
||||
### 📡 Telemetry In Release Builds
|
||||
- `release.yml` e `release-stable.yml` devono ricevere `VITE_SENTRY_DSN`, `SENTRY_DSN`, `VITE_POSTHOG_KEY`, `VITE_POSTHOG_HOST`
|
||||
- `VITE_SENTRY_DSN` inizializza il frontend Sentry bundle
|
||||
- `SENTRY_DSN` inizializza Sentry nel binary Rust/Tauri
|
||||
- `VITE_POSTHOG_KEY` / `VITE_POSTHOG_HOST` permettono ai build distribuiti di inizializzare PostHog quando l'utente abilita analytics
|
||||
|
||||
### 📝 Documentation
|
||||
- **Warning se modifichi `src/` o `src-tauri/` ma non aggiorni `docs/`**
|
||||
- Non blocca il merge, solo un reminder
|
||||
|
||||
39
.github/hooks/install-hooks.sh
vendored
39
.github/hooks/install-hooks.sh
vendored
@@ -1,26 +1,25 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
# Install git hooks for laputa-app
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1 || ! command -v node >/dev/null 2>&1; then
|
||||
export NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
|
||||
if [ -s "$NVM_DIR/nvm.sh" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$NVM_DIR/nvm.sh" --no-use
|
||||
nvm use --silent node >/dev/null 2>&1 || true
|
||||
fi
|
||||
fi
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
HOOKS_DIR="$(git rev-parse --git-dir)/hooks"
|
||||
|
||||
if ! command -v pnpm >/dev/null 2>&1 || ! command -v node >/dev/null 2>&1; then
|
||||
echo "❌ node and pnpm must be available to install Husky hooks"
|
||||
exit 1
|
||||
fi
|
||||
echo "Installing git hooks..."
|
||||
|
||||
# Copy pre-commit hook
|
||||
cp "$SCRIPT_DIR/pre-commit" "$HOOKS_DIR/pre-commit"
|
||||
chmod +x "$HOOKS_DIR/pre-commit"
|
||||
echo "✅ Installed pre-commit hook"
|
||||
|
||||
# Copy post-commit hook
|
||||
cp "$SCRIPT_DIR/post-commit" "$HOOKS_DIR/post-commit"
|
||||
chmod +x "$HOOKS_DIR/post-commit"
|
||||
echo "✅ Installed post-commit hook"
|
||||
|
||||
echo "Installing Husky hooks from .husky/ ..."
|
||||
pnpm exec husky
|
||||
echo "✅ Husky hooks installed"
|
||||
echo ""
|
||||
echo "Source of truth:"
|
||||
echo " - .husky/pre-commit"
|
||||
echo " - .husky/pre-push"
|
||||
echo "Hooks installed:"
|
||||
echo " - pre-commit: CodeScene code health check"
|
||||
echo " - post-commit: Auto-implement design changes via Claude Code"
|
||||
echo ""
|
||||
echo "Never use --no-verify in this repo."
|
||||
echo "To bypass pre-commit, use: git commit --no-verify"
|
||||
echo "Or include [skip codescene] in your commit message"
|
||||
|
||||
72
.github/hooks/post-commit
vendored
Normal file
72
.github/hooks/post-commit
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
#!/bin/bash
|
||||
# Post-commit hook: Auto-implement design changes via Claude Code
|
||||
# Copy to .git/hooks/post-commit and make executable
|
||||
|
||||
set -e
|
||||
|
||||
# Check if ui-design.pen was modified in this commit
|
||||
if ! git diff --name-only HEAD~1 HEAD | grep -q "ui-design.pen"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🎨 Design file changed - analyzing..."
|
||||
|
||||
# Run analyzer
|
||||
ANALYZER_OUTPUT=$(node scripts/design-diff-analyzer.js --json 2>&1)
|
||||
|
||||
if [ $? -eq 0 ]; then
|
||||
echo "✅ No implementation tasks needed (content-only changes)"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Extract tasks from JSON
|
||||
TASKS_JSON=$(echo "$ANALYZER_OUTPUT" | sed -n '/---JSON---/,$ p' | tail -n +2)
|
||||
|
||||
if [ -z "$TASKS_JSON" ]; then
|
||||
echo "✅ No significant design changes"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "$ANALYZER_OUTPUT" | sed '/---JSON---/,$ d'
|
||||
|
||||
# Generate Claude Code prompt
|
||||
PROMPT=$(cat <<EOF
|
||||
The design file ui-design.pen was just updated. Analyze the changes and implement them.
|
||||
|
||||
Design changes detected:
|
||||
$ANALYZER_OUTPUT
|
||||
|
||||
Tasks:
|
||||
1. Review the git diff of ui-design.pen (HEAD vs HEAD~1)
|
||||
2. Identify what changed (colors, typography, spacing, layout)
|
||||
3. Update the corresponding code:
|
||||
- Colors/Typography/Spacing → update src/theme.json
|
||||
- Layout changes → update React components
|
||||
- New elements → create new components
|
||||
4. Test visually in Chrome (pnpm dev, open localhost:5173)
|
||||
5. Run tests: pnpm test
|
||||
6. Commit changes with descriptive message referencing the design update
|
||||
|
||||
When completely finished, run:
|
||||
openclaw system event --text "✅ Design changes implemented and tested" --mode now
|
||||
EOF
|
||||
)
|
||||
|
||||
echo ""
|
||||
echo "🚀 Spawning Claude Code to implement changes..."
|
||||
echo ""
|
||||
|
||||
# Spawn Claude Code via OpenClaw
|
||||
openclaw sessions spawn \
|
||||
--task "$PROMPT" \
|
||||
--label "design-auto-implement" \
|
||||
--cleanup delete \
|
||||
--timeout-seconds 600 \
|
||||
--agent-id main
|
||||
|
||||
echo ""
|
||||
echo "✅ Claude Code spawned - you'll be notified when implementation is complete"
|
||||
echo ""
|
||||
|
||||
exit 0
|
||||
137
.github/scripts/prefetch-tauri-nsis.ps1
vendored
137
.github/scripts/prefetch-tauri-nsis.ps1
vendored
@@ -1,137 +0,0 @@
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
$nsisUrl = "https://github.com/tauri-apps/binary-releases/releases/download/nsis-3.11/nsis-3.11.zip"
|
||||
$nsisSha1 = "EF7FF767E5CBD9EDD22ADD3A32C9B8F4500BB10D"
|
||||
$tauriUtilsUrl = "https://github.com/tauri-apps/nsis-tauri-utils/releases/download/nsis_tauri_utils-v0.5.3/nsis_tauri_utils.dll"
|
||||
$tauriUtilsSha1 = "75197FEE3C6A814FE035788D1C34EAD39349B860"
|
||||
$tauriUtilsRelativePath = "Plugins\x86-unicode\additional\nsis_tauri_utils.dll"
|
||||
|
||||
$nsisRequiredFiles = @(
|
||||
"makensis.exe",
|
||||
"Bin\makensis.exe",
|
||||
"Stubs\lzma-x86-unicode",
|
||||
"Stubs\lzma_solid-x86-unicode",
|
||||
"Include\MUI2.nsh",
|
||||
"Include\FileFunc.nsh",
|
||||
"Include\x64.nsh",
|
||||
"Include\nsDialogs.nsh",
|
||||
"Include\WinMessages.nsh",
|
||||
"Include\Win\COM.nsh",
|
||||
"Include\Win\Propkey.nsh",
|
||||
"Include\Win\RestartManager.nsh"
|
||||
)
|
||||
|
||||
function Get-UpperSha1 {
|
||||
param([Parameter(Mandatory = $true)][string]$Path)
|
||||
|
||||
return (Get-FileHash -Algorithm SHA1 -LiteralPath $Path).Hash.ToUpperInvariant()
|
||||
}
|
||||
|
||||
function Test-FileSha1 {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Path,
|
||||
[Parameter(Mandatory = $true)][string]$ExpectedSha1
|
||||
)
|
||||
|
||||
return (Test-Path -LiteralPath $Path) -and ((Get-UpperSha1 -Path $Path) -eq $ExpectedSha1)
|
||||
}
|
||||
|
||||
function Save-VerifiedDownload {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Uri,
|
||||
[Parameter(Mandatory = $true)][string]$OutFile,
|
||||
[Parameter(Mandatory = $true)][string]$ExpectedSha1
|
||||
)
|
||||
|
||||
$parent = Split-Path -Parent $OutFile
|
||||
New-Item -ItemType Directory -Force -Path $parent | Out-Null
|
||||
|
||||
$tempFile = "$OutFile.download"
|
||||
for ($attempt = 1; $attempt -le 5; $attempt++) {
|
||||
try {
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath $tempFile
|
||||
Invoke-WebRequest -Uri $Uri -OutFile $tempFile -TimeoutSec 120
|
||||
|
||||
$actualSha1 = Get-UpperSha1 -Path $tempFile
|
||||
if ($actualSha1 -ne $ExpectedSha1) {
|
||||
throw "SHA1 mismatch for $Uri. Expected $ExpectedSha1, got $actualSha1."
|
||||
}
|
||||
|
||||
Move-Item -Force -LiteralPath $tempFile -Destination $OutFile
|
||||
return
|
||||
} catch {
|
||||
Remove-Item -Force -ErrorAction SilentlyContinue -LiteralPath $tempFile
|
||||
if ($attempt -eq 5) {
|
||||
throw
|
||||
}
|
||||
|
||||
$delaySeconds = [Math]::Min(30, 5 * $attempt)
|
||||
Write-Warning "Download attempt ${attempt} failed: $($_.Exception.Message). Retrying in ${delaySeconds}s."
|
||||
Start-Sleep -Seconds $delaySeconds
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function Find-MissingFile {
|
||||
param(
|
||||
[Parameter(Mandatory = $true)][string]$Root,
|
||||
[Parameter(Mandatory = $true)][string[]]$RelativePaths
|
||||
)
|
||||
|
||||
foreach ($relativePath in $RelativePaths) {
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $Root $relativePath))) {
|
||||
return $relativePath
|
||||
}
|
||||
}
|
||||
|
||||
return $null
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($env:LOCALAPPDATA)) {
|
||||
throw "LOCALAPPDATA is required to resolve Tauri's Windows tool cache."
|
||||
}
|
||||
|
||||
$tauriToolsPath = Join-Path $env:LOCALAPPDATA "tauri"
|
||||
$nsisPath = Join-Path $tauriToolsPath "NSIS"
|
||||
$downloadRoot = if ([string]::IsNullOrWhiteSpace($env:RUNNER_TEMP)) {
|
||||
[System.IO.Path]::GetTempPath()
|
||||
} else {
|
||||
$env:RUNNER_TEMP
|
||||
}
|
||||
|
||||
New-Item -ItemType Directory -Force -Path $tauriToolsPath | Out-Null
|
||||
|
||||
$missingNsisFile = Find-MissingFile -Root $nsisPath -RelativePaths $nsisRequiredFiles
|
||||
if ($missingNsisFile) {
|
||||
Write-Host "Tauri NSIS cache is missing $missingNsisFile; downloading NSIS 3.11."
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -LiteralPath $nsisPath
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue -LiteralPath (Join-Path $tauriToolsPath "nsis-3.11")
|
||||
|
||||
$zipPath = Join-Path $downloadRoot "nsis-3.11.zip"
|
||||
Save-VerifiedDownload -Uri $nsisUrl -OutFile $zipPath -ExpectedSha1 $nsisSha1
|
||||
Expand-Archive -Force -LiteralPath $zipPath -DestinationPath $tauriToolsPath
|
||||
|
||||
$extractedNsisPath = Join-Path $tauriToolsPath "nsis-3.11"
|
||||
if (-not (Test-Path -LiteralPath $extractedNsisPath)) {
|
||||
throw "Downloaded NSIS archive did not contain the expected nsis-3.11 directory."
|
||||
}
|
||||
|
||||
Move-Item -Force -LiteralPath $extractedNsisPath -Destination $nsisPath
|
||||
} else {
|
||||
Write-Host "Tauri NSIS cache already contains NSIS 3.11."
|
||||
}
|
||||
|
||||
$tauriUtilsPath = Join-Path $nsisPath $tauriUtilsRelativePath
|
||||
if (-not (Test-FileSha1 -Path $tauriUtilsPath -ExpectedSha1 $tauriUtilsSha1)) {
|
||||
Write-Host "Downloading Tauri NSIS utility plugin."
|
||||
Save-VerifiedDownload -Uri $tauriUtilsUrl -OutFile $tauriUtilsPath -ExpectedSha1 $tauriUtilsSha1
|
||||
} else {
|
||||
Write-Host "Tauri NSIS utility plugin is already cached."
|
||||
}
|
||||
|
||||
$missingFile = Find-MissingFile -Root $nsisPath -RelativePaths ($nsisRequiredFiles + @($tauriUtilsRelativePath))
|
||||
if ($missingFile) {
|
||||
throw "Tauri NSIS toolchain is incomplete after prefetch; missing $missingFile."
|
||||
}
|
||||
|
||||
Write-Host "Tauri NSIS toolchain ready at $nsisPath."
|
||||
23
.github/workflows/README.md
vendored
23
.github/workflows/README.md
vendored
@@ -10,7 +10,6 @@ Il workflow `ci.yml` esegue i seguenti check automatici:
|
||||
|
||||
### 2. Test Coverage
|
||||
- Frontend: vitest con coverage reporting
|
||||
- Upload automatico su Codecov dai report LCOV frontend + Rust
|
||||
- Threshold configurabile in `vitest.config.ts`
|
||||
|
||||
### 3. Code Health (CodeScene)
|
||||
@@ -41,23 +40,6 @@ CODESCENE_PROJECT_ID=<your-project-id>
|
||||
Il PAT di CodeScene è lo stesso che usi localmente (~/.codescene/token).
|
||||
Il project ID lo trovi nella dashboard CodeScene.
|
||||
|
||||
### Codecov Setup
|
||||
- Installa/attiva il repo in Codecov una volta sola tramite GitHub App / import del repository.
|
||||
- Nessun `CODECOV_TOKEN` richiesto in GitHub Actions: `ci.yml` usa OIDC (`id-token: write` + `use_oidc: true`).
|
||||
- Il workflow carica `coverage/lcov.info` (Vitest) e `coverage/rust.lcov` (cargo-llvm-cov).
|
||||
|
||||
### Telemetry Secrets For Release Builds
|
||||
Aggiungi anche questi secrets per i workflow `release.yml` e `release-stable.yml`:
|
||||
|
||||
```
|
||||
VITE_SENTRY_DSN=<frontend sentry dsn>
|
||||
SENTRY_DSN=<same dsn for rust/native crash reporting>
|
||||
VITE_POSTHOG_KEY=<posthog project api key>
|
||||
VITE_POSTHOG_HOST=https://eu.i.posthog.com
|
||||
```
|
||||
|
||||
Senza questi valori, i build distribuiti possono mantenere i toggle telemetry nelle Settings ma non inizializzare davvero PostHog/Sentry.
|
||||
|
||||
### Coverage Thresholds
|
||||
Configura in `vitest.config.ts`:
|
||||
|
||||
@@ -103,11 +85,8 @@ codescene delta-analysis --base-revision origin/main
|
||||
|
||||
## Workflow Triggers
|
||||
|
||||
- **Push**: su `main`
|
||||
- **Push**: su `main` e branch `experiment/*`
|
||||
- **Pull Request**: verso `main`
|
||||
- **Manuale**: `workflow_dispatch`
|
||||
|
||||
Nota: l'upload a Codecov gira su push a `main` e sulle PR dello stesso repository. Le PR da fork saltano l'upload per evitare problemi di permessi OIDC.
|
||||
|
||||
## Status Checks
|
||||
|
||||
|
||||
149
.github/workflows/ci.yml
vendored
149
.github/workflows/ci.yml
vendored
@@ -2,18 +2,9 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
branches: [main, experiment/*]
|
||||
pull_request:
|
||||
branches: [main]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
|
||||
env:
|
||||
# Bump this when Tauri/Rust target artifacts capture stale absolute paths.
|
||||
RUST_TARGET_CACHE_VERSION: v2026-04-14-tolaria
|
||||
|
||||
jobs:
|
||||
test:
|
||||
@@ -48,9 +39,9 @@ jobs:
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-cargo-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
key: ${{ runner.os }}-cargo-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
${{ runner.os }}-cargo-
|
||||
|
||||
- name: Install cargo-llvm-cov
|
||||
uses: taiki-e/install-action@cargo-llvm-cov
|
||||
@@ -65,75 +56,55 @@ jobs:
|
||||
- name: Vite build check
|
||||
run: pnpm build
|
||||
|
||||
# ── 1. Coverage-backed tests ──────────────────────────────────────────
|
||||
# The coverage commands run the same frontend and Rust test suites, so keep
|
||||
# them as the canonical test lane instead of running every suite twice.
|
||||
# ── 1. Tests ──────────────────────────────────────────────────────────
|
||||
- name: Run frontend tests
|
||||
run: pnpm test
|
||||
|
||||
- name: Bundle MCP server resources (required by Tauri build)
|
||||
run: node scripts/bundle-mcp-server.mjs
|
||||
|
||||
# ── 2. Tests + coverage (enforced — fails build if thresholds not met) ─
|
||||
- name: Frontend tests + coverage (≥70% lines/functions/branches/statements)
|
||||
- name: Run Rust tests
|
||||
run: cargo test --manifest-path=src-tauri/Cargo.toml
|
||||
|
||||
# ── 2. Coverage (enforced — fails build if thresholds not met) ────────
|
||||
- name: Frontend coverage (≥70% lines/functions/branches/statements)
|
||||
run: pnpm test:coverage
|
||||
# Thresholds configured in vite.config.ts — exits non-zero if coverage drops
|
||||
|
||||
- name: Rust tests + coverage (≥85% lines)
|
||||
- name: Rust coverage (≥85% lines)
|
||||
run: |
|
||||
cargo llvm-cov \
|
||||
--manifest-path src-tauri/Cargo.toml \
|
||||
--ignore-filename-regex 'lib\.rs|main\.rs|menu\.rs' \
|
||||
--lcov \
|
||||
--output-path coverage/rust.lcov \
|
||||
--fail-under-lines 85
|
||||
# cargo-llvm-cov exits non-zero if line coverage drops below 85%
|
||||
# lib.rs/main.rs/menu.rs are Tauri boilerplate -- not meaningfully unit-testable.
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
|
||||
uses: codecov/codecov-action@v5
|
||||
with:
|
||||
use_oidc: true
|
||||
fail_ci_if_error: true
|
||||
disable_search: true
|
||||
files: ./coverage/lcov.info,./coverage/rust.lcov
|
||||
verbose: true
|
||||
# OIDC avoids long-lived CODECOV_TOKEN secrets.
|
||||
|
||||
# ── 3. Code Health (CodeScene — Hotspot + Average Code Health gates) ──
|
||||
# Enforces minimum floors on BOTH hotspot and average code health.
|
||||
# Thresholds come from .codescene-thresholds so CI and local hooks match.
|
||||
- name: Code Health gates
|
||||
# ── 3. Code Health (CodeScene — Hotspot Code Health gate) ────────────
|
||||
# The webhook integration handles per-PR delta analysis (posts review
|
||||
# comments on PRs). This step enforces a minimum floor on the
|
||||
# project-wide Hotspot Code Health score (weighted avg of the most
|
||||
# frequently edited files — the ones that matter most).
|
||||
# Current baseline: 9.33 | Aspirational target: 9.5
|
||||
- name: Hotspot Code Health gate (≥9.2)
|
||||
env:
|
||||
CODESCENE_PAT: ${{ secrets.CODESCENE_PAT }}
|
||||
CODESCENE_PROJECT_ID: ${{ secrets.CODESCENE_PROJECT_ID }}
|
||||
run: |
|
||||
HOTSPOT_THRESHOLD=$(grep '^HOTSPOT_THRESHOLD=' .codescene-thresholds | cut -d= -f2)
|
||||
AVERAGE_THRESHOLD=$(grep '^AVERAGE_THRESHOLD=' .codescene-thresholds | cut -d= -f2)
|
||||
API_RESPONSE=$(curl -sf \
|
||||
THRESHOLD=9.2
|
||||
SCORE=$(curl -sf \
|
||||
-H "Authorization: Bearer $CODESCENE_PAT" \
|
||||
-H "Accept: application/json" \
|
||||
"https://api.codescene.io/v2/projects/$CODESCENE_PROJECT_ID")
|
||||
HOTSPOT_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['hotspot_code_health']['now'])")
|
||||
AVERAGE_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['code_health']['now'])")
|
||||
echo "Hotspot Code Health: $HOTSPOT_SCORE (threshold: $HOTSPOT_THRESHOLD)"
|
||||
echo "Average Code Health: $AVERAGE_SCORE (threshold: $AVERAGE_THRESHOLD)"
|
||||
"https://api.codescene.io/v2/projects/$CODESCENE_PROJECT_ID" \
|
||||
| python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['hotspot_code_health']['now'])")
|
||||
echo "Hotspot Code Health: $SCORE (threshold: $THRESHOLD)"
|
||||
python3 -c "
|
||||
hotspot = float('$HOTSPOT_SCORE')
|
||||
average = float('$AVERAGE_SCORE')
|
||||
ht = float('$HOTSPOT_THRESHOLD')
|
||||
at = float('$AVERAGE_THRESHOLD')
|
||||
failed = False
|
||||
if hotspot < ht:
|
||||
print(f'❌ Hotspot Code Health {hotspot:.2f} is below threshold {ht}')
|
||||
failed = True
|
||||
else:
|
||||
print(f'✅ Hotspot Code Health {hotspot:.2f} ≥ {ht}')
|
||||
if average < at:
|
||||
print(f'❌ Average Code Health {average:.2f} is below threshold {at}')
|
||||
failed = True
|
||||
else:
|
||||
print(f'✅ Average Code Health {average:.2f} ≥ {at}')
|
||||
if failed:
|
||||
score = float('$SCORE')
|
||||
threshold = float('$THRESHOLD')
|
||||
if score < threshold:
|
||||
print(f'❌ Hotspot Code Health {score:.2f} is below threshold {threshold}')
|
||||
exit(1)
|
||||
print(f'✅ Hotspot Code Health {score:.2f} ≥ {threshold}')
|
||||
"
|
||||
|
||||
# ── 4. Documentation check (warning only — does not fail build) ───────
|
||||
@@ -163,63 +134,3 @@ jobs:
|
||||
|
||||
- name: Format check (Rust)
|
||||
run: cargo fmt --manifest-path=src-tauri/Cargo.toml -- --check
|
||||
|
||||
linux-build:
|
||||
name: Linux build verification
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Tauri Linux system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libsoup-3.0-dev \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev \
|
||||
patchelf \
|
||||
build-essential \
|
||||
file
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
components: clippy
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-cargo-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-cargo-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Install dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Frontend build
|
||||
run: pnpm build
|
||||
|
||||
- name: Cargo check
|
||||
run: cargo check --manifest-path=src-tauri/Cargo.toml
|
||||
|
||||
- name: Clippy
|
||||
run: cargo clippy --manifest-path=src-tauri/Cargo.toml -- -D warnings
|
||||
|
||||
749
.github/workflows/release-stable.yml
vendored
749
.github/workflows/release-stable.yml
vendored
@@ -1,749 +0,0 @@
|
||||
name: Release (Stable)
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'stable-v*'
|
||||
|
||||
env:
|
||||
# Bump this when Tauri/Rust target artifacts capture stale absolute paths.
|
||||
RUST_TARGET_CACHE_VERSION: v2026-04-14-tolaria
|
||||
|
||||
concurrency:
|
||||
group: release-stable-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 1: Compute the stable version string once
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
version:
|
||||
name: Compute stable version
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.ver.outputs.version }}
|
||||
display_version: ${{ steps.ver.outputs.display_version }}
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
steps:
|
||||
- id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
python3 <<'PY' > version.env
|
||||
import os
|
||||
import re
|
||||
from datetime import date
|
||||
|
||||
tag = os.environ["GITHUB_REF_NAME"]
|
||||
version = tag.removeprefix("stable-v")
|
||||
match = re.fullmatch(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", version)
|
||||
if not match:
|
||||
raise SystemExit(f"Stable tags must use stable-vYYYY.M.D, got {tag}")
|
||||
|
||||
date(*map(int, match.groups()))
|
||||
print(f"version={version}")
|
||||
print(f"display_version={version}")
|
||||
print(f"tag={tag}")
|
||||
PY
|
||||
|
||||
cat version.env >> "$GITHUB_OUTPUT"
|
||||
DISPLAY_VERSION=$(grep '^display_version=' version.env | cut -d= -f2-)
|
||||
echo "### Stable version: \`$DISPLAY_VERSION\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 2: Build release bundles in parallel
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
build:
|
||||
name: Build (${{ matrix.arch }})
|
||||
needs: version
|
||||
runs-on: macos-15
|
||||
strategy:
|
||||
fail-fast: true
|
||||
matrix:
|
||||
include:
|
||||
- arch: aarch64
|
||||
target: aarch64-apple-darwin
|
||||
- arch: x86_64
|
||||
target: x86_64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Bun (required for bundle-qmd.sh)
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: ${{ matrix.target }}
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-release-cargo-${{ matrix.target }}-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-${{ matrix.target }}-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached bundle artifacts
|
||||
run: |
|
||||
rm -rf src-tauri/target/${{ matrix.target }}/release/bundle
|
||||
|
||||
- name: Set version
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
jq --arg v "$VERSION" '.version = $v' src-tauri/tauri.conf.json > tmp.json && mv tmp.json src-tauri/tauri.conf.json
|
||||
sed -i '' "s/^version = \".*\"/version = \"$VERSION\"/" src-tauri/Cargo.toml
|
||||
|
||||
- name: Import Apple Developer certificate into keychain
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
run: |
|
||||
CERT_PATH="$RUNNER_TEMP/apple_cert.p12"
|
||||
KEYCHAIN_PATH="$RUNNER_TEMP/laputa-signing.keychain-db"
|
||||
KEYCHAIN_PASSWORD="$(uuidgen)"
|
||||
echo "$APPLE_CERTIFICATE" | base64 --decode > "$CERT_PATH"
|
||||
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
|
||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
security import "$CERT_PATH" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
|
||||
security list-keychain -d user -s "$KEYCHAIN_PATH"
|
||||
security set-key-partition-list -S apple-tool:,apple: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
echo "KEYCHAIN_PATH=$KEYCHAIN_PATH" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Validate telemetry env
|
||||
env:
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
python3 <<'PY'
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DISALLOWED_PLACEHOLDERS = {
|
||||
"",
|
||||
"-",
|
||||
"_",
|
||||
"false",
|
||||
"true",
|
||||
"null",
|
||||
"undefined",
|
||||
"none",
|
||||
"disabled",
|
||||
}
|
||||
|
||||
def normalize(name: str) -> str:
|
||||
value = os.getenv(name, "").strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
||||
value = value[1:-1].strip()
|
||||
return value
|
||||
|
||||
def normalize_http_like(value: str) -> str:
|
||||
if "://" in value:
|
||||
return value
|
||||
return f"https://{value}"
|
||||
|
||||
def normalize_hostname(hostname: str) -> str:
|
||||
normalized = hostname.strip().rstrip('.').lower()
|
||||
if normalized.startswith('[') and normalized.endswith(']'):
|
||||
normalized = normalized[1:-1]
|
||||
return normalized
|
||||
|
||||
def is_ip_address(hostname: str) -> bool:
|
||||
if re.fullmatch(r"(?:\d{1,3}\.){3}\d{1,3}", hostname):
|
||||
return all(0 <= int(part) <= 255 for part in hostname.split('.'))
|
||||
return ':' in hostname and re.fullmatch(r"[\da-f:]+", hostname, re.IGNORECASE) is not None
|
||||
|
||||
def is_allowed_hostname(hostname: str) -> bool:
|
||||
normalized = normalize_hostname(hostname)
|
||||
if not normalized or normalized in DISALLOWED_PLACEHOLDERS:
|
||||
return False
|
||||
if normalized == 'localhost':
|
||||
return True
|
||||
return '.' in normalized or is_ip_address(normalized)
|
||||
|
||||
def is_http_url(value: str) -> bool:
|
||||
parsed = urlparse(normalize_http_like(value))
|
||||
return parsed.scheme in {"http", "https"} and is_allowed_hostname(parsed.hostname or "")
|
||||
|
||||
values = {
|
||||
name: normalize(name)
|
||||
for name in (
|
||||
"VITE_SENTRY_DSN",
|
||||
"SENTRY_DSN",
|
||||
"VITE_POSTHOG_KEY",
|
||||
"VITE_POSTHOG_HOST",
|
||||
)
|
||||
}
|
||||
errors = []
|
||||
|
||||
for name in ("VITE_SENTRY_DSN", "SENTRY_DSN", "VITE_POSTHOG_HOST"):
|
||||
value = values[name]
|
||||
if value.lower() in DISALLOWED_PLACEHOLDERS:
|
||||
errors.append(f"{name} must be set to a real value, not a placeholder")
|
||||
elif not is_http_url(value):
|
||||
errors.append(f"{name} must be a valid http(s) URL with a non-placeholder host")
|
||||
|
||||
if values["VITE_POSTHOG_KEY"].lower() in DISALLOWED_PLACEHOLDERS:
|
||||
errors.append("VITE_POSTHOG_KEY must be set to a real project API key, not a placeholder")
|
||||
|
||||
if errors:
|
||||
print("Telemetry env validation failed:", file=sys.stderr)
|
||||
for error in errors:
|
||||
print(f"- {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
print("Telemetry env validation passed.")
|
||||
PY
|
||||
|
||||
- name: Build Tauri app (with signing + notarization)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
APPLE_SIGNING_IDENTITY: ${{ secrets.APPLE_SIGNING_IDENTITY }}
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target ${{ matrix.target }}
|
||||
|
||||
- name: Upload .dmg
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmg-${{ matrix.arch }}
|
||||
path: src-tauri/target/${{ matrix.target }}/release/bundle/dmg/*.dmg
|
||||
retention-days: 1
|
||||
|
||||
- name: Upload updater artifacts (.tar.gz + .sig)
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: updater-${{ matrix.arch }}
|
||||
path: |
|
||||
src-tauri/target/${{ matrix.target }}/release/bundle/macos/*.app.tar.gz
|
||||
src-tauri/target/${{ matrix.target }}/release/bundle/macos/*.app.tar.gz.sig
|
||||
retention-days: 1
|
||||
|
||||
build-linux:
|
||||
name: Build (linux-x86_64)
|
||||
needs: version
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Tauri Linux system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libsoup-3.0-dev \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev \
|
||||
curl \
|
||||
wget \
|
||||
patchelf \
|
||||
build-essential \
|
||||
file \
|
||||
rpm
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-unknown-linux-gnu
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-release-cargo-x86_64-unknown-linux-gnu-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-unknown-linux-gnu-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached bundle artifacts
|
||||
run: |
|
||||
rm -rf src-tauri/target/x86_64-unknown-linux-gnu/release/bundle
|
||||
|
||||
- name: Set version
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
jq --arg v "$VERSION" '.version = $v' src-tauri/tauri.conf.json > tmp.json && mv tmp.json src-tauri/tauri.conf.json
|
||||
sed -i "s/^version = \".*\"/version = \"$VERSION\"/" src-tauri/Cargo.toml
|
||||
|
||||
- name: Build Tauri app (Linux bundles)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,rpm,appimage
|
||||
|
||||
- name: Validate Linux bundles
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
installers=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no AppImage, deb or rpm bundle."
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no updater signature (.sig) artifact."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Linux bundles
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x86_64-bundles
|
||||
path: |
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz.sig
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
build-windows:
|
||||
name: Build (windows-x86_64)
|
||||
needs: version
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\.cargo\registry
|
||||
~\.cargo\git
|
||||
src-tauri\target
|
||||
key: ${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Cache Tauri Windows tools
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~\AppData\Local\tauri
|
||||
key: ${{ runner.os }}-tauri-tools-nsis-3.11-nsis-tauri-utils-0.5.3
|
||||
|
||||
- name: Prefetch Tauri NSIS toolchain
|
||||
shell: pwsh
|
||||
run: ./.github/scripts/prefetch-tauri-nsis.ps1
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached Windows bundle artifacts
|
||||
shell: pwsh
|
||||
run: |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue "src-tauri/target/x86_64-pc-windows-msvc/release/bundle"
|
||||
|
||||
- name: Set version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ needs.version.outputs.version }}"
|
||||
$tauri = Get-Content "src-tauri/tauri.conf.json" | ConvertFrom-Json
|
||||
$tauri.version = $version
|
||||
$tauri | ConvertTo-Json -Depth 100 | Set-Content "src-tauri/tauri.conf.json"
|
||||
(Get-Content "src-tauri/Cargo.toml") -replace '^version = ".*"$', "version = `"$version`"" | Set-Content "src-tauri/Cargo.toml"
|
||||
|
||||
- name: Validate Windows release env
|
||||
shell: bash
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
run: |
|
||||
for name in TAURI_SIGNING_PRIVATE_KEY TAURI_KEY_PASSWORD; do
|
||||
if [ -z "${!name}" ]; then
|
||||
echo "::error::$name is required to build signed Windows updater artifacts."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Build Tauri app (Windows bundles)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis
|
||||
|
||||
- name: Validate Windows bundles
|
||||
shell: bash
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
installers=(
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*-setup.exe
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*-setup.exe.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.nsis.zip.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.zip.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Windows build produced no installable NSIS or MSI bundle."
|
||||
exit 1
|
||||
fi
|
||||
for installer in "${installers[@]}"; do
|
||||
if [[ "$(basename "$installer")" != *"${{ needs.version.outputs.version }}"* ]]; then
|
||||
echo "::error::Windows build produced an installer for a different version: $(basename "$installer")"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
echo "::error::Windows build produced no updater signature (.sig) artifact."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Windows bundles
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x86_64-bundles
|
||||
path: |
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.exe
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.exe.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.zip
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.zip.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.zip
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.zip.sig
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 3: Publish GitHub Release
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
release:
|
||||
name: GitHub Release (stable)
|
||||
needs: [version, build, build-linux, build-windows]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
|
||||
- name: Normalize macOS release artifact names
|
||||
run: |
|
||||
normalize_macos_artifacts() {
|
||||
local arch="$1"
|
||||
local normalized_updater="$2"
|
||||
local normalized_dmg="$3"
|
||||
local updater_dir="updater-${arch}"
|
||||
local updater_file
|
||||
updater_file=$(find "$updater_dir" -maxdepth 1 -name "*.app.tar.gz" -print -quit)
|
||||
if [ -z "$updater_file" ]; then
|
||||
echo "::error::Missing macOS updater artifact in ${updater_dir}" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local sig_file="${updater_file}.sig"
|
||||
if [ ! -f "$sig_file" ]; then
|
||||
echo "::error::Missing macOS updater signature for ${updater_file}" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local normalized_sig="${normalized_updater}.sig"
|
||||
if [ "$updater_file" != "$normalized_updater" ]; then
|
||||
mv "$updater_file" "$normalized_updater"
|
||||
fi
|
||||
if [ "$sig_file" != "$normalized_sig" ]; then
|
||||
mv "$sig_file" "$normalized_sig"
|
||||
fi
|
||||
|
||||
local dmg_dir="dmg-${arch}"
|
||||
local dmg_file
|
||||
dmg_file=$(find "$dmg_dir" -maxdepth 1 -name "*.dmg" -print -quit)
|
||||
if [ -z "$dmg_file" ]; then
|
||||
echo "::error::Missing macOS DMG artifact in ${dmg_dir}" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ "$dmg_file" != "$normalized_dmg" ]; then
|
||||
mv "$dmg_file" "$normalized_dmg"
|
||||
fi
|
||||
}
|
||||
|
||||
normalize_macos_artifacts aarch64 \
|
||||
"updater-aarch64/Tolaria_${{ needs.version.outputs.version }}_macOS_Silicon.app.tar.gz" \
|
||||
"dmg-aarch64/Tolaria_${{ needs.version.outputs.version }}_macOS_Silicon.dmg"
|
||||
normalize_macos_artifacts x86_64 \
|
||||
"updater-x86_64/Tolaria_${{ needs.version.outputs.version }}_macOS_Intel.app.tar.gz" \
|
||||
"dmg-x86_64/Tolaria_${{ needs.version.outputs.version }}_macOS_Intel.dmg"
|
||||
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
PREV_TAG=$(git tag --list 'stable-v*' --sort=-version:refname | grep -vx "${{ needs.version.outputs.tag }}" | head -n 1 || echo "")
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
NOTES=$(git log --oneline --no-merges -20)
|
||||
else
|
||||
NOTES=$(git log --oneline --no-merges "${PREV_TAG}..${{ needs.version.outputs.tag }}")
|
||||
fi
|
||||
{
|
||||
echo "## What's Changed"
|
||||
echo ""
|
||||
echo "$NOTES" | while IFS= read -r line; do echo "- $line"; done
|
||||
echo ""
|
||||
echo "---"
|
||||
echo "**Stable release — manually promoted from \`main\`**"
|
||||
echo ""
|
||||
echo "**Includes macOS (Apple Silicon and Intel), Windows x64, and Linux x64 bundles**"
|
||||
echo ""
|
||||
echo "*Built from \`$(git rev-parse --short ${{ needs.version.outputs.tag }})\` on $(date -u +%Y-%m-%d)*"
|
||||
} > release_notes.md
|
||||
|
||||
- name: Build stable-latest.json
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
TAG="${{ needs.version.outputs.tag }}"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
REPO_NAME="${REPO#*/}"
|
||||
PAGES_URL="https://refactoringhq.github.io/${REPO_NAME}/"
|
||||
|
||||
find_required() {
|
||||
local patterns=("$@")
|
||||
for pattern in "${patterns[@]}"; do
|
||||
set -- $pattern
|
||||
if [ -e "$1" ]; then
|
||||
printf '%s\n' "$1"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
echo "::error::Missing required artifact matching one of: ${patterns[*]}" >&2
|
||||
return 1
|
||||
}
|
||||
|
||||
ARM_SIG_FILE=$(find_required "updater-aarch64/*.app.tar.gz.sig")
|
||||
ARM_UPDATER_FILE="${ARM_SIG_FILE%.sig}"
|
||||
ARM_SIG=$(cat "$ARM_SIG_FILE")
|
||||
ARM_TARBALL=$(basename "$ARM_UPDATER_FILE")
|
||||
ARM_DMG=$(basename "$(find_required "dmg-aarch64/*.dmg")")
|
||||
|
||||
INTEL_SIG_FILE=$(find_required "updater-x86_64/*.app.tar.gz.sig")
|
||||
INTEL_UPDATER_FILE="${INTEL_SIG_FILE%.sig}"
|
||||
INTEL_SIG=$(cat "$INTEL_SIG_FILE")
|
||||
INTEL_TARBALL=$(basename "$INTEL_UPDATER_FILE")
|
||||
INTEL_DMG=$(basename "$(find_required "dmg-x86_64/*.dmg")")
|
||||
|
||||
LINUX_SIG_FILE=$(find_required "linux-x86_64-bundles/*/*.AppImage.sig" "linux-x86_64-bundles/*/*.AppImage.tar.gz.sig" "linux-x86_64-bundles/*/*.deb.sig" "linux-x86_64-bundles/*.AppImage.sig" "linux-x86_64-bundles/*.AppImage.tar.gz.sig" "linux-x86_64-bundles/*.deb.sig")
|
||||
LINUX_UPDATER_FILE="${LINUX_SIG_FILE%.sig}"
|
||||
LINUX_SIG=$(cat "$LINUX_SIG_FILE")
|
||||
LINUX_UPDATER=$(basename "$LINUX_UPDATER_FILE")
|
||||
LINUX_DOWNLOAD=$(basename "$(find_required "linux-x86_64-bundles/*/*.AppImage" "linux-x86_64-bundles/*/*.deb" "linux-x86_64-bundles/*/*.AppImage.tar.gz" "linux-x86_64-bundles/*.AppImage" "linux-x86_64-bundles/*.deb" "linux-x86_64-bundles/*.AppImage.tar.gz")")
|
||||
|
||||
WINDOWS_SIG_FILE=$(find_required "windows-x86_64-bundles/*/*-setup.exe.sig" "windows-x86_64-bundles/*/*.msi.sig" "windows-x86_64-bundles/*/*.nsis.zip.sig" "windows-x86_64-bundles/*/*.msi.zip.sig" "windows-x86_64-bundles/*-setup.exe.sig" "windows-x86_64-bundles/*.msi.sig" "windows-x86_64-bundles/*.nsis.zip.sig" "windows-x86_64-bundles/*.msi.zip.sig")
|
||||
WINDOWS_UPDATER_FILE="${WINDOWS_SIG_FILE%.sig}"
|
||||
WINDOWS_SIG=$(cat "$WINDOWS_SIG_FILE")
|
||||
WINDOWS_UPDATER=$(basename "$WINDOWS_UPDATER_FILE")
|
||||
WINDOWS_DOWNLOAD=$(basename "$(find_required "windows-x86_64-bundles/*/*-setup.exe" "windows-x86_64-bundles/*/*.msi" "windows-x86_64-bundles/*/*.nsis.zip" "windows-x86_64-bundles/*/*.msi.zip" "windows-x86_64-bundles/*-setup.exe" "windows-x86_64-bundles/*.msi" "windows-x86_64-bundles/*.nsis.zip" "windows-x86_64-bundles/*.msi.zip")")
|
||||
|
||||
cat > stable-latest.json << EOF
|
||||
{
|
||||
"version": "${VERSION}",
|
||||
"notes": "Stable release. See ${PAGES_URL} for full release notes.",
|
||||
"pub_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"signature": "${ARM_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${ARM_TARBALL}",
|
||||
"dmg_url": "https://github.com/${REPO}/releases/download/${TAG}/${ARM_DMG}"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"signature": "${INTEL_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${INTEL_TARBALL}",
|
||||
"dmg_url": "https://github.com/${REPO}/releases/download/${TAG}/${INTEL_DMG}"
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"signature": "${LINUX_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${LINUX_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${LINUX_DOWNLOAD}"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"signature": "${WINDOWS_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${WINDOWS_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${WINDOWS_DOWNLOAD}"
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
echo "stable-latest.json:"; cat stable-latest.json
|
||||
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.version.outputs.tag }}
|
||||
name: Tolaria ${{ needs.version.outputs.display_version }}
|
||||
body_path: release_notes.md
|
||||
draft: false
|
||||
prerelease: false
|
||||
files: |
|
||||
dmg-aarch64/*.dmg
|
||||
updater-aarch64/*.app.tar.gz
|
||||
updater-aarch64/*.app.tar.gz.sig
|
||||
dmg-x86_64/*.dmg
|
||||
updater-x86_64/*.app.tar.gz
|
||||
updater-x86_64/*.app.tar.gz.sig
|
||||
linux-x86_64-bundles/*.deb
|
||||
linux-x86_64-bundles/*.deb.sig
|
||||
linux-x86_64-bundles/*.rpm
|
||||
linux-x86_64-bundles/*.AppImage
|
||||
linux-x86_64-bundles/*.AppImage.sig
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz.sig
|
||||
linux-x86_64-bundles/*/*.deb
|
||||
linux-x86_64-bundles/*/*.deb.sig
|
||||
linux-x86_64-bundles/*/*.rpm
|
||||
linux-x86_64-bundles/*/*.AppImage
|
||||
linux-x86_64-bundles/*/*.AppImage.sig
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz.sig
|
||||
windows-x86_64-bundles/*.exe
|
||||
windows-x86_64-bundles/*.exe.sig
|
||||
windows-x86_64-bundles/*.msi
|
||||
windows-x86_64-bundles/*.msi.sig
|
||||
windows-x86_64-bundles/*.zip
|
||||
windows-x86_64-bundles/*.zip.sig
|
||||
windows-x86_64-bundles/*/*.exe
|
||||
windows-x86_64-bundles/*/*.exe.sig
|
||||
windows-x86_64-bundles/*/*.msi
|
||||
windows-x86_64-bundles/*/*.msi.sig
|
||||
windows-x86_64-bundles/*/*.zip
|
||||
windows-x86_64-bundles/*/*.zip.sig
|
||||
stable-latest.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 4: Update GitHub Pages
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
pages:
|
||||
name: Update release history page
|
||||
needs: [version, release]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
concurrency:
|
||||
group: github-pages
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Build release history page
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
mkdir -p _site/alpha _site/stable
|
||||
gh api -H "Accept: application/vnd.github.html+json" repos/${{ github.repository }}/releases --paginate > _site/releases.json
|
||||
PAGES_URL="https://refactoringhq.github.io/${GITHUB_REPOSITORY#*/}"
|
||||
|
||||
curl -fsSL "${PAGES_URL}/alpha/latest.json" -o _site/alpha/latest.json || echo '{}' > _site/alpha/latest.json
|
||||
gh release download --repo ${{ github.repository }} "${{ needs.version.outputs.tag }}" --pattern "stable-latest.json" --output _site/stable/latest.json || echo '{}' > _site/stable/latest.json
|
||||
bun scripts/build-release-download-page.ts --latest-json _site/stable/latest.json --releases-json _site/releases.json --output-file _site/stable/download/index.html
|
||||
bun scripts/build-release-history-page.ts --releases-json _site/releases.json --output-file _site/index.html
|
||||
mkdir -p _site/download
|
||||
cp _site/stable/download/index.html _site/download/index.html
|
||||
|
||||
cp _site/alpha/latest.json _site/latest.json
|
||||
cp _site/alpha/latest.json _site/latest-canary.json
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
uses: peaceiris/actions-gh-pages@v4
|
||||
with:
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
publish_dir: ./_site
|
||||
commit_message: "Update release history for ${{ needs.version.outputs.tag }}"
|
||||
710
.github/workflows/release.yml
vendored
710
.github/workflows/release.yml
vendored
@@ -1,111 +1,31 @@
|
||||
name: Release (Alpha)
|
||||
name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
env:
|
||||
# Bump this when Tauri/Rust target artifacts capture stale absolute paths.
|
||||
RUST_TARGET_CACHE_VERSION: v2026-04-14-tolaria
|
||||
|
||||
concurrency:
|
||||
group: release-alpha-${{ github.ref }}
|
||||
group: release-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 1: Compute the alpha version string once
|
||||
# Alpha builds use calendar semver and stay newer than the latest stable tag.
|
||||
# Phase 1: Compute the version string once
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
version:
|
||||
name: Compute alpha version
|
||||
name: Compute version
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
version: ${{ steps.ver.outputs.version }}
|
||||
display_version: ${{ steps.ver.outputs.display_version }}
|
||||
tag: ${{ steps.ver.outputs.tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- id: ver
|
||||
shell: bash
|
||||
run: |
|
||||
python3 <<'PY' > version.env
|
||||
import re
|
||||
import subprocess
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
def lines(command: list[str]) -> list[str]:
|
||||
output = subprocess.check_output(command, text=True).strip()
|
||||
return [line for line in output.splitlines() if line]
|
||||
|
||||
alpha_pattern = re.compile(r"^alpha-v(\d{4}\.\d{1,2}\.\d{1,2})-alpha\.(\d+)$")
|
||||
|
||||
def parse_alpha_tag(tag: str) -> tuple[str, int] | None:
|
||||
match = alpha_pattern.fullmatch(tag)
|
||||
if not match:
|
||||
return None
|
||||
calendar_version, sequence = match.groups()
|
||||
return calendar_version, int(sequence)
|
||||
|
||||
def alpha_version(calendar_version: str, sequence: int) -> str:
|
||||
return f"{calendar_version}-alpha.{sequence}"
|
||||
|
||||
def alpha_tag(calendar_version: str, sequence: int) -> str:
|
||||
return f"alpha-v{calendar_version}-alpha.{sequence:04d}"
|
||||
|
||||
existing_tags = [
|
||||
tag for tag in lines(["git", "tag", "--points-at", "HEAD"])
|
||||
if tag.startswith("alpha-v")
|
||||
]
|
||||
|
||||
if existing_tags:
|
||||
tag = existing_tags[0]
|
||||
parsed = parse_alpha_tag(tag)
|
||||
version = alpha_version(*parsed) if parsed is not None else tag.removeprefix("alpha-v")
|
||||
else:
|
||||
today = datetime.now(timezone.utc).date()
|
||||
stable_date = None
|
||||
stable_pattern = re.compile(r"^stable-v(\d{4})\.(\d{1,2})\.(\d{1,2})$")
|
||||
|
||||
for stable_tag in lines(["git", "tag", "--list", "stable-v*", "--sort=-version:refname"]):
|
||||
match = stable_pattern.fullmatch(stable_tag)
|
||||
if not match:
|
||||
continue
|
||||
|
||||
year, month, day = map(int, match.groups())
|
||||
try:
|
||||
stable_date = datetime(year, month, day, tzinfo=timezone.utc).date()
|
||||
except ValueError:
|
||||
continue
|
||||
break
|
||||
|
||||
alpha_date = today if stable_date is None or today > stable_date else stable_date + timedelta(days=1)
|
||||
calendar_version = f"{alpha_date.year}.{alpha_date.month}.{alpha_date.day}"
|
||||
sequence = len(lines(["git", "tag", "--list", f"alpha-v{calendar_version}-alpha.*"])) + 1
|
||||
|
||||
version = alpha_version(calendar_version, sequence)
|
||||
tag = alpha_tag(calendar_version, sequence)
|
||||
|
||||
display_match = re.fullmatch(r"(\d{4})\.(\d{1,2})\.(\d{1,2})-alpha\.(\d+)", version)
|
||||
display_version = (
|
||||
f"Alpha {int(display_match.group(1))}.{int(display_match.group(2))}.{int(display_match.group(3))}.{int(display_match.group(4))}"
|
||||
if display_match
|
||||
else version
|
||||
)
|
||||
|
||||
print(f"version={version}")
|
||||
print(f"display_version={display_version}")
|
||||
print(f"tag={tag}")
|
||||
PY
|
||||
|
||||
cat version.env >> "$GITHUB_OUTPUT"
|
||||
VERSION=$(grep '^version=' version.env | cut -d= -f2-)
|
||||
DISPLAY_VERSION=$(grep '^display_version=' version.env | cut -d= -f2-)
|
||||
echo "### Alpha version: \`$DISPLAY_VERSION\` (\`$VERSION\`)" >> "$GITHUB_STEP_SUMMARY"
|
||||
VERSION="0.$(date -u +%Y%m%d).${GITHUB_RUN_NUMBER}"
|
||||
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "tag=v$VERSION" >> "$GITHUB_OUTPUT"
|
||||
echo "### Version: \`$VERSION\`" >> "$GITHUB_STEP_SUMMARY"
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 2: Build each architecture in parallel
|
||||
@@ -121,8 +41,6 @@ jobs:
|
||||
include:
|
||||
- arch: aarch64
|
||||
target: aarch64-apple-darwin
|
||||
- arch: x86_64
|
||||
target: x86_64-apple-darwin
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -137,11 +55,6 @@ jobs:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Bun (required for bundle-qmd.sh)
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
@@ -154,129 +67,19 @@ jobs:
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-release-cargo-${{ matrix.target }}-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
key: ${{ runner.os }}-release-cargo-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-${{ matrix.target }}-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
${{ runner.os }}-release-cargo-
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached bundle artifacts
|
||||
run: |
|
||||
rm -rf src-tauri/target/${{ matrix.target }}/release/bundle
|
||||
|
||||
- name: Set version
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
jq --arg v "$VERSION" '.version = $v' src-tauri/tauri.conf.json > tmp.json && mv tmp.json src-tauri/tauri.conf.json
|
||||
sed -i '' "s/^version = \".*\"/version = \"$VERSION\"/" src-tauri/Cargo.toml
|
||||
|
||||
- name: Import Apple Developer certificate into keychain
|
||||
env:
|
||||
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
|
||||
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
|
||||
run: |
|
||||
CERT_PATH="$RUNNER_TEMP/apple_cert.p12"
|
||||
KEYCHAIN_PATH="$RUNNER_TEMP/laputa-signing.keychain-db"
|
||||
KEYCHAIN_PASSWORD="$(uuidgen)"
|
||||
echo "$APPLE_CERTIFICATE" | base64 --decode > "$CERT_PATH"
|
||||
security create-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
security set-keychain-settings -lut 21600 "$KEYCHAIN_PATH"
|
||||
security unlock-keychain -p "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
security import "$CERT_PATH" -P "$APPLE_CERTIFICATE_PASSWORD" -A -t cert -f pkcs12 -k "$KEYCHAIN_PATH"
|
||||
security list-keychain -d user -s "$KEYCHAIN_PATH"
|
||||
security set-key-partition-list -S apple-tool:,apple: -s -k "$KEYCHAIN_PASSWORD" "$KEYCHAIN_PATH"
|
||||
echo "KEYCHAIN_PATH=$KEYCHAIN_PATH" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Validate telemetry env
|
||||
env:
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
python3 <<'PY'
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from urllib.parse import urlparse
|
||||
|
||||
DISALLOWED_PLACEHOLDERS = {
|
||||
"",
|
||||
"-",
|
||||
"_",
|
||||
"false",
|
||||
"true",
|
||||
"null",
|
||||
"undefined",
|
||||
"none",
|
||||
"disabled",
|
||||
}
|
||||
|
||||
def normalize(name: str) -> str:
|
||||
value = os.getenv(name, "").strip()
|
||||
if len(value) >= 2 and value[0] == value[-1] and value[0] in ("'", '"'):
|
||||
value = value[1:-1].strip()
|
||||
return value
|
||||
|
||||
def normalize_http_like(value: str) -> str:
|
||||
if "://" in value:
|
||||
return value
|
||||
return f"https://{value}"
|
||||
|
||||
def normalize_hostname(hostname: str) -> str:
|
||||
normalized = hostname.strip().rstrip('.').lower()
|
||||
if normalized.startswith('[') and normalized.endswith(']'):
|
||||
normalized = normalized[1:-1]
|
||||
return normalized
|
||||
|
||||
def is_ip_address(hostname: str) -> bool:
|
||||
if re.fullmatch(r"(?:\d{1,3}\.){3}\d{1,3}", hostname):
|
||||
return all(0 <= int(part) <= 255 for part in hostname.split('.'))
|
||||
return ':' in hostname and re.fullmatch(r"[\da-f:]+", hostname, re.IGNORECASE) is not None
|
||||
|
||||
def is_allowed_hostname(hostname: str) -> bool:
|
||||
normalized = normalize_hostname(hostname)
|
||||
if not normalized or normalized in DISALLOWED_PLACEHOLDERS:
|
||||
return False
|
||||
if normalized == 'localhost':
|
||||
return True
|
||||
return '.' in normalized or is_ip_address(normalized)
|
||||
|
||||
def is_http_url(value: str) -> bool:
|
||||
parsed = urlparse(normalize_http_like(value))
|
||||
return parsed.scheme in {"http", "https"} and is_allowed_hostname(parsed.hostname or "")
|
||||
|
||||
values = {
|
||||
name: normalize(name)
|
||||
for name in (
|
||||
"VITE_SENTRY_DSN",
|
||||
"SENTRY_DSN",
|
||||
"VITE_POSTHOG_KEY",
|
||||
"VITE_POSTHOG_HOST",
|
||||
)
|
||||
}
|
||||
errors = []
|
||||
|
||||
for name in ("VITE_SENTRY_DSN", "SENTRY_DSN", "VITE_POSTHOG_HOST"):
|
||||
value = values[name]
|
||||
if value.lower() in DISALLOWED_PLACEHOLDERS:
|
||||
errors.append(f"{name} must be set to a real value, not a placeholder")
|
||||
elif not is_http_url(value):
|
||||
errors.append(f"{name} must be a valid http(s) URL with a non-placeholder host")
|
||||
|
||||
if values["VITE_POSTHOG_KEY"].lower() in DISALLOWED_PLACEHOLDERS:
|
||||
errors.append("VITE_POSTHOG_KEY must be set to a real project API key, not a placeholder")
|
||||
|
||||
if errors:
|
||||
print("Telemetry env validation failed:", file=sys.stderr)
|
||||
for error in errors:
|
||||
print(f"- {error}", file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
|
||||
print("Telemetry env validation passed.")
|
||||
PY
|
||||
|
||||
- name: Build Tauri app (with signing + notarization)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
@@ -287,15 +90,15 @@ jobs:
|
||||
APPLE_ID: ${{ secrets.APPLE_ID }}
|
||||
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
|
||||
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
# Alpha releases only need the notarized app bundle and updater tarball.
|
||||
# Skipping DMG packaging avoids fragile bundle_dmg.sh failures on macOS runners.
|
||||
pnpm tauri build --target ${{ matrix.target }} --bundles app
|
||||
pnpm tauri build --target ${{ matrix.target }}
|
||||
|
||||
- name: Upload .dmg
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: dmg-${{ matrix.arch }}
|
||||
path: src-tauri/target/${{ matrix.target }}/release/bundle/dmg/*.dmg
|
||||
retention-days: 1
|
||||
|
||||
- name: Upload updater artifacts (.tar.gz + .sig)
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -306,258 +109,13 @@ jobs:
|
||||
src-tauri/target/${{ matrix.target }}/release/bundle/macos/*.app.tar.gz.sig
|
||||
retention-days: 1
|
||||
|
||||
build-linux:
|
||||
name: Build (linux-x86_64)
|
||||
needs: version
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Tauri Linux system dependencies
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y \
|
||||
libwebkit2gtk-4.1-dev \
|
||||
libsoup-3.0-dev \
|
||||
libxdo-dev \
|
||||
libssl-dev \
|
||||
libayatana-appindicator3-dev \
|
||||
librsvg2-dev \
|
||||
curl \
|
||||
wget \
|
||||
patchelf \
|
||||
build-essential \
|
||||
file \
|
||||
rpm
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-unknown-linux-gnu
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
src-tauri/target
|
||||
key: ${{ runner.os }}-release-cargo-x86_64-unknown-linux-gnu-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-unknown-linux-gnu-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached bundle artifacts
|
||||
run: |
|
||||
rm -rf src-tauri/target/x86_64-unknown-linux-gnu/release/bundle
|
||||
|
||||
- name: Set version
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
jq --arg v "$VERSION" '.version = $v' src-tauri/tauri.conf.json > tmp.json && mv tmp.json src-tauri/tauri.conf.json
|
||||
sed -i "s/^version = \".*\"/version = \"$VERSION\"/" src-tauri/Cargo.toml
|
||||
|
||||
- name: Build Tauri app (Linux bundles)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-unknown-linux-gnu --bundles deb,rpm,appimage
|
||||
|
||||
- name: Validate Linux bundles
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
installers=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no AppImage, deb or rpm bundle."
|
||||
exit 1
|
||||
fi
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
echo "::error::Linux build produced no updater signature (.sig) artifact."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Linux bundles
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: linux-x86_64-bundles
|
||||
path: |
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/deb/*.deb.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/rpm/*.rpm
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.sig
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz
|
||||
src-tauri/target/x86_64-unknown-linux-gnu/release/bundle/appimage/*.AppImage.tar.gz.sig
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
build-windows:
|
||||
name: Build (windows-x86_64)
|
||||
needs: version
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 10
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '22'
|
||||
cache: 'pnpm'
|
||||
|
||||
- name: Setup Rust
|
||||
uses: dtolnay/rust-toolchain@stable
|
||||
with:
|
||||
targets: x86_64-pc-windows-msvc
|
||||
|
||||
- name: Cache Rust dependencies
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: |
|
||||
~\.cargo\registry
|
||||
~\.cargo\git
|
||||
src-tauri\target
|
||||
key: ${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-${{ hashFiles('src-tauri/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
${{ runner.os }}-release-cargo-x86_64-pc-windows-msvc-${{ env.RUST_TARGET_CACHE_VERSION }}-
|
||||
|
||||
- name: Cache Tauri Windows tools
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: ~\AppData\Local\tauri
|
||||
key: ${{ runner.os }}-tauri-tools-nsis-3.11-nsis-tauri-utils-0.5.3
|
||||
|
||||
- name: Prefetch Tauri NSIS toolchain
|
||||
shell: pwsh
|
||||
run: ./.github/scripts/prefetch-tauri-nsis.ps1
|
||||
|
||||
- name: Install frontend dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Clear cached Windows bundle artifacts
|
||||
shell: pwsh
|
||||
run: |
|
||||
Remove-Item -Recurse -Force -ErrorAction SilentlyContinue "src-tauri/target/x86_64-pc-windows-msvc/release/bundle"
|
||||
|
||||
- name: Set version
|
||||
shell: pwsh
|
||||
run: |
|
||||
$version = "${{ needs.version.outputs.version }}"
|
||||
$tauri = Get-Content "src-tauri/tauri.conf.json" | ConvertFrom-Json
|
||||
$tauri.version = $version
|
||||
$tauri | ConvertTo-Json -Depth 100 | Set-Content "src-tauri/tauri.conf.json"
|
||||
(Get-Content "src-tauri/Cargo.toml") -replace '^version = ".*"$', "version = `"$version`"" | Set-Content "src-tauri/Cargo.toml"
|
||||
|
||||
- name: Validate Windows release env
|
||||
shell: bash
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
run: |
|
||||
for name in TAURI_SIGNING_PRIVATE_KEY TAURI_KEY_PASSWORD; do
|
||||
if [ -z "${!name}" ]; then
|
||||
echo "::error::$name is required to build signed Windows updater artifacts."
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: Build Tauri app (Windows bundles)
|
||||
env:
|
||||
TAURI_SIGNING_PRIVATE_KEY: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY }}
|
||||
TAURI_SIGNING_PRIVATE_KEY_PASSWORD: ${{ secrets.TAURI_KEY_PASSWORD }}
|
||||
VITE_SENTRY_DSN: ${{ secrets.VITE_SENTRY_DSN }}
|
||||
VITE_SENTRY_RELEASE: ${{ needs.version.outputs.version }}
|
||||
SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
|
||||
VITE_POSTHOG_KEY: ${{ secrets.VITE_POSTHOG_KEY }}
|
||||
VITE_POSTHOG_HOST: ${{ secrets.VITE_POSTHOG_HOST }}
|
||||
run: |
|
||||
pnpm tauri build --target x86_64-pc-windows-msvc --bundles nsis
|
||||
|
||||
- name: Validate Windows bundles
|
||||
shell: bash
|
||||
run: |
|
||||
shopt -s nullglob
|
||||
installers=(
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*-setup.exe
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi
|
||||
)
|
||||
signatures=(
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*-setup.exe.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.nsis.zip.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.zip.sig
|
||||
)
|
||||
if [ ${#installers[@]} -eq 0 ]; then
|
||||
echo "::error::Windows build produced no installable NSIS or MSI bundle."
|
||||
exit 1
|
||||
fi
|
||||
for installer in "${installers[@]}"; do
|
||||
if [[ "$(basename "$installer")" != *"${{ needs.version.outputs.version }}"* ]]; then
|
||||
echo "::error::Windows build produced an installer for a different version: $(basename "$installer")"
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
if [ ${#signatures[@]} -eq 0 ]; then
|
||||
echo "::error::Windows build produced no updater signature (.sig) artifact."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Upload Windows bundles
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: windows-x86_64-bundles
|
||||
path: |
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.exe
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.exe.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.zip
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/nsis/*.zip.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.msi.sig
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.zip
|
||||
src-tauri/target/x86_64-pc-windows-msvc/release/bundle/msi/*.zip.sig
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 3: Publish GitHub Release
|
||||
# No lipo/re-signing — use the per-arch artifacts directly
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
release:
|
||||
name: GitHub Release (alpha)
|
||||
needs: [version, build, build-linux, build-windows]
|
||||
name: GitHub Release
|
||||
needs: [version, build]
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -569,190 +127,62 @@ jobs:
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
|
||||
- name: Normalize macOS updater artifact names
|
||||
run: |
|
||||
normalize_updater() {
|
||||
local arch="$1"
|
||||
local normalized_updater="$2"
|
||||
local artifact_dir="updater-${arch}"
|
||||
local updater_file
|
||||
updater_file=$(find "$artifact_dir" -maxdepth 1 -name "*.app.tar.gz" -print -quit)
|
||||
if [ -z "$updater_file" ]; then
|
||||
echo "::error::Missing macOS updater artifact in ${artifact_dir}" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local sig_file="${updater_file}.sig"
|
||||
if [ ! -f "$sig_file" ]; then
|
||||
echo "::error::Missing macOS updater signature for ${updater_file}" >&2
|
||||
return 1
|
||||
fi
|
||||
|
||||
local normalized_sig="${normalized_updater}.sig"
|
||||
if [ "$updater_file" != "$normalized_updater" ]; then
|
||||
mv "$updater_file" "$normalized_updater"
|
||||
fi
|
||||
if [ "$sig_file" != "$normalized_sig" ]; then
|
||||
mv "$sig_file" "$normalized_sig"
|
||||
fi
|
||||
}
|
||||
|
||||
normalize_updater aarch64 "updater-aarch64/Tolaria_${{ needs.version.outputs.version }}_macOS_Silicon.app.tar.gz"
|
||||
normalize_updater x86_64 "updater-x86_64/Tolaria_${{ needs.version.outputs.version }}_macOS_Intel.app.tar.gz"
|
||||
|
||||
- name: Generate release notes
|
||||
run: |
|
||||
PREV_TAG=$(python3 <<'PY'
|
||||
import re
|
||||
import subprocess
|
||||
|
||||
current_tag = '${{ needs.version.outputs.tag }}'
|
||||
pattern = re.compile(r'^alpha-v(\d{4})\.(\d{1,2})\.(\d{1,2})-alpha\.(\d+)$')
|
||||
|
||||
output = subprocess.check_output(['git', 'tag', '--list', 'alpha-v*'], text=True).strip()
|
||||
tags = [line for line in output.splitlines() if line and line != current_tag]
|
||||
|
||||
parsed_tags = []
|
||||
for tag in tags:
|
||||
match = pattern.fullmatch(tag)
|
||||
if not match:
|
||||
continue
|
||||
year, month, day, sequence = map(int, match.groups())
|
||||
parsed_tags.append(((year, month, day, sequence), tag))
|
||||
|
||||
print(max(parsed_tags)[1] if parsed_tags else '')
|
||||
PY
|
||||
)
|
||||
PREV_TAG=$(git tag --sort=-version:refname | head -n 1 || echo "")
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
NOTES=$(git log --oneline --no-merges -20)
|
||||
else
|
||||
NOTES=$(git log --oneline --no-merges "${PREV_TAG}..HEAD")
|
||||
fi
|
||||
{
|
||||
echo "## What's Changed (Alpha)"
|
||||
echo "## What's Changed"
|
||||
echo ""
|
||||
echo "$NOTES" | while IFS= read -r line; do echo "- $line"; done
|
||||
echo ""
|
||||
echo "---"
|
||||
echo "**Alpha build — updated on every push to \`main\`**"
|
||||
echo ""
|
||||
echo "**Includes macOS (Apple Silicon and Intel), Linux x64, and Windows x64 bundles**"
|
||||
echo "**Requires Apple Silicon (M1/M2/M3)**"
|
||||
echo ""
|
||||
echo "*Built from \`$(git rev-parse --short HEAD)\` on $(date -u +%Y-%m-%d)*"
|
||||
} > release_notes.md
|
||||
|
||||
- name: Build alpha-latest.json
|
||||
- name: Build latest.json
|
||||
run: |
|
||||
VERSION="${{ needs.version.outputs.version }}"
|
||||
TAG="${{ needs.version.outputs.tag }}"
|
||||
REPO="${GITHUB_REPOSITORY}"
|
||||
REPO_NAME="${REPO#*/}"
|
||||
PAGES_URL="https://refactoringhq.github.io/${REPO_NAME}/"
|
||||
REPO="refactoringhq/laputa-app"
|
||||
|
||||
find_required() {
|
||||
for pattern in "$@"; do
|
||||
set -- $pattern
|
||||
if [ -e "$1" ]; then
|
||||
printf '%s\n' "$1"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
ARM_SIG=$(cat updater-aarch64/*.app.tar.gz.sig)
|
||||
ARM_DMG=$(ls dmg-aarch64/*.dmg | xargs basename)
|
||||
|
||||
ARM_SIG_FILE=$(find_required "updater-aarch64/*.app.tar.gz.sig")
|
||||
ARM_UPDATER_FILE="${ARM_SIG_FILE%.sig}"
|
||||
ARM_SIG=$(cat "$ARM_SIG_FILE")
|
||||
ARM_UPDATER=$(basename "$ARM_UPDATER_FILE")
|
||||
|
||||
INTEL_SIG_FILE=$(find_required "updater-x86_64/*.app.tar.gz.sig")
|
||||
INTEL_UPDATER_FILE="${INTEL_SIG_FILE%.sig}"
|
||||
INTEL_SIG=$(cat "$INTEL_SIG_FILE")
|
||||
INTEL_UPDATER=$(basename "$INTEL_UPDATER_FILE")
|
||||
|
||||
LINUX_SIG_FILE=$(find_required "linux-x86_64-bundles/*/*.AppImage.sig" "linux-x86_64-bundles/*/*.AppImage.tar.gz.sig" "linux-x86_64-bundles/*/*.deb.sig" "linux-x86_64-bundles/*.AppImage.sig" "linux-x86_64-bundles/*.AppImage.tar.gz.sig" "linux-x86_64-bundles/*.deb.sig")
|
||||
LINUX_UPDATER_FILE="${LINUX_SIG_FILE%.sig}"
|
||||
LINUX_SIG=$(cat "$LINUX_SIG_FILE")
|
||||
LINUX_UPDATER=$(basename "$LINUX_UPDATER_FILE")
|
||||
LINUX_DOWNLOAD=$(basename "$(find_required "linux-x86_64-bundles/*/*.AppImage" "linux-x86_64-bundles/*/*.deb" "linux-x86_64-bundles/*/*.AppImage.tar.gz" "linux-x86_64-bundles/*.AppImage" "linux-x86_64-bundles/*.deb" "linux-x86_64-bundles/*.AppImage.tar.gz")")
|
||||
|
||||
WINDOWS_SIG_FILE=$(find_required "windows-x86_64-bundles/*/*-setup.exe.sig" "windows-x86_64-bundles/*/*.msi.sig" "windows-x86_64-bundles/*/*.nsis.zip.sig" "windows-x86_64-bundles/*/*.msi.zip.sig" "windows-x86_64-bundles/*-setup.exe.sig" "windows-x86_64-bundles/*.msi.sig" "windows-x86_64-bundles/*.nsis.zip.sig" "windows-x86_64-bundles/*.msi.zip.sig")
|
||||
WINDOWS_UPDATER_FILE="${WINDOWS_SIG_FILE%.sig}"
|
||||
WINDOWS_SIG=$(cat "$WINDOWS_SIG_FILE")
|
||||
WINDOWS_UPDATER=$(basename "$WINDOWS_UPDATER_FILE")
|
||||
WINDOWS_DOWNLOAD=$(basename "$(find_required "windows-x86_64-bundles/*/*-setup.exe" "windows-x86_64-bundles/*/*.msi" "windows-x86_64-bundles/*/*.nsis.zip" "windows-x86_64-bundles/*/*.msi.zip" "windows-x86_64-bundles/*-setup.exe" "windows-x86_64-bundles/*.msi" "windows-x86_64-bundles/*.nsis.zip" "windows-x86_64-bundles/*.msi.zip")")
|
||||
|
||||
cat > alpha-latest.json << EOF
|
||||
cat > latest.json << EOF
|
||||
{
|
||||
"version": "${VERSION}",
|
||||
"notes": "Alpha build. See ${PAGES_URL} for full release notes.",
|
||||
"notes": "See https://refactoringhq.github.io/laputa-app/ for full release notes.",
|
||||
"pub_date": "$(date -u +%Y-%m-%dT%H:%M:%SZ)",
|
||||
"platforms": {
|
||||
"darwin-aarch64": {
|
||||
"signature": "${ARM_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${ARM_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${ARM_UPDATER}"
|
||||
},
|
||||
"darwin-x86_64": {
|
||||
"signature": "${INTEL_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${INTEL_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${INTEL_UPDATER}"
|
||||
},
|
||||
"linux-x86_64": {
|
||||
"signature": "${LINUX_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${LINUX_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${LINUX_DOWNLOAD}"
|
||||
},
|
||||
"windows-x86_64": {
|
||||
"signature": "${WINDOWS_SIG}",
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${WINDOWS_UPDATER}",
|
||||
"download_url": "https://github.com/${REPO}/releases/download/${TAG}/${WINDOWS_DOWNLOAD}"
|
||||
"url": "https://github.com/${REPO}/releases/download/${TAG}/${ARM_DMG}"
|
||||
}
|
||||
}
|
||||
}
|
||||
EOF
|
||||
echo "alpha-latest.json:"; cat alpha-latest.json
|
||||
echo "latest.json:"; cat latest.json
|
||||
|
||||
- name: Publish GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ needs.version.outputs.tag }}
|
||||
name: Tolaria ${{ needs.version.outputs.display_version }}
|
||||
name: Laputa ${{ needs.version.outputs.version }}
|
||||
body_path: release_notes.md
|
||||
draft: false
|
||||
prerelease: true
|
||||
prerelease: false
|
||||
files: |
|
||||
dmg-aarch64/*.dmg
|
||||
updater-aarch64/*.app.tar.gz
|
||||
updater-aarch64/*.app.tar.gz.sig
|
||||
updater-x86_64/*.app.tar.gz
|
||||
updater-x86_64/*.app.tar.gz.sig
|
||||
linux-x86_64-bundles/*.deb
|
||||
linux-x86_64-bundles/*.deb.sig
|
||||
linux-x86_64-bundles/*.rpm
|
||||
linux-x86_64-bundles/*.AppImage
|
||||
linux-x86_64-bundles/*.AppImage.sig
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*.AppImage.tar.gz.sig
|
||||
linux-x86_64-bundles/*/*.deb
|
||||
linux-x86_64-bundles/*/*.deb.sig
|
||||
linux-x86_64-bundles/*/*.rpm
|
||||
linux-x86_64-bundles/*/*.AppImage
|
||||
linux-x86_64-bundles/*/*.AppImage.sig
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz
|
||||
linux-x86_64-bundles/*/*.AppImage.tar.gz.sig
|
||||
windows-x86_64-bundles/*.exe
|
||||
windows-x86_64-bundles/*.exe.sig
|
||||
windows-x86_64-bundles/*.msi
|
||||
windows-x86_64-bundles/*.msi.sig
|
||||
windows-x86_64-bundles/*.zip
|
||||
windows-x86_64-bundles/*.zip.sig
|
||||
windows-x86_64-bundles/*/*.exe
|
||||
windows-x86_64-bundles/*/*.exe.sig
|
||||
windows-x86_64-bundles/*/*.msi
|
||||
windows-x86_64-bundles/*/*.msi.sig
|
||||
windows-x86_64-bundles/*/*.zip
|
||||
windows-x86_64-bundles/*/*.zip.sig
|
||||
alpha-latest.json
|
||||
latest.json
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Phase 4: Update GitHub Pages with release history
|
||||
@@ -763,34 +193,62 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: write
|
||||
concurrency:
|
||||
group: github-pages
|
||||
cancel-in-progress: false
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: latest
|
||||
|
||||
- name: Build release history page
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
mkdir -p _site/alpha _site/stable
|
||||
gh api -H "Accept: application/vnd.github.html+json" repos/${{ github.repository }}/releases --paginate > _site/releases.json
|
||||
PAGES_URL="https://refactoringhq.github.io/${GITHUB_REPOSITORY#*/}"
|
||||
|
||||
gh release download --repo ${{ github.repository }} "${{ needs.version.outputs.tag }}" --pattern "alpha-latest.json" --output _site/alpha/latest.json || echo '{}' > _site/alpha/latest.json
|
||||
curl -fsSL "${PAGES_URL}/stable/latest.json" -o _site/stable/latest.json || echo '{}' > _site/stable/latest.json
|
||||
bun scripts/build-release-download-page.ts --latest-json _site/stable/latest.json --releases-json _site/releases.json --output-file _site/stable/download/index.html
|
||||
bun scripts/build-release-history-page.ts --releases-json _site/releases.json --output-file _site/index.html
|
||||
mkdir -p _site/download
|
||||
cp _site/stable/download/index.html _site/download/index.html
|
||||
|
||||
cp _site/alpha/latest.json _site/latest.json
|
||||
cp _site/alpha/latest.json _site/latest-canary.json
|
||||
mkdir -p _site
|
||||
gh api repos/${{ github.repository }}/releases --paginate > _site/releases.json
|
||||
# Copy latest.json to GitHub Pages for auto-updater endpoint
|
||||
gh release download --repo ${{ github.repository }} --pattern "latest.json" --output _site/latest.json || true
|
||||
cat > _site/index.html << 'HTMLEOF'
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Laputa — Release History</title>
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: #F7F6F3; color: #37352F; line-height: 1.6; padding: 2rem; max-width: 720px; margin: 0 auto; }
|
||||
h1 { font-size: 1.75rem; font-weight: 600; margin-bottom: 0.5rem; }
|
||||
.subtitle { color: #787774; margin-bottom: 2rem; }
|
||||
.release { background: #fff; border: 1px solid #E9E9E7; border-radius: 8px; padding: 1.25rem 1.5rem; margin-bottom: 1rem; }
|
||||
.release h2 { font-size: 1.125rem; font-weight: 600; margin-bottom: 0.25rem; }
|
||||
.release .meta { font-size: 0.8125rem; color: #787774; margin-bottom: 0.75rem; }
|
||||
.release .body { font-size: 0.875rem; white-space: pre-wrap; }
|
||||
.release .downloads { margin-top: 0.75rem; display: flex; gap: 0.5rem; flex-wrap: wrap; }
|
||||
.release .downloads a { display: inline-block; padding: 0.375rem 0.75rem; background: #155DFF; color: #fff; border-radius: 6px; text-decoration: none; font-size: 0.8125rem; font-weight: 500; }
|
||||
.release .downloads a:hover { background: #1248CC; }
|
||||
.empty { color: #787774; text-align: center; padding: 3rem; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Laputa Release History</h1>
|
||||
<p class="subtitle">Auto-updated on every release</p>
|
||||
<div id="releases"></div>
|
||||
<script>
|
||||
fetch('releases.json').then(r=>r.json()).then(releases=>{
|
||||
const el=document.getElementById('releases');
|
||||
if(!releases.length){el.innerHTML='<p class="empty">No releases yet.</p>';return;}
|
||||
releases.forEach(r=>{
|
||||
const date=new Date(r.published_at).toLocaleDateString('en-US',{year:'numeric',month:'long',day:'numeric'});
|
||||
const dmgs=(r.assets||[]).filter(a=>a.name.endsWith('.dmg'));
|
||||
const links=dmgs.map(a=>'<a href="'+a.browser_download_url+'">'+a.name+'</a>').join('');
|
||||
const body=(r.body||'').replace(/</g,'<').replace(/>/g,'>');
|
||||
const div=document.createElement('div');
|
||||
div.className='release';
|
||||
div.innerHTML='<h2>'+(r.name||r.tag_name)+'</h2><div class="meta">'+date+' · '+r.tag_name+'</div><div class="body">'+body+'</div>'+(links?'<div class="downloads">'+links+'</div>':'');
|
||||
el.appendChild(div);
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
HTMLEOF
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
uses: peaceiris/actions-gh-pages@v4
|
||||
|
||||
34
.gitignore
vendored
34
.gitignore
vendored
@@ -30,9 +30,11 @@ dist-ssr
|
||||
# Coverage reports
|
||||
/coverage/
|
||||
|
||||
# Laputa vault cache
|
||||
.laputa-cache.json
|
||||
|
||||
# Demo vault and helper scripts
|
||||
demo-vault/
|
||||
generated-fixtures/
|
||||
select_demo_notes*.py
|
||||
final_selection.py
|
||||
|
||||
@@ -43,33 +45,3 @@ src-tauri/target
|
||||
|
||||
# Generated mcp-server bundle (built by scripts/bundle-mcp-server.mjs)
|
||||
src-tauri/resources/
|
||||
|
||||
# Python cache
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
|
||||
# Dev screenshots
|
||||
screenshots/
|
||||
|
||||
# Stale planning docs (keep locally if needed, not in repo)
|
||||
REDESIGN-PLAN.md
|
||||
SF-SYMBOLS-MIGRATION.md
|
||||
CODE-HEALTH-REPORT.md
|
||||
|
||||
# Local home dir artifact from worktree ops
|
||||
(HOME)/
|
||||
|
||||
# Runtime / process files
|
||||
.claude-pid
|
||||
|
||||
# Generated vault index files (qmd/search artifacts)
|
||||
.laputa-index.json
|
||||
|
||||
# Tauri signing keys (never commit private keys)
|
||||
*.key
|
||||
*.key.pub
|
||||
|
||||
# Local environment variables (never commit)
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
@@ -1,48 +1,6 @@
|
||||
#!/bin/sh
|
||||
# Pre-commit: fast local gate before commit. Full suite runs in pre-push/CI.
|
||||
# Pre-commit: same checks as CI. Fix here, not in CI.
|
||||
set -e
|
||||
|
||||
ensure_node_tooling() {
|
||||
if command -v node >/dev/null 2>&1 && command -v pnpm >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
|
||||
if [ -s "$NVM_DIR/nvm.sh" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$NVM_DIR/nvm.sh" --no-use
|
||||
nvm use --silent node >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
if ! command -v node >/dev/null 2>&1 || ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "❌ node and pnpm must be available before committing"
|
||||
echo " Install them or make sure your nvm setup is available to git hooks."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_main_branch() {
|
||||
if ! git symbolic-ref -q HEAD >/dev/null 2>&1; then
|
||||
echo "❌ Commits must happen on main. Detached HEAD is not allowed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||
case "$CURRENT_BRANCH" in
|
||||
main|codex/mobile)
|
||||
return 0
|
||||
;;
|
||||
*)
|
||||
echo "❌ Commits must happen on main. Current branch: $CURRENT_BRANCH"
|
||||
echo " Merge or cherry-pick your work onto main, then commit there."
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
}
|
||||
|
||||
require_main_branch
|
||||
ensure_node_tooling
|
||||
|
||||
echo "🔍 Pre-commit checks..."
|
||||
|
||||
# Lint + types (only if TS files staged)
|
||||
@@ -55,61 +13,6 @@ fi
|
||||
|
||||
# Unit tests
|
||||
echo " → tests..."
|
||||
pnpm test -- --silent
|
||||
pnpm test --run --silent
|
||||
|
||||
echo "✅ Pre-commit passed"
|
||||
|
||||
# ── CodeScene Code Health gate ────────────────────────────────────────────
|
||||
# Uses the remote project score as an early warning signal.
|
||||
# Thresholds are a ratchet — only go up.
|
||||
# When the remote baseline is already below threshold, allow recovery commits to
|
||||
# land; otherwise the stale remote score would block the refactors needed to
|
||||
# restore the gate.
|
||||
# Never use eslint-disable, #[allow(...)], or `as any`.
|
||||
echo "🏥 CodeScene code health check..."
|
||||
THRESHOLDS_FILE=".codescene-thresholds"
|
||||
if [ -z "$CODESCENE_PAT" ] || [ -z "$CODESCENE_PROJECT_ID" ]; then
|
||||
echo " ⚠️ CODESCENE_PAT or CODESCENE_PROJECT_ID not set — skipping (CI will enforce)"
|
||||
elif [ ! -f "$THRESHOLDS_FILE" ]; then
|
||||
echo " ⚠️ $THRESHOLDS_FILE not found — skipping (CI will enforce)"
|
||||
else
|
||||
# Read ratchet thresholds
|
||||
HOTSPOT_THRESHOLD=$(grep '^HOTSPOT_THRESHOLD=' "$THRESHOLDS_FILE" | cut -d= -f2)
|
||||
AVERAGE_THRESHOLD=$(grep '^AVERAGE_THRESHOLD=' "$THRESHOLDS_FILE" | cut -d= -f2)
|
||||
if [ -z "$HOTSPOT_THRESHOLD" ] || [ -z "$AVERAGE_THRESHOLD" ]; then
|
||||
echo " ⚠️ Could not parse thresholds from $THRESHOLDS_FILE — skipping"
|
||||
else
|
||||
API_RESPONSE=$(curl -sf \
|
||||
-H "Authorization: Bearer $CODESCENE_PAT" \
|
||||
-H "Accept: application/json" \
|
||||
"https://api.codescene.io/v2/projects/$CODESCENE_PROJECT_ID" 2>/dev/null || echo "{}")
|
||||
HOTSPOT_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['hotspot_code_health']['now'])" 2>/dev/null || echo "")
|
||||
AVERAGE_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['code_health']['now'])" 2>/dev/null || echo "")
|
||||
if [ -z "$HOTSPOT_SCORE" ] || [ -z "$AVERAGE_SCORE" ]; then
|
||||
echo " ⚠️ Could not fetch CodeScene scores — skipping (CI will enforce)"
|
||||
else
|
||||
echo " Hotspot Code Health: $HOTSPOT_SCORE (threshold: $HOTSPOT_THRESHOLD)"
|
||||
echo " Average Code Health: $AVERAGE_SCORE (threshold: $AVERAGE_THRESHOLD)"
|
||||
python3 -c "
|
||||
import sys
|
||||
hotspot = float('$HOTSPOT_SCORE')
|
||||
average = float('$AVERAGE_SCORE')
|
||||
h_thresh = float('$HOTSPOT_THRESHOLD')
|
||||
a_thresh = float('$AVERAGE_THRESHOLD')
|
||||
failed = False
|
||||
if hotspot < h_thresh:
|
||||
print(f'WARN: Hotspot Code Health {hotspot:.2f} < {h_thresh} — remote baseline is currently red')
|
||||
failed = True
|
||||
else:
|
||||
print(f'OK: Hotspot {hotspot:.2f} >= {h_thresh}')
|
||||
if average < a_thresh:
|
||||
print(f'WARN: Average Code Health {average:.2f} < {a_thresh} — remote baseline is currently red')
|
||||
failed = True
|
||||
else:
|
||||
print(f'OK: Average {average:.2f} >= {a_thresh}')
|
||||
if failed:
|
||||
print(' ⚠️ Recovery mode: allowing this commit so refactors can land and restore the gate on a later push.')
|
||||
" || exit 1
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
173
.husky/pre-push
173
.husky/pre-push
@@ -28,64 +28,6 @@
|
||||
# ─────────────────────────────────────────────────────────────────────────
|
||||
set -e
|
||||
|
||||
ensure_node_tooling() {
|
||||
if command -v node >/dev/null 2>&1 && command -v pnpm >/dev/null 2>&1; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
NVM_DIR="${NVM_DIR:-$HOME/.nvm}"
|
||||
if [ -s "$NVM_DIR/nvm.sh" ]; then
|
||||
# shellcheck disable=SC1090
|
||||
. "$NVM_DIR/nvm.sh" --no-use
|
||||
nvm use --silent node >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
if ! command -v node >/dev/null 2>&1 || ! command -v pnpm >/dev/null 2>&1; then
|
||||
echo "❌ node and pnpm must be available before pushing"
|
||||
echo " Install them or make sure your nvm setup is available to git hooks."
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
require_main_push() {
|
||||
if ! git symbolic-ref -q HEAD >/dev/null 2>&1; then
|
||||
echo "❌ Pushes must happen from main. Detached HEAD is not allowed."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||
if [ "$CURRENT_BRANCH" != "main" ]; then
|
||||
echo "❌ Pushes must happen from main. Current branch: $CURRENT_BRANCH"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
while IFS=' ' read -r LOCAL_REF LOCAL_SHA REMOTE_REF REMOTE_SHA; do
|
||||
[ -z "$LOCAL_REF" ] && continue
|
||||
|
||||
case "$LOCAL_REF:$REMOTE_REF" in
|
||||
refs/heads/main:refs/heads/main)
|
||||
;;
|
||||
refs/tags/*:refs/tags/*)
|
||||
;;
|
||||
*)
|
||||
echo "❌ Pushes must be main -> main only."
|
||||
echo " Attempted: ${LOCAL_REF:-<none>} -> ${REMOTE_REF:-<none>}"
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done <<EOF
|
||||
$PUSH_INPUT
|
||||
EOF
|
||||
}
|
||||
|
||||
if [ -t 0 ]; then
|
||||
PUSH_INPUT=""
|
||||
else
|
||||
PUSH_INPUT=$(cat)
|
||||
fi
|
||||
require_main_push
|
||||
ensure_node_tooling
|
||||
|
||||
START_TIME=$(date +%s)
|
||||
|
||||
echo ""
|
||||
@@ -105,26 +47,26 @@ fi
|
||||
|
||||
# ── 0. TypeScript + Vite build ──────────────────────────────────────────
|
||||
echo ""
|
||||
echo "📦 [0/5] TypeScript + Vite build..."
|
||||
echo "📦 [0/4] TypeScript + Vite build..."
|
||||
pnpm exec tsc --noEmit
|
||||
pnpm build
|
||||
echo " ✅ Build OK"
|
||||
|
||||
# ── 1. Frontend coverage (≥70%) — includes all unit tests ───────────────
|
||||
echo ""
|
||||
echo "📊 [1/5] Frontend tests + coverage (≥70%)..."
|
||||
echo "📊 [1/4] Frontend tests + coverage (≥70%)..."
|
||||
pnpm test:coverage --silent
|
||||
echo " ✅ Frontend coverage OK"
|
||||
|
||||
# ── 2. Rust lint (clippy + fmt) — fast, run before coverage ─────────────
|
||||
echo ""
|
||||
if [ "$RUST_CHANGED" = true ]; then
|
||||
echo "🔧 [2/5] Clippy + rustfmt..."
|
||||
echo "🔧 [2/4] Clippy + rustfmt..."
|
||||
cargo clippy --manifest-path=src-tauri/Cargo.toml -- -D warnings
|
||||
cargo fmt --manifest-path=src-tauri/Cargo.toml -- --check
|
||||
echo " ✅ Rust lint OK"
|
||||
else
|
||||
echo "⏭️ [2/5] Rust lint — skipped (no src-tauri/ changes)"
|
||||
echo "⏭️ [2/4] Rust lint — skipped (no src-tauri/ changes)"
|
||||
fi
|
||||
|
||||
# ── 3. Rust coverage (≥85% lines) ──────────────────────────────────────
|
||||
@@ -133,9 +75,9 @@ if [ "$RUST_CHANGED" = true ]; then
|
||||
LLVM_COV_FLAGS="--no-clean"
|
||||
if [ "${LAPUTA_FULL_COVERAGE:-0}" = "1" ]; then
|
||||
LLVM_COV_FLAGS=""
|
||||
echo "🦀 [3/5] Rust coverage — FULL (LAPUTA_FULL_COVERAGE=1)..."
|
||||
echo "🦀 [3/4] Rust coverage — FULL (LAPUTA_FULL_COVERAGE=1)..."
|
||||
else
|
||||
echo "🦀 [3/5] Rust coverage (≥85%, incremental)..."
|
||||
echo "🦀 [3/4] Rust coverage (≥85%, incremental)..."
|
||||
fi
|
||||
# Unset GIT_DIR so git tests create isolated repos without inheriting hook context
|
||||
unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE
|
||||
@@ -143,104 +85,35 @@ if [ "$RUST_CHANGED" = true ]; then
|
||||
cargo llvm-cov \
|
||||
--manifest-path src-tauri/Cargo.toml \
|
||||
$LLVM_COV_FLAGS \
|
||||
--ignore-filename-regex "lib\.rs|main\.rs|menu\.rs" \
|
||||
--ignore-filename-regex "search\.rs|lib\.rs" \
|
||||
--fail-under-lines 85 \
|
||||
-- --test-threads=1
|
||||
echo " ✅ Rust coverage OK"
|
||||
else
|
||||
echo "⏭️ [3/5] Rust coverage — skipped (no src-tauri/ changes)"
|
||||
echo "⏭️ [3/4] Rust coverage — skipped (no src-tauri/ changes)"
|
||||
fi
|
||||
|
||||
# ── 4. Playwright core smoke lane (if any exist) ──────────────────────
|
||||
# ── 4. CodeScene code health gate (≥9.2) ────────────────────────────────
|
||||
echo ""
|
||||
SMOKE_FILES=$(find tests/smoke tests/integration -name '*.spec.ts' 2>/dev/null | head -1)
|
||||
if [ -n "$SMOKE_FILES" ]; then
|
||||
echo "🎭 [4/5] Playwright core smoke tests..."
|
||||
if ! pnpm playwright:smoke; then
|
||||
echo " ❌ Core smoke tests FAILED"
|
||||
exit 1
|
||||
fi
|
||||
echo " ✅ Core smoke tests OK"
|
||||
else
|
||||
echo "⏭️ [4/5] Playwright core smoke tests — skipped (no tests/**/*.spec.ts)"
|
||||
fi
|
||||
|
||||
# ── 5. CodeScene code health gate (ratchet) ──────────────────────────────
|
||||
# Thresholds live in .codescene-thresholds and only ever go UP (ratchet).
|
||||
# If remote scores improved, the hook updates the file and stops so the new
|
||||
# floor is committed with normal verified hooks before the next push.
|
||||
# If the remote baseline is already below threshold, allow recovery pushes to
|
||||
# land; otherwise the stale remote score would block the refactors required to
|
||||
# restore the gate.
|
||||
THRESHOLDS_FILE="$(git rev-parse --show-toplevel)/.codescene-thresholds"
|
||||
HOTSPOT_MIN=9.45
|
||||
AVERAGE_MIN=9.29
|
||||
if [ -f "$THRESHOLDS_FILE" ]; then
|
||||
HOTSPOT_MIN=$(grep HOTSPOT_THRESHOLD "$THRESHOLDS_FILE" | cut -d= -f2)
|
||||
AVERAGE_MIN=$(grep AVERAGE_THRESHOLD "$THRESHOLDS_FILE" | cut -d= -f2)
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "🏥 [5/5] CodeScene code health (Hotspot ≥${HOTSPOT_MIN} + Average ≥${AVERAGE_MIN})..."
|
||||
echo "🏥 [4/4] CodeScene code health gate (≥9.2)..."
|
||||
if [ -z "$CODESCENE_PAT" ] || [ -z "$CODESCENE_PROJECT_ID" ]; then
|
||||
echo " ⚠️ CODESCENE_PAT or CODESCENE_PROJECT_ID not set — skipping"
|
||||
else
|
||||
API_RESPONSE=$(curl -sf \
|
||||
THRESHOLD=9.2
|
||||
SCORE=$(curl -sf \
|
||||
-H "Authorization: Bearer $CODESCENE_PAT" \
|
||||
-H "Accept: application/json" \
|
||||
"https://api.codescene.io/v2/projects/$CODESCENE_PROJECT_ID" 2>/dev/null || echo "{}")
|
||||
HOTSPOT_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['hotspot_code_health']['now'])" 2>/dev/null || echo "")
|
||||
AVERAGE_SCORE=$(echo "$API_RESPONSE" | python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['code_health']['now'])" 2>/dev/null || echo "")
|
||||
if [ -z "$HOTSPOT_SCORE" ] || [ -z "$AVERAGE_SCORE" ]; then
|
||||
echo " ⚠️ Could not fetch remote scores — skipping (CI will enforce)"
|
||||
else
|
||||
echo " Remote Hotspot Code Health: $HOTSPOT_SCORE (threshold: $HOTSPOT_MIN)"
|
||||
echo " Remote Average Code Health: $AVERAGE_SCORE (threshold: $AVERAGE_MIN)"
|
||||
PYTHON_STATUS=0
|
||||
python3 -c "
|
||||
import sys
|
||||
|
||||
hotspot = float('$HOTSPOT_SCORE')
|
||||
average = float('$AVERAGE_SCORE')
|
||||
hotspot_min = float('$HOTSPOT_MIN')
|
||||
average_min = float('$AVERAGE_MIN')
|
||||
failed = False
|
||||
|
||||
if hotspot < hotspot_min:
|
||||
print(f'WARN: Hotspot Code Health {hotspot:.2f} < {hotspot_min} — remote baseline is currently red')
|
||||
failed = True
|
||||
else:
|
||||
print(f'OK: Hotspot {hotspot:.2f} >= {hotspot_min}')
|
||||
|
||||
if average < average_min:
|
||||
print(f'WARN: Average Code Health {average:.2f} < {average_min} — remote baseline is currently red')
|
||||
failed = True
|
||||
else:
|
||||
print(f'OK: Average {average:.2f} >= {average_min}')
|
||||
|
||||
if failed:
|
||||
print(' ⚠️ Recovery mode: allowing this push so refactors can land and restore the gate on a later analysis.')
|
||||
sys.exit(0)
|
||||
|
||||
import math
|
||||
thresholds_file = '$THRESHOLDS_FILE'
|
||||
new_hotspot = max(hotspot_min, math.floor(hotspot * 100) / 100)
|
||||
new_average = max(average_min, math.floor(average * 100) / 100)
|
||||
if new_hotspot > hotspot_min or new_average > average_min:
|
||||
with open(thresholds_file, 'w') as f:
|
||||
f.write(f'HOTSPOT_THRESHOLD={new_hotspot}\nAVERAGE_THRESHOLD={new_average}\n')
|
||||
print(f' 📈 Ratchet updated: Hotspot {hotspot_min} → {new_hotspot}, Average {average_min} → {new_average}')
|
||||
sys.exit(3)
|
||||
" || PYTHON_STATUS=$?
|
||||
if [ "$PYTHON_STATUS" -ne 0 ] && [ "$PYTHON_STATUS" -ne 3 ]; then
|
||||
exit "$PYTHON_STATUS"
|
||||
fi
|
||||
if [ "$PYTHON_STATUS" -eq 3 ]; then
|
||||
git add "$THRESHOLDS_FILE"
|
||||
echo " ❌ Commit the updated .codescene-thresholds with a normal verified commit, then push again."
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
"https://api.codescene.io/v2/projects/$CODESCENE_PROJECT_ID" \
|
||||
| python3 -c "import sys,json; d=json.load(sys.stdin); print(d['analysis']['hotspot_code_health']['now'])")
|
||||
echo " Hotspot Code Health: $SCORE (threshold: $THRESHOLD)"
|
||||
python3 -c "
|
||||
score = float('$SCORE')
|
||||
threshold = float('$THRESHOLD')
|
||||
if score < threshold:
|
||||
print(f' ❌ Code Health {score:.2f} below threshold {threshold}')
|
||||
exit(1)
|
||||
print(f' ✅ Code Health {score:.2f} ≥ {threshold}')
|
||||
"
|
||||
fi
|
||||
|
||||
END_TIME=$(date +%s)
|
||||
|
||||
179
AGENTS.md
179
AGENTS.md
@@ -1,179 +0,0 @@
|
||||
# AGENTS.md — Tolaria App
|
||||
|
||||
> Quick links: [Architecture](docs/ARCHITECTURE.md) · [Abstractions](docs/ABSTRACTIONS.md) · [Wireframes](ui-design.pen)
|
||||
|
||||
---
|
||||
|
||||
## 1. Task Workflow
|
||||
|
||||
### 1a. Pick up a task
|
||||
|
||||
Run `/laputa-next-task` — fetches next task (To Rework first, then Open), moves to In Progress, returns full description.
|
||||
|
||||
**Before writing a single line of code:** run `mcp__codescene__code_health_score` to check the current codebase health against `.codescene-thresholds`. If the score is already below the threshold, **stop and refactor first** — find the worst files with the MCP, improve them, commit, then start the task. Never start feature work on a codebase that is already below the gate.
|
||||
|
||||
- Read task description and all comments fully
|
||||
- For To Rework: the ❌ QA failed comment tells you exactly what to fix
|
||||
- Check `docs/adr/` for relevant architecture decisions before structural choices
|
||||
- Add a comment: `🚀 Starting work on this task. [Brief description of approach]`
|
||||
|
||||
### 1b. Implement
|
||||
|
||||
- Work on `main` branch — **no branches, no PRs, ever**. Pre-commit and pre-push block work from any other branch.
|
||||
- Commit every 20–30 min: `feat:`, `fix:`, `refactor:`, `test:`, `docs:`
|
||||
- **⛔ NEVER use --no-verify**
|
||||
- For UI tasks: open `ui-design.pen` first, study visual language, design in light mode. You don't need Pencil to use it – you can open it as a JSON file.
|
||||
|
||||
### 1c. When done
|
||||
|
||||
**Phase 1 — Playwright (only for core user flows):**
|
||||
|
||||
Write Playwright test in `tests/smoke/<slug>.spec.ts` only if feature touches: vault open, note create/save/delete, search, wikilink navigation, git commit/push, conflict resolution. Tag a test with `@smoke` only if it protects a core pre-push workflow. Do NOT tag cosmetic or mock-heavy checks — keep those in the full regression lane. The curated `pnpm playwright:smoke` suite must stay under **5 minutes**; use `pnpm playwright:regression` for the full Playwright pass.
|
||||
|
||||
```bash
|
||||
pnpm dev --port 5201 &
|
||||
sleep 3
|
||||
BASE_URL="http://localhost:5201" npx playwright test tests/smoke/<slug>.spec.ts
|
||||
```
|
||||
|
||||
**Phase 2 — Native app QA:**
|
||||
|
||||
```bash
|
||||
pnpm tauri dev &
|
||||
sleep 10
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/focus-app.sh laputa
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/screenshot.sh /tmp/qa-native.png
|
||||
```
|
||||
|
||||
Use `osascript` for keyboard interactions. Write result as Todoist comment (✅ or ❌). **⚠️ WKWebView:** `osascript keystroke` blocked inside editor — rely on Playwright for text input features.
|
||||
|
||||
After both phases pass, add a **completion comment** to the Todoist task. The comment must include:
|
||||
- What was implemented (a few lines covering logic and UX/UI)
|
||||
- QA: what was tested and how (Playwright / native screenshot / osascript)
|
||||
- Refactoring: any files refactored to meet the CodeScene gate (or "none needed")
|
||||
- ADRs: any new/updated ADRs (or "none")
|
||||
- Docs: any updated docs (ARCHITECTURE.md, ABSTRACTIONS.md, etc.) (or "none")
|
||||
- Code health: final Hotspot and Average scores after push
|
||||
|
||||
---
|
||||
|
||||
## 2. Development Process
|
||||
|
||||
### Commits & pushes
|
||||
|
||||
- Push directly to `main` — no PRs, no branches. Pre-push blocks non-`main` pushes.
|
||||
- Pre-push hook runs full check suite (build + tests + core Playwright smoke + CodeScene)
|
||||
- **A task is NOT done until `git push origin main` succeeds.** If the hook blocks: read the error, fix it (clippy, tests, CodeScene, build), commit the fix, push again. **⛔ NEVER use --no-verify**
|
||||
|
||||
### TDD (mandatory)
|
||||
|
||||
Red → Green → Refactor → Commit. One cycle per commit. For bugs: write failing regression test first, then fix. Exception: pure CSS/layout changes.
|
||||
|
||||
**Test quality (Kent Beck's Desiderata):** Isolated · Deterministic · Fast · Behavioral · Structure-insensitive · Specific · Predictive. Fix flaky tests first. Prefer E2E over unit tests for user flows.
|
||||
|
||||
### Localization (mandatory for UI copy)
|
||||
|
||||
All user-facing UI labels/copy must live in `src/lib/locales/en.json` and be translated into every target listed in `lara.yaml`. When adding or changing interface copy:
|
||||
|
||||
```bash
|
||||
pnpm l10n:translate
|
||||
```
|
||||
|
||||
Use `pnpm l10n:translate:force` only when intentionally regenerating existing translations. Commit `src/lib/locales/*.json`, `lara.yaml`/`lara.lock` changes if produced, and verify placeholders/product names stayed intact.
|
||||
|
||||
### Product analytics (mandatory for meaningful features)
|
||||
|
||||
New features should almost always emit a PostHog event so we can see whether users actually discover and use them. Skip instrumentation only for very small changes where a dedicated event would create noise. Use clear, stable event names, avoid PII or note content, and include only safe metadata that helps evaluate adoption and failures.
|
||||
|
||||
When adding or changing a meaningful user-facing feature, include the event name(s) in the Todoist completion comment alongside QA, docs, and code health. If intentionally not instrumenting a feature, explain why in the completion comment.
|
||||
|
||||
### Code health (mandatory)
|
||||
|
||||
Pre-commit and pre-push hooks enforce **Hotspot Code Health** and **Average Code Health** ≥ thresholds in `.codescene-thresholds`. Both gates block commit/push. Thresholds are a **ratchet** — only go up. When pre-push sees improved remote scores, it updates `.codescene-thresholds`, stages it, and stops so you can commit the new floor with normal verified hooks before pushing again. Never add `// eslint-disable`, `#[allow(...)]`, or `as any`.
|
||||
|
||||
**⛔ NEVER edit `.codescene-thresholds` to lower the values.** If the gate blocks you, improve the code — do not lower the bar.
|
||||
|
||||
**CodeScene access order:** use CodeScene MCP tools if available. If MCP is unavailable, use the installed `cs` CLI for file-level review/delta work, and use the CodeScene API (`CODESCENE_PAT` + `CODESCENE_PROJECT_ID`) for project-wide Hotspot/Average threshold checks from `.codescene-thresholds`.
|
||||
|
||||
**Before editing any existing code file:** capture its current file-level CodeScene score. After your edits, re-run the same file-level review and verify the score is higher. If the file already starts at `10.0`, it must remain `10.0`.
|
||||
|
||||
**New files:** every new **scorable code file** must reach CodeScene score `10.0` before commit. If CodeScene reports `null` / "no scorable code" for a new file, it must still have zero CodeScene findings/warnings.
|
||||
|
||||
**Before every commit:** run CodeScene file-level review on every touched or newly created code file and verify the rule above. **Boy Scout Rule:** every file you touch must leave with a higher score, unless it was already `10.0`, in which case it must stay `10.0`.
|
||||
|
||||
**If CodeScene gate blocks your push:** use `mcp__codescene__code_health_score` to find the worst file, refactor it, commit, push again. Do NOT stop or wait for laputa-refactor — that is a background loop, not a substitute for fixing your own regressions.
|
||||
|
||||
### Check suite (runs on every push)
|
||||
```bash
|
||||
pnpm lint && npx tsc --noEmit && pnpm test && pnpm test:coverage # frontend ≥70%
|
||||
cargo test && cargo llvm-cov --manifest-path src-tauri/Cargo.toml --no-clean --fail-under-lines 85
|
||||
```
|
||||
|
||||
### ADRs & docs
|
||||
|
||||
ADRs live in `docs/adr/`. Create in the same commit as the code. Never edit existing — create a new one that supersedes. Use `/create-adr`. **When:** new dependency, storage strategy, platform target, core abstraction, cross-cutting pattern. **Not for:** bug fixes, styling, refactors.
|
||||
|
||||
After any Tauri command, new component/hook, data model change, or new integration: update `docs/ARCHITECTURE.md`, `docs/ABSTRACTIONS.md`, and/or `docs/GETTING-STARTED.md` in the same commit.
|
||||
|
||||
---
|
||||
|
||||
## 3. Product Rules
|
||||
|
||||
### Demo vault hygiene (`demo-vault/`, `demo-vault-v2/`)
|
||||
|
||||
Default to `demo-vault-v2/` for testing.
|
||||
|
||||
- Treat `demo-vault/` and `demo-vault-v2/` as disposable QA fixtures unless the task explicitly changes demo content.
|
||||
- If you create untracked notes, attachments, or other temporary files there for testing, delete them before the task is complete.
|
||||
- If you modify tracked demo-vault files only to test or QA behavior, revert those edits before the final commit.
|
||||
- Before declaring a task done, make sure `git status --short -- demo-vault demo-vault-v2` is empty unless demo fixture changes are part of the task.
|
||||
- If a fresh run starts and the only local dirt is inside `demo-vault/` or `demo-vault-v2/`, clean those paths first and continue. That case is recoverable QA residue, not a blocker.
|
||||
|
||||
### User vault (`~/Laputa/`)
|
||||
|
||||
Default to `demo-vault-v2/`. If you must use `~/Laputa/` for testing:
|
||||
- **Never commit or push** any test notes to the remote vault
|
||||
- **Delete all test notes from disk** when done — do not leave untitled or temporary notes on the filesystem. Run `cd ~/Laputa && git checkout -- . && git clean -fd` to restore the vault to its last committed state.
|
||||
- **Rationale:** test notes pollute the local vault over time, making it a collection of nonsensical untitled files. The vault must stay clean on disk, not just on the remote.
|
||||
|
||||
### UI components — mandatory rules
|
||||
|
||||
**Always use shadcn/ui components.** Never use raw HTML form elements (`<input>`, `<select>`, `<button>`, native `<input type="date">`, etc.) for user-facing UI. Every interactive element must use the shadcn/ui equivalent:
|
||||
|
||||
| Need | Use |
|
||||
|---|---|
|
||||
| Text input | `Input` from shadcn/ui |
|
||||
| Dropdown/select | `Select` from shadcn/ui |
|
||||
| Date picker | `Calendar` + `Popover` from shadcn/ui (NOT native `<input type="date">`) |
|
||||
| Button | `Button` from shadcn/ui |
|
||||
| Autocomplete/combobox | Reuse existing combobox components from the app (check `src/components/`) |
|
||||
| Wikilink picker | Reuse the wikilink autocomplete component already used in the editor and Properties panel |
|
||||
| Emoji picker | Reuse the emoji picker component already used for note/type icons |
|
||||
| Color picker | Reuse the color swatch picker used for type customization |
|
||||
| Toggle/switch | `Switch` or `ToggleGroup` from shadcn/ui |
|
||||
| Dialog/modal | `Dialog` from shadcn/ui |
|
||||
|
||||
**When in doubt:** search `src/components/` for an existing component before building new. **Visual language:** all new UI must feel native to Tolaria — if it looks like a browser default, it's wrong.
|
||||
|
||||
---
|
||||
|
||||
## 4. Reference
|
||||
|
||||
### macOS / Tauri gotchas
|
||||
|
||||
- `Option+N` → special chars on macOS. Use `e.code` or `Cmd+N`
|
||||
- Tauri menu accelerators: `MenuItemBuilder::new(label).accelerator("CmdOrCtrl+1")`
|
||||
- `app.set_menu()` replaces the ENTIRE menu bar — include all submenus
|
||||
- `mock-tauri.ts` silently swallows Tauri calls — not a substitute for native testing
|
||||
|
||||
### QA scripts
|
||||
|
||||
```bash
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/focus-app.sh Tolaria
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/screenshot.sh /tmp/out.png
|
||||
bash ~/.openclaw/skills/tolaria-qa/scripts/shortcut.sh "command" "s"
|
||||
```
|
||||
|
||||
### Diagrams
|
||||
|
||||
Prefer Mermaid (`flowchart`, `sequenceDiagram`, `classDiagram`, `stateDiagram-v2`). ASCII only for spatial wireframe layouts.
|
||||
156
CLAUDE.md
156
CLAUDE.md
@@ -1,3 +1,155 @@
|
||||
@AGENTS.md
|
||||
# CLAUDE.md — Laputa App
|
||||
|
||||
This file is a Claude Code compatibility shim. Keep shared agent instructions in `AGENTS.md`.
|
||||
## ⛔ BEFORE EVERY COMMIT — Non-negotiable checklist
|
||||
|
||||
Run all of these. If any fails, fix before committing. No exceptions.
|
||||
|
||||
```bash
|
||||
pnpm lint && npx tsc --noEmit # lint + types
|
||||
pnpm test # unit tests
|
||||
pnpm test:coverage # frontend ≥70% coverage
|
||||
cargo test # Rust tests
|
||||
cargo llvm-cov --manifest-path src-tauri/Cargo.toml --no-clean --fail-under-lines 85
|
||||
pre_commit_code_health_safeguard # CodeScene ≥9.2 — if it fails, fix structurally (see below)
|
||||
```
|
||||
|
||||
**CI is a safety net, not a discovery tool.** If CI catches something you didn't catch locally, that's a process failure. All these tools are available locally — use them while you code, not just at the end.
|
||||
|
||||
## ⛔ BEFORE FIRING laputa-task-done — QA on real vault
|
||||
|
||||
> **⚠️ TAURI APP ONLY — never test in browser (`pnpm dev` / localhost)**
|
||||
> The browser dev server has a fake HTTP server (`/api/*` routes, mock handlers) that doesn't exist in the real Tauri app.
|
||||
> If it works in the browser but crashes in Tauri, it's broken. Always test in `pnpm tauri dev`.
|
||||
|
||||
1. Acquire lockfile: `echo $$ > /tmp/laputa-qa.lock && trap "rm -f /tmp/laputa-qa.lock" EXIT`
|
||||
2. Kill other instances: `pkill -x laputa 2>/dev/null || true; sleep 1`
|
||||
3. Start app: `pnpm tauri dev` from worktree
|
||||
4. Switch vault to `~/Laputa` (not demo)
|
||||
5. Test the feature/fix with real mouse clicks (`cliclick`) on real notes
|
||||
6. If task touches file save: verify `git -C ~/Laputa diff` shows changes
|
||||
7. If QA fails → fix and re-run. Do NOT fire the signal until it passes.
|
||||
|
||||
Fire done signal only after QA passes:
|
||||
```bash
|
||||
rm -f /tmp/laputa-qa.lock
|
||||
openclaw system event --text "laputa-task-done:<task_id>:<slug>" --mode now
|
||||
```
|
||||
|
||||
## ⛔ CODE HEALTH — No shortcuts
|
||||
|
||||
If `pre_commit_code_health_safeguard` flags a file:
|
||||
- **Understand why** — use `code_health_review` via CodeScene MCP
|
||||
- Fix the structural problem (extract hooks, split components, reduce complexity)
|
||||
- **Never** add a JSDoc comment, `#[allow(...)]`, `// eslint-disable`, or `as any` just to pass the gate
|
||||
- It's fine to take longer. False quality is worse than no quality.
|
||||
|
||||
---
|
||||
|
||||
## Project
|
||||
|
||||
Tauri v2 + React + TypeScript desktop app. Reads a vault of markdown files with YAML frontmatter.
|
||||
|
||||
- **Spec**: `docs/PROJECT-SPEC.md`
|
||||
- **Architecture**: `docs/ARCHITECTURE.md`
|
||||
- **Abstractions**: `docs/ABSTRACTIONS.md`
|
||||
- **Wireframes**: `ui-design.pen`
|
||||
- **Luca's vault**: `~/Laputa/` (~9200 markdown files)
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- Desktop: Tauri v2 (Rust backend)
|
||||
- Frontend: React 18 + TypeScript + BlockNote editor
|
||||
- Tests: Vitest (unit), Playwright (E2E), `cargo test` (Rust)
|
||||
- Package manager: pnpm
|
||||
|
||||
## Architecture
|
||||
|
||||
- `src-tauri/src/` — Rust backend (file I/O, git, frontmatter parsing)
|
||||
- `src/` — React frontend
|
||||
- `src/mock-tauri.ts` — Mock layer for browser/test env (silently swallows Tauri calls — **not a substitute for native app testing**)
|
||||
- `src/types.ts` — Shared TypeScript types
|
||||
|
||||
## How to Work
|
||||
|
||||
- **Never develop on `main`** — always on `task/<slug>` branch
|
||||
- **Commit every 20–30 min** — atomic commits, one concern per commit (`feat:`, `fix:`, `refactor:`, `test:`, `docs:`)
|
||||
- **Update docs/** when changing architecture, abstractions, or significant design
|
||||
- **Test as you go** — write tests alongside code, not after
|
||||
|
||||
## Testing
|
||||
|
||||
- Unit tests must cover real business logic, not "component renders"
|
||||
- Every bug fixed manually → add a regression test
|
||||
- Every new feature → new tests for new behavior paths
|
||||
- `pnpm test:coverage` and `cargo llvm-cov` must pass before committing
|
||||
|
||||
## Design File (every UI task)
|
||||
|
||||
Every task with UI changes needs a design file. Follow this process:
|
||||
|
||||
1. **Open `ui-design.pen` first** — study existing frames to understand the visual language, spacing, and component style before designing anything new.
|
||||
2. **Design in light mode** — all existing designs use light mode. New frames must match. Never use dark mode for designs.
|
||||
3. **Create `design/<slug>.pen`** for the new feature — additive only, NOT a copy of ui-design.pen.
|
||||
4. **When merging to main** — merge your frames into `ui-design.pen` with proper layout:
|
||||
- Place frames in a logical area (group by feature area, not stacked on top of each other)
|
||||
- Leave at least 100px spacing between frames
|
||||
- **Delete `design/<slug>.pen`** after merging — the frames now live in `ui-design.pen`
|
||||
|
||||
```bash
|
||||
mkdir -p design
|
||||
# Study schema first:
|
||||
node -e "const f=JSON.parse(require('fs').readFileSync('ui-design.pen','utf8')); console.log(JSON.stringify(f.children[0],null,2))"
|
||||
# Start fresh:
|
||||
echo '{"children":[],"variables":{}}' > design/<slug>.pen
|
||||
```
|
||||
|
||||
## macOS / Tauri Gotchas
|
||||
|
||||
- `Option+N` on macOS → special chars (`¡`, `™`), not `key:'N'`. Use `e.code` or `Cmd+N`.
|
||||
- Tauri menu accelerators: use `MenuItemBuilder::new(label).accelerator("CmdOrCtrl+1")` — decorative text in labels doesn't register shortcuts.
|
||||
- `app.set_menu()` replaces the ENTIRE menu bar — include all submenus.
|
||||
|
||||
## QA Scripts
|
||||
|
||||
```bash
|
||||
bash ~/.openclaw/skills/laputa-qa/scripts/focus-app.sh laputa
|
||||
bash ~/.openclaw/skills/laputa-qa/scripts/screenshot.sh /tmp/out.png
|
||||
bash ~/.openclaw/skills/laputa-qa/scripts/shortcut.sh "command" "s"
|
||||
bash ~/.openclaw/skills/laputa-qa/scripts/click.sh 400 300 # logical coords
|
||||
```
|
||||
|
||||
## Keyboard-First Principle (mandatory for every new feature)
|
||||
|
||||
Every feature must be reachable via keyboard. This is both a UX requirement and a QA requirement — Brian tests the native app using keyboard only (osascript key events, no mouse).
|
||||
|
||||
**Before marking any task done:**
|
||||
- Can the feature be triggered/used without touching the mouse?
|
||||
- If it requires clicking a button, add a command palette entry or keyboard shortcut
|
||||
- Document the shortcut in the command palette or menu bar
|
||||
|
||||
**If you add UI that is only reachable by mouse**, you must also add a keyboard path (command palette entry, shortcut, or Tab-navigable focus). No exceptions.
|
||||
|
||||
## Push Workflow (IMPORTANT — changed Feb 27, 2026)
|
||||
|
||||
**Push directly to main** — no PRs, no branches, no CI queue.
|
||||
|
||||
The pre-push hook runs all checks locally before the push goes through. This replaces remote CI.
|
||||
|
||||
```bash
|
||||
# After QA passes and you're ready to ship:
|
||||
git push origin main # pre-push hook runs automatically
|
||||
```
|
||||
|
||||
### ⛔ NEVER open a Pull Request
|
||||
PRs on separate branches diverge from main with every merge, requiring continuous rebases and creating unnecessary conflicts. Always push directly to main. If the push fails (disk full, test failure, etc.) — fix the problem, then push again. There is no scenario where opening a PR is the right fallback.
|
||||
|
||||
### ⛔ NEVER use --no-verify
|
||||
```bash
|
||||
# FORBIDDEN — will be caught and rejected:
|
||||
git push --no-verify
|
||||
git commit --no-verify # also forbidden for pre-push bypass
|
||||
```
|
||||
|
||||
The hook runs: tsc, Vite build, frontend tests, frontend coverage, Rust coverage, Clippy, rustfmt, CodeScene. Fix any failures before pushing — do not skip.
|
||||
|
||||
If a check fails, fix the issue and push again. The hook is the gate — not remote CI.
|
||||
|
||||
345
CODE-HEALTH-REPORT.md
Normal file
345
CODE-HEALTH-REPORT.md
Normal file
@@ -0,0 +1,345 @@
|
||||
# Code Health Report — Laputa App
|
||||
|
||||
**Date:** 2026-02-20
|
||||
**Branch:** `main`
|
||||
**Overall Project Score:** 9.33 / 10.0 (Green — up from 9.14)
|
||||
**Tool:** CodeScene Code Health Analysis (project ID: 76865)
|
||||
**Previous Report:** 2026-02-20 on `main` — 9.14 / 10.0
|
||||
|
||||
---
|
||||
|
||||
## Summary
|
||||
|
||||
The Laputa App codebase scores **9.33** overall — a further improvement of **+0.19** from the previous report (9.14). The codebase remains solidly in **Green**, driven by the `vault.rs` refactoring (+2.59 to 8.81) and the `frontmatter.rs` refactoring (+2.79 to 9.68, now Green). Five files remain in the Yellow zone, down from six — `frontmatter.rs` has exited Yellow into Green.
|
||||
|
||||
| Zone | Score Range | File Count | Description |
|
||||
|------|------------|------------|-------------|
|
||||
| Optimal | 10.0 | 8 | Perfect — optimized for human and AI comprehension |
|
||||
| Green | 9.0 – 9.9 | 15 | High quality, minor issues only |
|
||||
| Yellow | 4.0 – 8.9 | 5 | Problematic technical debt |
|
||||
| Red | 1.0 – 3.9 | 0 | — |
|
||||
| N/A | — | 6 | CSS files (4) and tiny utility files (2) — unsupported by CodeScene |
|
||||
|
||||
---
|
||||
|
||||
## Refactoring Completed (vault.rs + frontmatter.rs)
|
||||
|
||||
The following refactorings were executed on vault.rs and frontmatter.rs, raising both files significantly:
|
||||
|
||||
### vault.rs: 6.22 → 8.81 (+2.59)
|
||||
|
||||
Refactored in 5 commits across multiple phases:
|
||||
|
||||
1. **Extracted `run_git` helper** — Consolidated duplicated git command execution into a single helper function, flattening git functions (`git_changed_files`, `git_uncommitted_new_files`).
|
||||
2. **Decomposed `parse_md_file`** — Extracted `parse_frontmatter_fields`, `extract_title`, `extract_snippet`, and `extract_relationships` into focused sub-functions. Flattened deep nesting with early returns.
|
||||
3. **Decomposed `scan_vault_cached`** — Extracted `process_vault_entry`, `collect_vault_entries`, `apply_git_status`, and `build_vault_response` as focused functions.
|
||||
4. **Split large test assertion blocks** — Broke monolithic assertion blocks into per-field assertions for readability and maintainability.
|
||||
5. **Converted internal functions to use `&Path`** instead of `&str` for vault/file paths, reducing string-heavy arguments.
|
||||
|
||||
All 8 original code smells (3 Bumpy Roads, 4 Deep Nestings, 2 Complex Methods, 2 Large Methods, String-Heavy Args, Large Assertion Blocks) have been resolved. The CodeScene review now reports **zero code smells**.
|
||||
|
||||
### frontmatter.rs: 6.89 → 9.68 (+2.79) — Yellow → Green
|
||||
|
||||
Refactored in 4 commits:
|
||||
|
||||
1. **Flattened `update_frontmatter_content`** — Used early returns and extracted `find_key_line_range` and `build_updated_content` helpers. Eliminated bumpy road (4 bumps) and deep nesting (4 levels).
|
||||
2. **Simplified `FrontmatterValue::to_yaml_value`** — Extracted `needs_yaml_quoting` predicate, simplified match arms. Reduced cc from 17.
|
||||
3. **Simplified `format_yaml_key`** — Extracted key-quoting rules into `key_needs_quoting` predicate. Reduced complex conditionals from 5.
|
||||
4. **Extracted line-parsing helpers** — `line_is_key` and related helpers for clean YAML line detection.
|
||||
|
||||
All original code smells (1 Bumpy Road, 1 Deep Nesting, 2 Complex Methods, 4 Complex Conditionals) have been resolved. Only one minor issue remains: **String Heavy Function Arguments** (73% of args are string types).
|
||||
|
||||
---
|
||||
|
||||
## Change Summary vs Previous Report (Feb 17)
|
||||
|
||||
| File | Previous | Current | Delta | Notes |
|
||||
|------|----------|---------|-------|-------|
|
||||
| `src/App.tsx` | 7.13 | **9.28** | **+2.15** | Yellow -> Green. Brain Method eliminated via hook extraction |
|
||||
| `src/components/Inspector.tsx` | 7.49 | **9.02** | **+1.53** | Yellow -> Green. Decomposed into sub-components |
|
||||
| `src-tauri/src/vault.rs` | 4.80 | **8.81** | **+4.01** | Still Yellow but near-Green. All code smells resolved |
|
||||
| `src-tauri/src/frontmatter.rs` | 6.89* | **9.68** | **+2.79** | Yellow -> Green. All major smells resolved |
|
||||
| `src/components/Editor.tsx` | 6.94 | **7.68** | **+0.74** | Still Yellow. DiffView/wikilinks extracted but Editor still too large |
|
||||
| `src/components/Sidebar.tsx` | 9.02 | **9.14** | +0.12 | Green (stable) |
|
||||
| `src/components/NoteList.tsx` | 8.11 | **8.05** | -0.06 | Yellow (stable, slight regression) |
|
||||
| `src/components/QuickOpenPalette.tsx` | 9.55 | **9.55** | = | Green (unchanged) |
|
||||
| `src-tauri/src/lib.rs` | 9.68 | **9.68** | = | Green (unchanged) |
|
||||
| `src-tauri/src/main.rs` | 10.0 | **10.0** | = | Optimal (unchanged) |
|
||||
| `src-tauri/src/git.rs` | 10.0 | **10.0** | = | Optimal (unchanged) |
|
||||
| `src/components/StatusBar.tsx` | 10.0 | **9.23** | -0.77 | Regression: Optimal -> Green (new features added) |
|
||||
| `src/mock-tauri.ts` | 10.0 | **9.37** | -0.63 | Regression: Optimal -> Green (new mock data added) |
|
||||
|
||||
*frontmatter.rs was extracted from vault.rs; "previous" is its initial score after extraction.
|
||||
|
||||
### New Files (not in previous report)
|
||||
|
||||
| File | Score | Zone | Notes |
|
||||
|------|-------|------|-------|
|
||||
| `src/hooks/useNoteActions.ts` | **7.81** | Yellow | Extracted from App.tsx — still needs decomposition |
|
||||
| `src/components/AIChatPanel.tsx` | **8.51** | Yellow | New feature — large component |
|
||||
| `src/components/DynamicPropertiesPanel.tsx` | **9.06** | Green | Extracted from Inspector.tsx |
|
||||
| `src/components/DiffView.tsx` | **9.09** | Green | Extracted from Editor.tsx |
|
||||
| `src/utils/frontmatter.ts` | **9.24** | Green | Extracted from Inspector.tsx |
|
||||
| `src/components/CommitDialog.tsx` | **9.38** | Green | New component |
|
||||
| `src/hooks/useVaultLoader.ts` | **9.41** | Green | Extracted from App.tsx |
|
||||
| `src/utils/wikilinks.ts` | **9.53** | Green | Extracted from Editor.tsx |
|
||||
| `src/hooks/useTheme.ts` | **9.68** | Green | New hook |
|
||||
| `src/components/EditableValue.tsx` | **10.0** | Optimal | Extracted from Inspector.tsx |
|
||||
| `src/components/ResizeHandle.tsx` | **10.0** | Optimal | New component |
|
||||
| `src/components/CreateNoteDialog.tsx` | **10.0** | Optimal | New component |
|
||||
| `src/components/Toast.tsx` | **10.0** | Optimal | New component |
|
||||
| `src/utils/typeColors.ts` | **10.0** | Optimal | New utility |
|
||||
| `src/main.tsx` | **10.0** | Optimal | Entry point |
|
||||
|
||||
---
|
||||
|
||||
## File-by-File Scores (All 34 Files)
|
||||
|
||||
| File | LoC | Score | Zone | Key Issues |
|
||||
|------|-----|-------|------|------------|
|
||||
| `src-tauri/src/main.rs` | 6 | **10.0** | Optimal | None |
|
||||
| `src-tauri/src/git.rs` | 423 | **10.0** | Optimal | None |
|
||||
| `src/components/EditableValue.tsx` | 167 | **10.0** | Optimal | None |
|
||||
| `src/components/ResizeHandle.tsx` | 74 | **10.0** | Optimal | None |
|
||||
| `src/components/CreateNoteDialog.tsx` | 99 | **10.0** | Optimal | None |
|
||||
| `src/components/Toast.tsx` | 28 | **10.0** | Optimal | None |
|
||||
| `src/utils/typeColors.ts` | 37 | **10.0** | Optimal | None |
|
||||
| `src/main.tsx` | 16 | **10.0** | Optimal | None |
|
||||
| `src-tauri/src/frontmatter.rs` | 279 | **9.68** | Green | String-heavy function arguments (73%) |
|
||||
| `src-tauri/src/lib.rs` | 80 | **9.68** | Green | String-heavy function arguments |
|
||||
| `src/hooks/useTheme.ts` | 51 | **9.68** | Green | None significant |
|
||||
| `src/components/QuickOpenPalette.tsx` | 145 | **9.55** | Green | Complex Method (cc=16) |
|
||||
| `src/utils/wikilinks.ts` | 68 | **9.53** | Green | None significant |
|
||||
| `src/hooks/useVaultLoader.ts` | 123 | **9.41** | Green | None significant |
|
||||
| `src/components/CommitDialog.tsx` | 73 | **9.38** | Green | None significant |
|
||||
| `src/mock-tauri.ts` | 894 | **9.37** | Green | None significant |
|
||||
| `src/App.tsx` | 176 | **9.28** | Green | Complex Method: App() cc=16 / 130 LoC |
|
||||
| `src/utils/frontmatter.ts` | 72 | **9.24** | Green | None significant |
|
||||
| `src/components/StatusBar.tsx` | 159 | **9.23** | Green | None significant |
|
||||
| `src/components/Sidebar.tsx` | 208 | **9.14** | Green | None significant |
|
||||
| `src/components/DiffView.tsx` | 45 | **9.09** | Green | None significant |
|
||||
| `src/components/DynamicPropertiesPanel.tsx` | 265 | **9.06** | Green | None significant |
|
||||
| `src/components/Inspector.tsx` | 312 | **9.02** | Green | None significant |
|
||||
| `src-tauri/src/vault.rs` | 1111 | **8.81** | Yellow | No code smells reported — near Green threshold |
|
||||
| `src/components/AIChatPanel.tsx` | 364 | **8.51** | Yellow | Complex Method: AIChatPanel() cc=15 / 285 LoC |
|
||||
| `src/components/NoteList.tsx` | 434 | **8.05** | Yellow | Complex Method: NoteListInner() cc=28 / 208 LoC |
|
||||
| `src/hooks/useNoteActions.ts` | 280 | **7.81** | Yellow | Bumpy Road, Deep Nesting, Complex Method: useNoteActions() cc=30 / 169 LoC |
|
||||
| `src/components/Editor.tsx` | 575 | **7.68** | Yellow | **Brain Method**: Editor() cc=61 / 385 LoC, Bumpy Road |
|
||||
| `src/types.ts` | 38 | N/A | — | Type definitions only |
|
||||
| `src/lib/utils.ts` | 6 | N/A | — | Utility (too small) |
|
||||
| `src/App.css` | — | N/A | — | CSS not supported |
|
||||
| `src/index.css` | — | N/A | — | CSS not supported |
|
||||
| `src/components/Editor.css` | — | N/A | — | CSS not supported |
|
||||
| `src/components/EditorTheme.css` | — | N/A | — | CSS not supported |
|
||||
|
||||
---
|
||||
|
||||
## Technical Debt Hotspots
|
||||
|
||||
Based on code health scores, file sizes, and change frequency:
|
||||
|
||||
| Priority | File | Score | LoC | Risk Factor |
|
||||
|----------|------|-------|-----|-------------|
|
||||
| 1 | `src/components/Editor.tsx` | 7.68 | 575 | **Brain Method** (cc=61, 385 LoC) — worst single function in codebase |
|
||||
| 2 | `src/hooks/useNoteActions.ts` | 7.81 | 280 | Brain Method (cc=30, 169 LoC), deep nesting in updateMockFrontmatter |
|
||||
| 3 | `src/components/NoteList.tsx` | 8.05 | 434 | Complex Method (cc=28, 208 LoC) |
|
||||
| 4 | `src/components/AIChatPanel.tsx` | 8.51 | 364 | Large component (cc=15, 285 LoC) — new, address before it grows |
|
||||
| 5 | `src-tauri/src/vault.rs` | 8.81 | 1111 | Near-Green, no code smells — minor improvement needed to cross 9.0 |
|
||||
|
||||
---
|
||||
|
||||
## Detailed Analysis — Files Scoring Below 9.0
|
||||
|
||||
### 1. `src/components/Editor.tsx` — Score: 7.68 (Now #1 Priority)
|
||||
|
||||
The core `Editor` component function remains a **Brain Method** — the single worst function in the codebase at cc=61 and 385 LoC (3.2x the 120 LoC limit).
|
||||
|
||||
**Code Smells Found:**
|
||||
|
||||
| Smell | Location | Details | Severity |
|
||||
|-------|----------|---------|----------|
|
||||
| Bumpy Road | `Editor` (L154–575) | 2 bumps | High |
|
||||
| Complex Method | `Editor` (L154–575) | cc = 61 (**Brain Method**) | High |
|
||||
| Complex Conditional | `Editor:196` | 2 complex expressions | Medium |
|
||||
| Large Method | `Editor` (L154–575) | 385 LoC (limit: 120) | Medium |
|
||||
|
||||
---
|
||||
|
||||
### 2. `src/hooks/useNoteActions.ts` — Score: 7.81
|
||||
|
||||
Extracted from App.tsx. Contains the `updateMockFrontmatter` function which has deep nesting, plus the `useNoteActions` hook itself is still too large.
|
||||
|
||||
**Code Smells Found:**
|
||||
|
||||
| Smell | Location | Details | Severity |
|
||||
|-------|----------|---------|----------|
|
||||
| Bumpy Road | `updateMockFrontmatter` (L14–66) | 2 bumps | High |
|
||||
| Deep Nesting | `updateMockFrontmatter` (L14–66) | 4 levels deep | High |
|
||||
| Complex Method | `useNoteActions` (L93–280) | cc = 30 | Medium |
|
||||
| Complex Method | `updateMockFrontmatter` (L14–66) | cc = 17 | Medium |
|
||||
| Complex Method | `deleteMockFrontmatterProperty` (L68–91) | cc = 9 | Medium |
|
||||
| Large Method | `useNoteActions` (L93–280) | 169 LoC (limit: 70) | Medium |
|
||||
|
||||
---
|
||||
|
||||
### 3. `src/components/NoteList.tsx` — Score: 8.05
|
||||
|
||||
Slightly regressed from 8.11. The `NoteListInner` component and `buildRelationshipGroups` remain complex.
|
||||
|
||||
**Code Smells Found:**
|
||||
|
||||
| Smell | Location | Details | Severity |
|
||||
|-------|----------|---------|----------|
|
||||
| Complex Method | `NoteListInner` (L211–432) | cc = 28 | Medium |
|
||||
| Complex Method | `buildRelationshipGroups` (L125–188) | cc = 13 | Medium |
|
||||
| Large Method | `NoteListInner` (L211–432) | 208 LoC (limit: 120) | Medium |
|
||||
| Overall Code Complexity | File-wide | High mean cyclomatic complexity | Medium |
|
||||
|
||||
---
|
||||
|
||||
### 4. `src/components/AIChatPanel.tsx` — Score: 8.51
|
||||
|
||||
New file (mock AI chat feature). Already showing signs of complexity that should be addressed early.
|
||||
|
||||
**Code Smells Found:**
|
||||
|
||||
| Smell | Location | Details | Severity |
|
||||
|-------|----------|---------|----------|
|
||||
| Complex Method | `AIChatPanel` (L62–364) | cc = 15 | Medium |
|
||||
| Large Method | `AIChatPanel` (L62–364) | 285 LoC (limit: 120) | Medium |
|
||||
|
||||
---
|
||||
|
||||
### 5. `src-tauri/src/vault.rs` — Score: 8.81
|
||||
|
||||
Dramatically improved from 6.22. The CodeScene review reports **zero code smells** after the refactoring. The file is near the Green threshold (9.0) and may only need minor adjustments to cross it.
|
||||
|
||||
---
|
||||
|
||||
## Quick Wins (Low Effort, High Impact)
|
||||
|
||||
### 1. Decompose `Editor` into hooks (highest ROI)
|
||||
**File:** `src/components/Editor.tsx` | **Impact:** cc 61 -> ~10 per hook
|
||||
- Extract `useEditorExtensions()` — all CodeMirror extension setup (themes, keybindings, decorations)
|
||||
- Extract `useEditorContent()` — content loading, saving, dirty state management
|
||||
- Extract `useEditorKeymap()` — custom keymap handlers
|
||||
- The `Editor` component becomes a thin composition + JSX layer
|
||||
|
||||
### 2. Decompose `useNoteActions` hook
|
||||
**File:** `src/hooks/useNoteActions.ts` | **Impact:** cc 30 -> ~8 per hook
|
||||
- Extract `useFrontmatterSync()` — `updateMockFrontmatter` + `deleteMockFrontmatterProperty`
|
||||
- Flatten `updateMockFrontmatter` with early returns and helper functions
|
||||
- Keep `useNoteActions` as pure action dispatch (create, delete, rename)
|
||||
|
||||
### 3. Split `NoteListInner` into sub-components
|
||||
**File:** `src/components/NoteList.tsx` | **Impact:** cc 28 -> ~8 per component
|
||||
- Extract `NoteListItem` component for individual note rendering
|
||||
- Extract `RelationshipGroup` component for grouped entries
|
||||
- Extract `buildRelationshipGroups` to a utility file
|
||||
|
||||
### 4. Extract `AIChatPanel` hooks early
|
||||
**File:** `src/components/AIChatPanel.tsx` | **Impact:** Prevent further complexity growth
|
||||
- Extract `useChatMessages()` — message state, send/receive logic
|
||||
- Extract `ChatMessage` component for individual message rendering
|
||||
|
||||
### 5. Push `vault.rs` past 9.0
|
||||
**File:** `src-tauri/src/vault.rs` | **Impact:** 8.81 -> 9.0+
|
||||
- Minor: reduce string-heavy args further with `&Path` conversions
|
||||
- Minor: simplify any remaining complex expressions
|
||||
|
||||
---
|
||||
|
||||
## Path to 9.5 Overall
|
||||
|
||||
**Current:** 9.33 (28 scored files, sum = 261.20)
|
||||
**Target:** 9.5
|
||||
|
||||
To reach 9.5, all 5 Yellow files must reach at least 9.5:
|
||||
|
||||
| File | Current | Target | Points Needed |
|
||||
|------|---------|--------|---------------|
|
||||
| `vault.rs` | 8.81 | 9.5 | +0.69 |
|
||||
| `Editor.tsx` | 7.68 | 9.5 | +1.82 |
|
||||
| `useNoteActions.ts` | 7.81 | 9.5 | +1.69 |
|
||||
| `NoteList.tsx` | 8.05 | 9.5 | +1.45 |
|
||||
| `AIChatPanel.tsx` | 8.51 | 9.5 | +0.99 |
|
||||
| **Total points needed** | | | **+6.64** |
|
||||
|
||||
**Projected score if all Yellow files reach 9.5:** (261.20 + 6.64) / 28 = **9.57**
|
||||
|
||||
**Recommended execution order for maximum impact:**
|
||||
1. `Editor.tsx` (7.68 -> 9.5) — highest user-facing impact, hook extraction is mechanical
|
||||
2. `useNoteActions.ts` (7.81 -> 9.5) — extracted hook, straightforward decomposition
|
||||
3. `NoteList.tsx` (8.05 -> 9.5) — component extraction
|
||||
4. `AIChatPanel.tsx` (8.51 -> 9.5) — closest to target, prevent drift
|
||||
5. `vault.rs` (8.81 -> 9.5) — near-Green already, minor tweaks
|
||||
|
||||
---
|
||||
|
||||
## Refactoring ROI Summary
|
||||
|
||||
| File | Current | Target | Defect Reduction | Speed Improvement |
|
||||
|------|---------|--------|------------------|-------------------|
|
||||
| `Editor.tsx` | 7.68 | 9.5 | 25–38% | 19–30% |
|
||||
| `useNoteActions.ts` | 7.81 | 9.5 | 24–36% | 18–28% |
|
||||
| `NoteList.tsx` | 8.05 | 9.5 | 22–33% | 16–26% |
|
||||
| `AIChatPanel.tsx` | 8.51 | 9.5 | 18–27% | 13–21% |
|
||||
| `vault.rs` | 8.81 | 9.5 | 10–18% | 8–14% |
|
||||
|
||||
---
|
||||
|
||||
## Files in Good Shape
|
||||
|
||||
These files need no immediate attention:
|
||||
|
||||
**Optimal (10.0):**
|
||||
- `src-tauri/src/main.rs` — 6 LoC, clean entry point
|
||||
- `src-tauri/src/git.rs` — 423 LoC, well-structured
|
||||
- `src/components/EditableValue.tsx` — 167 LoC, clean extracted component
|
||||
- `src/components/ResizeHandle.tsx` — 74 LoC, simple component
|
||||
- `src/components/CreateNoteDialog.tsx` — 99 LoC, clean dialog
|
||||
- `src/components/Toast.tsx` — 28 LoC, minimal component
|
||||
- `src/utils/typeColors.ts` — 37 LoC, simple utility
|
||||
- `src/main.tsx` — 16 LoC, entry point
|
||||
|
||||
**Green (9.0–9.9):**
|
||||
- `src-tauri/src/frontmatter.rs` — 9.68 (up from 6.89! Only: string-heavy args)
|
||||
- `src-tauri/src/lib.rs` — 9.68 (minor: string-heavy args)
|
||||
- `src/hooks/useTheme.ts` — 9.68 (clean hook)
|
||||
- `src/components/QuickOpenPalette.tsx` — 9.55 (minor: cc=16)
|
||||
- `src/utils/wikilinks.ts` — 9.53 (clean utility)
|
||||
- `src/hooks/useVaultLoader.ts` — 9.41 (clean hook)
|
||||
- `src/components/CommitDialog.tsx` — 9.38 (clean component)
|
||||
- `src/mock-tauri.ts` — 9.37 (large but clean)
|
||||
- `src/App.tsx` — 9.28 (dramatically improved from 7.13)
|
||||
- `src/utils/frontmatter.ts` — 9.24 (clean utility)
|
||||
- `src/components/StatusBar.tsx` — 9.23 (slightly regressed from 10.0)
|
||||
- `src/components/Sidebar.tsx` — 9.14 (stable)
|
||||
- `src/components/DiffView.tsx` — 9.09 (clean extracted component)
|
||||
- `src/components/DynamicPropertiesPanel.tsx` — 9.06 (clean extracted component)
|
||||
- `src/components/Inspector.tsx` — 9.02 (dramatically improved from 7.49)
|
||||
|
||||
---
|
||||
|
||||
## What Worked Since Last Report
|
||||
|
||||
The following refactorings from the Feb 17 recommendations were executed:
|
||||
|
||||
1. **App.tsx decomposition** (Plan C) — Extracted `useNoteActions`, `useVaultLoader`, and other hooks. App dropped from cc=56/381 LoC to cc=16/130 LoC. Score: 7.13 -> 9.28.
|
||||
2. **Inspector.tsx decomposition** (Plan D) — Extracted `DynamicPropertiesPanel`, `EditableValue`, and `frontmatter.ts` utility. Score: 7.49 -> 9.02.
|
||||
3. **vault.rs full refactoring** (Plan A) — Extracted `run_git` helper, decomposed `parse_md_file` and `scan_vault_cached`, split large assertion blocks, converted to `&Path` args. Score: 4.80 -> 8.81. **All code smells resolved.**
|
||||
4. **frontmatter.rs full refactoring** (Plan B) — Flattened `update_frontmatter_content`, simplified `to_yaml_value` and `format_yaml_key`, extracted line-parsing helpers. Score: 6.89 -> 9.68. **Yellow -> Green.**
|
||||
5. **Editor.tsx partial decomposition** (Plan B, Steps 2–3) — Extracted `DiffView.tsx` and `wikilinks.ts`. Score: 6.94 -> 7.68.
|
||||
|
||||
## What Still Needs Work
|
||||
|
||||
1. **Editor.tsx** — DiffView and wikilinks were extracted, but the core Editor function was NOT decomposed into hooks. It's now the worst function (cc=61, 385 LoC). Hook extraction (useEditorExtensions, useEditorContent, useEditorKeymap) is the next high-impact target.
|
||||
2. **useNoteActions.ts** — Inherited App.tsx's `updateMockFrontmatter` complexity. Needs decomposition into smaller hooks.
|
||||
3. **NoteList.tsx** — Slight regression, needs component extraction (NoteListItem, RelationshipGroup).
|
||||
4. **AIChatPanel.tsx** — New file already showing complexity. Address early before it grows.
|
||||
5. **vault.rs** — Near-Green at 8.81 with zero code smells. Minor tweaks may push it past 9.0.
|
||||
|
||||
---
|
||||
|
||||
*Report generated by CodeScene MCP analysis on 2026-02-20. For interactive exploration, visit: https://codescene.io/projects/76865*
|
||||
*Note: CodeScene MCP Server MCP-0.1.5 was used. Version MCP-0.2.0 is available — consider updating via `brew upgrade cs-mcp`.*
|
||||
@@ -1,49 +0,0 @@
|
||||
# Contributing to Tolaria
|
||||
|
||||
Thanks for being here! Tolaria is still early, and every bug report, idea, and contribution genuinely helps shape the app.
|
||||
|
||||
## 🗳️ Where to share what
|
||||
|
||||
To keep things clean:
|
||||
|
||||
- 🐛 Bugs → GitHub Issues
|
||||
- 💡 Feature requests / ideas → Canny • <https://tolaria.canny.io/>
|
||||
|
||||
If you have a feature idea, please check Canny first and upvote it if it already exists.
|
||||
|
||||
## 📥 Pull requests are welcome
|
||||
|
||||
PRs are very welcome.
|
||||
|
||||
A few things to keep in mind before opening one:
|
||||
|
||||
- Bug fixes are always great
|
||||
- Small improvements are great too
|
||||
- For bigger features, please check Canny first before building
|
||||
- Try to avoid things that are already marked **in progress**
|
||||
- Requests marked **planned** are usually great contribution targets
|
||||
- Keep PRs small, focused, and easy to review
|
||||
- Include a short explanation of the problem and your solution
|
||||
- Follow the dev process described in Tolaria’s `AGENTS.md` (tests, code health, etc.)
|
||||
- Avoid bundling unrelated refactors into the same PR
|
||||
|
||||
If you want to contribute a feature, the best place to start is here: <https://tolaria.canny.io/>
|
||||
|
||||
## 📋 What makes a good bug report
|
||||
|
||||
If you open a bug report on GitHub, it really helps to include:
|
||||
|
||||
- your Tolaria version
|
||||
- your OS version
|
||||
- steps to reproduce
|
||||
- what you expected to happen
|
||||
- what actually happened
|
||||
- screenshots or screen recordings if useful
|
||||
|
||||
The clearer the report, the easier it is for us to reproduce and fix it.
|
||||
|
||||
## 🙏 Thank you
|
||||
|
||||
Tolaria is getting better because people care enough to try it, report what’s broken, suggest what’s missing, and contribute improvements.
|
||||
|
||||
That means a lot. Thanks for helping build it.
|
||||
BIN
GT-Pressura-Regular-Trial.otf
Normal file
BIN
GT-Pressura-Regular-Trial.otf
Normal file
Binary file not shown.
661
LICENSE
661
LICENSE
@@ -1,661 +0,0 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
158
README.md
158
README.md
@@ -1,112 +1,96 @@
|
||||
 [](https://github.com/refactoringhq/tolaria/actions/workflows/ci.yml) [](https://github.com/refactoringhq/tolaria/actions/workflows/release.yml) [](https://codecov.io/gh/refactoringhq/tolaria) [](https://codescene.io/projects/76865)
|
||||
# Laputa App
|
||||
|
||||
# 💧 Tolaria
|
||||
Personal knowledge and life management desktop app built with Tauri v2 + React + TypeScript + BlockNote.
|
||||
|
||||
Tolaria is a desktop app for macOS, Windows, and Linux for managing **markdown knowledge bases**. People use it for a variety of use cases:
|
||||
## Documentation
|
||||
|
||||
* Operate second brains and personal knowledge
|
||||
* Organize company docs as context for AI
|
||||
* Store OpenClaw/assistants memory and procedures
|
||||
- 📐 [ARCHITECTURE.md](docs/ARCHITECTURE.md) — System design, tech stack, data flow
|
||||
- 🧩 [ABSTRACTIONS.md](docs/ABSTRACTIONS.md) — Core abstractions and models
|
||||
- 🚀 [GETTING-STARTED.md](docs/GETTING-STARTED.md) — How to navigate the codebase
|
||||
- 🎨 [THEMING.md](docs/THEMING.md) — Theme system and customization
|
||||
|
||||
Personally, I use it to **run my life** (hey 👋 [Luca here](http://x.com/lucaronin)). I have a massive workspace of 10,000+ notes, which are the result of my [Refactoring](https://refactoring.fm/) work + a ton of personal journaling and *second braining*.
|
||||
|
||||
<img width="1000" height="656" alt="1776506856823-CleanShot_2026-04-18_at_12 06 57_2x" src="https://github.com/user-attachments/assets/8aeafb0a-b236-43c2-a083-ec111f903c38" />
|
||||
|
||||
## Walkthroughs
|
||||
|
||||
You can find some Loom walkthroughs below — they are short and to the point:
|
||||
- [How I Organize My Own Tolaria Workspace](https://www.loom.com/share/bb3aaffa238b4be0bd62e4464bca2528)
|
||||
- [My Inbox Workflow](https://www.loom.com/share/dffda263317b4fa8b47b59cdf9330571)
|
||||
- [How I Save Web Resources to Tolaria](https://www.loom.com/share/8a3c1776f801402ebbf4d7b0f31e9882)
|
||||
|
||||
## Principles
|
||||
|
||||
- 📑 **Files-first** — Your notes are plain markdown files. They're portable, work with any editor, and require no export step. Your data belongs to you, not to any app.
|
||||
- 🔌 **Git-first** — Every vault is a git repository. You get full version history, the ability to use any git remote, and zero dependency on Tolaria servers.
|
||||
- 🛜 **Offline-first, zero lock-in** — No accounts, no subscriptions, no cloud dependencies. Your vault works completely offline and always will. If you stop using Tolaria, you lose nothing.
|
||||
- 🔬 **Open source** — Tolaria is free and open source. I built this for [myself](https://x.com/lucaronin) and for sharing it with others.
|
||||
- 📋 **Standards-based** — Notes are markdown files with YAML frontmatter. No proprietary formats, no locked-in data. Everything works with standard tools if you decide to move away from Tolaria.
|
||||
- 🔍 **Types as lenses, not schemas** — Types in Tolaria are navigation aids, not enforcement mechanisms. There's no required fields, no validation, just helpful categories for finding notes.
|
||||
- 🪄**AI-first but not AI-only** — A vault of files works very well with AI agents, but you are free to use whatever you want. We support Claude Code, Codex CLI, and Gemini CLI setup paths, but you can edit the vault with any AI you want. We provide an AGENTS file for your agents to figure out.
|
||||
- ⌨️ **Keyboard-first** — Tolaria is designed for power-users who want to use keyboard as much as possible. A lot of how we designed the Editor and the Command Palette is based on this.
|
||||
- 💪 **Built from real use** — Tolaria was created for manage my personal vault of 10,000+ notes, and I use it every day. Every feature exists because it solved a real problem.
|
||||
|
||||
## Installation
|
||||
|
||||
### Homebrew
|
||||
|
||||
Install via Homebrew on macOS:
|
||||
|
||||
```batch
|
||||
brew install --cask tolaria
|
||||
```
|
||||
|
||||
### Download from releases
|
||||
|
||||
Download the [latest release here](https://refactoringhq.github.io/tolaria/download/) for macOS, Windows, or Linux.
|
||||
|
||||
## Getting started
|
||||
|
||||
When you open Tolaria for the first time you get the chance of cloning the [getting started vault](https://github.com/refactoringhq/tolaria-getting-started) — which gives you a walkthrough of the whole app.
|
||||
|
||||
## Open source and local setup
|
||||
|
||||
Tolaria is open source and built with Tauri, React, and TypeScript. If you want to run or contribute to the app locally, here is [how to get started](https://github.com/refactoringhq/tolaria/blob/main/docs/GETTING-STARTED.md). You can also find the gist below 👇
|
||||
## Quick Start
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js 20+
|
||||
- pnpm 8+
|
||||
- Rust stable
|
||||
- macOS or Linux for development
|
||||
- Rust (latest stable)
|
||||
- macOS (for development)
|
||||
|
||||
#### Linux system dependencies
|
||||
|
||||
Tauri 2 on Linux requires WebKit2GTK 4.1 and GTK 3:
|
||||
|
||||
- Arch / Manjaro:
|
||||
```bash
|
||||
sudo pacman -S --needed webkit2gtk-4.1 base-devel curl wget file openssl \
|
||||
appmenu-gtk-module libappindicator-gtk3 librsvg
|
||||
```
|
||||
- Debian / Ubuntu (22.04+):
|
||||
```bash
|
||||
sudo apt install libwebkit2gtk-4.1-dev build-essential curl wget file \
|
||||
libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev \
|
||||
libsoup-3.0-dev patchelf
|
||||
```
|
||||
- Fedora 38+:
|
||||
```bash
|
||||
sudo dnf install webkit2gtk4.1-devel openssl-devel curl wget file \
|
||||
libappindicator-gtk3-devel librsvg2-devel
|
||||
```
|
||||
|
||||
The bundled MCP server still spawns the system `node` binary at runtime on Linux, so install Node from your distro package manager if you want the external AI tooling flow.
|
||||
|
||||
### Quick start
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Install git hooks (optional but recommended)
|
||||
.github/hooks/install-hooks.sh
|
||||
|
||||
# Run dev server
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Open `http://localhost:5173` for the browser-based mock mode, or run the native desktop app with:
|
||||
# Open in browser (mock mode)
|
||||
open http://localhost:5173
|
||||
|
||||
```bash
|
||||
# Or run in Tauri
|
||||
pnpm tauri dev
|
||||
```
|
||||
|
||||
## Tech Docs
|
||||
### Testing
|
||||
|
||||
- 📐 [ARCHITECTURE.md](docs/ARCHITECTURE.md) — System design, tech stack, data flow
|
||||
- 🧩 [ABSTRACTIONS.md](docs/ABSTRACTIONS.md) — Core abstractions and models
|
||||
- 🚀 [GETTING-STARTED.md](docs/GETTING-STARTED.md) — How to navigate the codebase
|
||||
- 📚 [ADRs](docs/adr) — Architecture Decision Records
|
||||
```bash
|
||||
# Frontend tests
|
||||
pnpm test
|
||||
|
||||
## Security
|
||||
# Backend tests
|
||||
cargo test
|
||||
|
||||
If you believe you have found a security issue, please report it privately as described in [SECURITY.md](./SECURITY.md).
|
||||
# Coverage
|
||||
pnpm test:coverage
|
||||
|
||||
# E2E tests
|
||||
pnpm test:e2e
|
||||
```
|
||||
|
||||
### Code Quality
|
||||
|
||||
```bash
|
||||
# Lint
|
||||
pnpm lint
|
||||
|
||||
# Rust checks
|
||||
cargo clippy
|
||||
cargo fmt --check
|
||||
|
||||
# CodeScene (via Claude Code)
|
||||
claude 'Check code health with CodeScene MCP'
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
See [CLAUDE.md](CLAUDE.md) for coding guidelines and workflow.
|
||||
|
||||
**Key principles:**
|
||||
- Small, atomic commits
|
||||
- Test as you go
|
||||
- Visual verification mandatory
|
||||
- Documentation updated with code changes
|
||||
|
||||
## CI/CD
|
||||
|
||||
GitHub Actions runs on every push/PR:
|
||||
- ✅ Tests (frontend + Rust)
|
||||
- 📊 Coverage (70% threshold)
|
||||
- 🎨 Lint & format
|
||||
- ⚠️ Documentation check
|
||||
|
||||
See [.github/SETUP.md](.github/SETUP.md) for CI/CD configuration.
|
||||
|
||||
## Git Hooks
|
||||
|
||||
Pre-commit hook checks code health before every commit. See [.github/HOOKS.md](.github/HOOKS.md) for details.
|
||||
|
||||
## License
|
||||
|
||||
Tolaria is licensed under AGPL-3.0-or-later. The Tolaria name and logo remain covered by the project’s trademark policy.
|
||||
Private repository — not licensed for public use.
|
||||
|
||||
362
REDESIGN-PLAN.md
Normal file
362
REDESIGN-PLAN.md
Normal file
@@ -0,0 +1,362 @@
|
||||
# Laputa App Redesign — Implementation Plan
|
||||
|
||||
> Generated from `ui-design.pen` (V2) vs current implementation. **Analysis only — do not implement yet.**
|
||||
|
||||
---
|
||||
|
||||
## Summary of Changes
|
||||
|
||||
The V2 design introduces: a **Status Bar**, **Tab Bar** in the editor, an **Info Bar** (breadcrumb + actions), restructured **Sidebar** with Phosphor icons and collapsible groups with count badges, **IBM Plex Mono** for type pills, updated **color palette** (new primary `#155DFF`, new accent colors), and several layout/spacing refinements throughout.
|
||||
|
||||
---
|
||||
|
||||
## Design Specs Reference (from .pen file)
|
||||
|
||||
### Colors Changed
|
||||
| Variable | Old (Light) | New (Light) | Old (Dark) | New (Dark) |
|
||||
|---|---|---|---|---|
|
||||
| `--primary` | `#2383E2` | `#155DFF` | `#4a9eff` | `#155DFF` |
|
||||
| `--accent-green` | `#0F7B6C` | `#00B38B` | `#4caf50` | `#00B38B` |
|
||||
| `--accent-purple` | `#9065B0` | `#A932FF` | `#9c72ff` | `#A932FF` |
|
||||
| `--accent-blue` | `#2383E2` | `#155DFF` | `#4a9eff` | `#155DFF` |
|
||||
|
||||
### New Color Variables (not in current CSS)
|
||||
| Variable | Light | Dark |
|
||||
|---|---|---|
|
||||
| `--accent-yellow` | `#F0B100` | `#F0B100` |
|
||||
| `--accent-blue-light` | `#155DFF14` | `#155DFF20` |
|
||||
| `--accent-green-light` | `#00B38B14` | `#00B38B20` |
|
||||
| `--accent-purple-light` | `#A932FF14` | `#A932FF20` |
|
||||
| `--accent-red-light` | `#E03E3E14` | `#f4433620` |
|
||||
| `--accent-yellow-light` | `#F0B10014` | `#F0B10020` |
|
||||
|
||||
### Typography
|
||||
- **Font**: Inter (primary), IBM Plex Mono (labels/pills) — **IBM Plex Mono not currently loaded**
|
||||
- App title: 17px / Bold / letter-spacing -0.3
|
||||
- Sidebar items: 13px / Medium (font-weight 500)
|
||||
- Sidebar section headers: 13px / Semibold (600) — currently 11px
|
||||
- Type pills: 11px / IBM Plex Mono / normal weight / ALL CAPS
|
||||
- Editor H1: 32px / Bold / lh 1.2
|
||||
- Editor H2: 24px / Semibold / lh 1.3
|
||||
- Editor body: 16px / Regular / lh 1.6
|
||||
- Info bar / breadcrumb: 12px
|
||||
- Status bar: 11px
|
||||
|
||||
### Panel Widths
|
||||
| Panel | Design | Current |
|
||||
|---|---|---|
|
||||
| Sidebar | 250px | 250px ✅ |
|
||||
| NoteList | 300px | 300px ✅ |
|
||||
| Editor | flexible | flexible ✅ |
|
||||
| Inspector | 260px (design) / 280px (spec) | 280px ✅ |
|
||||
|
||||
### Border Radius Scale
|
||||
- 4px (sm) — chips
|
||||
- 6px (md) — buttons, inputs
|
||||
- 8px (lg) — cards, dialogs
|
||||
- 9999px — pills, badges (full-round)
|
||||
- 16px — larger badges
|
||||
|
||||
---
|
||||
|
||||
## Difference Map
|
||||
|
||||
### 1. NEW: Status Bar (bottom of app)
|
||||
**Files**: New component `StatusBar.tsx`, `App.tsx`, `App.css`
|
||||
- 30px height, `bg: --sidebar`, `border-top: 1px --border`
|
||||
- **Left**: box icon + "v0.4.2" | git-branch + "main" | refresh-cw (green) + "Synced 2m ago"
|
||||
- **Right**: sparkles (purple) + "Claude Sonnet 4" | file-text + "1,247 notes" | bell icon | settings icon
|
||||
- Padding: 0 8px, items aligned center, gap 12px between items
|
||||
- Font: Inter 11px, text color `--muted-foreground`
|
||||
- Separators: "|" in `--border` color
|
||||
- **All icons**: Lucide, 13-14px
|
||||
|
||||
### 2. NEW: Tab Bar (top of editor panel)
|
||||
**Files**: `Editor.tsx`
|
||||
- 45px height, `bg: --sidebar`, `border-bottom: 1px --sidebar-border`
|
||||
- **Active tab**: `bg: --background`, border-right 1px `--border`, text 12px/500 `--foreground`, X close icon (14px lucide)
|
||||
- **Inactive tab**: no fill, border-right + border-bottom 1px `--sidebar-border`, text 12px/normal `--muted-foreground`, X icon opacity 0 (show on hover)
|
||||
- **Spacer**: fills remaining width, border-bottom 1px `--border`
|
||||
- **Controls area** (right): border-left + border-bottom 1px `--border`, gap 12px, padding 0 12px
|
||||
- Plus icon (Phosphor, 16px)
|
||||
- Columns/split icon (Phosphor, 16px) — **disabled placeholder**
|
||||
- Arrows-out-simple/expand icon (Phosphor, 16px) — **disabled placeholder**
|
||||
|
||||
### 3. NEW: Breadcrumb Bar (below tab bar, above editor content)
|
||||
**Files**: `Editor.tsx`
|
||||
- 45px height, `bg: --background`, `border-bottom: 1px --border`
|
||||
- Padding: 6px 16px
|
||||
- **Left (breadcrumb)**: "Project" (12px, muted) › "Laputa App" (12px/500, foreground) · "1,284 words" (12px, muted) · "M" (12px/600, `--accent-yellow`) — M only when file modified
|
||||
- **Right (actions)**: gap 12px, each 16px Phosphor icon in `--muted-foreground`
|
||||
- magnifying-glass (search in file)
|
||||
- git-branch (version history) — **disabled placeholder**
|
||||
- cursor-text (focus mode) — **disabled placeholder**
|
||||
- sparkle (AI assist) — **disabled placeholder**
|
||||
- dots-three (more options) — **disabled placeholder**
|
||||
|
||||
### 4. Sidebar Restructure
|
||||
**Files**: `Sidebar.tsx`
|
||||
|
||||
#### Header changes:
|
||||
- Current: "Laputa" title + theme toggle button
|
||||
- New: "Laputa" title (17px/700, -0.3 ls) + search icon (16px Phosphor magnifying-glass) + settings/gear icon (16px)
|
||||
- Theme toggle moved elsewhere (or removed from header)
|
||||
- Padding: 12px 16px, height 45px, border-bottom 1px
|
||||
|
||||
#### Search bar added:
|
||||
- Below header, padding 6px 12px, border-bottom 1px
|
||||
- Input with magnifying-glass icon prefix, 13px text, placeholder "Search notes..."
|
||||
- Height ~32px, border-radius 6px, bg `--secondary`
|
||||
|
||||
#### Navigation section restructured:
|
||||
**Current**: flat list of filters (All Notes, People, Events, Changes, Favorites, Trash)
|
||||
**New**: Two items in top nav:
|
||||
- "All Notes" — file-text icon (Phosphor 16px) + label 13px/500 + count badge (pill, bg `--secondary`, 10px text)
|
||||
- "Favorites" — star icon (Phosphor 16px) + same style
|
||||
|
||||
#### Section groups restructured:
|
||||
**Current**: PROJECTS, EXPERIMENTS, RESPONSIBILITIES, PROCEDURES as expandable sections with items listed under each
|
||||
**New**: Collapsible groups with consistent pattern:
|
||||
- Each group: chevron-right (12px Lucide) + icon (18px Phosphor, bold) + label (13px/600) + count badge (pill)
|
||||
- **Projects** — folder-open icon (Phosphor)
|
||||
- **Experiments** — flask icon (Phosphor)
|
||||
- **Responsibilities** — target icon (Phosphor) — **currently not in sidebar**
|
||||
- **Procedures** — arrows-clockwise icon (Phosphor)
|
||||
- **People** — users icon (Phosphor) — **moved from filter to section group**
|
||||
- **Events** — calendar-blank icon (Phosphor) — **moved from filter to section group**
|
||||
- **Topics** — tag icon (Phosphor) — **currently at bottom, now integrated as a group**
|
||||
|
||||
Each group has:
|
||||
- Container: padding 4px 6px, border-bottom 1px (disabled in some), vertical layout, gap 2px
|
||||
- Header row: padding 6px 16px, corner-radius 4px, gap 8px, justify space-between
|
||||
- Badge: height 20px, bg `--secondary`, corner-radius 9999px, padding 0 6px
|
||||
|
||||
#### Removed from sidebar:
|
||||
- "Untagged" filter — not in new design
|
||||
- "Changes" filter — not in new design (modified files shown elsewhere)
|
||||
- "Trash" filter — not in new design
|
||||
- "People" as top-level filter — now a collapsible section group
|
||||
- "Events" as top-level filter — now a collapsible section group
|
||||
|
||||
#### Commit button:
|
||||
- Same concept but refined: padding 12px, border-top 1px
|
||||
- Button: fill `--primary`, corner-radius 6px, gap 6px, padding 8px 16px
|
||||
- Icon: git-commit-horizontal (Lucide 14px) in `--primary-foreground`
|
||||
- Text: "Commit & Push" (13px/500)
|
||||
- Badge: bg `#ffffff40`, corner-radius 9px, text `--white` 10px/600
|
||||
|
||||
### 5. NoteList Changes
|
||||
**Files**: `NoteList.tsx`
|
||||
|
||||
#### Header:
|
||||
- Current: title + count badge + create button
|
||||
- New: "Notes" title (14px/600) + search icon (16px Phosphor) + plus icon (16px Phosphor) — gap 12px
|
||||
- No separate count badge in header
|
||||
|
||||
#### Search:
|
||||
- Current: always-visible search input below header
|
||||
- New: search icon in header (search may toggle inline or use command palette)
|
||||
- **Remove the always-visible search input** or keep it hidden until search icon clicked
|
||||
|
||||
#### Type pills:
|
||||
- Current: rounded-full, border, `text-[11px]`, system font, "Projects 4" format
|
||||
- New: `IBM Plex Mono` font, 11px, ALL CAPS format "ALL 24" / "PROJECTS 4" / "NOTES 12" / "EVENTS 5"
|
||||
- Active pill: `bg: #4a9eff18` (blue tint), `border: 1px --primary`, text `--primary`
|
||||
- Inactive pill: `border: 1px --border`, text `--muted-foreground`
|
||||
- Pill padding: 2px 10px, corner-radius 9999px
|
||||
- Height: ~18px (compact)
|
||||
- Layout: absolute positioned at x offsets (12, 76, 166, 243) within 45px height container — effectively a horizontal scrollable row
|
||||
|
||||
#### Note items:
|
||||
- Selected: `bg: #2383E212` (very light blue), left accent bar 3px `#2383E2`, title 13px/600
|
||||
- Normal: border-bottom 1px `#E9E9E7`, title 13px/500, time 11px, snippet 12px/lh1.5
|
||||
- Padding: 10px 16px
|
||||
- **No type badge** on individual items (simplified)
|
||||
- **No status text** on items
|
||||
|
||||
### 6. Editor Content Area
|
||||
**⚠️ SKIP — Keep editor as-is. Editor changes in the design are NOT intentional.**
|
||||
|
||||
### 7. Inspector Refinements
|
||||
**Files**: `Inspector.tsx`
|
||||
|
||||
#### Header:
|
||||
- Current: collapsed toggle + title
|
||||
- New: sliders-horizontal icon (16px Phosphor) + "Properties" (13px/600, `--muted-foreground`) + X close button (16px Phosphor)
|
||||
- Height 45px, border-bottom 1px, padding 0 12px, gap 8px
|
||||
|
||||
#### Properties section:
|
||||
- Key-value rows: label (12px, muted) — value (12px, foreground), space-between
|
||||
- Status badge: colored bg (e.g., `--accent-green-light`) with colored text (e.g., `--accent-green`), rounded, padding 1px 6px, 10px font
|
||||
- "+ Add property" button: full-width, border 1px `--border`, corner-radius 6px, padding 6px 12px, centered text (12px, muted)
|
||||
|
||||
#### Relationships section:
|
||||
- Group title: 12px/600 foreground
|
||||
- Link buttons: full-width, bg `--accent-blue-light`, corner-radius 6px, padding 6px 10px, text `--primary` 12px/500, icon (tag/flask, Phosphor 14px, 0.5 opacity)
|
||||
- "+ Link existing" button: border 1px `--border`, corner-radius 6px, same padding
|
||||
|
||||
#### Backlinks:
|
||||
- Title: "Backlinks" 12px/600 + count 11px/500 muted
|
||||
- Items: text `--primary` 12px
|
||||
|
||||
#### History:
|
||||
- Title: "History" 12px/600
|
||||
- Items: left border 2px `--border`, padding-left 10px
|
||||
- Hash line: 11px foreground
|
||||
- Date line: 10px muted
|
||||
|
||||
### 8. Icon Library Change
|
||||
**Current**: Lucide React throughout
|
||||
**New**: **SF Symbols** (Apple's native icon set) for all new/redesigned icons. Use `sf-symbols-react` or inline SVGs extracted from SF Symbols app.
|
||||
|
||||
**Note**: The Pencil design used Phosphor as a placeholder — Luca's intent is SF Symbols throughout. Map Phosphor names to SF Symbol equivalents:
|
||||
- `magnifying-glass` → `magnifyingglass`
|
||||
- `star` → `star.fill`
|
||||
- `folder-open` → `folder`
|
||||
- `flask` → `flask`
|
||||
- `target` → `target`
|
||||
- `arrows-clockwise` → `arrow.clockwise`
|
||||
- `users` → `person.2`
|
||||
- `calendar-blank` → `calendar`
|
||||
- `tag` → `tag`
|
||||
- `plus` → `plus`
|
||||
- `columns` → `rectangle.split.2x1`
|
||||
- `arrows-out-simple` → `arrow.up.left.and.arrow.down.right`
|
||||
- `sliders-horizontal` → `slider.horizontal.3`
|
||||
- `cursor-text` → `character.cursor.ibeam`
|
||||
- `sparkle` → `sparkles`
|
||||
- `dots-three` → `ellipsis`
|
||||
- `git-branch` → `arrow.triangle.branch`
|
||||
- `gear` → `gearshape`
|
||||
|
||||
**Action**: Find the best approach for SF Symbols in React/Tauri (e.g., `sf-symbols-react`, SVG extraction, or native font)
|
||||
|
||||
---
|
||||
|
||||
## Implementation Phases
|
||||
|
||||
### Phase 1: Theme & Typography Updates
|
||||
**Scope**: CSS variables, fonts, colors — no structural changes
|
||||
**Files**: `src/index.css`, `index.html` (or font import)
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **Add IBM Plex Mono font** — add Google Fonts import or npm package
|
||||
2. **Update color variables in `index.css`**:
|
||||
- `:root` (light): `--primary: #155DFF`, `--accent-green: #00B38B`, `--accent-purple: #A932FF`, `--accent-blue: #155DFF`
|
||||
- `.dark`: same primary `#155DFF`, accent-green `#00B38B`, accent-purple `#A932FF`
|
||||
- Add new variables: `--accent-yellow`, `--accent-blue-light`, `--accent-green-light`, `--accent-purple-light`, `--accent-red-light`, `--accent-yellow-light` (both modes)
|
||||
- Update all `--ring`, `--sidebar-primary`, `--sidebar-ring` to match new primary
|
||||
- Update app-specific vars: `--accent-blue`, `--accent-green`, `--accent-purple`, `--accent-blue-bg` etc.
|
||||
3. **Update `theme.json`**:
|
||||
- `headings.h2.fontSize`: 27 → 24
|
||||
- `editor.paddingHorizontal`: 40 → 64
|
||||
- `editor.paddingVertical`: 20 → 32
|
||||
4. **Install Phosphor Icons**: `pnpm add @phosphor-icons/react`
|
||||
|
||||
### Phase 2: Sidebar Restructure
|
||||
**Scope**: Sidebar layout, navigation, icons
|
||||
**Files**: `src/components/Sidebar.tsx`
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **Header**: Replace theme toggle with search icon (Phosphor `MagnifyingGlass`) + gear icon. Move theme toggle to status bar settings or a menu.
|
||||
2. **Add search input** below header: Phosphor magnifying-glass prefix, 13px, bg `--secondary`, border-radius 6px
|
||||
3. **Top nav**: Reduce to "All Notes" (Phosphor `FileText` 16px) and "Favorites" (Phosphor `Star` 16px), each with count badge pill
|
||||
4. **Section groups**: Restructure to new pattern with:
|
||||
- Consistent chevron + Phosphor icon (18px, bold) + label (13px/600) + count badge
|
||||
- Icons: `FolderOpen` (Projects), `Flask` (Experiments), `Target` (Responsibilities), `ArrowsClockwise` (Procedures), `Users` (People), `CalendarBlank` (Events), `Tag` (Topics)
|
||||
- Move People and Events from filters to section groups
|
||||
- Remove "Untagged", "Changes", "Trash" from nav
|
||||
5. **Commit button**: Update styling to match design (padding, badge style)
|
||||
6. **Remove** People/Events/Changes/Trash/Untagged filter items
|
||||
|
||||
### Phase 3: NoteList Updates
|
||||
**Scope**: Header, type pills, note item styling
|
||||
**Files**: `src/components/NoteList.tsx`
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **Header**: Replace badge + create button with search icon (Phosphor `MagnifyingGlass`) + plus icon (Phosphor `Plus`), gap 12px
|
||||
2. **Remove or hide** the always-visible search input — add toggle behavior on search icon click
|
||||
3. **Type pills**: Switch to IBM Plex Mono, ALL CAPS format ("ALL 24", "PROJECTS 4"), update active/inactive styles per design
|
||||
4. **Selected note**: Update to `bg: #2383E212`, left accent 3px `#2383E2` (update to new primary), remove type badge and status text from items
|
||||
5. **Note items**: Adjust padding to 10px 16px, snippet line-height 1.5, remove type/status badges from individual items
|
||||
|
||||
### Phase 4: Editor — Tab Bar & Info Bar
|
||||
**Scope**: New sub-components within Editor
|
||||
**Files**: `src/components/Editor.tsx`, `src/components/Editor.css`
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **Tab Bar** (top of editor):
|
||||
- 45px, bg `--sidebar`, border-bottom
|
||||
- Active tab: bg `--background`, border-right, 12px/500 text, X close button
|
||||
- Inactive tab: muted text, hidden X (show on hover)
|
||||
- Right controls: Plus + Split (disabled) + Expand (disabled) — Phosphor icons
|
||||
2. **Info Bar** (below tab bar):
|
||||
- 45px, bg `--background`, border-bottom
|
||||
- Left: breadcrumb `Type › Title · N words · M` (M in accent-yellow when modified)
|
||||
- Right: icon buttons (magnifying-glass functional, git-branch/cursor-text/sparkle/dots-three as **disabled placeholders** with `opacity: 0.4, cursor: not-allowed`)
|
||||
3. **Adjust editor content padding** to 32px 64px per design
|
||||
|
||||
### Phase 5: Status Bar + Inspector Polish
|
||||
**Scope**: New StatusBar component, Inspector refinements
|
||||
**Files**: New `src/components/StatusBar.tsx`, `App.tsx`, `App.css`, `src/components/Inspector.tsx`
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **StatusBar.tsx** (new component):
|
||||
- 30px fixed at bottom, bg `--sidebar`, border-top 1px
|
||||
- Left: version + branch + sync status
|
||||
- Right: AI model + notes count + bell (disabled placeholder) + settings (disabled placeholder)
|
||||
- All Lucide icons 13-14px
|
||||
2. **App.tsx / App.css**: Add StatusBar below main content, wrap layout in vertical flex (main panels + status bar)
|
||||
3. **Inspector refinements**:
|
||||
- Header: Phosphor `SlidersHorizontal` icon + "Properties" label + Phosphor `X` close
|
||||
- Status badge: use `--accent-*-light` bg colors with `--accent-*` text
|
||||
- "+ Add property" and "+ Link existing" buttons: match border/radius/padding from design
|
||||
- History items: left-border 2px timeline style, 10px date text
|
||||
|
||||
### Phase 6: Icon Migration & Cleanup
|
||||
**Scope**: Replace Lucide icons with Phosphor where specified
|
||||
**Files**: All components
|
||||
**Estimated effort**: 1 Claude Code session
|
||||
|
||||
1. **Audit all icon usage** across components
|
||||
2. **Replace with Phosphor** where the design specifies (sidebar nav, section icons, NoteList header, editor toolbar icons, inspector)
|
||||
3. **Keep Lucide** for: chevrons, X/close, tab close, status bar icons, git-commit-horizontal
|
||||
4. **Remove unused Lucide imports**
|
||||
5. **Visual verification**: Run `pnpm dev` and compare with `ui-design-screenshot.png`
|
||||
|
||||
---
|
||||
|
||||
## New Features as Disabled Placeholders
|
||||
|
||||
These buttons/icons appear in the design but don't have backend functionality yet. Add them as disabled UI elements:
|
||||
|
||||
| Element | Location | Icon | Notes |
|
||||
|---|---|---|---|
|
||||
| Split view | Tab bar controls | Phosphor `Columns` | `opacity: 0.4, cursor: not-allowed, title="Coming soon"` |
|
||||
| Expand/focus | Tab bar controls | Phosphor `ArrowsOutSimple` | Same |
|
||||
| Git branch viewer | Info bar right | Phosphor `GitBranch` | Same |
|
||||
| Focus mode | Info bar right | Phosphor `CursorText` | Same |
|
||||
| AI assist | Info bar right | Phosphor `Sparkle` | Same |
|
||||
| More options | Info bar right | Phosphor `DotsThree` | Same |
|
||||
| Bell/notifications | Status bar right | Lucide `Bell` | Same |
|
||||
| Settings | Status bar right | Lucide `Settings` | Same |
|
||||
| Gear/settings | Sidebar header | Phosphor `Gear` | Same |
|
||||
|
||||
---
|
||||
|
||||
## Files Inventory
|
||||
|
||||
| File | Changes |
|
||||
|---|---|
|
||||
| `src/index.css` | Color variables, font import |
|
||||
| `src/theme.json` | H2 size, editor padding |
|
||||
| `index.html` | IBM Plex Mono font link (if using CDN) |
|
||||
| `package.json` | Add `@phosphor-icons/react` |
|
||||
| `src/App.tsx` | Add StatusBar, adjust layout |
|
||||
| `src/App.css` | Vertical flex for status bar |
|
||||
| `src/components/Sidebar.tsx` | Major restructure |
|
||||
| `src/components/NoteList.tsx` | Header, pills, item styling |
|
||||
| `src/components/Editor.tsx` | Add TabBar, InfoBar sections |
|
||||
| `src/components/Editor.css` | Tab/info bar styles |
|
||||
| `src/components/Inspector.tsx` | Header, badges, history styling |
|
||||
| `src/components/StatusBar.tsx` | **NEW** |
|
||||
55
SECURITY.md
55
SECURITY.md
@@ -1,55 +0,0 @@
|
||||
# Security Policy
|
||||
|
||||
Thanks for helping keep Tolaria safe.
|
||||
|
||||
If you believe you have found a security vulnerability, **please do not open a public GitHub issue**. Report it privately instead.
|
||||
|
||||
## Supported versions
|
||||
|
||||
We currently support security fixes for:
|
||||
|
||||
| Version | Supported |
|
||||
| --- | --- |
|
||||
| Latest stable release | ✅ |
|
||||
| `main` branch | Best effort |
|
||||
| Older releases / prereleases | ❌ |
|
||||
|
||||
## Reporting a vulnerability
|
||||
|
||||
Please email **luca@refactoring.club** with the subject line **`[Tolaria Security]`**.
|
||||
|
||||
Include as much of the following as you can:
|
||||
|
||||
- a short description of the issue
|
||||
- reproduction steps or a proof of concept
|
||||
- affected version / commit, if known
|
||||
- impact assessment
|
||||
- any suggested mitigation
|
||||
|
||||
If the issue involves sensitive user data, credentials, or a working exploit, keep the report private and do not post details publicly.
|
||||
|
||||
## What to expect
|
||||
|
||||
We will try to:
|
||||
|
||||
- acknowledge receipt within a few business days
|
||||
- reproduce and assess the report
|
||||
- work on a fix or mitigation if the issue is valid
|
||||
- coordinate public disclosure after users have had a reasonable chance to update
|
||||
|
||||
## Disclosure guidelines
|
||||
|
||||
Please give us a reasonable amount of time to investigate and ship a fix before publishing details.
|
||||
|
||||
We appreciate responsible disclosure and good-faith research.
|
||||
|
||||
## Out of scope
|
||||
|
||||
The following are generally out of scope unless they demonstrate a real security impact:
|
||||
|
||||
- missing best-practice headers or hardening with no practical exploit
|
||||
- self-XSS or editor behavior that requires unrealistic user actions
|
||||
- reports that only affect unsupported old builds
|
||||
- purely theoretical issues with no plausible attack path
|
||||
|
||||
If you are unsure whether something qualifies, please still report it privately.
|
||||
130
SF-SYMBOLS-MIGRATION.md
Normal file
130
SF-SYMBOLS-MIGRATION.md
Normal file
@@ -0,0 +1,130 @@
|
||||
# SF Symbols Migration Plan
|
||||
|
||||
> Current state: All icons use either **Phosphor Icons** (`@phosphor-icons/react`) or **Lucide React** (`lucide-react`). This document maps every icon to its SF Symbol equivalent for future migration.
|
||||
|
||||
---
|
||||
|
||||
## Icon Audit Summary (Phase 6 — 2026-02-17)
|
||||
|
||||
| Category | Count | Files | Status |
|
||||
|---|---|---|---|
|
||||
| Phosphor icons | 22 | `Sidebar.tsx`, `Editor.tsx`, `NoteList.tsx`, `Inspector.tsx` | All used, migrate to SF Symbols |
|
||||
| Phosphor types | 1 (`IconProps`) | `Sidebar.tsx` | Type only — replace when migrating |
|
||||
| Lucide (app components) | 4 | `Sidebar.tsx`, `Editor.tsx` | Evaluate per-icon |
|
||||
| Lucide (StatusBar) | 7 | `StatusBar.tsx` | Keep Lucide per design |
|
||||
| Lucide (shadcn/ui) | 7 | `ui/select.tsx`, `ui/dropdown-menu.tsx`, `ui/dialog.tsx` | Keep Lucide — library internals |
|
||||
| **Total icon imports** | **41** | **8 files** | **0 unused** |
|
||||
|
||||
**Unused imports found**: None. All icon imports are actively used in JSX.
|
||||
|
||||
---
|
||||
|
||||
## Phosphor Icons — Current Usage
|
||||
|
||||
These are the primary UI icons introduced during the redesign. All should migrate to SF Symbols.
|
||||
|
||||
| Phosphor Icon | SF Symbol Equivalent | File(s) | Usage |
|
||||
|---|---|---|---|
|
||||
| `MagnifyingGlass` | `magnifyingglass` | `Sidebar.tsx`, `NoteList.tsx`, `Editor.tsx` | Search icon in sidebar header, note list header, editor info bar |
|
||||
| `Gear` | `gearshape` | `Sidebar.tsx` | Settings icon in sidebar header (disabled placeholder) |
|
||||
| `FileText` | `doc.text` | `Sidebar.tsx` | "All Notes" nav item icon |
|
||||
| `Star` | `star.fill` | `Sidebar.tsx` | "Favorites" nav item icon |
|
||||
| `FolderOpen` | `folder` | `Sidebar.tsx` | "Projects" section group icon |
|
||||
| `Flask` | `flask` | `Sidebar.tsx` | "Experiments" section group icon |
|
||||
| `Target` | `target` | `Sidebar.tsx` | "Responsibilities" section group icon |
|
||||
| `ArrowsClockwise` | `arrow.clockwise` | `Sidebar.tsx` | "Procedures" section group icon |
|
||||
| `Users` | `person.2` | `Sidebar.tsx` | "People" section group icon |
|
||||
| `CalendarBlank` | `calendar` | `Sidebar.tsx` | "Events" section group icon |
|
||||
| `Tag` | `tag` | `Sidebar.tsx` | "Topics" section group icon |
|
||||
| `TagSimple` | `tag` | `Sidebar.tsx` | "Untagged" nav item icon |
|
||||
| `Trash` | `trash` | `Sidebar.tsx` | "Trash" nav item icon |
|
||||
| `Plus` | `plus` | `NoteList.tsx`, `Editor.tsx` | Create note button, new tab button |
|
||||
| `Columns` | `rectangle.split.2x1` | `Editor.tsx` | Split view button (disabled placeholder) |
|
||||
| `ArrowsOutSimple` | `arrow.up.left.and.arrow.down.right` | `Editor.tsx` | Expand/focus button (disabled placeholder) |
|
||||
| `GitBranch` | `arrow.triangle.branch` | `Editor.tsx` | Version history button (disabled placeholder) |
|
||||
| `CursorText` | `character.cursor.ibeam` | `Editor.tsx` | Focus mode button (disabled placeholder) |
|
||||
| `Sparkle` | `sparkles` | `Editor.tsx` | AI assist button (disabled placeholder) |
|
||||
| `DotsThree` | `ellipsis` | `Editor.tsx` | More options button (disabled placeholder) |
|
||||
| `SlidersHorizontal` | `slider.horizontal.3` | `Inspector.tsx` | Inspector header icon |
|
||||
| `X` (Phosphor) | `xmark` | `Inspector.tsx` | Inspector close button |
|
||||
| `IconProps` (type) | n/a | `Sidebar.tsx` | TypeScript type for icon component props |
|
||||
|
||||
---
|
||||
|
||||
## Lucide React — Current Usage
|
||||
|
||||
### App Components
|
||||
|
||||
These Lucide icons are used in custom app components. Some may migrate to SF Symbols; others are kept for specific reasons.
|
||||
|
||||
| Lucide Icon | SF Symbol Equivalent | File | Usage | Migration Notes |
|
||||
|---|---|---|---|---|
|
||||
| `ChevronRight` | `chevron.right` | `Sidebar.tsx` | Section group expand chevron | Keep Lucide or migrate — small utility icon |
|
||||
| `ChevronDown` | `chevron.down` | `Sidebar.tsx` | Section group collapse chevron | Keep Lucide or migrate — small utility icon |
|
||||
| `GitCommitHorizontal` | `circle.dotted` | `Sidebar.tsx` | Commit & Push button icon | Keep Lucide or migrate |
|
||||
| `X` (Lucide) | `xmark` | `Editor.tsx` | Tab close button | Keep Lucide or migrate |
|
||||
| `Package` | `shippingbox` | `StatusBar.tsx` | App version indicator | Keep Lucide — status bar uses Lucide per design |
|
||||
| `GitBranch` (Lucide) | `arrow.triangle.branch` | `StatusBar.tsx` | Git branch indicator | Keep Lucide — status bar uses Lucide per design |
|
||||
| `RefreshCw` | `arrow.clockwise` | `StatusBar.tsx` | Sync status indicator | Keep Lucide — status bar uses Lucide per design |
|
||||
| `Sparkles` (Lucide) | `sparkles` | `StatusBar.tsx` | AI model indicator | Keep Lucide — status bar uses Lucide per design |
|
||||
| `FileText` (Lucide) | `doc.text` | `StatusBar.tsx` | Notes count indicator | Keep Lucide — status bar uses Lucide per design |
|
||||
| `Bell` | `bell` | `StatusBar.tsx` | Notifications (disabled placeholder) | Keep Lucide — status bar uses Lucide per design |
|
||||
| `Settings` | `gearshape` | `StatusBar.tsx` | Settings (disabled placeholder) | Keep Lucide — status bar uses Lucide per design |
|
||||
|
||||
### shadcn/ui Components (Keep Lucide)
|
||||
|
||||
These are standard shadcn/ui library components that use Lucide as their built-in icon system. These should **not** be migrated — they are part of the component library's internal implementation.
|
||||
|
||||
| Lucide Icon | File | Usage |
|
||||
|---|---|---|
|
||||
| `CheckIcon` | `ui/select.tsx` | Selected item indicator |
|
||||
| `ChevronDownIcon` | `ui/select.tsx` | Select trigger arrow, scroll-down button |
|
||||
| `ChevronUpIcon` | `ui/select.tsx` | Scroll-up button |
|
||||
| `CheckIcon` | `ui/dropdown-menu.tsx` | Checkbox item indicator |
|
||||
| `ChevronRightIcon` | `ui/dropdown-menu.tsx` | Sub-menu trigger arrow |
|
||||
| `CircleIcon` | `ui/dropdown-menu.tsx` | Radio item indicator |
|
||||
| `XIcon` | `ui/dialog.tsx` | Dialog close button |
|
||||
|
||||
---
|
||||
|
||||
## Approach Options for SF Symbols in React/Tauri
|
||||
|
||||
### Option 1: `sf-symbols-react` npm package
|
||||
- **Pros**: Drop-in React components, familiar API (`<SFSymbol name="magnifyingglass" />`)
|
||||
- **Cons**: Third-party package, may lag behind Apple's symbol updates, limited weight/rendering options
|
||||
- **Status**: Check npm for current maintenance state before adopting
|
||||
|
||||
### Option 2: SVG extraction from SF Symbols app
|
||||
- **Pros**: Exact Apple-quality vectors, no runtime dependency, full control over styling
|
||||
- **Cons**: Manual export process per icon, potential licensing concerns (SF Symbols license restricts use to Apple platforms), need to manage SVG sprite or individual files
|
||||
- **How**: Export SVGs from the SF Symbols macOS app, create a `src/icons/` directory with individual SVG components or a sprite sheet
|
||||
|
||||
### Option 3: Apple's SF Symbols font (native approach via Tauri)
|
||||
- **Pros**: Pixel-perfect on macOS, automatic weight matching, system-native feel
|
||||
- **Cons**: Only works on macOS (not cross-platform), requires Tauri native font access, won't render in browser dev mode
|
||||
- **How**: Use CSS `font-family: "SF Pro"` with Unicode code points, or invoke native APIs from Tauri's Rust backend
|
||||
|
||||
### Option 4: Hybrid — SVG in browser, native in Tauri
|
||||
- **Pros**: Best of both worlds — browser dev mode uses SVGs, production Tauri build uses native SF Symbols
|
||||
- **Cons**: More complex build setup, need to maintain two icon systems
|
||||
- **How**: Build an `<Icon>` wrapper component that checks `window.__TAURI__` and renders native or SVG accordingly
|
||||
|
||||
### Recommendation
|
||||
**Option 2 (SVG extraction)** is the most practical starting point:
|
||||
- Laputa is a macOS-only Tauri app, so SF Symbols licensing applies (Apple platform)
|
||||
- SVGs work in both browser dev mode and Tauri production
|
||||
- No third-party dependency to maintain
|
||||
- Can later upgrade to Option 4 (hybrid native) for perfect macOS integration
|
||||
|
||||
---
|
||||
|
||||
## Migration Steps (Future)
|
||||
|
||||
1. Export all needed SF Symbol SVGs from the SF Symbols macOS app
|
||||
2. Create `src/icons/sf-symbols/` with a React component per icon (or a single sprite)
|
||||
3. Build a thin `<SFIcon name="..." size={} />` wrapper for consistent API
|
||||
4. Replace Phosphor imports file-by-file (Sidebar → NoteList → Editor → Inspector)
|
||||
5. Decide whether to also replace Lucide in StatusBar and utility icons (chevrons, X)
|
||||
6. Keep Lucide in shadcn/ui components — do not modify those
|
||||
7. Once all Phosphor icons are replaced, remove `@phosphor-icons/react` from dependencies
|
||||
8. Run `pnpm build` and visually verify all icons render correctly
|
||||
53
VISION.md
Normal file
53
VISION.md
Normal file
@@ -0,0 +1,53 @@
|
||||
# Laputa — Vision
|
||||
|
||||
Laputa is a personal knowledge base where humans and AI agents collaborate as equals.
|
||||
|
||||
---
|
||||
|
||||
## Core principles
|
||||
|
||||
### 1. The vault is the source of truth
|
||||
Everything lives in the vault as plain text files. Notes, relations, configuration, instructions — all Markdown with YAML frontmatter. No proprietary database, no hidden state. If you can open a terminal, you can read your vault. If you can write Markdown, you can modify it.
|
||||
|
||||
### 2. Vault-native configuration
|
||||
Laputa configures itself through files inside the vault — the same files you write and read every day. There is no separate "settings app" or admin panel. If you want to change a theme, you edit a note. If you want to give instructions to an AI agent, you write a note. If you want to define a template, you create a note.
|
||||
|
||||
This applies to:
|
||||
- **`_themes/`** — themes as notes with a YAML block in the body. Edit `_themes/dark.md`, see the colors change in real time.
|
||||
- **`AGENTS.md`** — instructions for AI agents. Write what you want them to know about your vault in plain language. They read it before acting.
|
||||
- **`_templates/`** — note templates per type. Create `_templates/event.md` and every new event starts from that structure.
|
||||
- **`_procedures/`** — recurring tasks as notes with a `schedule` frontmatter field.
|
||||
|
||||
The principle: **if it can be expressed in frontmatter + Markdown, it doesn't need a UI**.
|
||||
|
||||
### 3. Structure through types, not folders
|
||||
Notes have a `type` field. Types determine folders, icons, and colors — but the structure is defined by the data, not the filesystem hierarchy. You can query "all events in February" without knowing anything about folder layout.
|
||||
|
||||
Relations between notes are expressed as frontmatter arrays: `people: [Marco, Sara]`. A wikilink `[[Marco]]` in the body navigates to the person note. The graph emerges from the data, not from a separate graph database.
|
||||
|
||||
### 4. The file is the interface
|
||||
You can use Laputa's UI, or you can open a terminal. Or a text editor. Or Claude Code. They all operate on the same files. There is no difference between "the app" and "the vault" — the vault is the app.
|
||||
|
||||
This is why Laputa has an MCP server: external agents get the same tools the in-app AI panel uses. The interface is a convenience, not a requirement.
|
||||
|
||||
### 5. Humans and AI as collaborators
|
||||
Pulse — the activity feed — shows the history of the vault without distinguishing between human commits and agent commits. That's intentional. Laputa is designed to be a space where you and your AI agents work together, each contributing to the same knowledge base.
|
||||
|
||||
The AI doesn't have a separate workspace. It works in yours.
|
||||
|
||||
---
|
||||
|
||||
## What Laputa is not
|
||||
|
||||
- Not a todo app (though you can use it as one)
|
||||
- Not a note-taking app that syncs to the cloud (the vault is yours, sync however you want — git, iCloud, rsync)
|
||||
- Not a replacement for a terminal (power users will use both)
|
||||
- Not trying to abstract away git (git is a feature, not an implementation detail)
|
||||
|
||||
---
|
||||
|
||||
## The long game
|
||||
|
||||
A vault that grows with you for years. Events, people, projects, thoughts — all interconnected, all version-controlled, all accessible to any tool that can read a file.
|
||||
|
||||
Ten years from now, your vault should still be readable. Plain text is forever.
|
||||
BIN
__pycache__/select_demo_notes.cpython-310.pyc
Normal file
BIN
__pycache__/select_demo_notes.cpython-310.pyc
Normal file
Binary file not shown.
41
analyze_broken_links.py
Normal file
41
analyze_broken_links.py
Normal file
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Analyze which broken links are to existing vs non-existent notes."""
|
||||
|
||||
import sys
|
||||
sys.path.insert(0, '/Users/luca/Workspace/laputa-app')
|
||||
from select_demo_notes import build_graph, select_notes, LAPUTA_ROOT
|
||||
|
||||
nodes, link_lookup = build_graph()
|
||||
selected = select_notes(nodes, link_lookup, target_count=1000)
|
||||
|
||||
print("\n🔍 Analyzing broken links...")
|
||||
|
||||
# Count links by type
|
||||
total_outlinks = 0
|
||||
resolved = 0
|
||||
unresolved_but_exists = 0
|
||||
unresolved_not_exists = 0
|
||||
|
||||
for path in selected:
|
||||
node = nodes[path]
|
||||
for link_ref in node['outlinks']:
|
||||
total_outlinks += 1
|
||||
|
||||
if link_ref in link_lookup:
|
||||
target = link_lookup[link_ref]
|
||||
if target in selected:
|
||||
resolved += 1
|
||||
else:
|
||||
# Exists but not in selection
|
||||
unresolved_but_exists += 1
|
||||
else:
|
||||
# Doesn't exist at all
|
||||
unresolved_not_exists += 1
|
||||
|
||||
print(f"Total outlinks: {total_outlinks}")
|
||||
print(f" Resolved (in selection): {resolved} ({resolved/total_outlinks*100:.1f}%)")
|
||||
print(f" Unresolved but note exists: {unresolved_but_exists} ({unresolved_but_exists/total_outlinks*100:.1f}%)")
|
||||
print(f" Unresolved - note doesn't exist: {unresolved_not_exists} ({unresolved_not_exists/total_outlinks*100:.1f}%)")
|
||||
|
||||
print(f"\nIf we include ALL existing notes (not just selected):")
|
||||
print(f" Max possible resolution: {(resolved + unresolved_but_exists)/total_outlinks*100:.1f}%")
|
||||
41
apps/mobile/.gitignore
vendored
41
apps/mobile/.gitignore
vendored
@@ -1,41 +0,0 @@
|
||||
# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# Expo
|
||||
.expo/
|
||||
dist/
|
||||
web-build/
|
||||
expo-env.d.ts
|
||||
|
||||
# Native
|
||||
.kotlin/
|
||||
*.orig.*
|
||||
*.jks
|
||||
*.p8
|
||||
*.p12
|
||||
*.key
|
||||
*.mobileprovision
|
||||
|
||||
# Metro
|
||||
.metro-health-check*
|
||||
|
||||
# debug
|
||||
npm-debug.*
|
||||
yarn-debug.*
|
||||
yarn-error.*
|
||||
|
||||
# macOS
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
|
||||
# generated native folders
|
||||
/ios
|
||||
/android
|
||||
@@ -1,19 +0,0 @@
|
||||
import { StatusBar } from 'expo-status-bar'
|
||||
import { StyleSheet } from 'react-native'
|
||||
import { GestureHandlerRootView } from 'react-native-gesture-handler'
|
||||
import { MobileApp } from './src/MobileApp'
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<GestureHandlerRootView style={styles.root}>
|
||||
<MobileApp />
|
||||
<StatusBar style="auto" />
|
||||
</GestureHandlerRootView>
|
||||
)
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: {
|
||||
flex: 1,
|
||||
},
|
||||
})
|
||||
@@ -1,37 +0,0 @@
|
||||
{
|
||||
"expo": {
|
||||
"name": "Tolaria",
|
||||
"slug": "tolaria-mobile",
|
||||
"scheme": "tolaria",
|
||||
"version": "0.1.0",
|
||||
"orientation": "default",
|
||||
"icon": "./assets/icon.png",
|
||||
"userInterfaceStyle": "light",
|
||||
"newArchEnabled": true,
|
||||
"splash": {
|
||||
"image": "./assets/splash-icon.png",
|
||||
"resizeMode": "contain",
|
||||
"backgroundColor": "#ffffff"
|
||||
},
|
||||
"ios": {
|
||||
"bundleIdentifier": "com.tolaria.mobile.dev",
|
||||
"supportsTablet": true
|
||||
},
|
||||
"android": {
|
||||
"package": "com.tolaria.mobile.dev",
|
||||
"adaptiveIcon": {
|
||||
"foregroundImage": "./assets/adaptive-icon.png",
|
||||
"backgroundColor": "#ffffff"
|
||||
},
|
||||
"edgeToEdgeEnabled": true,
|
||||
"predictiveBackGestureEnabled": false
|
||||
},
|
||||
"web": {
|
||||
"favicon": "./assets/favicon.png"
|
||||
},
|
||||
"plugins": [
|
||||
"expo-secure-store",
|
||||
"expo-web-browser"
|
||||
]
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 1.4 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 22 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 17 KiB |
@@ -1,9 +0,0 @@
|
||||
import 'react-native-gesture-handler'
|
||||
import { registerRootComponent } from 'expo';
|
||||
|
||||
import App from './App';
|
||||
|
||||
// registerRootComponent calls AppRegistry.registerComponent('main', () => App);
|
||||
// It also ensures that whether you load the app in Expo Go or in a native build,
|
||||
// the environment is set up appropriately
|
||||
registerRootComponent(App);
|
||||
@@ -1,50 +0,0 @@
|
||||
const path = require('node:path')
|
||||
const { getDefaultConfig } = require('expo/metro-config')
|
||||
|
||||
const projectRoot = __dirname
|
||||
const workspaceRoot = path.resolve(projectRoot, '../..')
|
||||
const config = getDefaultConfig(projectRoot)
|
||||
const mobileNodeModules = path.resolve(projectRoot, 'node_modules')
|
||||
const workspaceNodeModules = path.resolve(workspaceRoot, 'node_modules')
|
||||
const mobileReactRoot = path.resolve(mobileNodeModules, 'react')
|
||||
const mobileReactDomRoot = path.resolve(mobileNodeModules, 'react-dom')
|
||||
|
||||
config.watchFolders = [workspaceRoot]
|
||||
config.resolver.nodeModulesPaths = [
|
||||
mobileNodeModules,
|
||||
workspaceNodeModules,
|
||||
]
|
||||
config.resolver.extraNodeModules = {
|
||||
...config.resolver.extraNodeModules,
|
||||
react: mobileReactRoot,
|
||||
'react-dom': mobileReactDomRoot,
|
||||
'react-native': path.resolve(workspaceNodeModules, 'react-native'),
|
||||
}
|
||||
config.resolver.resolveRequest = (context, moduleName, platform) => {
|
||||
if (moduleName === 'react' || moduleName.startsWith('react/')) {
|
||||
return context.resolveRequest(
|
||||
{ ...context, originModulePath: path.join(mobileReactRoot, 'index.js') },
|
||||
moduleName,
|
||||
platform,
|
||||
)
|
||||
}
|
||||
|
||||
if (moduleName === 'react-dom' || moduleName.startsWith('react-dom/')) {
|
||||
return context.resolveRequest(
|
||||
{ ...context, originModulePath: path.join(mobileReactDomRoot, 'index.js') },
|
||||
moduleName,
|
||||
platform,
|
||||
)
|
||||
}
|
||||
|
||||
if (moduleName === 'isomorphic-git') {
|
||||
return {
|
||||
filePath: path.resolve(workspaceNodeModules, 'isomorphic-git/index.js'),
|
||||
type: 'sourceFile',
|
||||
}
|
||||
}
|
||||
|
||||
return context.resolveRequest(context, moduleName, platform)
|
||||
}
|
||||
|
||||
module.exports = config
|
||||
@@ -1,44 +0,0 @@
|
||||
{
|
||||
"name": "@tolaria/mobile",
|
||||
"version": "0.1.0",
|
||||
"main": "index.ts",
|
||||
"scripts": {
|
||||
"start": "expo start",
|
||||
"start:dev-client": "expo start --dev-client",
|
||||
"android": "expo start --android",
|
||||
"ios": "expo start --ios",
|
||||
"ios:dev-client": "expo run:ios --port 8091",
|
||||
"test": "vitest run --config vitest.config.ts",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json",
|
||||
"web": "expo start --web"
|
||||
},
|
||||
"dependencies": {
|
||||
"@10play/tentap-editor": "^1.0.1",
|
||||
"@tolaria/markdown": "workspace:*",
|
||||
"buffer": "^6.0.3",
|
||||
"expo": "~54.0.34",
|
||||
"expo-auth-session": "~7.0.11",
|
||||
"expo-dev-client": "~6.0.21",
|
||||
"expo-file-system": "19.0.22",
|
||||
"expo-modules-core": "3.0.30",
|
||||
"expo-secure-store": "~15.0.8",
|
||||
"expo-status-bar": "~3.0.9",
|
||||
"expo-web-browser": "~15.0.11",
|
||||
"isomorphic-git": "^1.37.6",
|
||||
"phosphor-react-native": "^3.0.6",
|
||||
"react": "19.1.0",
|
||||
"react-dom": "19.1.0",
|
||||
"react-native": "0.81.5",
|
||||
"react-native-gesture-handler": "~2.28.0",
|
||||
"react-native-safe-area-context": "^5.6.2",
|
||||
"react-native-svg": "^15.12.1",
|
||||
"react-native-webview": "13.15.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "~19.1.17",
|
||||
"@types/react-dom": "~19.1.11",
|
||||
"typescript": "~5.9.3",
|
||||
"vitest": "^4.0.18"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -1,148 +0,0 @@
|
||||
import { CaretLeft, GearSix, PaperPlaneTilt, Robot } from 'phosphor-react-native'
|
||||
import { useState } from 'react'
|
||||
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import type { MobileAiProvider } from './mobileAiSettings'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobileAiPanel({
|
||||
note,
|
||||
onClose,
|
||||
onOpenSettings,
|
||||
onSendPrompt,
|
||||
provider,
|
||||
}: {
|
||||
note: MobileNote
|
||||
onClose?: () => void
|
||||
onOpenSettings: () => void
|
||||
onSendPrompt: (prompt: string, provider: MobileAiProvider) => Promise<string>
|
||||
provider: MobileAiProvider | null
|
||||
}) {
|
||||
const [failed, setFailed] = useState(false)
|
||||
const [isSending, setIsSending] = useState(false)
|
||||
const [prompt, setPrompt] = useState('')
|
||||
const [response, setResponse] = useState('')
|
||||
|
||||
const sendPrompt = () => {
|
||||
if (!provider || prompt.trim().length === 0) return
|
||||
|
||||
setFailed(false)
|
||||
setIsSending(true)
|
||||
void onSendPrompt(prompt, provider)
|
||||
.then(setResponse)
|
||||
.catch(() => setFailed(true))
|
||||
.finally(() => setIsSending(false))
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.properties}>
|
||||
<AiToolbar onClose={onClose} onOpenSettings={onOpenSettings} />
|
||||
{provider ? (
|
||||
<AiChatSurface
|
||||
failed={failed}
|
||||
isSending={isSending}
|
||||
note={note}
|
||||
onChangePrompt={setPrompt}
|
||||
onSend={sendPrompt}
|
||||
prompt={prompt}
|
||||
provider={provider}
|
||||
response={response}
|
||||
/>
|
||||
) : (
|
||||
<AiEmptyState onOpenSettings={onOpenSettings} />
|
||||
)}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function AiToolbar({
|
||||
onClose,
|
||||
onOpenSettings,
|
||||
}: {
|
||||
onClose?: () => void
|
||||
onOpenSettings: () => void
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.toolbar}>
|
||||
<Text style={styles.propertiesTitle}>AI</Text>
|
||||
<View style={styles.toolbarSpacer} />
|
||||
<Pressable onPress={onOpenSettings} style={({ pressed }) => [styles.iconButton, pressed ? styles.pressed : null]}>
|
||||
<GearSix size={23} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
{onClose ? (
|
||||
<Pressable onPress={onClose} style={({ pressed }) => [styles.iconButton, pressed ? styles.pressed : null]}>
|
||||
<CaretLeft size={23} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function AiEmptyState({ onOpenSettings }: { onOpenSettings: () => void }) {
|
||||
return (
|
||||
<View style={styles.aiEmptyState}>
|
||||
<Robot color={colors.iconMuted} size={26} />
|
||||
<Text style={styles.aiEmptyTitle}>No API model configured</Text>
|
||||
<Text style={styles.aiEmptyDescription}>Add an API model in Settings before using the AI panel.</Text>
|
||||
<Pressable onPress={onOpenSettings} style={({ pressed }) => [styles.aiSettingsButton, pressed ? styles.pressed : null]}>
|
||||
<GearSix color="#ffffff" size={17} />
|
||||
<Text style={styles.aiSettingsButtonText}>Open Settings</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function AiChatSurface({
|
||||
failed,
|
||||
isSending,
|
||||
note,
|
||||
onChangePrompt,
|
||||
onSend,
|
||||
prompt,
|
||||
provider,
|
||||
response,
|
||||
}: {
|
||||
failed: boolean
|
||||
isSending: boolean
|
||||
note: MobileNote
|
||||
onChangePrompt: (value: string) => void
|
||||
onSend: () => void
|
||||
prompt: string
|
||||
provider: MobileAiProvider
|
||||
response: string
|
||||
}) {
|
||||
const canSend = prompt.trim().length > 0 && !isSending
|
||||
|
||||
return (
|
||||
<ScrollView contentContainerStyle={styles.aiContent}>
|
||||
<View style={styles.aiContextCard}>
|
||||
<Text style={styles.aiContextTitle}>{provider.name} · {provider.modelId}</Text>
|
||||
<Text numberOfLines={2} style={styles.aiContextDetail}>{note.title}</Text>
|
||||
</View>
|
||||
{response ? <Text style={styles.aiResponse}>{response}</Text> : <Text style={styles.aiEmptyDescription}>Ask about the active note. API models run in chat mode only.</Text>}
|
||||
{failed ? <Text style={styles.propertyError}>AI request failed.</Text> : null}
|
||||
<TextInput
|
||||
multiline
|
||||
onChangeText={onChangePrompt}
|
||||
placeholder={`Ask about ${note.title}`}
|
||||
placeholderTextColor={colors.mutedText}
|
||||
style={styles.aiPrompt}
|
||||
textAlignVertical="top"
|
||||
value={prompt}
|
||||
/>
|
||||
<Pressable
|
||||
disabled={!canSend}
|
||||
onPress={onSend}
|
||||
style={({ pressed }) => [
|
||||
styles.aiSendButton,
|
||||
!canSend ? styles.composeButtonDisabled : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
<PaperPlaneTilt color="#ffffff" size={18} weight="fill" />
|
||||
<Text style={styles.aiSendButtonText}>{isSending ? 'Sending' : 'Send'}</Text>
|
||||
</Pressable>
|
||||
</ScrollView>
|
||||
)
|
||||
}
|
||||
@@ -1,197 +0,0 @@
|
||||
import { CaretLeft, Trash } from 'phosphor-react-native'
|
||||
import { useState } from 'react'
|
||||
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native'
|
||||
import {
|
||||
mobileAiProviderPresets,
|
||||
type MobileAiProvider,
|
||||
type MobileAiProviderDraft,
|
||||
type MobileAiProviderKind,
|
||||
type MobileAiSettings,
|
||||
} from './mobileAiSettings'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
const providerKinds: MobileAiProviderKind[] = ['open_ai', 'anthropic', 'gemini', 'open_router', 'open_ai_compatible']
|
||||
|
||||
export function MobileAiSettingsPanel({
|
||||
failed,
|
||||
isSaving,
|
||||
onAddProvider,
|
||||
onClose,
|
||||
onRemoveProvider,
|
||||
settings,
|
||||
}: {
|
||||
failed: boolean
|
||||
isSaving: boolean
|
||||
onAddProvider: (draft: MobileAiProviderDraft) => Promise<boolean>
|
||||
onClose?: () => void
|
||||
onRemoveProvider: (providerId: string) => Promise<boolean>
|
||||
settings: MobileAiSettings
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.properties}>
|
||||
<SettingsToolbar onClose={onClose} />
|
||||
<ScrollView contentContainerStyle={styles.aiSettingsContent}>
|
||||
<Text style={styles.aiSettingsSectionTitle}>API models</Text>
|
||||
<Text style={styles.aiSettingsDescription}>API keys are saved locally on this device and are not written to vault settings.</Text>
|
||||
<ProviderList providers={settings.providers} onRemoveProvider={onRemoveProvider} />
|
||||
<ProviderDraftForm failed={failed} isSaving={isSaving} onAddProvider={onAddProvider} />
|
||||
</ScrollView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderDraftForm({
|
||||
failed,
|
||||
isSaving,
|
||||
onAddProvider,
|
||||
}: {
|
||||
failed: boolean
|
||||
isSaving: boolean
|
||||
onAddProvider: (draft: MobileAiProviderDraft) => Promise<boolean>
|
||||
}) {
|
||||
const [draft, setDraft] = useState<MobileAiProviderDraft>(() => initialDraft('open_ai'))
|
||||
const canSave = isProviderDraftReady(draft)
|
||||
const isDisabled = !canSave || isSaving
|
||||
const submitProvider = () => {
|
||||
if (isDisabled) return
|
||||
|
||||
void onAddProvider(draft).then((saved) => {
|
||||
if (saved) {
|
||||
setDraft(initialDraft(draft.kind))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ProviderKindPicker value={draft.kind} onChange={(kind) => setDraft(initialDraft(kind))} />
|
||||
<TextInput
|
||||
onChangeText={(modelId) => setDraft((current) => ({ ...current, modelId }))}
|
||||
placeholder={mobileAiProviderPresets[draft.kind].placeholder}
|
||||
placeholderTextColor={colors.mutedText}
|
||||
style={styles.aiInput}
|
||||
value={draft.modelId}
|
||||
/>
|
||||
<TextInput
|
||||
onChangeText={(apiKey) => setDraft((current) => ({ ...current, apiKey }))}
|
||||
placeholder="API key"
|
||||
placeholderTextColor={colors.mutedText}
|
||||
secureTextEntry
|
||||
style={styles.aiInput}
|
||||
value={draft.apiKey}
|
||||
/>
|
||||
<ProviderSaveError failed={failed} />
|
||||
<ProviderSaveButton disabled={isDisabled} isSaving={isSaving} onPress={submitProvider} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderSaveError({ failed }: { failed: boolean }) {
|
||||
return failed ? <Text style={styles.propertyError}>Could not save AI settings.</Text> : null
|
||||
}
|
||||
|
||||
function ProviderSaveButton({
|
||||
disabled,
|
||||
isSaving,
|
||||
onPress,
|
||||
}: {
|
||||
disabled: boolean
|
||||
isSaving: boolean
|
||||
onPress: () => void
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
styles.aiSettingsButton,
|
||||
disabled ? styles.composeButtonDisabled : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
<Text style={styles.aiSettingsButtonText}>{isSaving ? 'Saving' : 'Add API model'}</Text>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
function isProviderDraftReady(draft: MobileAiProviderDraft) {
|
||||
return draft.modelId.trim().length > 0 && draft.apiKey.trim().length > 0
|
||||
}
|
||||
|
||||
function SettingsToolbar({ onClose }: { onClose?: () => void }) {
|
||||
return (
|
||||
<View style={styles.toolbar}>
|
||||
<Text style={styles.propertiesTitle}>Settings</Text>
|
||||
<View style={styles.toolbarSpacer} />
|
||||
{onClose ? (
|
||||
<Pressable onPress={onClose} style={({ pressed }) => [styles.iconButton, pressed ? styles.pressed : null]}>
|
||||
<CaretLeft size={23} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderList({
|
||||
onRemoveProvider,
|
||||
providers,
|
||||
}: {
|
||||
onRemoveProvider: (providerId: string) => void
|
||||
providers: MobileAiProvider[]
|
||||
}) {
|
||||
if (providers.length === 0) {
|
||||
return <Text style={styles.aiSettingsEmpty}>No API models configured.</Text>
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.aiProviderList}>
|
||||
{providers.map((provider) => (
|
||||
<View key={provider.id} style={styles.aiProviderRow}>
|
||||
<View style={styles.aiProviderText}>
|
||||
<Text style={styles.aiProviderTitle}>{provider.name}</Text>
|
||||
<Text numberOfLines={1} style={styles.aiProviderDetail}>{provider.modelId}</Text>
|
||||
</View>
|
||||
<Pressable onPress={() => onRemoveProvider(provider.id)} style={({ pressed }) => [styles.iconButton, pressed ? styles.pressed : null]}>
|
||||
<Trash size={18} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function ProviderKindPicker({
|
||||
onChange,
|
||||
value,
|
||||
}: {
|
||||
onChange: (value: MobileAiProviderKind) => void
|
||||
value: MobileAiProviderKind
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.aiProviderKindRow}>
|
||||
{providerKinds.map((kind) => (
|
||||
<Pressable
|
||||
key={kind}
|
||||
onPress={() => onChange(kind)}
|
||||
style={({ pressed }) => [
|
||||
styles.aiProviderKindChip,
|
||||
value === kind ? styles.aiProviderKindChipSelected : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.aiProviderKindText, value === kind ? styles.aiProviderKindTextSelected : null]}>{mobileAiProviderPresets[kind].name}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function initialDraft(kind: MobileAiProviderKind): MobileAiProviderDraft {
|
||||
return {
|
||||
apiKey: '',
|
||||
kind,
|
||||
modelId: '',
|
||||
name: mobileAiProviderPresets[kind].name,
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,482 +0,0 @@
|
||||
import { CaretDown, CaretRight } from 'phosphor-react-native'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { Pressable, Text, TextInput, View, type StyleProp, type ViewStyle } from 'react-native'
|
||||
import type { MobileNote } from './demoData'
|
||||
import { NamedIcon, type IconName } from './NamedIcon'
|
||||
import {
|
||||
formatMobileNoteTags,
|
||||
isMobileNotePropertySelected,
|
||||
mobileNoteIconOptions,
|
||||
mobileNoteStatusOptions,
|
||||
mobileNoteTagOptions,
|
||||
mobileNoteTypeOptions,
|
||||
parseMobileNoteTags,
|
||||
toggleMobileNoteTag,
|
||||
type MobileNotePropertyPatch,
|
||||
} from './mobileNoteProperties'
|
||||
import { filterMobilePropertyComboOptions, resolveMobilePropertyComboValue } from './mobilePropertyCombo'
|
||||
import { mobilePropertyDisplayValue, type MobilePropertyPickerKey } from './mobilePropertyPicker'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobileEditablePropertyPickers({
|
||||
disabled,
|
||||
note,
|
||||
onChangeProperties,
|
||||
onSelectPicker,
|
||||
openPicker,
|
||||
}: {
|
||||
disabled: boolean
|
||||
note: MobileNote
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
onSelectPicker: (selected: MobilePropertyPickerKey) => void
|
||||
openPicker: MobilePropertyPickerKey | null
|
||||
}) {
|
||||
const today = formatMobilePropertyDate(new Date())
|
||||
|
||||
return (
|
||||
<>
|
||||
<EditableTextProperty
|
||||
disabled={disabled}
|
||||
isOpen={openPicker === 'type'}
|
||||
key={`type:${note.id}:${note.type}`}
|
||||
label="Type"
|
||||
placeholder="Type"
|
||||
suggestions={mobileNoteTypeOptions}
|
||||
value={note.type}
|
||||
onCommit={(type) => onChangeProperties?.({ type })}
|
||||
onOpen={() => onSelectPicker('type')}
|
||||
variant="combo"
|
||||
/>
|
||||
<EditableTextProperty
|
||||
disabled={disabled}
|
||||
isOpen={openPicker === 'status'}
|
||||
key={`status:${note.id}:${note.status ?? ''}`}
|
||||
label="Status"
|
||||
placeholder="Status"
|
||||
suggestions={mobileNoteStatusOptions}
|
||||
value={note.status ?? ''}
|
||||
onCommit={(status) => onChangeProperties?.({ status })}
|
||||
onOpen={() => onSelectPicker('status')}
|
||||
/>
|
||||
<EditableTextProperty
|
||||
disabled={disabled}
|
||||
isOpen={openPicker === 'date'}
|
||||
key={`date:${note.id}:${note.date}`}
|
||||
label="Date"
|
||||
placeholder="Date"
|
||||
suggestions={[today, '']}
|
||||
value={note.date}
|
||||
onCommit={(date) => onChangeProperties?.({ date })}
|
||||
onOpen={() => onSelectPicker('date')}
|
||||
/>
|
||||
<IconProperty
|
||||
disabled={disabled}
|
||||
isOpen={openPicker === 'icon'}
|
||||
note={note}
|
||||
onChangeProperties={onChangeProperties}
|
||||
onOpen={() => onSelectPicker('icon')}
|
||||
/>
|
||||
<TagsProperty
|
||||
disabled={disabled}
|
||||
isOpen={openPicker === 'tags'}
|
||||
key={`tags:${note.id}:${formatMobileNoteTags(note.tags)}`}
|
||||
note={note}
|
||||
onChangeProperties={onChangeProperties}
|
||||
onOpen={() => onSelectPicker('tags')}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function EditableTextProperty({
|
||||
disabled,
|
||||
isOpen,
|
||||
label,
|
||||
onCommit,
|
||||
onOpen,
|
||||
placeholder,
|
||||
suggestions,
|
||||
value,
|
||||
variant = 'chips',
|
||||
}: {
|
||||
disabled: boolean
|
||||
isOpen: boolean
|
||||
label: string
|
||||
onCommit: (value: string) => void
|
||||
onOpen: () => void
|
||||
placeholder: string
|
||||
suggestions: readonly string[]
|
||||
value: string
|
||||
variant?: 'chips' | 'combo'
|
||||
}) {
|
||||
const [draft, setDraft] = useState(value)
|
||||
const commitDraft = () => {
|
||||
const next = variant === 'combo'
|
||||
? resolveMobilePropertyComboValue({ options: suggestions, value: draft })
|
||||
: draft
|
||||
commitTextValue({ current: value, next, onCommit, onSettled: setDraft })
|
||||
}
|
||||
|
||||
return (
|
||||
<PropertyPickerSection
|
||||
disabled={disabled}
|
||||
isOpen={isOpen}
|
||||
label={label}
|
||||
value={mobilePropertyDisplayValue({ value })}
|
||||
onOpen={onOpen}
|
||||
>
|
||||
<View style={styles.propertyPickerOptions}>
|
||||
<TextInput
|
||||
autoCapitalize="sentences"
|
||||
autoFocus={variant === 'combo'}
|
||||
editable={!disabled}
|
||||
keyboardType="default"
|
||||
onBlur={commitDraft}
|
||||
onChangeText={setDraft}
|
||||
onSubmitEditing={commitDraft}
|
||||
placeholder={placeholder}
|
||||
placeholderTextColor={colors.mutedText}
|
||||
returnKeyType="done"
|
||||
selectTextOnFocus={variant === 'combo'}
|
||||
style={styles.propertyTextInput}
|
||||
value={draft}
|
||||
/>
|
||||
{variant === 'combo'
|
||||
? (
|
||||
<PropertyComboOptions
|
||||
disabled={disabled}
|
||||
query={draft}
|
||||
suggestions={suggestions}
|
||||
value={value}
|
||||
onSelect={(selected) => {
|
||||
setDraft(selected)
|
||||
onCommit(selected)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
: (
|
||||
<PropertyChipOptions>
|
||||
{suggestions.map((option) => (
|
||||
<PropertyTextChip
|
||||
disabled={disabled}
|
||||
key={option || 'none'}
|
||||
option={option}
|
||||
value={value}
|
||||
onSelect={(selected) => {
|
||||
setDraft(selected)
|
||||
onCommit(selected)
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</PropertyChipOptions>
|
||||
)}
|
||||
</View>
|
||||
</PropertyPickerSection>
|
||||
)
|
||||
}
|
||||
|
||||
function IconProperty({
|
||||
disabled,
|
||||
isOpen,
|
||||
note,
|
||||
onChangeProperties,
|
||||
onOpen,
|
||||
}: {
|
||||
disabled: boolean
|
||||
isOpen: boolean
|
||||
note: MobileNote
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
onOpen: () => void
|
||||
}) {
|
||||
return (
|
||||
<PropertyPickerSection
|
||||
disabled={disabled}
|
||||
isOpen={isOpen}
|
||||
label="Icon"
|
||||
value={mobilePropertyDisplayValue({ value: note.icon })}
|
||||
onOpen={onOpen}
|
||||
>
|
||||
<PropertyChipOptions>
|
||||
{mobileNoteIconOptions.map((option) => (
|
||||
<PropertyIconChip
|
||||
disabled={disabled}
|
||||
key={option}
|
||||
option={option}
|
||||
value={note.icon}
|
||||
onSelect={(icon) => onChangeProperties?.({ icon })}
|
||||
/>
|
||||
))}
|
||||
</PropertyChipOptions>
|
||||
</PropertyPickerSection>
|
||||
)
|
||||
}
|
||||
|
||||
function TagsProperty({
|
||||
disabled,
|
||||
isOpen,
|
||||
note,
|
||||
onChangeProperties,
|
||||
onOpen,
|
||||
}: {
|
||||
disabled: boolean
|
||||
isOpen: boolean
|
||||
note: MobileNote
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
onOpen: () => void
|
||||
}) {
|
||||
const [draft, setDraft] = useState(formatMobileNoteTags(note.tags))
|
||||
const commitDraft = () => onChangeProperties?.({ tags: parseMobileNoteTags(draft) })
|
||||
|
||||
return (
|
||||
<PropertyPickerSection
|
||||
disabled={disabled}
|
||||
isOpen={isOpen}
|
||||
label="Tags"
|
||||
value={note.tags.length > 0 ? formatMobileNoteTags(note.tags) : 'None'}
|
||||
onOpen={onOpen}
|
||||
>
|
||||
<View style={styles.propertyPickerOptions}>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
editable={!disabled}
|
||||
keyboardType="default"
|
||||
onBlur={commitDraft}
|
||||
onChangeText={setDraft}
|
||||
onSubmitEditing={commitDraft}
|
||||
placeholder="Tags"
|
||||
placeholderTextColor={colors.mutedText}
|
||||
returnKeyType="done"
|
||||
style={styles.propertyTextInput}
|
||||
value={draft}
|
||||
/>
|
||||
<PropertyChipOptions>
|
||||
{mobileNoteTagOptions.map((option) => (
|
||||
<PropertyTextChip
|
||||
disabled={disabled}
|
||||
key={option}
|
||||
option={option}
|
||||
value={note.tags}
|
||||
onSelect={(tag) => {
|
||||
const tags = toggleMobileNoteTag(note.tags, tag)
|
||||
setDraft(formatMobileNoteTags(tags))
|
||||
onChangeProperties?.({ tags })
|
||||
}}
|
||||
/>
|
||||
))}
|
||||
</PropertyChipOptions>
|
||||
</View>
|
||||
</PropertyPickerSection>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyPickerSection({
|
||||
children,
|
||||
disabled,
|
||||
isOpen,
|
||||
label,
|
||||
onOpen,
|
||||
value,
|
||||
}: {
|
||||
children: ReactNode
|
||||
disabled: boolean
|
||||
isOpen: boolean
|
||||
label: string
|
||||
onOpen: () => void
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<PropertyPickerRow disabled={disabled} isOpen={isOpen} label={label} value={value} onPress={onOpen} />
|
||||
{isOpen ? children : null}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyPickerRow({
|
||||
disabled,
|
||||
isOpen,
|
||||
label,
|
||||
onPress,
|
||||
value,
|
||||
}: {
|
||||
disabled: boolean
|
||||
isOpen: boolean
|
||||
label: string
|
||||
onPress: () => void
|
||||
value: string
|
||||
}) {
|
||||
const Caret = isOpen ? CaretDown : CaretRight
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [styles.propertyRow, disabled ? styles.propertyDisabled : null, pressed ? styles.pressed : null]}
|
||||
>
|
||||
<Text style={styles.propertyLabel}>{label}</Text>
|
||||
<Text numberOfLines={1} style={styles.propertyValue}>{value}</Text>
|
||||
<Caret size={16} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyIconChip({
|
||||
disabled,
|
||||
onSelect,
|
||||
option,
|
||||
value,
|
||||
}: {
|
||||
disabled: boolean
|
||||
onSelect: (option: string) => void
|
||||
option: string
|
||||
value: string | undefined
|
||||
}) {
|
||||
const isSelected = isMobileNotePropertySelected({ current: value, option })
|
||||
|
||||
return (
|
||||
<SelectablePropertyChip
|
||||
disabled={disabled}
|
||||
isSelected={isSelected}
|
||||
onPress={() => onSelect(option)}
|
||||
style={styles.propertyIconChip}
|
||||
>
|
||||
<NamedIcon color={isSelected ? colors.primary : colors.textSoft} name={option as IconName} size={20} />
|
||||
</SelectablePropertyChip>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyChipOptions({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<View style={styles.propertyChipRow}>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyComboOptions({
|
||||
disabled,
|
||||
onSelect,
|
||||
query,
|
||||
suggestions,
|
||||
value,
|
||||
}: {
|
||||
disabled: boolean
|
||||
onSelect: (option: string) => void
|
||||
query: string
|
||||
suggestions: readonly string[]
|
||||
value: string
|
||||
}) {
|
||||
const options = filterMobilePropertyComboOptions({ options: suggestions, query })
|
||||
|
||||
return (
|
||||
<View style={styles.propertyComboBox}>
|
||||
{options.map((option) => {
|
||||
const isSelected = isMobileNotePropertySelected({ current: value, option })
|
||||
|
||||
return (
|
||||
<Pressable
|
||||
disabled={disabled}
|
||||
key={option || 'none'}
|
||||
onPress={() => onSelect(option)}
|
||||
style={({ pressed }) => [
|
||||
styles.propertyComboOption,
|
||||
isSelected ? styles.propertyComboOptionSelected : null,
|
||||
disabled ? styles.propertyDisabled : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.propertyComboOptionText, isSelected ? styles.propertyComboOptionTextSelected : null]}>
|
||||
{option || 'None'}
|
||||
</Text>
|
||||
</Pressable>
|
||||
)
|
||||
})}
|
||||
{options.length === 0 ? <Text style={styles.propertyComboEmpty}>No matching types.</Text> : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyTextChip({
|
||||
disabled,
|
||||
onSelect,
|
||||
option,
|
||||
value,
|
||||
}: {
|
||||
disabled: boolean
|
||||
onSelect: (option: string) => void
|
||||
option: string
|
||||
value: readonly string[] | string | undefined
|
||||
}) {
|
||||
const isSelected = Array.isArray(value)
|
||||
? value.includes(option)
|
||||
: isMobileNotePropertySelected({ current: typeof value === 'string' ? value : undefined, option })
|
||||
|
||||
return (
|
||||
<SelectablePropertyChip
|
||||
disabled={disabled}
|
||||
isSelected={isSelected}
|
||||
onPress={() => onSelect(option)}
|
||||
style={styles.propertyChip}
|
||||
>
|
||||
<Text style={[styles.propertyChipText, isSelected ? styles.propertyChipTextSelected : null]}>
|
||||
{option || 'None'}
|
||||
</Text>
|
||||
</SelectablePropertyChip>
|
||||
)
|
||||
}
|
||||
|
||||
function SelectablePropertyChip({
|
||||
children,
|
||||
disabled,
|
||||
isSelected,
|
||||
onPress,
|
||||
style,
|
||||
}: {
|
||||
children: ReactNode
|
||||
disabled: boolean
|
||||
isSelected: boolean
|
||||
onPress: () => void
|
||||
style: StyleProp<ViewStyle>
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
style,
|
||||
isSelected ? styles.propertyChipSelected : null,
|
||||
disabled ? styles.propertyDisabled : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
{children}
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
|
||||
function commitTextValue({
|
||||
current,
|
||||
next,
|
||||
onCommit,
|
||||
onSettled,
|
||||
}: {
|
||||
current: string
|
||||
next: string
|
||||
onCommit: (value: string) => void
|
||||
onSettled?: (value: string) => void
|
||||
}) {
|
||||
const normalized = next.trim()
|
||||
onSettled?.(normalized)
|
||||
if (normalized !== current) {
|
||||
onCommit(normalized)
|
||||
}
|
||||
}
|
||||
|
||||
function formatMobilePropertyDate(date: Date) {
|
||||
return new Intl.DateTimeFormat(undefined, {
|
||||
day: 'numeric',
|
||||
month: 'short',
|
||||
year: 'numeric',
|
||||
}).format(date)
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { KeyboardAvoidingView, Platform, View } from 'react-native'
|
||||
import type { WebViewMessageEvent } from 'react-native-webview'
|
||||
import { RichText, Toolbar, useEditorBridge } from '@10play/tentap-editor'
|
||||
import { MobileEditorWikilinkSuggestions } from './MobileEditorWikilinkSuggestions'
|
||||
import { parseEditorMessage, type MobileEditorWikilinkFrame } from './mobileEditorMessages'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import { createMobileEditorDraft, type MobileEditorDraft } from './mobileEditorDraft'
|
||||
import {
|
||||
createMobileEditorDocument,
|
||||
createMobileEditorHtml,
|
||||
} from './mobileEditorDocument'
|
||||
import { resolveMobileRelationshipNote } from './mobileRelationshipRefs'
|
||||
import { mobileEditorBridgeExtensions } from './mobileWikilinkEditorBridge'
|
||||
import { mobileEditorCss, mobileEditorSetupScript } from './mobileEditorWebViewSetup'
|
||||
import { styles } from './styles'
|
||||
|
||||
export function MobileEditorAdapter({
|
||||
notes,
|
||||
note,
|
||||
onCreateNote,
|
||||
onDraftChange,
|
||||
onOpenNote,
|
||||
}: {
|
||||
notes: MobileNote[]
|
||||
note: MobileNote
|
||||
onCreateNote: () => void
|
||||
onDraftChange?: (draft: MobileEditorDraft) => void
|
||||
onOpenNote?: (noteId: string) => void
|
||||
}) {
|
||||
const document = useMemo(() => createMobileEditorDocument(note), [note])
|
||||
const initialContent = useMemo(() => createMobileEditorHtml(document), [document])
|
||||
const [wikilinkQuery, setWikilinkQuery] = useState<string | null>(null)
|
||||
const [wikilinkFrame, setWikilinkFrame] = useState<MobileEditorWikilinkFrame | null>(null)
|
||||
const draftTargetRef = useRef({ note, onDraftChange })
|
||||
useEffect(() => {
|
||||
draftTargetRef.current = { note, onDraftChange }
|
||||
}, [note, onDraftChange])
|
||||
const editor = useEditorBridge({
|
||||
avoidIosKeyboard: true,
|
||||
bridgeExtensions: mobileEditorBridgeExtensions,
|
||||
initialContent,
|
||||
onChange: () => {
|
||||
const draftTarget = draftTargetRef.current
|
||||
void editor.getHTML().then((editorHtml) => {
|
||||
draftTarget.onDraftChange?.(createMobileEditorDraft({ editorHtml, note: draftTarget.note }))
|
||||
})
|
||||
},
|
||||
})
|
||||
const handleMessage = (event: WebViewMessageEvent) => {
|
||||
const message = parseEditorMessage(event.nativeEvent.data)
|
||||
if (!message) return
|
||||
|
||||
if (message.type === 'shortcut' && message.command === 'fileNewNote') {
|
||||
onCreateNote()
|
||||
return
|
||||
}
|
||||
if (message.type === 'wikilinkQuery') {
|
||||
setWikilinkQuery(message.query)
|
||||
setWikilinkFrame(message.frame)
|
||||
return
|
||||
}
|
||||
if (message.type === 'listIndent') {
|
||||
handleListIndent({ direction: message.direction, editor })
|
||||
return
|
||||
}
|
||||
if (message.type !== 'openWikilink') return
|
||||
|
||||
const targetNote = resolveMobileRelationshipNote({ notes, target: message.target })
|
||||
if (targetNote) {
|
||||
onOpenNote?.(targetNote.id)
|
||||
}
|
||||
}
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => {
|
||||
applyMobileEditorWebViewSetup(editor)
|
||||
}, 250)
|
||||
|
||||
return () => clearTimeout(timer)
|
||||
}, [editor, note.id])
|
||||
|
||||
return (
|
||||
<View style={styles.editorAdapterContent}>
|
||||
<View style={styles.tentapEditor}>
|
||||
<RichText key={note.id} editor={editor} onLoad={() => applyMobileEditorWebViewSetup(editor)} onMessage={handleMessage} />
|
||||
</View>
|
||||
<MobileEditorWikilinkSuggestions
|
||||
excludeNoteId={note.id}
|
||||
frame={wikilinkFrame}
|
||||
notes={notes}
|
||||
onSelectNote={(targetNote) => {
|
||||
editor.insertWikilink({ label: targetNote.title, target: targetNote.id })
|
||||
setWikilinkQuery(null)
|
||||
setWikilinkFrame(null)
|
||||
}}
|
||||
query={wikilinkQuery}
|
||||
/>
|
||||
<KeyboardAvoidingView
|
||||
behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
|
||||
style={styles.tentapToolbar}
|
||||
>
|
||||
<Toolbar editor={editor} />
|
||||
</KeyboardAvoidingView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function applyMobileEditorWebViewSetup(editor: ReturnType<typeof useEditorBridge>) {
|
||||
editor.injectCSS(mobileEditorCss, 'tolaria-mobile-editor')
|
||||
editor.injectJS(mobileEditorSetupScript)
|
||||
}
|
||||
|
||||
function handleListIndent({
|
||||
direction,
|
||||
editor,
|
||||
}: {
|
||||
direction: 'in' | 'out'
|
||||
editor: ReturnType<typeof useEditorBridge>
|
||||
}) {
|
||||
if (direction === 'in') {
|
||||
editor.sink()
|
||||
return
|
||||
}
|
||||
|
||||
editor.lift()
|
||||
}
|
||||
@@ -1,81 +0,0 @@
|
||||
import { Archive, Code, PencilSimpleLine, Star, Tray } from 'phosphor-react-native'
|
||||
import type { ReactNode } from 'react'
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import type { MobileNote } from './demoData'
|
||||
import type { MobileEditorSaveState } from './mobileEditorSaveState'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobileEditorBreadcrumb({
|
||||
isRawMode,
|
||||
note,
|
||||
onToggleArchive,
|
||||
onToggleFavorite,
|
||||
onToggleRawMode,
|
||||
saveState,
|
||||
}: {
|
||||
isRawMode: boolean
|
||||
note: MobileNote
|
||||
onToggleArchive: () => void
|
||||
onToggleFavorite: () => void
|
||||
onToggleRawMode: () => void
|
||||
saveState: MobileEditorSaveState
|
||||
}) {
|
||||
const ArchiveIcon = note.archived ? Tray : Archive
|
||||
const RawIcon = isRawMode ? PencilSimpleLine : Code
|
||||
|
||||
return (
|
||||
<View style={styles.editorBreadcrumb}>
|
||||
<Text numberOfLines={1} style={styles.editorBreadcrumbText}>{note.type}</Text>
|
||||
<Text style={styles.editorBreadcrumbDivider}>/</Text>
|
||||
<Text numberOfLines={1} style={styles.editorBreadcrumbTitle}>{note.id}</Text>
|
||||
<Text style={[styles.editorSaveState, saveStateStyle(saveState)]}>{saveState.label}</Text>
|
||||
<BreadcrumbButton label={isRawMode ? 'Rich editor' : 'Raw editor'} onPress={onToggleRawMode}>
|
||||
<RawIcon color={isRawMode ? colors.primary : colors.textSoft} size={18} />
|
||||
</BreadcrumbButton>
|
||||
<BreadcrumbButton label={note.favorite ? 'Remove favorite' : 'Add favorite'} onPress={onToggleFavorite}>
|
||||
<Star color={note.favorite ? colors.primary : colors.textSoft} size={18} weight={note.favorite ? 'fill' : 'regular'} />
|
||||
</BreadcrumbButton>
|
||||
<BreadcrumbButton label={note.archived ? 'Move to inbox' : 'Archive'} onPress={onToggleArchive}>
|
||||
<ArchiveIcon color={colors.textSoft} size={18} />
|
||||
</BreadcrumbButton>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function saveStateStyle(saveState: MobileEditorSaveState) {
|
||||
switch (saveState.state) {
|
||||
case 'blocked':
|
||||
return styles.editorSaveState_blocked
|
||||
case 'failed':
|
||||
return styles.editorSaveState_failed
|
||||
case 'queued':
|
||||
return styles.editorSaveState_queued
|
||||
case 'saved':
|
||||
return styles.editorSaveState_saved
|
||||
case 'saving':
|
||||
return styles.editorSaveState_saving
|
||||
default:
|
||||
return styles.editorSaveState_idle
|
||||
}
|
||||
}
|
||||
|
||||
function BreadcrumbButton({
|
||||
children,
|
||||
label,
|
||||
onPress,
|
||||
}: {
|
||||
children: ReactNode
|
||||
label: string
|
||||
onPress: () => void
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
accessibilityLabel={label}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [styles.editorBreadcrumbButton, pressed ? styles.pressed : null]}
|
||||
>
|
||||
{children}
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { useMemo } from 'react'
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import type { MobileEditorWikilinkFrame } from './mobileEditorMessages'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import { mobileNoteSuggestions } from './mobileWikilinkAutocomplete'
|
||||
import { styles } from './styles'
|
||||
|
||||
export function MobileEditorWikilinkSuggestions({
|
||||
frame,
|
||||
excludeNoteId,
|
||||
notes,
|
||||
onSelectNote,
|
||||
query,
|
||||
}: {
|
||||
frame: MobileEditorWikilinkFrame | null
|
||||
excludeNoteId: string
|
||||
notes: MobileNote[]
|
||||
onSelectNote: (note: MobileNote) => void
|
||||
query: string | null
|
||||
}) {
|
||||
const suggestions = useMemo(() => {
|
||||
return query === null
|
||||
? []
|
||||
: mobileNoteSuggestions({ excludeNoteId, notes, query })
|
||||
}, [excludeNoteId, notes, query])
|
||||
|
||||
if (query === null || suggestions.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={[styles.rawEditorSuggestionMenu, suggestionMenuPosition(frame)]}>
|
||||
{suggestions.map((suggestion) => (
|
||||
<Pressable
|
||||
key={suggestion.id}
|
||||
onPress={() => onSelectNote(suggestion)}
|
||||
style={({ pressed }) => [styles.rawEditorSuggestion, pressed ? styles.pressed : null]}
|
||||
>
|
||||
<Text style={styles.rawEditorSuggestionTitle}>{suggestion.title}</Text>
|
||||
<Text style={styles.rawEditorSuggestionMeta}>{suggestion.id}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function suggestionMenuPosition(frame: MobileEditorWikilinkFrame | null) {
|
||||
if (!frame) {
|
||||
return null
|
||||
}
|
||||
|
||||
return {
|
||||
bottom: undefined,
|
||||
left: Math.max(16, frame.left),
|
||||
top: Math.max(16, frame.bottom + 8),
|
||||
}
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { GitBranch, WarningCircle } from 'phosphor-react-native'
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import { mobileGitSyncStatusView, type MobileGitSyncStatusTone } from './mobileGitSyncStatus'
|
||||
import type { MobileGitSyncPlan } from './mobileGitSyncPlan'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobileGitSyncStatusCard({
|
||||
onPrimaryAction,
|
||||
plan,
|
||||
}: {
|
||||
onPrimaryAction?: () => void
|
||||
plan: MobileGitSyncPlan
|
||||
}) {
|
||||
const status = mobileGitSyncStatusView(plan)
|
||||
if (!status) {
|
||||
return null
|
||||
}
|
||||
|
||||
const Icon = status.tone === 'warning' || status.tone === 'attention' ? WarningCircle : GitBranch
|
||||
|
||||
return (
|
||||
<View style={[styles.gitSyncStatus, gitSyncToneStyle(status.tone)]}>
|
||||
<Icon size={18} color={colors.textSoft} />
|
||||
<View style={styles.gitSyncStatusCopy}>
|
||||
<Text style={styles.gitSyncStatusLabel}>{status.label}</Text>
|
||||
<Text style={styles.gitSyncStatusDetail}>{status.detail}</Text>
|
||||
</View>
|
||||
{status.actionLabel ? (
|
||||
<Pressable
|
||||
accessibilityLabel={status.actionLabel}
|
||||
onPress={onPrimaryAction}
|
||||
style={({ pressed }) => pressed ? styles.pressed : null}
|
||||
>
|
||||
<Text style={styles.gitSyncStatusAction}>{status.actionLabel}</Text>
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function gitSyncToneStyle(tone: MobileGitSyncStatusTone) {
|
||||
switch (tone) {
|
||||
case 'attention':
|
||||
return styles.gitSyncStatus_attention
|
||||
case 'neutral':
|
||||
return styles.gitSyncStatus_neutral
|
||||
case 'positive':
|
||||
return styles.gitSyncStatus_positive
|
||||
case 'warning':
|
||||
return styles.gitSyncStatus_warning
|
||||
}
|
||||
}
|
||||
@@ -1,477 +0,0 @@
|
||||
import { CaretLeft, Plus, X } from 'phosphor-react-native'
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { Pressable, ScrollView, Text, TextInput, View } from 'react-native'
|
||||
import type { MobileNote } from './demoData'
|
||||
import { mobileDerivedRelationshipGroups } from './mobileDerivedRelationships'
|
||||
import { MobileEditablePropertyPickers } from './MobileEditablePropertyPickers'
|
||||
import { MobileRelationshipNotePicker } from './MobileRelationshipNotePicker'
|
||||
import type { MobileNotePropertyPatch } from './mobileNoteProperties'
|
||||
import { nextMobilePropertyPicker, type MobilePropertyPickerKey } from './mobilePropertyPicker'
|
||||
import {
|
||||
canonicalMobileRelationshipRef,
|
||||
filterMobileRelationshipRef,
|
||||
hasMobileRelationshipRef,
|
||||
mobileRelationshipDisplayLabel,
|
||||
mobileWikilinkForNote,
|
||||
resolveMobileRelationshipNote,
|
||||
uniqueMobileRelationshipRefs,
|
||||
} from './mobileRelationshipRefs'
|
||||
import { mobileRelationshipAppearance } from './mobileTypeAppearance'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobilePropertiesPanel({
|
||||
failed = false,
|
||||
isSaving = false,
|
||||
notes = [],
|
||||
note,
|
||||
onChangeProperties,
|
||||
onClose,
|
||||
onOpenNote,
|
||||
}: {
|
||||
failed?: boolean
|
||||
isSaving?: boolean
|
||||
notes?: MobileNote[]
|
||||
note: MobileNote
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
onClose?: () => void
|
||||
onOpenNote?: (noteId: string) => void
|
||||
}) {
|
||||
const [openPicker, setOpenPicker] = useState<MobilePropertyPickerKey | null>(null)
|
||||
const selectPicker = (selected: MobilePropertyPickerKey) => {
|
||||
setOpenPicker((current) => nextMobilePropertyPicker({ current, selected }))
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.properties}>
|
||||
<PanelToolbar onClose={onClose} />
|
||||
<ScrollView contentContainerStyle={styles.propertiesContent}>
|
||||
{failed ? <Text style={styles.propertyError}>Could not save property.</Text> : null}
|
||||
<PropertySection title="System">
|
||||
<MobileEditablePropertyPickers
|
||||
disabled={isSaving}
|
||||
note={note}
|
||||
openPicker={openPicker}
|
||||
onChangeProperties={onChangeProperties}
|
||||
onSelectPicker={selectPicker}
|
||||
/>
|
||||
</PropertySection>
|
||||
<PropertySection title="Relationships">
|
||||
<EditableRelationships note={note} notes={notes} onChangeProperties={onChangeProperties} onOpenNote={onOpenNote} />
|
||||
<DerivedRelationships note={note} notes={notes} onOpenNote={onOpenNote} />
|
||||
</PropertySection>
|
||||
<CustomProperties note={note} onChangeProperties={onChangeProperties} />
|
||||
<PropertySection title="Info">
|
||||
<BacklinkGroup backlinks={note.backlinks} onOpenNote={onOpenNote} />
|
||||
<PropertyRow label="Words" value={String(note.words)} />
|
||||
<PropertyRow label="Modified" value={note.modified} />
|
||||
</PropertySection>
|
||||
<PropertySection title="History">
|
||||
<Text style={styles.historyItem}>eb373865c - Updated 1 note</Text>
|
||||
<Text style={styles.historyItem}>5e853fdfe - Updated 1 note</Text>
|
||||
</PropertySection>
|
||||
</ScrollView>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertySection({
|
||||
children,
|
||||
title,
|
||||
}: {
|
||||
children: ReactNode
|
||||
title: string
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.propertySection}>
|
||||
<Text style={styles.propertyGroupTitle}>{title}</Text>
|
||||
{children}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function EditableRelationships({
|
||||
note,
|
||||
notes,
|
||||
onChangeProperties,
|
||||
onOpenNote,
|
||||
}: {
|
||||
note: MobileNote
|
||||
notes: MobileNote[]
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
onOpenNote?: (noteId: string) => void
|
||||
}) {
|
||||
return (
|
||||
<>
|
||||
<RelationshipGroup
|
||||
label="Belongs to"
|
||||
notes={notes}
|
||||
targets={note.belongsTo}
|
||||
onChangeTargets={(belongsTo) => onChangeProperties?.({ belongsTo })}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
<RelationshipGroup
|
||||
label="Related to"
|
||||
notes={notes}
|
||||
targets={[...note.relatedTo, ...note.outgoingLinks]}
|
||||
writableTargets={note.relatedTo}
|
||||
onChangeTargets={(relatedTo) => onChangeProperties?.({ relatedTo })}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
<RelationshipGroup
|
||||
label="Has"
|
||||
notes={notes}
|
||||
targets={note.has}
|
||||
onChangeTargets={(has) => onChangeProperties?.({ has })}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
{Object.entries(note.relationships).map(([key, targets]) => (
|
||||
<RelationshipGroup
|
||||
key={key}
|
||||
label={formatRelationshipLabel(key)}
|
||||
notes={notes}
|
||||
onDeleteGroup={() => onChangeProperties?.({
|
||||
relationships: removeRelationshipKey({ key, relationships: note.relationships }),
|
||||
removedRelationshipKeys: [key],
|
||||
})}
|
||||
targets={targets}
|
||||
onChangeTargets={(nextTargets) => onChangeProperties?.({
|
||||
relationships: { ...note.relationships, [key]: nextTargets },
|
||||
removedRelationshipKeys: nextTargets.length === 0 ? [key] : undefined,
|
||||
})}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
))}
|
||||
<AddRelationshipGroup
|
||||
note={note}
|
||||
notes={notes}
|
||||
onAdd={(key, target) => onChangeProperties?.({ relationships: { ...note.relationships, [key]: [target] } })}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function DerivedRelationships({
|
||||
note,
|
||||
notes,
|
||||
onOpenNote,
|
||||
}: {
|
||||
note: MobileNote
|
||||
notes: MobileNote[]
|
||||
onOpenNote?: (noteId: string) => void
|
||||
}) {
|
||||
const groups = mobileDerivedRelationshipGroups({ note, notes })
|
||||
return (
|
||||
<>
|
||||
{groups.map((group) => (
|
||||
<RelationshipGroup
|
||||
key={group.label}
|
||||
label={group.label}
|
||||
notes={notes}
|
||||
targets={group.targets}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function RelationshipGroup({
|
||||
label,
|
||||
notes,
|
||||
onChangeTargets,
|
||||
onDeleteGroup,
|
||||
onOpenNote,
|
||||
targets,
|
||||
writableTargets = targets,
|
||||
}: {
|
||||
label: string
|
||||
notes: MobileNote[]
|
||||
onChangeTargets?: (targets: string[]) => void
|
||||
onDeleteGroup?: () => void
|
||||
onOpenNote?: (noteId: string) => void
|
||||
targets: string[]
|
||||
writableTargets?: string[]
|
||||
}) {
|
||||
const [isAdding, setIsAdding] = useState(false)
|
||||
const uniqueTargets = uniqueMobileRelationshipRefs(targets)
|
||||
const addTarget = (selectedNote: MobileNote) => {
|
||||
const target = canonicalMobileRelationshipRef({ notes, value: mobileWikilinkForNote(selectedNote) })
|
||||
if (!target) return
|
||||
|
||||
onChangeTargets?.(uniqueMobileRelationshipRefs([...writableTargets, target]))
|
||||
setIsAdding(false)
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.relationshipGroup}>
|
||||
<RelationshipHeader
|
||||
canAdd={Boolean(onChangeTargets)}
|
||||
canDelete={Boolean(onDeleteGroup)}
|
||||
label={label}
|
||||
onAdd={() => setIsAdding(true)}
|
||||
onDelete={onDeleteGroup}
|
||||
/>
|
||||
<View style={styles.relationshipChipRow}>
|
||||
{uniqueTargets.length === 0 ? <Text style={styles.relationshipEmpty}>None</Text> : null}
|
||||
{uniqueTargets.map((target) => (
|
||||
<RelationshipChip
|
||||
key={target}
|
||||
note={resolveMobileRelationshipNote({ notes, target })}
|
||||
onRemove={hasMobileRelationshipRef({ target, values: writableTargets }) && onChangeTargets
|
||||
? () => onChangeTargets(filterMobileRelationshipRef({ target, values: writableTargets }))
|
||||
: undefined}
|
||||
target={target}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
<MobileRelationshipNotePicker
|
||||
notes={notes}
|
||||
title={`Add ${label}`}
|
||||
visible={isAdding}
|
||||
onClose={() => setIsAdding(false)}
|
||||
onSelectNote={addTarget}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function RelationshipHeader({
|
||||
canAdd,
|
||||
canDelete,
|
||||
label,
|
||||
onAdd,
|
||||
onDelete,
|
||||
}: {
|
||||
canAdd: boolean
|
||||
canDelete: boolean
|
||||
label: string
|
||||
onAdd: () => void
|
||||
onDelete?: () => void
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.relationshipHeader}>
|
||||
<Text style={styles.propertyGroupTitle}>{label}</Text>
|
||||
<View style={styles.relationshipHeaderActions}>
|
||||
{canDelete ? (
|
||||
<Pressable onPress={onDelete} style={({ pressed }) => [styles.relationshipAddButton, pressed ? styles.pressed : null]}>
|
||||
<X color={colors.textSoft} size={14} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
{canAdd ? (
|
||||
<Pressable onPress={onAdd} style={({ pressed }) => [styles.relationshipAddButton, pressed ? styles.pressed : null]}>
|
||||
<Plus color={colors.textSoft} size={14} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function AddRelationshipGroup({
|
||||
note,
|
||||
notes,
|
||||
onAdd,
|
||||
}: {
|
||||
note: MobileNote
|
||||
notes: MobileNote[]
|
||||
onAdd: (key: string, target: string) => void
|
||||
}) {
|
||||
const [name, setName] = useState('')
|
||||
const [pendingKey, setPendingKey] = useState<string | null>(null)
|
||||
const openTargetPicker = () => {
|
||||
const key = relationshipKeyFromLabel(name)
|
||||
if (key && !note.relationships[key]) {
|
||||
setPendingKey(key)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.relationshipGroup}>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
onChangeText={setName}
|
||||
onSubmitEditing={openTargetPicker}
|
||||
placeholder="+ Add relationship"
|
||||
placeholderTextColor={colors.mutedText}
|
||||
style={styles.relationshipInput}
|
||||
value={name}
|
||||
/>
|
||||
<MobileRelationshipNotePicker
|
||||
notes={notes}
|
||||
title={`Add ${formatRelationshipLabel(pendingKey ?? 'relationship')}`}
|
||||
visible={Boolean(pendingKey)}
|
||||
onClose={() => setPendingKey(null)}
|
||||
onSelectNote={(targetNote) => {
|
||||
if (!pendingKey) return
|
||||
|
||||
onAdd(pendingKey, mobileWikilinkForNote(targetNote))
|
||||
setName('')
|
||||
setPendingKey(null)
|
||||
}}
|
||||
/>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function CustomProperties({
|
||||
note,
|
||||
onChangeProperties,
|
||||
}: {
|
||||
note: MobileNote
|
||||
onChangeProperties?: (patch: MobileNotePropertyPatch) => void
|
||||
}) {
|
||||
const entries = Object.entries(note.customProperties)
|
||||
|
||||
return (
|
||||
<PropertySection title="Custom properties">
|
||||
{entries.length === 0 ? <Text style={styles.relationshipEmpty}>None</Text> : null}
|
||||
{entries.map(([key, value]) => (
|
||||
<PropertyRow
|
||||
key={key}
|
||||
label={formatRelationshipLabel(key)}
|
||||
value={value}
|
||||
onDelete={() => onChangeProperties?.({
|
||||
customProperties: removeCustomPropertyKey({ customProperties: note.customProperties, key }),
|
||||
removedCustomPropertyKeys: [key],
|
||||
})}
|
||||
/>
|
||||
))}
|
||||
</PropertySection>
|
||||
)
|
||||
}
|
||||
|
||||
function BacklinkGroup({
|
||||
backlinks,
|
||||
onOpenNote,
|
||||
}: {
|
||||
backlinks: MobileNote['backlinks']
|
||||
onOpenNote?: (noteId: string) => void
|
||||
}) {
|
||||
if (backlinks.length === 0) {
|
||||
return null
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.relationshipGroup}>
|
||||
<Text style={styles.propertyGroupTitle}>Linked from</Text>
|
||||
<View style={styles.relationshipChipRow}>
|
||||
{backlinks.map((backlink) => (
|
||||
<RelationshipChip
|
||||
key={backlink.id}
|
||||
note={backlink}
|
||||
target={backlink.title}
|
||||
onOpenNote={onOpenNote}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function RelationshipChip({
|
||||
note,
|
||||
onOpenNote,
|
||||
onRemove,
|
||||
target,
|
||||
}: {
|
||||
note?: { id: string; title: string; type?: string }
|
||||
onOpenNote?: (noteId: string) => void
|
||||
onRemove?: () => void
|
||||
target: string
|
||||
}) {
|
||||
const appearance = mobileRelationshipAppearance(note?.type)
|
||||
const chip = <Text style={styles.relationshipChipText}>{note?.title ?? mobileRelationshipDisplayLabel(target)}</Text>
|
||||
|
||||
const content = (
|
||||
<>
|
||||
{chip}
|
||||
{onRemove ? (
|
||||
<Pressable onPress={onRemove} style={styles.relationshipRemoveButton}>
|
||||
<X color={appearance.color} size={12} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</>
|
||||
)
|
||||
|
||||
return note && onOpenNote ? (
|
||||
<Pressable
|
||||
onPress={() => onOpenNote(note.id)}
|
||||
style={({ pressed }) => [
|
||||
styles.relationshipChip,
|
||||
{ backgroundColor: appearance.backgroundColor, borderColor: appearance.borderColor },
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
{content}
|
||||
</Pressable>
|
||||
) : (
|
||||
<View style={[styles.relationshipChip, { backgroundColor: appearance.backgroundColor, borderColor: appearance.borderColor }]}>{content}</View>
|
||||
)
|
||||
}
|
||||
|
||||
function formatRelationshipLabel(key: string) {
|
||||
return key.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase())
|
||||
}
|
||||
|
||||
function relationshipKeyFromLabel(label: string) {
|
||||
return label.trim().toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '')
|
||||
}
|
||||
|
||||
function PanelToolbar({ onClose }: { onClose?: () => void }) {
|
||||
return (
|
||||
<View style={styles.toolbar}>
|
||||
<Text style={styles.propertiesTitle}>Properties</Text>
|
||||
<View style={styles.toolbarSpacer} />
|
||||
{onClose ? (
|
||||
<Pressable onPress={onClose} style={({ pressed }) => [styles.iconButton, pressed ? styles.pressed : null]}>
|
||||
<CaretLeft size={23} color={colors.textSoft} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function PropertyRow({
|
||||
label,
|
||||
onDelete,
|
||||
value,
|
||||
}: {
|
||||
label: string
|
||||
onDelete?: () => void
|
||||
value: string
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.propertyRow}>
|
||||
<Text style={styles.propertyLabel}>{label}</Text>
|
||||
<Text style={styles.propertyValue}>{value}</Text>
|
||||
{onDelete ? (
|
||||
<Pressable onPress={onDelete} style={styles.relationshipRemoveButton}>
|
||||
<X color={colors.textSoft} size={14} />
|
||||
</Pressable>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function removeRelationshipKey({
|
||||
key,
|
||||
relationships,
|
||||
}: {
|
||||
key: string
|
||||
relationships: Record<string, string[]>
|
||||
}) {
|
||||
return Object.fromEntries(Object.entries(relationships).filter(([relationshipKey]) => relationshipKey !== key))
|
||||
}
|
||||
|
||||
function removeCustomPropertyKey({
|
||||
customProperties,
|
||||
key,
|
||||
}: {
|
||||
customProperties: Record<string, string>
|
||||
key: string
|
||||
}) {
|
||||
return Object.fromEntries(Object.entries(customProperties).filter(([propertyKey]) => propertyKey !== key))
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Pressable, Text, TextInput, View } from 'react-native'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import { activeMobileWikilinkQuery, insertMobileWikilink, mobileNoteSuggestions } from './mobileWikilinkAutocomplete'
|
||||
import { styles } from './styles'
|
||||
|
||||
export function MobileRawEditor({
|
||||
notes,
|
||||
note,
|
||||
onRawMarkdownChange,
|
||||
}: {
|
||||
notes: MobileNote[]
|
||||
note: MobileNote
|
||||
onRawMarkdownChange: (markdown: string) => void
|
||||
}) {
|
||||
const [draft, setDraft] = useState(note.content)
|
||||
const [cursor, setCursor] = useState(note.content.length)
|
||||
const activeQuery = useMemo(() => activeMobileWikilinkQuery({ cursor, markdown: draft }), [cursor, draft])
|
||||
const suggestions = useMemo(
|
||||
() => activeQuery ? mobileNoteSuggestions({ excludeNoteId: note.id, notes, query: activeQuery.query }) : [],
|
||||
[activeQuery, note.id, notes],
|
||||
)
|
||||
|
||||
return (
|
||||
<View style={styles.rawEditorContent}>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
multiline
|
||||
onChangeText={(markdown) => {
|
||||
setDraft(markdown)
|
||||
onRawMarkdownChange(markdown)
|
||||
}}
|
||||
onSelectionChange={(event) => setCursor(event.nativeEvent.selection.start)}
|
||||
scrollEnabled
|
||||
spellCheck={false}
|
||||
style={styles.rawEditorInput}
|
||||
textAlignVertical="top"
|
||||
value={draft}
|
||||
/>
|
||||
{suggestions.length > 0 && activeQuery ? (
|
||||
<View style={styles.rawEditorSuggestionMenu}>
|
||||
{suggestions.map((suggestion) => (
|
||||
<Pressable
|
||||
key={suggestion.id}
|
||||
onPress={() => {
|
||||
const nextDraft = insertMobileWikilink({ markdown: draft, note: suggestion, query: activeQuery })
|
||||
setDraft(nextDraft)
|
||||
setCursor(activeQuery.start + suggestion.id.length + suggestion.title.length + 5)
|
||||
onRawMarkdownChange(nextDraft)
|
||||
}}
|
||||
style={({ pressed }) => [styles.rawEditorSuggestion, pressed ? styles.pressed : null]}
|
||||
>
|
||||
<Text style={styles.rawEditorSuggestionTitle}>{suggestion.title}</Text>
|
||||
<Text style={styles.rawEditorSuggestionMeta}>{suggestion.id}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { X } from 'phosphor-react-native'
|
||||
import { useMemo, useState } from 'react'
|
||||
import { Modal, Pressable, Text, TextInput, View, type GestureResponderEvent } from 'react-native'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import { mobileNoteSuggestions } from './mobileWikilinkAutocomplete'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
|
||||
export function MobileRelationshipNotePicker({
|
||||
notes,
|
||||
onClose,
|
||||
onSelectNote,
|
||||
title,
|
||||
visible,
|
||||
}: {
|
||||
notes: MobileNote[]
|
||||
onClose: () => void
|
||||
onSelectNote: (note: MobileNote) => void
|
||||
title: string
|
||||
visible: boolean
|
||||
}) {
|
||||
const [query, setQuery] = useState('')
|
||||
const suggestions = useMemo(
|
||||
() => query.trim() ? mobileNoteSuggestions({ notes, query }) : [],
|
||||
[notes, query],
|
||||
)
|
||||
|
||||
return (
|
||||
<Modal animationType="fade" transparent visible={visible} onRequestClose={onClose}>
|
||||
<Pressable style={styles.relationshipPickerOverlay} onPress={onClose}>
|
||||
<Pressable style={styles.relationshipPickerPanel} onPress={stopPressPropagation}>
|
||||
<View style={styles.relationshipPickerHeader}>
|
||||
<Text style={styles.relationshipPickerTitle}>{title}</Text>
|
||||
<Pressable onPress={onClose} style={styles.relationshipPickerClose}>
|
||||
<X color={colors.textSoft} size={18} />
|
||||
</Pressable>
|
||||
</View>
|
||||
<TextInput
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
autoFocus
|
||||
onChangeText={setQuery}
|
||||
placeholder="Search notes"
|
||||
placeholderTextColor={colors.mutedText}
|
||||
style={styles.relationshipPickerInput}
|
||||
value={query}
|
||||
/>
|
||||
<View style={styles.relationshipPickerResults}>
|
||||
{query.trim() ? null : <Text style={styles.relationshipPickerEmpty}>Type to find a note.</Text>}
|
||||
{query.trim() && suggestions.length === 0 ? <Text style={styles.relationshipPickerEmpty}>No matching notes.</Text> : null}
|
||||
{suggestions.map((suggestion) => (
|
||||
<Pressable
|
||||
key={suggestion.id}
|
||||
onPress={() => {
|
||||
onSelectNote(suggestion)
|
||||
setQuery('')
|
||||
}}
|
||||
style={({ pressed }) => [styles.relationshipPickerResult, pressed ? styles.pressed : null]}
|
||||
>
|
||||
<Text numberOfLines={1} style={styles.relationshipPickerResultTitle}>{suggestion.title}</Text>
|
||||
<Text numberOfLines={1} style={styles.relationshipPickerResultMeta}>{suggestion.type}</Text>
|
||||
</Pressable>
|
||||
))}
|
||||
</View>
|
||||
</Pressable>
|
||||
</Pressable>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
|
||||
function stopPressPropagation(event: GestureResponderEvent) {
|
||||
event.stopPropagation()
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import { Pressable, Text, View } from 'react-native'
|
||||
import { GitBranch, HardDrive, SlidersHorizontal } from 'phosphor-react-native'
|
||||
import { styles } from './styles'
|
||||
import { colors } from './theme'
|
||||
import type { MobileVaultMetadata } from './mobileVaultMetadata'
|
||||
import { createMobileVaultManagementSummary } from './mobileVaultManagementSummary'
|
||||
|
||||
export function MobileVaultManagementCard({
|
||||
onOpenRemoteSetup,
|
||||
vault,
|
||||
}: {
|
||||
onOpenRemoteSetup: () => void
|
||||
vault: MobileVaultMetadata
|
||||
}) {
|
||||
const summary = createMobileVaultManagementSummary(vault)
|
||||
|
||||
return (
|
||||
<View style={styles.vaultManagementCard}>
|
||||
<View style={styles.vaultManagementHeader}>
|
||||
<View style={styles.vaultManagementIcon}>
|
||||
<HardDrive size={18} color={colors.primary} />
|
||||
</View>
|
||||
<View style={styles.vaultManagementTitleGroup}>
|
||||
<Text numberOfLines={1} style={styles.vaultManagementTitle}>{summary.name}</Text>
|
||||
<Text style={styles.vaultManagementDetail}>{summary.storageLabel}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View style={styles.vaultManagementRemoteRow}>
|
||||
<GitBranch size={17} color={colors.iconMuted} />
|
||||
<View style={styles.vaultManagementRemoteText}>
|
||||
<Text style={styles.vaultManagementRemoteLabel}>{summary.remoteLabel}</Text>
|
||||
<Text numberOfLines={1} style={styles.vaultManagementDetail}>{summary.remoteDetail}</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Pressable
|
||||
accessibilityLabel="Configure Git remote"
|
||||
onPress={onOpenRemoteSetup}
|
||||
style={({ pressed }) => [styles.vaultManagementAction, pressed ? styles.pressed : null]}
|
||||
>
|
||||
<SlidersHorizontal size={17} color={colors.primary} />
|
||||
<Text style={styles.vaultManagementActionText}>{summary.actionLabel}</Text>
|
||||
</Pressable>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
@@ -1,73 +0,0 @@
|
||||
import { Pressable, Text, TextInput, View } from 'react-native'
|
||||
import { styles } from './styles'
|
||||
|
||||
export function MobileVaultRemotePrompt({
|
||||
failed,
|
||||
hasGitHubOAuthClientId,
|
||||
isSaving,
|
||||
onCancel,
|
||||
onChangeRemoteUrl,
|
||||
onSubmit,
|
||||
remoteUrl,
|
||||
}: {
|
||||
failed: boolean
|
||||
hasGitHubOAuthClientId: boolean
|
||||
isSaving: boolean
|
||||
onCancel: () => void
|
||||
onChangeRemoteUrl: (remoteUrl: string) => void
|
||||
onSubmit: () => void
|
||||
remoteUrl: string
|
||||
}) {
|
||||
return (
|
||||
<View style={styles.remotePrompt}>
|
||||
<Text style={styles.remotePromptTitle}>Git remote</Text>
|
||||
<TextInput
|
||||
accessibilityLabel="Git remote URL"
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!isSaving}
|
||||
onChangeText={onChangeRemoteUrl}
|
||||
onSubmitEditing={onSubmit}
|
||||
placeholder="https://github.com/owner/repo.git"
|
||||
returnKeyType="done"
|
||||
style={styles.remotePromptInput}
|
||||
value={remoteUrl}
|
||||
/>
|
||||
{!hasGitHubOAuthClientId ? (
|
||||
<Text style={styles.remotePromptError}>GitHub login needs EXPO_PUBLIC_GITHUB_OAUTH_CLIENT_ID</Text>
|
||||
) : null}
|
||||
{failed ? <Text style={styles.remotePromptError}>Enter a valid Git remote URL</Text> : null}
|
||||
<View style={styles.remotePromptActions}>
|
||||
<PromptButton label="Cancel" onPress={onCancel} />
|
||||
<PromptButton label={isSaving ? 'Saving' : 'Save'} onPress={onSubmit} disabled={isSaving} primary />
|
||||
</View>
|
||||
</View>
|
||||
)
|
||||
}
|
||||
|
||||
function PromptButton({
|
||||
disabled,
|
||||
label,
|
||||
onPress,
|
||||
primary,
|
||||
}: {
|
||||
disabled?: boolean
|
||||
label: string
|
||||
onPress: () => void
|
||||
primary?: boolean
|
||||
}) {
|
||||
return (
|
||||
<Pressable
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={({ pressed }) => [
|
||||
styles.remotePromptAction,
|
||||
primary ? styles.remotePromptActionPrimary : null,
|
||||
disabled ? styles.remotePromptActionDisabled : null,
|
||||
pressed ? styles.pressed : null,
|
||||
]}
|
||||
>
|
||||
<Text style={[styles.remotePromptActionText, primary ? styles.remotePromptActionTextPrimary : null]}>{label}</Text>
|
||||
</Pressable>
|
||||
)
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import {
|
||||
Archive,
|
||||
Books,
|
||||
Drop,
|
||||
FileText,
|
||||
Flag,
|
||||
GitBranch,
|
||||
PenNib,
|
||||
Robot,
|
||||
Star,
|
||||
Sun,
|
||||
Tray,
|
||||
Wrench,
|
||||
} from 'phosphor-react-native'
|
||||
|
||||
export type IconName = 'archive' | 'books' | 'drop' | 'file-text' | 'flag' | 'git-branch' | 'pen-nib' | 'robot' | 'star' | 'sun' | 'tray' | 'wrench'
|
||||
|
||||
const iconByName = {
|
||||
archive: Archive,
|
||||
books: Books,
|
||||
drop: Drop,
|
||||
'file-text': FileText,
|
||||
flag: Flag,
|
||||
'git-branch': GitBranch,
|
||||
'pen-nib': PenNib,
|
||||
robot: Robot,
|
||||
star: Star,
|
||||
sun: Sun,
|
||||
tray: Tray,
|
||||
wrench: Wrench,
|
||||
} as const
|
||||
|
||||
export function NamedIcon({ color, name, size }: { color: string; name: IconName; size: number }) {
|
||||
const Icon = iconByName[name]
|
||||
return <Icon color={color} size={size} weight="regular" />
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
import { View } from 'react-native'
|
||||
import {
|
||||
PanGestureHandler,
|
||||
State,
|
||||
type PanGestureHandlerStateChangeEvent,
|
||||
} from 'react-native-gesture-handler'
|
||||
import { compactSwipeEvent, detectHorizontalSwipe } from './compactGestures'
|
||||
import type { CompactNavigationEvent, CompactPanel } from './compactNavigation'
|
||||
import { styles } from './styles'
|
||||
|
||||
export function SwipeSurface({
|
||||
children,
|
||||
panel,
|
||||
onNavigate,
|
||||
}: {
|
||||
children: React.ReactNode
|
||||
panel: CompactPanel
|
||||
onNavigate: (event: CompactNavigationEvent) => void
|
||||
}) {
|
||||
const handleStateChange = (event: PanGestureHandlerStateChangeEvent) => {
|
||||
if (event.nativeEvent.state !== State.END) {
|
||||
return
|
||||
}
|
||||
|
||||
const direction = detectHorizontalSwipe(event.nativeEvent)
|
||||
const navigationEvent = direction ? compactSwipeEvent(panel, direction) : null
|
||||
if (navigationEvent) {
|
||||
onNavigate(navigationEvent)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<PanGestureHandler activeOffsetX={[-18, 18]} failOffsetY={[-24, 24]} onHandlerStateChange={handleStateChange}>
|
||||
<View style={styles.swipeSurface}>{children}</View>
|
||||
</PanGestureHandler>
|
||||
)
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { compactSwipeEvent, detectHorizontalSwipe } from './compactGestures'
|
||||
|
||||
describe('compact mobile gestures', () => {
|
||||
it('ignores short slow horizontal drags', () => {
|
||||
expect(detectHorizontalSwipe({ translationX: 24, velocityX: 90 })).toBeNull()
|
||||
})
|
||||
|
||||
it('detects committed left and right swipes', () => {
|
||||
expect(detectHorizontalSwipe({ translationX: -72, velocityX: -120 })).toBe('left')
|
||||
expect(detectHorizontalSwipe({ translationX: 20, velocityX: 520 })).toBe('right')
|
||||
})
|
||||
|
||||
it('maps the requested Bear-style compact panel swipes', () => {
|
||||
expect(compactSwipeEvent('list', 'left')).toEqual({ type: 'openSidebar' })
|
||||
expect(compactSwipeEvent('sidebar', 'right')).toEqual({ type: 'closeSidebar' })
|
||||
expect(compactSwipeEvent('note', 'right')).toEqual({ type: 'openProperties' })
|
||||
expect(compactSwipeEvent('properties', 'left')).toEqual({ type: 'closeProperties' })
|
||||
})
|
||||
|
||||
it('does not invent transitions for unsupported panel directions', () => {
|
||||
expect(compactSwipeEvent('list', 'right')).toBeNull()
|
||||
expect(compactSwipeEvent('note', 'left')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { CompactNavigationEvent, CompactPanel } from './compactNavigation'
|
||||
|
||||
export type SwipeDirection = 'left' | 'right'
|
||||
|
||||
export type SwipeSample = {
|
||||
translationX: number
|
||||
velocityX: number
|
||||
}
|
||||
|
||||
const MIN_TRANSLATION = 56
|
||||
const MIN_VELOCITY = 420
|
||||
const compactGestureEvents: Partial<Record<`${CompactPanel}:${SwipeDirection}`, CompactNavigationEvent>> = {
|
||||
'list:left': { type: 'openSidebar' },
|
||||
'sidebar:right': { type: 'closeSidebar' },
|
||||
'note:right': { type: 'openProperties' },
|
||||
'properties:left': { type: 'closeProperties' },
|
||||
}
|
||||
|
||||
export function detectHorizontalSwipe(sample: SwipeSample): SwipeDirection | null {
|
||||
if (!isCommittedSwipe(sample)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return sample.translationX < 0 ? 'left' : 'right'
|
||||
}
|
||||
|
||||
export function compactSwipeEvent(
|
||||
panel: CompactPanel,
|
||||
direction: SwipeDirection,
|
||||
): CompactNavigationEvent | null {
|
||||
return compactGestureEvents[`${panel}:${direction}`] ?? null
|
||||
}
|
||||
|
||||
function isCommittedSwipe(sample: SwipeSample) {
|
||||
return Math.abs(sample.translationX) >= MIN_TRANSLATION || Math.abs(sample.velocityX) >= MIN_VELOCITY
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createCompactNavigationState,
|
||||
transitionCompactNavigation,
|
||||
type CompactNavigationState,
|
||||
} from './compactNavigation'
|
||||
|
||||
describe('compact mobile navigation', () => {
|
||||
it('starts on the note list with the first note selected', () => {
|
||||
expect(createCompactNavigationState('workflow')).toEqual({
|
||||
panel: 'list',
|
||||
selectedNoteId: 'workflow',
|
||||
})
|
||||
})
|
||||
|
||||
it('opens a selected note from the list', () => {
|
||||
const next = transitionCompactNavigation(createCompactNavigationState('workflow'), {
|
||||
type: 'selectNote',
|
||||
noteId: 'release',
|
||||
})
|
||||
|
||||
expect(next).toEqual({
|
||||
panel: 'note',
|
||||
selectedNoteId: 'release',
|
||||
})
|
||||
})
|
||||
|
||||
it('returns from sidebar and note surfaces to the list', () => {
|
||||
expect(panelAfter({ type: 'openSidebar' })).toBe('sidebar')
|
||||
expect(panelAfter({ type: 'closeSidebar' }, 'sidebar')).toBe('list')
|
||||
expect(panelAfter({ type: 'backToList' }, 'note')).toBe('list')
|
||||
})
|
||||
|
||||
it('opens and closes note properties without changing the selected note', () => {
|
||||
const noteState: CompactNavigationState = {
|
||||
panel: 'note',
|
||||
selectedNoteId: 'workflow',
|
||||
}
|
||||
|
||||
const propertiesState = transitionCompactNavigation(noteState, { type: 'openProperties' })
|
||||
const closedState = transitionCompactNavigation(propertiesState, { type: 'closeProperties' })
|
||||
|
||||
expect(propertiesState).toEqual({
|
||||
panel: 'properties',
|
||||
selectedNoteId: 'workflow',
|
||||
})
|
||||
expect(closedState).toEqual({
|
||||
panel: 'note',
|
||||
selectedNoteId: 'workflow',
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function panelAfter(
|
||||
event: Parameters<typeof transitionCompactNavigation>[1],
|
||||
panel: CompactNavigationState['panel'] = 'list',
|
||||
) {
|
||||
const state = transitionCompactNavigation({ panel, selectedNoteId: 'workflow' }, event)
|
||||
return state.panel
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
export type CompactPanel = 'sidebar' | 'list' | 'note' | 'properties'
|
||||
|
||||
export type CompactNavigationState = {
|
||||
panel: CompactPanel
|
||||
selectedNoteId: string
|
||||
}
|
||||
|
||||
export type CompactNavigationEvent =
|
||||
| { type: 'backToList' }
|
||||
| { type: 'closeProperties' }
|
||||
| { type: 'closeSidebar' }
|
||||
| { type: 'openProperties' }
|
||||
| { type: 'openSidebar' }
|
||||
| { type: 'selectNote'; noteId: string }
|
||||
|
||||
export function createCompactNavigationState(initialNoteId: string): CompactNavigationState {
|
||||
return {
|
||||
panel: 'list',
|
||||
selectedNoteId: initialNoteId,
|
||||
}
|
||||
}
|
||||
|
||||
export function transitionCompactNavigation(
|
||||
state: CompactNavigationState,
|
||||
event: CompactNavigationEvent,
|
||||
): CompactNavigationState {
|
||||
if (event.type === 'selectNote') {
|
||||
return { panel: 'note', selectedNoteId: event.noteId }
|
||||
}
|
||||
|
||||
return {
|
||||
...state,
|
||||
panel: nextPanel(state.panel, event),
|
||||
}
|
||||
}
|
||||
|
||||
function nextPanel(currentPanel: CompactPanel, event: Exclude<CompactNavigationEvent, { type: 'selectNote' }>) {
|
||||
if (event.type === 'openSidebar') {
|
||||
return 'sidebar'
|
||||
}
|
||||
|
||||
if (event.type === 'closeSidebar' || event.type === 'backToList') {
|
||||
return 'list'
|
||||
}
|
||||
|
||||
if (event.type === 'openProperties') {
|
||||
return 'properties'
|
||||
}
|
||||
|
||||
if (event.type === 'closeProperties') {
|
||||
return 'note'
|
||||
}
|
||||
|
||||
return currentPanel
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { notes } from './demoData'
|
||||
import { createMobileSidebarSections } from './mobileSidebarNavigation'
|
||||
|
||||
describe('mobile demo data', () => {
|
||||
it('derives note titles and snippets through shared markdown utilities', () => {
|
||||
expect(notes[0].title).toBe('Workflow Orchestration Essay')
|
||||
expect(notes[0].snippet).toContain('The current narrative / temptation')
|
||||
expect(notes[0].words).toBeGreaterThan(20)
|
||||
})
|
||||
|
||||
it('keeps the initial sidebar focused on inbox', () => {
|
||||
const sidebarSections = createMobileSidebarSections(notes)
|
||||
|
||||
expect(sidebarSections[0].items[0]).toMatchObject({
|
||||
label: 'Inbox',
|
||||
selection: { kind: 'library', id: 'inbox' },
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,242 +0,0 @@
|
||||
import { projectMobileNotes, type MobileNote, type MobileNoteSource } from './mobileNoteProjection'
|
||||
import { createFixtureMobileVaultRepository } from './mobileVaultRepository'
|
||||
|
||||
export type { MobileNote } from './mobileNoteProjection'
|
||||
|
||||
export const demoNoteSources: MobileNoteSource[] = [
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['Tolaria MVP'],
|
||||
customProperties: { review_stage: 'Draft outline' },
|
||||
favorite: true,
|
||||
favoriteIndex: 0,
|
||||
has: ['workflow-orchestration-checklist'],
|
||||
id: 'workflow',
|
||||
type: 'Essay',
|
||||
icon: 'pen-nib',
|
||||
date: 'May 13, 2026',
|
||||
modified: '6h ago',
|
||||
filename: 'workflow.md',
|
||||
relatedTo: ['release', 'mobile-roadmap'],
|
||||
relationships: { people: ['Malte Ubl'], topics: ['workflow orchestration'] },
|
||||
tags: ['Design Inspiration', 'Tolaria MVP'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Workflow Orchestration Essay',
|
||||
'_favorite: true',
|
||||
'_favorite_index: 0',
|
||||
'type: Essay',
|
||||
'status: Draft',
|
||||
'tags: [Design Inspiration, Tolaria MVP]',
|
||||
'belongs_to: [Tolaria MVP]',
|
||||
'related_to: [release, mobile-roadmap]',
|
||||
'has: [workflow-orchestration-checklist]',
|
||||
'people: [Malte Ubl]',
|
||||
'review_stage: Draft outline',
|
||||
'topics: [workflow orchestration]',
|
||||
'---',
|
||||
'',
|
||||
'# Workflow Orchestration Essay',
|
||||
'',
|
||||
'- The current narrative / temptation: everything routed through an LLM.',
|
||||
'- A real example (Tolaria + OpenClaw): OpenClaw does a lot for me in product development.',
|
||||
'- The cost of AI everywhere: expensive, slow, and unpredictable.',
|
||||
'- Where orchestration wins: observability, human-in-the-loop approvals, reliability.',
|
||||
'',
|
||||
'This connects to [[mobile-roadmap|the mobile roadmap]] and the [[workflow-orchestration-checklist]].',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['Tolaria MVP'],
|
||||
customProperties: { platform: 'iPad first' },
|
||||
favorite: true,
|
||||
favoriteIndex: 1,
|
||||
has: ['workflow'],
|
||||
id: 'mobile-roadmap',
|
||||
type: 'Project',
|
||||
icon: 'wrench',
|
||||
date: 'May 5, 2026',
|
||||
modified: '1h ago',
|
||||
filename: 'mobile-roadmap.md',
|
||||
relatedTo: ['release'],
|
||||
relationships: { depends_on: ['workflow-orchestration-checklist'] },
|
||||
tags: ['Tolaria MVP', 'mobile'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Mobile Roadmap',
|
||||
'_favorite: true',
|
||||
'_favorite_index: 1',
|
||||
'type: Project',
|
||||
'status: Active',
|
||||
'tags: [Tolaria MVP, mobile]',
|
||||
'belongs_to: [Tolaria MVP]',
|
||||
'related_to: [release]',
|
||||
'has: [workflow]',
|
||||
'depends_on: [workflow-orchestration-checklist]',
|
||||
'platform: iPad first',
|
||||
'---',
|
||||
'',
|
||||
'# Mobile Roadmap',
|
||||
'',
|
||||
'Local-first workflow parity comes before cloud sync.',
|
||||
'',
|
||||
'- Sidebar navigation by type',
|
||||
'- Raw editor for direct markdown edits',
|
||||
'- Wikilinks like [[workflow]] and [[release]]',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['workflow'],
|
||||
customProperties: {},
|
||||
has: [],
|
||||
id: 'workflow-orchestration-checklist',
|
||||
type: 'Note',
|
||||
icon: 'file-text',
|
||||
date: 'May 5, 2026',
|
||||
modified: '2h ago',
|
||||
filename: 'workflow-orchestration-checklist.md',
|
||||
relatedTo: ['workflow'],
|
||||
relationships: {},
|
||||
tags: ['mobile'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Workflow Orchestration Checklist',
|
||||
'type: Note',
|
||||
'status: Draft',
|
||||
'tags: [mobile]',
|
||||
'belongs_to: [workflow]',
|
||||
'related_to: [workflow]',
|
||||
'---',
|
||||
'',
|
||||
'# Workflow Orchestration Checklist',
|
||||
'',
|
||||
'- Validate breadcrumbs',
|
||||
'- Validate [[workflow]] wikilinks',
|
||||
'- Validate relationships panel',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['Tolaria MVP'],
|
||||
customProperties: {},
|
||||
has: [],
|
||||
id: 'release',
|
||||
type: 'Release Note',
|
||||
icon: 'flag',
|
||||
date: 'May 2, 2026',
|
||||
modified: '12h ago',
|
||||
filename: 'release.md',
|
||||
relatedTo: ['workflow', 'mobile-roadmap'],
|
||||
relationships: {},
|
||||
tags: ['Release', 'Stable'],
|
||||
content: [
|
||||
'---',
|
||||
'title: v2026-05-02',
|
||||
'type: Release Note',
|
||||
'status: Done',
|
||||
'tags: [Release, Stable]',
|
||||
'belongs_to: [Tolaria MVP]',
|
||||
'related_to: [workflow, mobile-roadmap]',
|
||||
'---',
|
||||
'',
|
||||
'# v2026-05-02',
|
||||
'',
|
||||
'Another Tolaria release in the bag. This one is focused on performance, bug fixes, and lower-friction note workflows.',
|
||||
'',
|
||||
'Follow-up work lives in [[mobile-roadmap]].',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['Tolaria MVP'],
|
||||
customProperties: {},
|
||||
has: ['resources'],
|
||||
id: 'migration',
|
||||
type: 'Project',
|
||||
icon: 'git-branch',
|
||||
date: 'Apr 28, 2026',
|
||||
modified: '1d ago',
|
||||
filename: 'migration.md',
|
||||
relatedTo: ['mobile-roadmap'],
|
||||
relationships: {},
|
||||
tags: ['Project', 'Resources'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Tolaria <> Obsidian migration proposal',
|
||||
'type: Project',
|
||||
'status: Active',
|
||||
'tags: [Project, Resources]',
|
||||
'belongs_to: [Tolaria MVP]',
|
||||
'related_to: [mobile-roadmap]',
|
||||
'has: [resources]',
|
||||
'---',
|
||||
'',
|
||||
'# Tolaria <> Obsidian migration proposal',
|
||||
'',
|
||||
'Obsidian vaults are already close to Tolaria ideal substrate: local Markdown, portable attachments, and git-backed history.',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: false,
|
||||
belongsTo: ['migration'],
|
||||
customProperties: {},
|
||||
has: [],
|
||||
id: 'resources',
|
||||
type: 'Resource',
|
||||
icon: 'books',
|
||||
date: 'Apr 20, 2026',
|
||||
modified: '3d ago',
|
||||
filename: 'resources.md',
|
||||
relatedTo: ['migration', 'mobile-roadmap'],
|
||||
relationships: {},
|
||||
tags: ['Resources', 'mobile'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Mobile Resources',
|
||||
'type: Resource',
|
||||
'status: Active',
|
||||
'tags: [Resources, mobile]',
|
||||
'belongs_to: [migration]',
|
||||
'related_to: [migration, mobile-roadmap]',
|
||||
'---',
|
||||
'',
|
||||
'# Mobile Resources',
|
||||
'',
|
||||
'References for [[mobile-roadmap]] and local vault workflow QA.',
|
||||
].join('\n'),
|
||||
},
|
||||
{
|
||||
archived: true,
|
||||
belongsTo: [],
|
||||
customProperties: {},
|
||||
has: [],
|
||||
id: 'old-mobile-spike',
|
||||
type: 'Note',
|
||||
icon: 'archive',
|
||||
date: 'Mar 30, 2026',
|
||||
modified: 'last month',
|
||||
filename: 'old-mobile-spike.md',
|
||||
relatedTo: ['mobile-roadmap'],
|
||||
relationships: {},
|
||||
tags: ['mobile'],
|
||||
content: [
|
||||
'---',
|
||||
'title: Old Mobile Spike',
|
||||
'type: Note',
|
||||
'archived: true',
|
||||
'tags: [mobile]',
|
||||
'related_to: [mobile-roadmap]',
|
||||
'---',
|
||||
'',
|
||||
'# Old Mobile Spike',
|
||||
'',
|
||||
'Archived prototype notes kept around for comparison with [[mobile-roadmap]].',
|
||||
].join('\n'),
|
||||
},
|
||||
]
|
||||
|
||||
export const notes: MobileNote[] = projectMobileNotes(demoNoteSources)
|
||||
|
||||
export const demoVaultRepository = createFixtureMobileVaultRepository(demoNoteSources)
|
||||
@@ -1,58 +0,0 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { sendMobileAiRequest } from './mobileAiClient'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
|
||||
describe('mobile AI client', () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('sends an OpenAI-compatible chat completion request with note context', async () => {
|
||||
const fetchMock = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
|
||||
json: async () => ({ choices: [{ message: { content: 'Answer' } }] }),
|
||||
ok: true,
|
||||
} as Response)
|
||||
|
||||
await expect(sendMobileAiRequest({
|
||||
apiKey: 'key',
|
||||
note: note(),
|
||||
prompt: 'Summarize',
|
||||
provider: {
|
||||
baseUrl: 'https://api.example.com/v1/',
|
||||
id: 'provider',
|
||||
kind: 'open_ai_compatible',
|
||||
modelId: 'model',
|
||||
name: 'Provider',
|
||||
},
|
||||
})).resolves.toBe('Answer')
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith('https://api.example.com/v1/chat/completions', expect.objectContaining({
|
||||
method: 'POST',
|
||||
}))
|
||||
})
|
||||
})
|
||||
|
||||
function note(): MobileNote {
|
||||
return {
|
||||
archived: false,
|
||||
backlinks: [],
|
||||
belongsTo: [],
|
||||
content: '# Workflow\n\nBody',
|
||||
customProperties: {},
|
||||
date: '',
|
||||
favorite: false,
|
||||
favoriteIndex: null,
|
||||
has: [],
|
||||
icon: 'file-text',
|
||||
id: 'workflow',
|
||||
modified: '',
|
||||
outgoingLinks: [],
|
||||
relatedTo: [],
|
||||
relationships: {},
|
||||
snippet: '',
|
||||
tags: [],
|
||||
title: 'Workflow',
|
||||
type: 'Note',
|
||||
words: 1,
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import type { MobileAiProvider } from './mobileAiSettings'
|
||||
|
||||
export type MobileAiRequest = {
|
||||
apiKey: string
|
||||
note: MobileNote
|
||||
prompt: string
|
||||
provider: MobileAiProvider
|
||||
}
|
||||
|
||||
export async function sendMobileAiRequest(request: MobileAiRequest) {
|
||||
const response = await fetch(`${request.provider.baseUrl.replace(/\/$/, '')}/chat/completions`, {
|
||||
body: JSON.stringify({
|
||||
messages: [
|
||||
{
|
||||
content: [
|
||||
'You are helping with a Tolaria markdown note.',
|
||||
'Use concise answers and preserve [[wikilink]] syntax when referencing notes.',
|
||||
`Active note: ${request.note.title}`,
|
||||
request.note.content,
|
||||
].join('\n\n'),
|
||||
role: 'system',
|
||||
},
|
||||
{ content: request.prompt, role: 'user' },
|
||||
],
|
||||
model: request.provider.modelId,
|
||||
}),
|
||||
headers: {
|
||||
Authorization: `Bearer ${request.apiKey}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
method: 'POST',
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`AI request failed with ${response.status}`)
|
||||
}
|
||||
|
||||
return extractAssistantMessage(await response.json())
|
||||
}
|
||||
|
||||
function extractAssistantMessage(payload: unknown) {
|
||||
const content = (payload as { choices?: Array<{ message?: { content?: unknown } }> }).choices?.[0]?.message?.content
|
||||
return typeof content === 'string' ? content : ''
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileAiProviderSecretStorage } from './mobileAiProviderSecretStorage'
|
||||
|
||||
describe('mobile AI provider secret storage', () => {
|
||||
it('stores API keys in secure provider-scoped records', async () => {
|
||||
const secrets = new Map<string, string>()
|
||||
const storage = createMobileAiProviderSecretStorage({
|
||||
deleteItemAsync: async (key) => {
|
||||
secrets.delete(key)
|
||||
},
|
||||
getItemAsync: async (key) => secrets.get(key) ?? null,
|
||||
setItemAsync: async (key, value) => {
|
||||
secrets.set(key, value)
|
||||
},
|
||||
})
|
||||
|
||||
await storage.saveApiKey('Open-AI', 'secret')
|
||||
|
||||
expect(await storage.loadApiKey('open-ai')).toBe('secret')
|
||||
|
||||
await storage.removeApiKey('open-ai')
|
||||
|
||||
expect(await storage.loadApiKey('open-ai')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,29 +0,0 @@
|
||||
export type MobileAiProviderSecretStore = {
|
||||
deleteItemAsync: (key: string) => Promise<void>
|
||||
getItemAsync: (key: string) => Promise<string | null>
|
||||
setItemAsync: (key: string, value: string) => Promise<void>
|
||||
}
|
||||
|
||||
export type MobileAiProviderSecretStorage = {
|
||||
loadApiKey: (providerId: string) => Promise<string | null>
|
||||
removeApiKey: (providerId: string) => Promise<void>
|
||||
saveApiKey: (providerId: string, apiKey: string) => Promise<void>
|
||||
}
|
||||
|
||||
export function createMobileAiProviderSecretStorage(
|
||||
secureStore: MobileAiProviderSecretStore,
|
||||
): MobileAiProviderSecretStorage {
|
||||
return {
|
||||
loadApiKey: async (providerId) => secureStore.getItemAsync(providerKey(providerId)),
|
||||
removeApiKey: async (providerId) => {
|
||||
await secureStore.deleteItemAsync(providerKey(providerId))
|
||||
},
|
||||
saveApiKey: async (providerId, apiKey) => {
|
||||
await secureStore.setItemAsync(providerKey(providerId), apiKey)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function providerKey(providerId: string) {
|
||||
return ['tolaria', 'ai-provider', providerId.trim().toLowerCase(), 'api-key'].join(':')
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
buildMobileAiProvider,
|
||||
normalizeMobileAiSettings,
|
||||
removeMobileAiProvider,
|
||||
selectedMobileAiProvider,
|
||||
upsertMobileAiProvider,
|
||||
} from './mobileAiSettings'
|
||||
|
||||
describe('mobile AI settings', () => {
|
||||
it('builds API providers from presets without storing API keys', () => {
|
||||
expect(buildMobileAiProvider({
|
||||
draft: {
|
||||
apiKey: 'secret',
|
||||
kind: 'open_ai',
|
||||
modelId: ' gpt-4.1-mini ',
|
||||
name: '',
|
||||
},
|
||||
providerId: 'open-ai',
|
||||
})).toEqual({
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
id: 'open-ai',
|
||||
kind: 'open_ai',
|
||||
modelId: 'gpt-4.1-mini',
|
||||
name: 'OpenAI',
|
||||
})
|
||||
})
|
||||
|
||||
it('normalizes persisted settings and selected provider', () => {
|
||||
const settings = normalizeMobileAiSettings({
|
||||
defaultProviderId: 'open-ai',
|
||||
providers: [{
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
id: 'open-ai',
|
||||
kind: 'open_ai',
|
||||
modelId: 'gpt-4.1-mini',
|
||||
name: 'OpenAI',
|
||||
}],
|
||||
})
|
||||
|
||||
expect(selectedMobileAiProvider(settings)?.id).toBe('open-ai')
|
||||
})
|
||||
|
||||
it('upserts and removes providers while maintaining the default target', () => {
|
||||
const settings = upsertMobileAiProvider({
|
||||
provider: provider('one'),
|
||||
settings: { defaultProviderId: null, providers: [] },
|
||||
})
|
||||
|
||||
expect(settings.defaultProviderId).toBe('one')
|
||||
expect(removeMobileAiProvider({ providerId: 'one', settings })).toEqual({
|
||||
defaultProviderId: null,
|
||||
providers: [],
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function provider(id: string) {
|
||||
return {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
id,
|
||||
kind: 'open_ai' as const,
|
||||
modelId: 'gpt-4.1-mini',
|
||||
name: 'OpenAI',
|
||||
}
|
||||
}
|
||||
@@ -1,166 +0,0 @@
|
||||
export type MobileAiProviderKind = 'anthropic' | 'gemini' | 'open_ai' | 'open_ai_compatible' | 'open_router'
|
||||
|
||||
export type MobileAiProvider = {
|
||||
baseUrl: string
|
||||
id: string
|
||||
kind: MobileAiProviderKind
|
||||
modelId: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type MobileAiSettings = {
|
||||
defaultProviderId: string | null
|
||||
providers: MobileAiProvider[]
|
||||
}
|
||||
|
||||
export type MobileAiProviderDraft = {
|
||||
apiKey: string
|
||||
kind: MobileAiProviderKind
|
||||
modelId: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export const defaultMobileAiSettings: MobileAiSettings = {
|
||||
defaultProviderId: null,
|
||||
providers: [],
|
||||
}
|
||||
|
||||
export const mobileAiProviderPresets: Record<MobileAiProviderKind, { baseUrl: string; name: string; placeholder: string }> = {
|
||||
anthropic: {
|
||||
baseUrl: 'https://api.anthropic.com/v1',
|
||||
name: 'Anthropic',
|
||||
placeholder: 'claude-3-5-sonnet-latest',
|
||||
},
|
||||
gemini: {
|
||||
baseUrl: 'https://generativelanguage.googleapis.com/v1beta/openai',
|
||||
name: 'Gemini',
|
||||
placeholder: 'gemini-2.5-flash',
|
||||
},
|
||||
open_ai: {
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
name: 'OpenAI',
|
||||
placeholder: 'gpt-4.1-mini',
|
||||
},
|
||||
open_ai_compatible: {
|
||||
baseUrl: 'https://api.example.com/v1',
|
||||
name: 'Custom provider',
|
||||
placeholder: 'model-id',
|
||||
},
|
||||
open_router: {
|
||||
baseUrl: 'https://openrouter.ai/api/v1',
|
||||
name: 'OpenRouter',
|
||||
placeholder: 'openai/gpt-4.1-mini',
|
||||
},
|
||||
}
|
||||
|
||||
export function buildMobileAiProvider({
|
||||
draft,
|
||||
providerId,
|
||||
}: {
|
||||
draft: MobileAiProviderDraft
|
||||
providerId: string
|
||||
}): MobileAiProvider {
|
||||
const preset = mobileAiProviderPresets[draft.kind]
|
||||
return {
|
||||
baseUrl: preset.baseUrl,
|
||||
id: providerId,
|
||||
kind: draft.kind,
|
||||
modelId: draft.modelId.trim(),
|
||||
name: draft.name.trim() || preset.name,
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeMobileAiSettings(value: unknown): MobileAiSettings {
|
||||
if (!isSettingsRecord(value)) {
|
||||
return defaultMobileAiSettings
|
||||
}
|
||||
|
||||
const providers = value.providers.flatMap(normalizeMobileAiProvider)
|
||||
return {
|
||||
defaultProviderId: defaultProviderId({ providers, value: value.defaultProviderId }),
|
||||
providers,
|
||||
}
|
||||
}
|
||||
|
||||
export function selectedMobileAiProvider(settings: MobileAiSettings) {
|
||||
return settings.providers.find((provider) => provider.id === settings.defaultProviderId) ?? settings.providers[0] ?? null
|
||||
}
|
||||
|
||||
export function upsertMobileAiProvider({
|
||||
provider,
|
||||
settings,
|
||||
}: {
|
||||
provider: MobileAiProvider
|
||||
settings: MobileAiSettings
|
||||
}): MobileAiSettings {
|
||||
const providers = [provider, ...settings.providers.filter((item) => item.id !== provider.id)]
|
||||
return { defaultProviderId: provider.id, providers }
|
||||
}
|
||||
|
||||
export function removeMobileAiProvider({
|
||||
providerId,
|
||||
settings,
|
||||
}: {
|
||||
providerId: string
|
||||
settings: MobileAiSettings
|
||||
}): MobileAiSettings {
|
||||
const providers = settings.providers.filter((provider) => provider.id !== providerId)
|
||||
return {
|
||||
defaultProviderId: settings.defaultProviderId === providerId ? providers[0]?.id ?? null : settings.defaultProviderId,
|
||||
providers,
|
||||
}
|
||||
}
|
||||
|
||||
function defaultProviderId({
|
||||
providers,
|
||||
value,
|
||||
}: {
|
||||
providers: MobileAiProvider[]
|
||||
value: unknown
|
||||
}) {
|
||||
return typeof value === 'string' && providers.some((provider) => provider.id === value)
|
||||
? value
|
||||
: providers[0]?.id ?? null
|
||||
}
|
||||
|
||||
function normalizeMobileAiProvider(value: unknown): MobileAiProvider[] {
|
||||
if (!isProviderRecord(value)) {
|
||||
return []
|
||||
}
|
||||
|
||||
return [{
|
||||
baseUrl: value.baseUrl.trim(),
|
||||
id: value.id.trim(),
|
||||
kind: value.kind,
|
||||
modelId: value.modelId.trim(),
|
||||
name: value.name.trim(),
|
||||
}]
|
||||
}
|
||||
|
||||
function isSettingsRecord(value: unknown): value is { defaultProviderId?: unknown; providers: unknown[] } {
|
||||
return typeof value === 'object'
|
||||
&& value !== null
|
||||
&& Array.isArray((value as { providers?: unknown }).providers)
|
||||
}
|
||||
|
||||
function isProviderRecord(value: unknown): value is MobileAiProvider {
|
||||
return typeof value === 'object'
|
||||
&& value !== null
|
||||
&& hasText((value as MobileAiProvider).baseUrl)
|
||||
&& hasText((value as MobileAiProvider).id)
|
||||
&& isProviderKind((value as MobileAiProvider).kind)
|
||||
&& hasText((value as MobileAiProvider).modelId)
|
||||
&& hasText((value as MobileAiProvider).name)
|
||||
}
|
||||
|
||||
function hasText(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.trim().length > 0
|
||||
}
|
||||
|
||||
function isProviderKind(value: unknown): value is MobileAiProviderKind {
|
||||
return value === 'anthropic'
|
||||
|| value === 'gemini'
|
||||
|| value === 'open_ai'
|
||||
|| value === 'open_ai_compatible'
|
||||
|| value === 'open_router'
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileAiSettingsStorage } from './mobileAiSettingsStorage'
|
||||
|
||||
describe('mobile AI settings storage', () => {
|
||||
it('loads default settings when no file exists and saves normalized settings', async () => {
|
||||
const files = new Map<string, string>()
|
||||
const storage = createMobileAiSettingsStorage({
|
||||
documentDirectory: 'file:///docs',
|
||||
getInfoAsync: async (uri) => ({ exists: files.has(uri) }),
|
||||
makeDirectoryAsync: async (uri) => {
|
||||
files.set(uri, '')
|
||||
},
|
||||
readAsStringAsync: async (uri) => files.get(uri) ?? '',
|
||||
writeAsStringAsync: async (uri, content) => {
|
||||
files.set(uri, content)
|
||||
},
|
||||
})
|
||||
|
||||
expect(await storage.load()).toEqual({ defaultProviderId: null, providers: [] })
|
||||
|
||||
await storage.save({
|
||||
defaultProviderId: 'provider',
|
||||
providers: [{
|
||||
baseUrl: 'https://api.openai.com/v1',
|
||||
id: 'provider',
|
||||
kind: 'open_ai',
|
||||
modelId: 'gpt-4.1-mini',
|
||||
name: 'OpenAI',
|
||||
}],
|
||||
})
|
||||
|
||||
expect(await storage.load()).toMatchObject({ defaultProviderId: 'provider' })
|
||||
})
|
||||
})
|
||||
@@ -1,82 +0,0 @@
|
||||
import { defaultMobileAiSettings, normalizeMobileAiSettings, type MobileAiSettings } from './mobileAiSettings'
|
||||
|
||||
export type MobileAiSettingsFileInfo = {
|
||||
exists: boolean
|
||||
isDirectory?: boolean
|
||||
}
|
||||
|
||||
export type MobileAiSettingsFileSystem = {
|
||||
documentDirectory: string | null
|
||||
getInfoAsync: (uri: string) => Promise<MobileAiSettingsFileInfo>
|
||||
makeDirectoryAsync: (uri: string, options: { intermediates: true }) => Promise<void>
|
||||
readAsStringAsync: (uri: string) => Promise<string>
|
||||
writeAsStringAsync: (uri: string, content: string) => Promise<void>
|
||||
}
|
||||
|
||||
export type MobileAiSettingsStorage = {
|
||||
load: () => Promise<MobileAiSettings>
|
||||
save: (settings: MobileAiSettings) => Promise<void>
|
||||
}
|
||||
|
||||
export function createMobileAiSettingsStorage(
|
||||
fileSystem: MobileAiSettingsFileSystem,
|
||||
): MobileAiSettingsStorage {
|
||||
return {
|
||||
load: async () => loadMobileAiSettings(fileSystem),
|
||||
save: async (settings) => saveMobileAiSettings({ fileSystem, settings }),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMobileAiSettings(fileSystem: MobileAiSettingsFileSystem) {
|
||||
const fileUri = settingsFileUri(fileSystem)
|
||||
const info = await fileSystem.getInfoAsync(fileUri)
|
||||
if (!info.exists || info.isDirectory) {
|
||||
return defaultMobileAiSettings
|
||||
}
|
||||
|
||||
return parseMobileAiSettings(await fileSystem.readAsStringAsync(fileUri))
|
||||
}
|
||||
|
||||
async function saveMobileAiSettings({
|
||||
fileSystem,
|
||||
settings,
|
||||
}: {
|
||||
fileSystem: MobileAiSettingsFileSystem
|
||||
settings: MobileAiSettings
|
||||
}) {
|
||||
await ensureDirectory({ fileSystem, uri: settingsRootUri(fileSystem) })
|
||||
await fileSystem.writeAsStringAsync(settingsFileUri(fileSystem), JSON.stringify(settings))
|
||||
}
|
||||
|
||||
function parseMobileAiSettings(content: string) {
|
||||
try {
|
||||
return normalizeMobileAiSettings(JSON.parse(content))
|
||||
} catch {
|
||||
return defaultMobileAiSettings
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureDirectory({
|
||||
fileSystem,
|
||||
uri,
|
||||
}: {
|
||||
fileSystem: MobileAiSettingsFileSystem
|
||||
uri: string
|
||||
}) {
|
||||
const info = await fileSystem.getInfoAsync(uri)
|
||||
if (!info.exists) {
|
||||
await fileSystem.makeDirectoryAsync(uri, { intermediates: true })
|
||||
}
|
||||
}
|
||||
|
||||
function settingsFileUri(fileSystem: MobileAiSettingsFileSystem) {
|
||||
return `${settingsRootUri(fileSystem)}/ai-settings.json`
|
||||
}
|
||||
|
||||
function settingsRootUri(fileSystem: MobileAiSettingsFileSystem) {
|
||||
if (!fileSystem.documentDirectory) {
|
||||
throw new Error('Expo FileSystem documentDirectory is unavailable')
|
||||
}
|
||||
|
||||
return `${fileSystem.documentDirectory.replace(/\/+$/, '')}/state`
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
createMobileAppStateStorage,
|
||||
type MobileAppStateFileSystem,
|
||||
} from './mobileAppStateStorage'
|
||||
|
||||
describe('mobile app state storage', () => {
|
||||
it('returns default state when no app state file exists', async () => {
|
||||
const storage = createMobileAppStateStorage(createMemoryAppStateFileSystem())
|
||||
|
||||
await expect(storage.load('personal')).resolves.toEqual({
|
||||
activeVaultId: 'personal',
|
||||
selectedNoteId: null,
|
||||
})
|
||||
})
|
||||
|
||||
it('persists and restores selected note id for the active vault', async () => {
|
||||
const fileSystem = createMemoryAppStateFileSystem()
|
||||
const storage = createMobileAppStateStorage(fileSystem)
|
||||
|
||||
await storage.save({ activeVaultId: 'personal', selectedNoteId: 'workflow' })
|
||||
|
||||
await expect(storage.load('personal')).resolves.toEqual({
|
||||
activeVaultId: 'personal',
|
||||
selectedNoteId: 'workflow',
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores corrupt or mismatched state files', async () => {
|
||||
const fileSystem = createMemoryAppStateFileSystem({
|
||||
'file:///docs/state/app-state.json': '{"activeVaultId":"other","selectedNoteId":"workflow"}',
|
||||
})
|
||||
const storage = createMobileAppStateStorage(fileSystem)
|
||||
|
||||
await expect(storage.load('personal')).resolves.toEqual({
|
||||
activeVaultId: 'personal',
|
||||
selectedNoteId: null,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
function createMemoryAppStateFileSystem(files: Record<string, string> = {}): MobileAppStateFileSystem {
|
||||
const fileByUri = new Map(Object.entries(files))
|
||||
const directoryUris = new Set(['file:///docs'])
|
||||
|
||||
return {
|
||||
documentDirectory: 'file:///docs/',
|
||||
getInfoAsync: async (uri) => ({
|
||||
exists: fileByUri.has(uri) || directoryUris.has(uri),
|
||||
isDirectory: directoryUris.has(uri),
|
||||
}),
|
||||
makeDirectoryAsync: async (uri) => {
|
||||
directoryUris.add(uri)
|
||||
},
|
||||
readAsStringAsync: async (uri) => fileByUri.get(uri) ?? '',
|
||||
writeAsStringAsync: async (uri, content) => {
|
||||
fileByUri.set(uri, content)
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -1,126 +0,0 @@
|
||||
export type MobileAppState = {
|
||||
activeVaultId: string
|
||||
selectedNoteId: string | null
|
||||
}
|
||||
|
||||
export type MobileAppStateFileInfo = {
|
||||
exists: boolean
|
||||
isDirectory?: boolean
|
||||
}
|
||||
|
||||
export type MobileAppStateFileSystem = {
|
||||
documentDirectory: string | null
|
||||
getInfoAsync: (uri: string) => Promise<MobileAppStateFileInfo>
|
||||
makeDirectoryAsync: (uri: string, options: { intermediates: true }) => Promise<void>
|
||||
readAsStringAsync: (uri: string) => Promise<string>
|
||||
writeAsStringAsync: (uri: string, content: string) => Promise<void>
|
||||
}
|
||||
|
||||
export type MobileAppStateStorage = {
|
||||
load: (activeVaultId: string) => Promise<MobileAppState>
|
||||
save: (state: MobileAppState) => Promise<void>
|
||||
}
|
||||
|
||||
export function createMobileAppStateStorage(
|
||||
fileSystem: MobileAppStateFileSystem,
|
||||
): MobileAppStateStorage {
|
||||
return {
|
||||
load: async (activeVaultId) => loadMobileAppState({ activeVaultId, fileSystem }),
|
||||
save: async (state) => saveMobileAppState({ fileSystem, state }),
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMobileAppState({
|
||||
activeVaultId,
|
||||
fileSystem,
|
||||
}: {
|
||||
activeVaultId: string
|
||||
fileSystem: MobileAppStateFileSystem
|
||||
}) {
|
||||
const fileUri = appStateFileUri(fileSystem)
|
||||
const info = await fileSystem.getInfoAsync(fileUri)
|
||||
if (!info.exists || info.isDirectory) {
|
||||
return defaultMobileAppState(activeVaultId)
|
||||
}
|
||||
|
||||
return parseMobileAppState({
|
||||
activeVaultId,
|
||||
content: await fileSystem.readAsStringAsync(fileUri),
|
||||
})
|
||||
}
|
||||
|
||||
async function saveMobileAppState({
|
||||
fileSystem,
|
||||
state,
|
||||
}: {
|
||||
fileSystem: MobileAppStateFileSystem
|
||||
state: MobileAppState
|
||||
}) {
|
||||
const rootUri = appStateRootUri(fileSystem)
|
||||
await ensureDirectory({ fileSystem, uri: rootUri })
|
||||
await fileSystem.writeAsStringAsync(appStateFileUri(fileSystem), JSON.stringify(state))
|
||||
}
|
||||
|
||||
function parseMobileAppState({
|
||||
activeVaultId,
|
||||
content,
|
||||
}: {
|
||||
activeVaultId: string
|
||||
content: string
|
||||
}) {
|
||||
try {
|
||||
return coerceMobileAppState({ activeVaultId, value: JSON.parse(content) })
|
||||
} catch {
|
||||
return defaultMobileAppState(activeVaultId)
|
||||
}
|
||||
}
|
||||
|
||||
function coerceMobileAppState({
|
||||
activeVaultId,
|
||||
value,
|
||||
}: {
|
||||
activeVaultId: string
|
||||
value: unknown
|
||||
}): MobileAppState {
|
||||
if (!isStateRecord(value) || value.activeVaultId !== activeVaultId) {
|
||||
return defaultMobileAppState(activeVaultId)
|
||||
}
|
||||
|
||||
return {
|
||||
activeVaultId,
|
||||
selectedNoteId: typeof value.selectedNoteId === 'string' ? value.selectedNoteId : null,
|
||||
}
|
||||
}
|
||||
|
||||
function defaultMobileAppState(activeVaultId: string): MobileAppState {
|
||||
return { activeVaultId, selectedNoteId: null }
|
||||
}
|
||||
|
||||
async function ensureDirectory({
|
||||
fileSystem,
|
||||
uri,
|
||||
}: {
|
||||
fileSystem: MobileAppStateFileSystem
|
||||
uri: string
|
||||
}) {
|
||||
const info = await fileSystem.getInfoAsync(uri)
|
||||
if (!info.exists) {
|
||||
await fileSystem.makeDirectoryAsync(uri, { intermediates: true })
|
||||
}
|
||||
}
|
||||
|
||||
function appStateFileUri(fileSystem: MobileAppStateFileSystem) {
|
||||
return `${appStateRootUri(fileSystem)}/app-state.json`
|
||||
}
|
||||
|
||||
function appStateRootUri(fileSystem: MobileAppStateFileSystem) {
|
||||
if (!fileSystem.documentDirectory) {
|
||||
throw new Error('Expo FileSystem documentDirectory is unavailable')
|
||||
}
|
||||
|
||||
return `${fileSystem.documentDirectory.replace(/\/+$/, '')}/state`
|
||||
}
|
||||
|
||||
function isStateRecord(value: unknown): value is { activeVaultId?: unknown; selectedNoteId?: unknown } {
|
||||
return typeof value === 'object' && value !== null
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileEditorDraft, type MobileEditorDraft } from './mobileEditorDraft'
|
||||
import { createMobileAutosaveQueue, type MobileAutosaveScheduler } from './mobileAutosaveQueue'
|
||||
import type { MobileEditorSaveState } from './mobileEditorSaveState'
|
||||
|
||||
describe('mobile autosave queue', () => {
|
||||
it('debounces drafts for the same note', async () => {
|
||||
const scheduler = createManualScheduler()
|
||||
const savedDrafts: MobileEditorDraft[] = []
|
||||
const states: string[] = []
|
||||
const queue = createMobileAutosaveQueue({
|
||||
delayMs: 300,
|
||||
scheduler,
|
||||
onStateChange: (_noteId, state) => states.push(state.state),
|
||||
saveDraft: async (draft) => {
|
||||
savedDrafts.push(draft)
|
||||
return { status: 'saved', path: `${draft.noteId}.md` }
|
||||
},
|
||||
})
|
||||
|
||||
queue.enqueue(draftFor('workflow', '<h1>Workflow</h1><p>First</p>'))
|
||||
queue.enqueue(draftFor('workflow', '<h1>Workflow</h1><p>Second</p>'))
|
||||
|
||||
await scheduler.flush()
|
||||
|
||||
expect(savedDrafts).toHaveLength(1)
|
||||
expect(savedDrafts[0]).toMatchObject({ canonicalMarkdown: '# Workflow\n\nSecond' })
|
||||
expect(states).toEqual(['queued', 'queued', 'saving', 'saved'])
|
||||
})
|
||||
|
||||
it('ignores stale save results when a newer draft was queued', async () => {
|
||||
const scheduler = createManualScheduler()
|
||||
const savedMarkdown: string[] = []
|
||||
const states: MobileEditorSaveState[] = []
|
||||
let resolveFirstSave: () => void = () => {
|
||||
throw new Error('First save was not scheduled')
|
||||
}
|
||||
const queue = createMobileAutosaveQueue({
|
||||
delayMs: 300,
|
||||
scheduler,
|
||||
onSavedDraft: (draft) => savedMarkdown.push(draft.canonicalMarkdown),
|
||||
onStateChange: (_noteId, state) => states.push(state),
|
||||
saveDraft: (draft) =>
|
||||
draftMarkdown(draft).includes('First')
|
||||
? new Promise((resolve) => {
|
||||
resolveFirstSave = () => resolve({ status: 'saved', path: `${draft.noteId}.md` })
|
||||
})
|
||||
: Promise.resolve({ status: 'saved', path: `${draft.noteId}.md` }),
|
||||
})
|
||||
|
||||
queue.enqueue(draftFor('workflow', '<h1>Workflow</h1><p>First</p>'))
|
||||
await scheduler.flush()
|
||||
queue.enqueue(draftFor('workflow', '<h1>Workflow</h1><p>Second</p>'))
|
||||
resolveFirstSave()
|
||||
await Promise.resolve()
|
||||
await scheduler.flush()
|
||||
|
||||
expect(states.map((state) => state.state)).toEqual(['queued', 'saving', 'queued', 'saving', 'saved'])
|
||||
expect(savedMarkdown).toEqual(['# Workflow\n\nSecond'])
|
||||
})
|
||||
|
||||
it('can cancel pending draft saves', async () => {
|
||||
const scheduler = createManualScheduler()
|
||||
const savedDrafts: MobileEditorDraft[] = []
|
||||
const queue = createMobileAutosaveQueue({
|
||||
delayMs: 300,
|
||||
scheduler,
|
||||
onStateChange: () => {},
|
||||
saveDraft: async (draft) => {
|
||||
savedDrafts.push(draft)
|
||||
return { status: 'saved', path: `${draft.noteId}.md` }
|
||||
},
|
||||
})
|
||||
|
||||
queue.enqueue(draftFor('workflow', '<h1>Workflow</h1><p>First</p>'))
|
||||
queue.cancelAll()
|
||||
await scheduler.flush()
|
||||
|
||||
expect(savedDrafts).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function draftFor(noteId: string, editorHtml: string) {
|
||||
return createMobileEditorDraft({
|
||||
note: { id: noteId, title: 'Workflow', content: '# Workflow' },
|
||||
editorHtml,
|
||||
})
|
||||
}
|
||||
|
||||
function draftMarkdown(draft: MobileEditorDraft) {
|
||||
if (!draft.persistable) {
|
||||
throw new Error('Expected persistable test draft')
|
||||
}
|
||||
|
||||
return draft.canonicalMarkdown
|
||||
}
|
||||
|
||||
function createManualScheduler() {
|
||||
type ManualTimer = {
|
||||
callback: () => void
|
||||
active: boolean
|
||||
}
|
||||
const timers: ManualTimer[] = []
|
||||
const scheduler: MobileAutosaveScheduler & { flush: () => Promise<void> } = {
|
||||
set: (callback) => {
|
||||
const timer = { callback, active: true }
|
||||
timers.push(timer)
|
||||
|
||||
return timer
|
||||
},
|
||||
clear: (timer) => {
|
||||
const manualTimer = timer as unknown as ManualTimer
|
||||
manualTimer.active = false
|
||||
},
|
||||
flush: async () => {
|
||||
const activeTimers = timers.splice(0).filter((timer) => timer.active)
|
||||
for (const timer of activeTimers) {
|
||||
timer.callback()
|
||||
}
|
||||
await Promise.resolve()
|
||||
},
|
||||
}
|
||||
|
||||
return scheduler
|
||||
}
|
||||
@@ -1,137 +0,0 @@
|
||||
import type { MobileEditorDraft } from './mobileEditorDraft'
|
||||
import type { MobileEditorDraftSaveResult } from './mobileEditorDraftSave'
|
||||
import {
|
||||
queuedMobileEditorSaveState,
|
||||
saveResultState,
|
||||
savingMobileEditorSaveState,
|
||||
failedMobileEditorSaveState,
|
||||
type MobileEditorSaveState,
|
||||
} from './mobileEditorSaveState'
|
||||
|
||||
export type MobileAutosaveTimer = unknown
|
||||
|
||||
export type MobileAutosaveScheduler = {
|
||||
set: (callback: () => void, delayMs: number) => MobileAutosaveTimer
|
||||
clear: (timer: MobileAutosaveTimer) => void
|
||||
}
|
||||
|
||||
export type MobileAutosaveQueue = {
|
||||
enqueue: (draft: MobileEditorDraft) => void
|
||||
cancelAll: () => void
|
||||
}
|
||||
|
||||
export type SavedMobileEditorDraft = Extract<MobileEditorDraft, { persistable: true }>
|
||||
|
||||
export function createMobileAutosaveQueue({
|
||||
delayMs,
|
||||
onSavedDraft,
|
||||
onStateChange,
|
||||
saveDraft,
|
||||
scheduler = nativeScheduler,
|
||||
}: {
|
||||
delayMs: number
|
||||
onSavedDraft?: (draft: SavedMobileEditorDraft) => void
|
||||
onStateChange: (noteId: string, state: MobileEditorSaveState) => void
|
||||
saveDraft: (draft: MobileEditorDraft) => Promise<MobileEditorDraftSaveResult>
|
||||
scheduler?: MobileAutosaveScheduler
|
||||
}): MobileAutosaveQueue {
|
||||
const generationByNoteId = new Map<string, number>()
|
||||
const timerByNoteId = new Map<string, MobileAutosaveTimer>()
|
||||
|
||||
return {
|
||||
enqueue: (draft) => {
|
||||
const generation = nextGeneration({ draft, generationByNoteId })
|
||||
clearPendingTimer({ draft, scheduler, timerByNoteId })
|
||||
onStateChange(draft.noteId, queuedMobileEditorSaveState)
|
||||
timerByNoteId.set(
|
||||
draft.noteId,
|
||||
scheduler.set(() => {
|
||||
timerByNoteId.delete(draft.noteId)
|
||||
void saveLatestDraft({ draft, generation, generationByNoteId, onSavedDraft, onStateChange, saveDraft })
|
||||
}, delayMs),
|
||||
)
|
||||
},
|
||||
cancelAll: () => {
|
||||
for (const timer of timerByNoteId.values()) {
|
||||
scheduler.clear(timer)
|
||||
}
|
||||
timerByNoteId.clear()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
const nativeScheduler: MobileAutosaveScheduler = {
|
||||
set: (callback, delayMs) => setTimeout(callback, delayMs),
|
||||
clear: (timer) => clearTimeout(timer as ReturnType<typeof setTimeout>),
|
||||
}
|
||||
|
||||
async function saveLatestDraft({
|
||||
draft,
|
||||
generation,
|
||||
generationByNoteId,
|
||||
onSavedDraft,
|
||||
onStateChange,
|
||||
saveDraft,
|
||||
}: {
|
||||
draft: MobileEditorDraft
|
||||
generation: number
|
||||
generationByNoteId: Map<string, number>
|
||||
onSavedDraft?: (draft: SavedMobileEditorDraft) => void
|
||||
onStateChange: (noteId: string, state: MobileEditorSaveState) => void
|
||||
saveDraft: (draft: MobileEditorDraft) => Promise<MobileEditorDraftSaveResult>
|
||||
}) {
|
||||
onStateChange(draft.noteId, savingMobileEditorSaveState)
|
||||
try {
|
||||
const result = await saveDraft(draft)
|
||||
if (isLatestGeneration({ draft, generation, generationByNoteId })) {
|
||||
onStateChange(draft.noteId, saveResultState(result))
|
||||
if (result.status === 'saved' && draft.persistable) {
|
||||
onSavedDraft?.(draft)
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
if (isLatestGeneration({ draft, generation, generationByNoteId })) {
|
||||
onStateChange(draft.noteId, failedMobileEditorSaveState)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function nextGeneration({
|
||||
draft,
|
||||
generationByNoteId,
|
||||
}: {
|
||||
draft: MobileEditorDraft
|
||||
generationByNoteId: Map<string, number>
|
||||
}) {
|
||||
const generation = (generationByNoteId.get(draft.noteId) ?? 0) + 1
|
||||
generationByNoteId.set(draft.noteId, generation)
|
||||
|
||||
return generation
|
||||
}
|
||||
|
||||
function clearPendingTimer({
|
||||
draft,
|
||||
scheduler,
|
||||
timerByNoteId,
|
||||
}: {
|
||||
draft: MobileEditorDraft
|
||||
scheduler: MobileAutosaveScheduler
|
||||
timerByNoteId: Map<string, MobileAutosaveTimer>
|
||||
}) {
|
||||
const timer = timerByNoteId.get(draft.noteId)
|
||||
if (timer) {
|
||||
scheduler.clear(timer)
|
||||
}
|
||||
}
|
||||
|
||||
function isLatestGeneration({
|
||||
draft,
|
||||
generation,
|
||||
generationByNoteId,
|
||||
}: {
|
||||
draft: MobileEditorDraft
|
||||
generation: number
|
||||
generationByNoteId: Map<string, number>
|
||||
}) {
|
||||
return generationByNoteId.get(draft.noteId) === generation
|
||||
}
|
||||
@@ -1,128 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileEditorDraft } from './mobileEditorDraft'
|
||||
import { saveMobileEditorDraft } from './mobileEditorDraftSave'
|
||||
import { createMobileNoteFile } from './mobileNoteCreate'
|
||||
import { saveMobileNoteFrontmatter } from './mobileNoteFrontmatterSave'
|
||||
import { createMobileVaultConfig, type MobileVaultConfig } from './mobileVaultConfig'
|
||||
import { createStoredMobileVaultRepository } from './mobileVaultRepository'
|
||||
import { createMemoryMobileVaultStorage, type MobileVaultStorageDriver } from './mobileVaultStorage'
|
||||
|
||||
describe('mobile core flow smoke', () => {
|
||||
it('creates, opens, edits, updates properties, and deletes an app-local note', async () => {
|
||||
const vault = createVault()
|
||||
const storage = createMemoryMobileVaultStorage([])
|
||||
const noteId = await createNote({ storage, vault })
|
||||
|
||||
const openedNote = await readNote({ noteId, storage, vault })
|
||||
expect(openedNote).toMatchObject({ id: noteId, title: 'Morning Plan', type: 'Note' })
|
||||
|
||||
await saveEditorContent({ note: openedNote, storage, vault })
|
||||
await expect(storage.readMarkdownFile(vault, `${noteId}.md`)).resolves.toBe([
|
||||
'---',
|
||||
'title: Morning Plan',
|
||||
'type: Note',
|
||||
'created: 2026-05-05T08:00:00.000Z',
|
||||
'---',
|
||||
'# Morning Plan',
|
||||
'',
|
||||
'Edited agenda',
|
||||
'',
|
||||
'> Follow up',
|
||||
].join('\n'))
|
||||
|
||||
await saveMobileNoteFrontmatter({
|
||||
metadata: {
|
||||
date: '5 May 2026',
|
||||
icon: 'wrench',
|
||||
status: 'Active',
|
||||
tags: ['Tolaria MVP', 'mobile'],
|
||||
type: 'Project',
|
||||
},
|
||||
noteId,
|
||||
storage,
|
||||
vault,
|
||||
})
|
||||
|
||||
await expect(readNote({ noteId, storage, vault })).resolves.toMatchObject({
|
||||
date: '5 May 2026',
|
||||
icon: 'wrench',
|
||||
status: 'Active',
|
||||
tags: ['Tolaria MVP', 'mobile'],
|
||||
type: 'Project',
|
||||
})
|
||||
|
||||
await repository({ storage, vault }).deleteNote(noteId)
|
||||
await expect(repository({ storage, vault }).readNote(noteId)).resolves.toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
async function createNote({
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
storage: MobileVaultStorageDriver
|
||||
vault: MobileVaultConfig
|
||||
}) {
|
||||
const file = createMobileNoteFile({
|
||||
now: new Date('2026-05-05T08:00:00.000Z'),
|
||||
title: 'Morning Plan',
|
||||
})
|
||||
await storage.writeMarkdownFile(vault, file.path, file.content)
|
||||
|
||||
return file.path.replace(/\.md$/, '')
|
||||
}
|
||||
|
||||
async function readNote({
|
||||
noteId,
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
noteId: string
|
||||
storage: MobileVaultStorageDriver
|
||||
vault: MobileVaultConfig
|
||||
}) {
|
||||
const note = await repository({ storage, vault }).readNote(noteId)
|
||||
if (!note) {
|
||||
throw new Error(`Expected note ${noteId}`)
|
||||
}
|
||||
|
||||
return note
|
||||
}
|
||||
|
||||
async function saveEditorContent({
|
||||
note,
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
note: Awaited<ReturnType<typeof readNote>>
|
||||
storage: MobileVaultStorageDriver
|
||||
vault: MobileVaultConfig
|
||||
}) {
|
||||
await saveMobileEditorDraft({
|
||||
draft: createMobileEditorDraft({
|
||||
note,
|
||||
editorHtml: '<h1>Morning Plan</h1><p>Edited agenda</p><blockquote><p>Follow up</p></blockquote>',
|
||||
}),
|
||||
storage,
|
||||
vault,
|
||||
})
|
||||
}
|
||||
|
||||
function repository({
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
storage: MobileVaultStorageDriver
|
||||
vault: MobileVaultConfig
|
||||
}) {
|
||||
return createStoredMobileVaultRepository({ storage, vault })
|
||||
}
|
||||
|
||||
function createVault() {
|
||||
const result = createMobileVaultConfig({ id: 'personal', name: 'Personal Journal' })
|
||||
if (!result.ok) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
|
||||
return result.config
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { shouldSeedDemoVault } from './mobileDemoVaultSeedPolicy'
|
||||
|
||||
describe('mobile demo vault loading', () => {
|
||||
it('does not seed demo notes into remote-backed vaults', () => {
|
||||
expect(shouldSeedDemoVault({
|
||||
id: 'personal',
|
||||
name: 'Personal Journal',
|
||||
remoteUrl: 'https://github.com/refactoringhq/tolaria.git',
|
||||
})).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps local-only vaults seeded for first-run simulator QA', () => {
|
||||
expect(shouldSeedDemoVault({ id: 'personal', name: 'Personal Journal' })).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -1,116 +0,0 @@
|
||||
import { demoNoteSources } from './demoData'
|
||||
import type { MobileEditorDraft } from './mobileEditorDraft'
|
||||
import { saveMobileEditorDraft } from './mobileEditorDraftSave'
|
||||
import { saveMobileNoteFrontmatter } from './mobileNoteFrontmatterSave'
|
||||
import type { WritableMobileNoteFrontmatter } from './mobileNoteFrontmatterWrite'
|
||||
import { createMobileNoteFile } from './mobileNoteCreate'
|
||||
import {
|
||||
createMobileVaultConfigFromMetadata,
|
||||
defaultMobileVaultMetadata,
|
||||
type MobileVaultMetadata,
|
||||
} from './mobileVaultMetadata'
|
||||
import { createNativeMobileVaultStorage } from './mobileNativeVaultStorage'
|
||||
import { createStoredMobileVaultRepository } from './mobileVaultRepository'
|
||||
import { seedMobileVaultIfEmpty } from './mobileVaultSeed'
|
||||
import type { MobileVaultFile } from './mobileVaultStorage'
|
||||
import { shouldSeedDemoVault } from './mobileDemoVaultSeedPolicy'
|
||||
|
||||
export async function loadDemoVaultNotes(vaultMetadata = defaultMobileVaultMetadata) {
|
||||
const storage = createNativeMobileVaultStorage()
|
||||
const demoVault = createDemoVaultConfig(vaultMetadata)
|
||||
if (shouldSeedDemoVault(vaultMetadata)) {
|
||||
await seedMobileVaultIfEmpty({ files: demoVaultFiles(), storage, vault: demoVault })
|
||||
await addMissingDemoVaultFiles({ files: demoVaultFiles(), storage, vault: demoVault })
|
||||
}
|
||||
|
||||
return createStoredMobileVaultRepository({ storage, vault: demoVault }).listNotes()
|
||||
}
|
||||
|
||||
export function saveDemoVaultDraft(draft: MobileEditorDraft, vaultMetadata = defaultMobileVaultMetadata) {
|
||||
return saveMobileEditorDraft({
|
||||
draft,
|
||||
storage: createNativeMobileVaultStorage(),
|
||||
vault: createDemoVaultConfig(vaultMetadata),
|
||||
})
|
||||
}
|
||||
|
||||
export async function createDemoVaultNote({
|
||||
title,
|
||||
vaultMetadata = defaultMobileVaultMetadata,
|
||||
}: {
|
||||
title?: string
|
||||
vaultMetadata?: MobileVaultMetadata
|
||||
} = {}) {
|
||||
const storage = createNativeMobileVaultStorage()
|
||||
const demoVault = createDemoVaultConfig(vaultMetadata)
|
||||
const file = createMobileNoteFile({ title })
|
||||
await storage.writeMarkdownFile(demoVault, file.path, file.content)
|
||||
|
||||
return createStoredMobileVaultRepository({ storage, vault: demoVault }).readNote(file.path.replace(/\.md$/, ''))
|
||||
}
|
||||
|
||||
export async function deleteDemoVaultNote(noteId: string, vaultMetadata = defaultMobileVaultMetadata) {
|
||||
const storage = createNativeMobileVaultStorage()
|
||||
await createStoredMobileVaultRepository({
|
||||
storage,
|
||||
vault: createDemoVaultConfig(vaultMetadata),
|
||||
}).deleteNote(noteId)
|
||||
}
|
||||
|
||||
export function saveDemoVaultNoteFrontmatter({
|
||||
metadata,
|
||||
noteId,
|
||||
vaultMetadata = defaultMobileVaultMetadata,
|
||||
}: {
|
||||
metadata: WritableMobileNoteFrontmatter
|
||||
noteId: string
|
||||
vaultMetadata?: MobileVaultMetadata
|
||||
}) {
|
||||
return saveDemoVaultDocumentChange({
|
||||
vaultMetadata,
|
||||
write: ({ storage, vault }) => saveMobileNoteFrontmatter({ metadata, noteId, storage, vault }),
|
||||
})
|
||||
}
|
||||
|
||||
function demoVaultFiles(): MobileVaultFile[] {
|
||||
return demoNoteSources.map((source) => ({
|
||||
path: source.filename,
|
||||
content: source.content,
|
||||
}))
|
||||
}
|
||||
|
||||
function createDemoVaultConfig(vaultMetadata: MobileVaultMetadata) {
|
||||
return createMobileVaultConfigFromMetadata(vaultMetadata)
|
||||
}
|
||||
|
||||
|
||||
function createDemoVaultStorageContext(vaultMetadata: MobileVaultMetadata) {
|
||||
return {
|
||||
storage: createNativeMobileVaultStorage(),
|
||||
vault: createDemoVaultConfig(vaultMetadata),
|
||||
}
|
||||
}
|
||||
|
||||
function saveDemoVaultDocumentChange<T>({
|
||||
vaultMetadata,
|
||||
write,
|
||||
}: {
|
||||
vaultMetadata: MobileVaultMetadata
|
||||
write: (context: ReturnType<typeof createDemoVaultStorageContext>) => T
|
||||
}) {
|
||||
return write(createDemoVaultStorageContext(vaultMetadata))
|
||||
}
|
||||
|
||||
async function addMissingDemoVaultFiles({
|
||||
files,
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
files: MobileVaultFile[]
|
||||
storage: ReturnType<typeof createNativeMobileVaultStorage>
|
||||
vault: ReturnType<typeof createDemoVaultConfig>
|
||||
}) {
|
||||
const existingPaths = new Set((await storage.listMarkdownFiles(vault)).map((file) => file.path))
|
||||
const missingFiles = files.filter((file) => !existingPaths.has(file.path))
|
||||
await Promise.all(missingFiles.map((file) => storage.writeMarkdownFile(vault, file.path, file.content)))
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { createNativeMobileVaultStorage } from './mobileNativeVaultStorage'
|
||||
import { saveMobileRawNote } from './mobileRawNoteSave'
|
||||
import { createMobileVaultConfigFromMetadata, defaultMobileVaultMetadata, type MobileVaultMetadata } from './mobileVaultMetadata'
|
||||
|
||||
export function saveDemoVaultRawNote({
|
||||
content,
|
||||
noteId,
|
||||
vaultMetadata = defaultMobileVaultMetadata,
|
||||
}: {
|
||||
content: string
|
||||
noteId: string
|
||||
vaultMetadata?: MobileVaultMetadata
|
||||
}) {
|
||||
return saveMobileRawNote({
|
||||
content,
|
||||
noteId,
|
||||
storage: createNativeMobileVaultStorage(),
|
||||
vault: createMobileVaultConfigFromMetadata(vaultMetadata),
|
||||
})
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { MobileVaultMetadata } from './mobileVaultMetadata'
|
||||
|
||||
export function shouldSeedDemoVault(vaultMetadata: MobileVaultMetadata) {
|
||||
return !vaultMetadata.remoteUrl?.trim()
|
||||
}
|
||||
@@ -1,71 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { mobileDerivedRelationshipGroups } from './mobileDerivedRelationships'
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
|
||||
describe('mobile derived relationships', () => {
|
||||
it('derives read-only inverse relationship groups from other notes', () => {
|
||||
const current = note({ id: 'project/tolaria', title: 'Tolaria' })
|
||||
const child = note({ belongsTo: ['[[project/tolaria|Tolaria]]'], id: 'essay', title: 'Essay' })
|
||||
const related = note({ id: 'release', relatedTo: ['Tolaria'], title: 'Release' })
|
||||
const custom = note({ id: 'owner', relationships: { owner: ['[[project/tolaria|Tolaria]]'] }, title: 'Owner' })
|
||||
|
||||
expect(mobileDerivedRelationshipGroups({ note: current, notes: [current, child, related, custom] })).toEqual([
|
||||
{ label: 'Contains', targets: ['[[essay|Essay]]'] },
|
||||
{ label: 'Related from', targets: ['[[release|Release]]'] },
|
||||
{ label: 'Owner from', targets: ['[[owner|Owner]]'] },
|
||||
])
|
||||
})
|
||||
|
||||
it('deduplicates inverse targets inside a group', () => {
|
||||
const current = note({ id: 'project/tolaria', title: 'Tolaria' })
|
||||
const source = note({
|
||||
belongsTo: ['[[project/tolaria|Tolaria]]', 'Tolaria'],
|
||||
id: 'essay',
|
||||
title: 'Essay',
|
||||
})
|
||||
|
||||
expect(mobileDerivedRelationshipGroups({ note: current, notes: [current, source] })).toEqual([
|
||||
{ label: 'Contains', targets: ['[[essay|Essay]]'] },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
function note({
|
||||
belongsTo = [],
|
||||
has = [],
|
||||
id,
|
||||
relatedTo = [],
|
||||
relationships = {},
|
||||
title,
|
||||
}: {
|
||||
belongsTo?: string[]
|
||||
has?: string[]
|
||||
id: string
|
||||
relatedTo?: string[]
|
||||
relationships?: Record<string, string[]>
|
||||
title: string
|
||||
}): MobileNote {
|
||||
return {
|
||||
archived: false,
|
||||
backlinks: [],
|
||||
belongsTo,
|
||||
content: `# ${title}`,
|
||||
customProperties: {},
|
||||
date: '',
|
||||
favorite: false,
|
||||
favoriteIndex: null,
|
||||
has,
|
||||
icon: 'file-text',
|
||||
id,
|
||||
modified: '',
|
||||
outgoingLinks: [],
|
||||
relatedTo,
|
||||
relationships,
|
||||
snippet: '',
|
||||
status: undefined,
|
||||
tags: [],
|
||||
title,
|
||||
type: 'Note',
|
||||
words: 1,
|
||||
}
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import type { MobileNote } from './mobileNoteProjection'
|
||||
import { hasMobileRelationshipRef, mobileWikilinkForNote, uniqueMobileRelationshipRefs } from './mobileRelationshipRefs'
|
||||
|
||||
export type MobileDerivedRelationshipGroup = {
|
||||
label: string
|
||||
targets: string[]
|
||||
}
|
||||
|
||||
export function mobileDerivedRelationshipGroups({
|
||||
note,
|
||||
notes,
|
||||
}: {
|
||||
note: MobileNote
|
||||
notes: MobileNote[]
|
||||
}) {
|
||||
const groups = new Map<string, string[]>()
|
||||
for (const source of notes) {
|
||||
if (source.id !== note.id) {
|
||||
appendDerivedGroups({ groups, note, source })
|
||||
}
|
||||
}
|
||||
|
||||
return [...groups.entries()]
|
||||
.map(([label, targets]) => ({ label, targets: uniqueMobileRelationshipRefs(targets) }))
|
||||
.filter((group) => group.targets.length > 0)
|
||||
}
|
||||
|
||||
function appendDerivedGroups({
|
||||
groups,
|
||||
note,
|
||||
source,
|
||||
}: {
|
||||
groups: Map<string, string[]>
|
||||
note: MobileNote
|
||||
source: MobileNote
|
||||
}) {
|
||||
appendIfLinked({ groups, label: 'Contains', note, source, values: source.belongsTo })
|
||||
appendIfLinked({ groups, label: 'Related from', note, source, values: source.relatedTo })
|
||||
appendIfLinked({ groups, label: 'Part of', note, source, values: source.has })
|
||||
for (const [key, values] of Object.entries(source.relationships)) {
|
||||
appendIfLinked({ groups, label: `${formatRelationshipLabel(key)} from`, note, source, values })
|
||||
}
|
||||
}
|
||||
|
||||
function appendIfLinked({
|
||||
groups,
|
||||
label,
|
||||
note,
|
||||
source,
|
||||
values,
|
||||
}: {
|
||||
groups: Map<string, string[]>
|
||||
label: string
|
||||
note: MobileNote
|
||||
source: MobileNote
|
||||
values: string[]
|
||||
}) {
|
||||
if (
|
||||
hasMobileRelationshipRef({ target: mobileWikilinkForNote(note), values })
|
||||
|| hasMobileRelationshipRef({ target: note.title, values })
|
||||
) {
|
||||
groups.set(label, [...groups.get(label) ?? [], mobileWikilinkForNote(source)])
|
||||
}
|
||||
}
|
||||
|
||||
function formatRelationshipLabel(key: string) {
|
||||
return key.replace(/_/g, ' ').replace(/\b\w/g, (letter) => letter.toUpperCase())
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileEditorDocument, createMobileEditorHtml } from './mobileEditorDocument'
|
||||
|
||||
describe('mobile editor document', () => {
|
||||
it('strips frontmatter and title heading from the displayed editor body', () => {
|
||||
expect(
|
||||
createMobileEditorDocument({
|
||||
id: 'workflow',
|
||||
title: 'Workflow Orchestration Essay',
|
||||
content: [
|
||||
'---',
|
||||
'type: Essay',
|
||||
'---',
|
||||
'',
|
||||
'# Workflow Orchestration Essay',
|
||||
'',
|
||||
'The current narrative: everything routed through an LLM.',
|
||||
].join('\n'),
|
||||
}),
|
||||
).toEqual({
|
||||
leadingTitle: 'Workflow Orchestration Essay',
|
||||
blocks: [
|
||||
{
|
||||
id: '0:The current narrative: everything routed through an LLM.',
|
||||
kind: 'paragraph',
|
||||
text: 'The current narrative: everything routed through an LLM.',
|
||||
},
|
||||
],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps colon paragraphs instead of treating them as frontmatter', () => {
|
||||
const document = createMobileEditorDocument({
|
||||
id: 'monday',
|
||||
title: 'Notes for Monday',
|
||||
content: '# Notes for Monday\n\nBottom line up front: ship the smallest useful slice.',
|
||||
})
|
||||
|
||||
expect(document.blocks).toEqual([
|
||||
{
|
||||
id: '0:Bottom line up front: ship the smallest useful slice.',
|
||||
kind: 'paragraph',
|
||||
text: 'Bottom line up front: ship the smallest useful slice.',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('normalizes markdown bullets for the native placeholder surface', () => {
|
||||
const document = createMobileEditorDocument({
|
||||
id: 'plan',
|
||||
title: 'Plan',
|
||||
content: '# Plan\n\n- Sidebar\n* Note list',
|
||||
})
|
||||
|
||||
expect(document.blocks).toEqual([
|
||||
{
|
||||
id: '0:- Sidebar',
|
||||
kind: 'bullet',
|
||||
text: 'Sidebar',
|
||||
},
|
||||
{
|
||||
id: '1:* Note list',
|
||||
kind: 'bullet',
|
||||
text: 'Note list',
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('creates escaped HTML for TenTap initial content', () => {
|
||||
const html = createMobileEditorHtml({
|
||||
leadingTitle: 'Tolaria <mobile>',
|
||||
blocks: [
|
||||
{
|
||||
id: '0:Use TenTap',
|
||||
kind: 'paragraph',
|
||||
text: 'Use TenTap & keep markdown durable',
|
||||
},
|
||||
{
|
||||
id: '1:- Escape quotes',
|
||||
kind: 'bullet',
|
||||
text: 'Escape "quotes"',
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
expect(html).toBe(
|
||||
'<h1>Tolaria <mobile></h1><p>Use TenTap & keep markdown durable</p><ul><li>Escape "quotes"</li></ul>',
|
||||
)
|
||||
})
|
||||
|
||||
it('does not reinsert an H1 after the note body no longer starts with the title heading', () => {
|
||||
const document = createMobileEditorDocument({
|
||||
id: 'untitled',
|
||||
title: 'Untitled',
|
||||
content: 'Body without a leading heading',
|
||||
})
|
||||
|
||||
expect(document.leadingTitle).toBeNull()
|
||||
expect(createMobileEditorHtml(document)).toBe('<p>Body without a leading heading</p>')
|
||||
})
|
||||
|
||||
it('renders wikilinks as clickable rich links in the editor HTML', () => {
|
||||
const document = createMobileEditorDocument({
|
||||
id: 'links',
|
||||
title: 'Links',
|
||||
content: '# Links\n\nSee [[mobile-roadmap|Mobile Roadmap]] next.',
|
||||
})
|
||||
|
||||
expect(createMobileEditorHtml(document)).toContain(
|
||||
'<a data-tolaria-wikilink="true" href="tolaria-note:mobile-roadmap">Mobile Roadmap</a>',
|
||||
)
|
||||
})
|
||||
|
||||
})
|
||||
@@ -1,89 +0,0 @@
|
||||
import { splitFrontmatter } from '@tolaria/markdown'
|
||||
|
||||
export type MobileEditorBlock = {
|
||||
id: string
|
||||
kind: 'bullet' | 'paragraph'
|
||||
text: string
|
||||
}
|
||||
|
||||
export type MobileEditorDocument = {
|
||||
leadingTitle: string | null
|
||||
blocks: MobileEditorBlock[]
|
||||
}
|
||||
|
||||
export type MobileEditorDocumentInput = {
|
||||
id: string
|
||||
title: string
|
||||
content: string
|
||||
}
|
||||
|
||||
export function createMobileEditorDocument(input: MobileEditorDocumentInput): MobileEditorDocument {
|
||||
const [, body] = splitFrontmatter(input.content)
|
||||
|
||||
return {
|
||||
leadingTitle: leadingTitle({ body, title: input.title }),
|
||||
blocks: createBlocks({ body, title: input.title }),
|
||||
}
|
||||
}
|
||||
|
||||
export function createMobileEditorHtml(document: MobileEditorDocument) {
|
||||
return `${titleHtml(document.leadingTitle)}${document.blocks.map(blockToHtml).join('') || '<p></p>'}`
|
||||
}
|
||||
|
||||
function leadingTitle({ body, title }: { body: string; title: string }) {
|
||||
const firstLine = body.split('\n').find((line) => line.trim().length > 0)?.trim()
|
||||
return firstLine && isTitleHeading({ line: firstLine, title }) ? title : null
|
||||
}
|
||||
|
||||
function createBlocks({ body, title }: { body: string; title: string }) {
|
||||
return body
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !isTitleHeading({ line, title }))
|
||||
.map((line, index) => createBlock({ index, line }))
|
||||
}
|
||||
|
||||
function createBlock({ index, line }: { index: number; line: string }): MobileEditorBlock {
|
||||
const bulletText = bulletContent({ line })
|
||||
|
||||
return {
|
||||
id: `${index}:${line}`,
|
||||
kind: bulletText ? 'bullet' : 'paragraph',
|
||||
text: bulletText ?? line,
|
||||
}
|
||||
}
|
||||
|
||||
function bulletContent({ line }: { line: string }) {
|
||||
const match = /^[-*]\s+(.+)$/.exec(line)
|
||||
return match?.[1] ?? null
|
||||
}
|
||||
|
||||
function isTitleHeading({ line, title }: { line: string; title: string }) {
|
||||
return line === `# ${title}`
|
||||
}
|
||||
|
||||
function blockToHtml(block: MobileEditorBlock) {
|
||||
const text = inlineTextToHtml(block.text)
|
||||
return block.kind === 'bullet' ? `<ul><li>${text}</li></ul>` : `<p>${text}</p>`
|
||||
}
|
||||
|
||||
function titleHtml(title: string | null) {
|
||||
return title ? `<h1>${escapeHtml({ value: title })}</h1>` : ''
|
||||
}
|
||||
|
||||
function inlineTextToHtml(value: string) {
|
||||
return escapeHtml({ value }).replace(/\[\[([^[\]]+?)\]\]/g, (_match, inner: string) => {
|
||||
const [target, alias] = inner.split('|')
|
||||
const label = alias?.trim() || target.trim()
|
||||
return `<a data-tolaria-wikilink="true" href="tolaria-note:${encodeURIComponent(target.trim())}">${label}</a>`
|
||||
})
|
||||
}
|
||||
|
||||
function escapeHtml({ value }: { value: string }) {
|
||||
return value
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''')
|
||||
}
|
||||
@@ -1,305 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileEditorDraft } from './mobileEditorDraft'
|
||||
|
||||
describe('mobile editor draft', () => {
|
||||
it('serializes supported TenTap HTML into canonical Markdown', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'workflow',
|
||||
title: 'Workflow',
|
||||
content: '# Workflow\n\nOriginal markdown',
|
||||
},
|
||||
editorHtml: '<h1>Workflow</h1><p>Edited content</p><ul><li>First</li><li>Second</li></ul>',
|
||||
}),
|
||||
).toEqual({
|
||||
noteId: 'workflow',
|
||||
sourceMarkdown: '# Workflow\n\nOriginal markdown',
|
||||
editorHtml: '<h1>Workflow</h1><p>Edited content</p><ul><li>First</li><li>Second</li></ul>',
|
||||
persistable: true,
|
||||
canonicalMarkdown: '# Workflow\n\nEdited content\n\n- First\n- Second',
|
||||
})
|
||||
})
|
||||
|
||||
it('preserves source frontmatter outside the edited body', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'workflow',
|
||||
title: 'Workflow',
|
||||
content: '---\ntype: Essay\n---\n\n# Workflow\n\nOriginal markdown',
|
||||
},
|
||||
editorHtml: '<h1>Workflow</h1><p>Edited content</p>',
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: '---\ntype: Essay\n---\n# Workflow\n\nEdited content',
|
||||
})
|
||||
})
|
||||
|
||||
it('decodes escaped text before writing Markdown', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'symbols',
|
||||
title: 'Symbols',
|
||||
content: '# Symbols',
|
||||
},
|
||||
editorHtml: '<h1>Symbols</h1><p>Use <tags> & "quotes", !? and non breaking space</p>',
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: '# Symbols\n\nUse <tags> & "quotes", !? and non breaking space',
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes headings, ordered lists, and inline marks', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'formatting',
|
||||
title: 'Formatting',
|
||||
content: '# Formatting',
|
||||
},
|
||||
editorHtml: [
|
||||
'<h2>Section</h2>',
|
||||
'<p>Use <strong>bold</strong>, <em>emphasis</em>, <code>code</code>, and <a href="https://tolaria.app">links</a>.</p>',
|
||||
'<ol><li>First</li><li>Second</li></ol>',
|
||||
].join(''),
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: [
|
||||
'## Section',
|
||||
'',
|
||||
'Use **bold**, *emphasis*, `code`, and [links](https://tolaria.app).',
|
||||
'',
|
||||
'1. First',
|
||||
'1. Second',
|
||||
].join('\n'),
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes safe link destinations and decodes escaped link URLs', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'links',
|
||||
title: 'Links',
|
||||
content: '# Links',
|
||||
},
|
||||
editorHtml: [
|
||||
'<p><a href="https://tolaria.app?ref=notes&device=ios">Website</a></p>',
|
||||
'<p><a href="mailto:hello@tolaria.app">Email</a></p>',
|
||||
'<p><a href="notes/workflow.md">Relative note</a></p>',
|
||||
].join(''),
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: [
|
||||
'[Website](https://tolaria.app?ref=notes&device=ios)',
|
||||
'',
|
||||
'[Email](mailto:hello@tolaria.app)',
|
||||
'',
|
||||
'[Relative note](notes/workflow.md)',
|
||||
].join('\n'),
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes rich wikilinks back to desktop-compatible wikilink markdown', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'links',
|
||||
title: 'Links',
|
||||
content: '# Links',
|
||||
},
|
||||
editorHtml: '<p>See <a data-tolaria-wikilink="true" href="tolaria-note:mobile-roadmap">Mobile Roadmap</a>.</p>',
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: 'See [[mobile-roadmap|Mobile Roadmap]].',
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes blockquotes, code blocks, and strikethrough', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'formatting',
|
||||
title: 'Formatting',
|
||||
content: '# Formatting',
|
||||
},
|
||||
editorHtml: [
|
||||
'<blockquote><p>Quoted idea</p><p>Second line</p></blockquote>',
|
||||
'<pre><code class="language-ts">const value = <string>input</code></pre>',
|
||||
'<p>Keep <s>stale</s> text visible.</p>',
|
||||
].join(''),
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: [
|
||||
'> Quoted idea',
|
||||
'> Second line',
|
||||
'',
|
||||
'```ts',
|
||||
'const value = <string>input',
|
||||
'```',
|
||||
'',
|
||||
'Keep ~~stale~~ text visible.',
|
||||
].join('\n'),
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes horizontal rules from TenTap HTML', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'break',
|
||||
title: 'Break',
|
||||
content: '# Break',
|
||||
},
|
||||
editorHtml: '<p>Before</p><hr><p>After</p>',
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: 'Before\n\n---\n\nAfter',
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes TenTap-style task list items', () => {
|
||||
const draft = createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'tasks',
|
||||
title: 'Tasks',
|
||||
content: '# Tasks',
|
||||
},
|
||||
editorHtml: [
|
||||
'<ul data-type="taskList">',
|
||||
'<li data-checked="true"><label><input type="checkbox" checked=""></label><div><p>Done</p></div></li>',
|
||||
'<li data-checked="false"><label><input type="checkbox"></label><div><p>Todo</p></div></li>',
|
||||
'</ul>',
|
||||
].join(''),
|
||||
})
|
||||
|
||||
expect(draft).toMatchObject({
|
||||
persistable: true,
|
||||
canonicalMarkdown: '- [x] Done\n- [ ] Todo',
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks unsupported HTML instead of persisting unknown editor output', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'workflow',
|
||||
title: 'Workflow',
|
||||
content: '# Workflow\n\nOriginal markdown',
|
||||
},
|
||||
editorHtml: '<figure><figcaption>Not yet supported</figcaption></figure>',
|
||||
}),
|
||||
).toEqual({
|
||||
noteId: 'workflow',
|
||||
sourceMarkdown: '# Workflow\n\nOriginal markdown',
|
||||
editorHtml: '<figure><figcaption>Not yet supported</figcaption></figure>',
|
||||
persistable: false,
|
||||
blockedReason: 'unsupportedEditorHtml',
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks unsafe link destinations instead of persisting risky Markdown', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'links',
|
||||
title: 'Links',
|
||||
content: '# Links',
|
||||
},
|
||||
editorHtml: '<p><a href="javascript:alert(1)">Unsafe</a></p>',
|
||||
}),
|
||||
).toMatchObject({
|
||||
noteId: 'links',
|
||||
persistable: false,
|
||||
blockedReason: 'unsupportedEditorHtml',
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes simple TenTap tables as Markdown tables', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'table',
|
||||
title: 'Table',
|
||||
content: '# Table',
|
||||
},
|
||||
editorHtml: [
|
||||
'<table><tbody>',
|
||||
'<tr><th><p>Name</p></th><th><p>Status</p></th></tr>',
|
||||
'<tr><td><p>Tolaria</p></td><td><p>Ready & synced</p></td></tr>',
|
||||
'<tr><td><p>Pipe</p></td><td><p>A | B</p></td></tr>',
|
||||
'</tbody></table>',
|
||||
].join(''),
|
||||
}),
|
||||
).toMatchObject({
|
||||
noteId: 'table',
|
||||
persistable: true,
|
||||
canonicalMarkdown: [
|
||||
'| Name | Status |',
|
||||
'| --- | --- |',
|
||||
'| Tolaria | Ready & synced |',
|
||||
'| Pipe | A \\| B |',
|
||||
].join('\n'),
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks malformed tables instead of guessing columns', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'table',
|
||||
title: 'Table',
|
||||
content: '# Table',
|
||||
},
|
||||
editorHtml: '<table><tbody><tr><td>Name</td><td>Status</td></tr><tr><td>Tolaria</td></tr></tbody></table>',
|
||||
}),
|
||||
).toMatchObject({
|
||||
noteId: 'table',
|
||||
persistable: false,
|
||||
blockedReason: 'unsupportedEditorHtml',
|
||||
})
|
||||
})
|
||||
|
||||
it('serializes safe image attachments inside supported blocks', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'image',
|
||||
title: 'Image',
|
||||
content: '# Image',
|
||||
},
|
||||
editorHtml: '<p>Before</p><p><img src="attachments/sketch.png" alt="Interface sketch"></p><p>After</p>',
|
||||
}),
|
||||
).toMatchObject({
|
||||
noteId: 'image',
|
||||
persistable: true,
|
||||
canonicalMarkdown: 'Before\n\n\n\nAfter',
|
||||
})
|
||||
})
|
||||
|
||||
it('blocks transient or unsafe image sources inside otherwise supported blocks', () => {
|
||||
expect(
|
||||
createMobileEditorDraft({
|
||||
note: {
|
||||
id: 'image',
|
||||
title: 'Image',
|
||||
content: '# Image',
|
||||
},
|
||||
editorHtml: '<p><img src="blob:https://tolaria.app/preview" alt="Attachment"></p>',
|
||||
}),
|
||||
).toMatchObject({
|
||||
noteId: 'image',
|
||||
persistable: false,
|
||||
blockedReason: 'unsupportedEditorHtml',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,67 +0,0 @@
|
||||
import { splitFrontmatter } from '@tolaria/markdown'
|
||||
import type { MobileEditorDocumentInput } from './mobileEditorDocument'
|
||||
import { serializeSupportedMobileEditorHtml } from './mobileEditorHtmlMarkdown'
|
||||
|
||||
export type MobileEditorDraft =
|
||||
| {
|
||||
noteId: string
|
||||
sourceMarkdown: string
|
||||
editorHtml: string
|
||||
persistable: true
|
||||
canonicalMarkdown: string
|
||||
}
|
||||
| {
|
||||
noteId: string
|
||||
sourceMarkdown: string
|
||||
editorHtml: string
|
||||
persistable: false
|
||||
blockedReason: 'unsupportedEditorHtml'
|
||||
}
|
||||
|
||||
export function createMobileEditorDraft({
|
||||
editorHtml,
|
||||
note,
|
||||
}: {
|
||||
editorHtml: string
|
||||
note: MobileEditorDocumentInput
|
||||
}): MobileEditorDraft {
|
||||
const markdownBody = serializeSupportedMobileEditorHtml({ editorHtml })
|
||||
if (!markdownBody) {
|
||||
return createBlockedDraft({ editorHtml, note })
|
||||
}
|
||||
|
||||
return {
|
||||
noteId: note.id,
|
||||
sourceMarkdown: note.content,
|
||||
editorHtml,
|
||||
persistable: true,
|
||||
canonicalMarkdown: withFrontmatter({ markdownBody, sourceMarkdown: note.content }),
|
||||
}
|
||||
}
|
||||
|
||||
function createBlockedDraft({
|
||||
editorHtml,
|
||||
note,
|
||||
}: {
|
||||
editorHtml: string
|
||||
note: MobileEditorDocumentInput
|
||||
}): MobileEditorDraft {
|
||||
return {
|
||||
noteId: note.id,
|
||||
sourceMarkdown: note.content,
|
||||
editorHtml,
|
||||
persistable: false,
|
||||
blockedReason: 'unsupportedEditorHtml',
|
||||
}
|
||||
}
|
||||
|
||||
function withFrontmatter({
|
||||
markdownBody,
|
||||
sourceMarkdown,
|
||||
}: {
|
||||
markdownBody: string
|
||||
sourceMarkdown: string
|
||||
}) {
|
||||
const [frontmatter] = splitFrontmatter(sourceMarkdown)
|
||||
return frontmatter ? `${frontmatter}${markdownBody}` : markdownBody
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { createMobileEditorDraft } from './mobileEditorDraft'
|
||||
import { saveMobileEditorDraft } from './mobileEditorDraftSave'
|
||||
import { createMobileVaultConfig } from './mobileVaultConfig'
|
||||
import { createMemoryMobileVaultStorage } from './mobileVaultStorage'
|
||||
|
||||
const vault = createVault()
|
||||
|
||||
describe('mobile editor draft save', () => {
|
||||
it('writes persistable editor drafts as canonical Markdown', async () => {
|
||||
const storage = createMemoryMobileVaultStorage([])
|
||||
const draft = createMobileEditorDraft({
|
||||
note: { id: 'notes/workflow', title: 'Workflow', content: '# Workflow' },
|
||||
editorHtml: '<h1>Workflow</h1><p>Edited</p>',
|
||||
})
|
||||
|
||||
await expect(saveMobileEditorDraft({ draft, storage, vault })).resolves.toEqual({
|
||||
status: 'saved',
|
||||
path: 'notes/workflow.md',
|
||||
})
|
||||
|
||||
await expect(storage.readMarkdownFile(vault, 'notes/workflow.md')).resolves.toBe('# Workflow\n\nEdited')
|
||||
})
|
||||
|
||||
it('does not write blocked editor drafts', async () => {
|
||||
const storage = createMemoryMobileVaultStorage([])
|
||||
const draft = createMobileEditorDraft({
|
||||
note: { id: 'workflow', title: 'Workflow', content: '# Workflow' },
|
||||
editorHtml: '<figure><figcaption>Unsupported</figcaption></figure>',
|
||||
})
|
||||
|
||||
await expect(saveMobileEditorDraft({ draft, storage, vault })).resolves.toEqual({
|
||||
status: 'blocked',
|
||||
reason: 'unsupportedEditorHtml',
|
||||
})
|
||||
|
||||
await expect(storage.listMarkdownFiles(vault)).resolves.toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
function createVault() {
|
||||
const result = createMobileVaultConfig({ id: 'personal', name: 'Personal Journal' })
|
||||
if (!result.ok) {
|
||||
throw new Error(result.error)
|
||||
}
|
||||
|
||||
return result.config
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
import type { MobileEditorDraft } from './mobileEditorDraft'
|
||||
import type { MobileVaultConfig } from './mobileVaultConfig'
|
||||
import type { MobileVaultStorageDriver } from './mobileVaultStorage'
|
||||
|
||||
export type MobileEditorDraftSaveResult =
|
||||
| {
|
||||
status: 'saved'
|
||||
path: string
|
||||
}
|
||||
| {
|
||||
status: 'blocked'
|
||||
reason: 'unsupportedEditorHtml'
|
||||
}
|
||||
|
||||
export async function saveMobileEditorDraft({
|
||||
draft,
|
||||
storage,
|
||||
vault,
|
||||
}: {
|
||||
draft: MobileEditorDraft
|
||||
storage: MobileVaultStorageDriver
|
||||
vault: MobileVaultConfig
|
||||
}): Promise<MobileEditorDraftSaveResult> {
|
||||
if (!draft.persistable) {
|
||||
return { status: 'blocked', reason: draft.blockedReason }
|
||||
}
|
||||
|
||||
const path = draftPath(draft)
|
||||
await storage.writeMarkdownFile(vault, path, draft.canonicalMarkdown)
|
||||
|
||||
return { status: 'saved', path }
|
||||
}
|
||||
|
||||
function draftPath(draft: MobileEditorDraft) {
|
||||
return `${draft.noteId}.md`
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
import {
|
||||
canSerializeMobileEditorTable,
|
||||
isMobileEditorTableBlock,
|
||||
mobileEditorTableMarkdown,
|
||||
} from './mobileEditorTableMarkdown'
|
||||
import { decodeMobileHtmlEntities } from './mobileHtmlEntities'
|
||||
|
||||
type EditorHtmlInput = {
|
||||
editorHtml: string
|
||||
}
|
||||
|
||||
type HtmlInput = {
|
||||
html: string
|
||||
}
|
||||
|
||||
type ListItemInput = HtmlInput & {
|
||||
ordered: boolean
|
||||
}
|
||||
|
||||
const supportedHtmlTags = new Set([
|
||||
'a',
|
||||
'b',
|
||||
'blockquote',
|
||||
'br',
|
||||
'code',
|
||||
'del',
|
||||
'div',
|
||||
'em',
|
||||
'h1',
|
||||
'h2',
|
||||
'h3',
|
||||
'h4',
|
||||
'h5',
|
||||
'h6',
|
||||
'hr',
|
||||
'i',
|
||||
'img',
|
||||
'input',
|
||||
'label',
|
||||
'li',
|
||||
'ol',
|
||||
'p',
|
||||
'pre',
|
||||
's',
|
||||
'strike',
|
||||
'strong',
|
||||
'table',
|
||||
'tbody',
|
||||
'td',
|
||||
'th',
|
||||
'thead',
|
||||
'tr',
|
||||
'ul',
|
||||
])
|
||||
|
||||
export function serializeSupportedMobileEditorHtml(input: EditorHtmlInput) {
|
||||
const html = normalizeBlockSpacing(input)
|
||||
const blocks = html.match(/<(h[1-6]|p|ul|ol|blockquote|pre|table)(?:\s[^>]*)?>[\s\S]*?<\/\1>|<hr(?:\s[^>]*)?\s*\/?>/gi)
|
||||
if (!blocks) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!canSerializeBlocks({ blocks, html })) {
|
||||
return null
|
||||
}
|
||||
|
||||
return blocks.map((block) => serializeBlock({ html: block })).join('\n\n')
|
||||
}
|
||||
|
||||
function canSerializeBlocks({
|
||||
blocks,
|
||||
html,
|
||||
}: {
|
||||
blocks: RegExpMatchArray
|
||||
html: string
|
||||
}) {
|
||||
return blocks.join('') === html && !blocks.some((block) => blocksUnsafeEditorOutput({ html: block }))
|
||||
}
|
||||
|
||||
function serializeBlock(input: HtmlInput) {
|
||||
const headingLevel = headingMarkdownLevel(input)
|
||||
if (headingLevel) {
|
||||
return `${'#'.repeat(headingLevel)} ${inlineMarkdown(input)}`
|
||||
}
|
||||
|
||||
if (isListBlock(input)) {
|
||||
return listItemMarkdown(input).join('\n')
|
||||
}
|
||||
|
||||
if (isBlockquote(input)) {
|
||||
return blockquoteMarkdown(input)
|
||||
}
|
||||
|
||||
if (isCodeBlock(input)) {
|
||||
return codeBlockMarkdown(input)
|
||||
}
|
||||
|
||||
if (isHorizontalRule(input)) {
|
||||
return '---'
|
||||
}
|
||||
|
||||
if (isMobileEditorTableBlock(input)) {
|
||||
return mobileEditorTableMarkdown(input)
|
||||
}
|
||||
|
||||
return inlineMarkdown(input)
|
||||
}
|
||||
|
||||
function normalizeBlockSpacing(input: EditorHtmlInput) {
|
||||
return input.editorHtml.trim().replace(/>\s+</g, '><')
|
||||
}
|
||||
|
||||
function headingMarkdownLevel(input: HtmlInput) {
|
||||
const match = input.html.match(/^<h([1-6])/i)
|
||||
return match ? Number(match[1]) : null
|
||||
}
|
||||
|
||||
function isListBlock(input: HtmlInput) {
|
||||
return input.html.match(/^<(ul|ol)/i)
|
||||
}
|
||||
|
||||
function isBlockquote(input: HtmlInput) {
|
||||
return input.html.match(/^<blockquote/i)
|
||||
}
|
||||
|
||||
function isCodeBlock(input: HtmlInput) {
|
||||
return input.html.match(/^<pre/i)
|
||||
}
|
||||
|
||||
function isHorizontalRule(input: HtmlInput) {
|
||||
return input.html.match(/^<hr/i)
|
||||
}
|
||||
|
||||
function listItemMarkdown(input: HtmlInput) {
|
||||
const ordered = input.html.match(/^<ol/i)
|
||||
return [...input.html.matchAll(/<li(?:\s[^>]*)?>([\s\S]*?)<\/li>/gi)].map((match) =>
|
||||
formatListItem({ ordered: Boolean(ordered), html: match[0] }),
|
||||
)
|
||||
}
|
||||
|
||||
function formatListItem(input: ListItemInput) {
|
||||
const taskMarker = markdownTaskMarker(input)
|
||||
const prefix = taskMarker ? `- ${taskMarker}` : input.ordered ? '1.' : '-'
|
||||
|
||||
return `${prefix} ${inlineMarkdown(input)}`
|
||||
}
|
||||
|
||||
function markdownTaskMarker(input: HtmlInput) {
|
||||
if (input.html.match(/data-checked=["']true/i) || input.html.match(/<input[^>]+checked/i)) {
|
||||
return '[x]'
|
||||
}
|
||||
|
||||
if (input.html.match(/data-checked=["']false/i) || input.html.match(/<input[^>]+type=["']checkbox/i)) {
|
||||
return '[ ]'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function blockquoteMarkdown(input: HtmlInput) {
|
||||
const paragraphLines = [...input.html.matchAll(/<p(?:\s[^>]*)?>([\s\S]*?)<\/p>/gi)].map((match) =>
|
||||
inlineMarkdown({ html: match[0] }),
|
||||
)
|
||||
const lines = paragraphLines.length > 0 ? paragraphLines : [inlineMarkdown(input)]
|
||||
|
||||
return lines.map((line) => `> ${line}`).join('\n')
|
||||
}
|
||||
|
||||
function codeBlockMarkdown(input: HtmlInput) {
|
||||
return [
|
||||
`\`\`\`${codeBlockLanguage(input)}`,
|
||||
decodeMobileHtmlEntities({ text: codeBlockText(input) }).trimEnd(),
|
||||
'```',
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function codeBlockLanguage(input: HtmlInput) {
|
||||
return input.html.match(/language-([A-Za-z0-9_-]+)/)?.[1] ?? ''
|
||||
}
|
||||
|
||||
function codeBlockText(input: HtmlInput) {
|
||||
const code = input.html.match(/<code(?:\s[^>]*)?>([\s\S]*?)<\/code>/i)?.[1] ?? input.html
|
||||
return stripRemainingTags(code.replace(/<br\s*\/?>/gi, '\n'))
|
||||
}
|
||||
|
||||
function inlineMarkdown(input: HtmlInput) {
|
||||
return decodeMobileHtmlEntities({ text: stripRemainingTags(markInlineHtml(input)).trim() })
|
||||
}
|
||||
|
||||
function markInlineHtml(input: HtmlInput) {
|
||||
return input.html
|
||||
.replace(/<br\s*\/?>/gi, '\n')
|
||||
.replace(/<img\b[^>]*>/gi, (tag) => imageMarkdown({ tag }) ?? tag)
|
||||
.replace(/<(strong|b)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi, '**$2**')
|
||||
.replace(/<(em|i)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi, '*$2*')
|
||||
.replace(/<(s|strike|del)(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi, '~~$2~~')
|
||||
.replace(/<code(?:\s[^>]*)?>([\s\S]*?)<\/code>/gi, '`$1`')
|
||||
.replace(/<a\b[^>]*>([\s\S]*?)<\/a>/gi, (tag, label) => linkMarkdown({ tag, label }) ?? tag)
|
||||
}
|
||||
|
||||
function containsUnsupportedTag(input: HtmlInput) {
|
||||
return [...input.html.matchAll(/<\/?([a-z0-9-]+)/gi)]
|
||||
.some((match) => !supportedHtmlTags.has(match[1].toLowerCase()))
|
||||
}
|
||||
|
||||
function blocksUnsafeEditorOutput(input: HtmlInput) {
|
||||
return containsUnsupportedTag(input) || containsUnsafeImage(input) || containsUnsafeLink(input) || containsUnsafeTable(input)
|
||||
}
|
||||
|
||||
function containsUnsafeImage(input: HtmlInput) {
|
||||
return [...input.html.matchAll(/<img\b[^>]*>/gi)].some((match) => !imageMarkdown({ tag: match[0] }))
|
||||
}
|
||||
|
||||
function containsUnsafeLink(input: HtmlInput) {
|
||||
return [...input.html.matchAll(/<a\b[^>]*>/gi)].some((match) => !linkMarkdown({ tag: match[0], label: '' }))
|
||||
}
|
||||
|
||||
function containsUnsafeTable(input: HtmlInput) {
|
||||
return Boolean(isMobileEditorTableBlock(input)) && !canSerializeMobileEditorTable(input)
|
||||
}
|
||||
|
||||
function imageMarkdown(input: { tag: string }) {
|
||||
const src = imageSource(input)
|
||||
if (!src) {
|
||||
return null
|
||||
}
|
||||
|
||||
const alt = htmlAttribute({ tag: input.tag, name: 'alt' }) ?? ''
|
||||
return `})`
|
||||
}
|
||||
|
||||
function imageSource(input: { tag: string }) {
|
||||
const src = htmlAttribute({ tag: input.tag, name: 'src' })
|
||||
return src && isPersistableImageSource({ src }) ? src : null
|
||||
}
|
||||
|
||||
function linkMarkdown(input: { tag: string; label: string }) {
|
||||
const wikilink = wikilinkMarkdown(input)
|
||||
if (wikilink) {
|
||||
return wikilink
|
||||
}
|
||||
|
||||
const href = linkDestination(input)
|
||||
return href ? `[${input.label}](${href})` : null
|
||||
}
|
||||
|
||||
function wikilinkMarkdown(input: { tag: string; label: string }) {
|
||||
const href = htmlAttribute({ tag: input.tag, name: 'href' })
|
||||
if (!href?.startsWith('tolaria-note:')) {
|
||||
return null
|
||||
}
|
||||
|
||||
const target = decodeURIComponent(href.slice('tolaria-note:'.length)).trim()
|
||||
const label = decodeMobileHtmlEntities({ text: input.label }).trim()
|
||||
if (!target) {
|
||||
return null
|
||||
}
|
||||
|
||||
return label && label !== target ? `[[${target}|${label}]]` : `[[${target}]]`
|
||||
}
|
||||
|
||||
function linkDestination(input: { tag: string }) {
|
||||
const href = htmlAttribute({ tag: input.tag, name: 'href' })
|
||||
return href && isPersistableLinkDestination({ href }) ? decodeMobileHtmlEntities({ text: href }) : null
|
||||
}
|
||||
|
||||
function htmlAttribute(input: { tag: string; name: string }) {
|
||||
const match = input.tag.match(new RegExp(`${input.name}=["']([^"']+)["']`, 'i'))
|
||||
return match?.[1] ?? null
|
||||
}
|
||||
|
||||
function isPersistableImageSource(input: { src: string }) {
|
||||
if (input.src.match(/[\n\r]/)) {
|
||||
return false
|
||||
}
|
||||
|
||||
return isRemoteImageSource(input) || isRelativeImageSource(input)
|
||||
}
|
||||
|
||||
function isRemoteImageSource(input: { src: string }) {
|
||||
return input.src.startsWith('https://') || input.src.startsWith('http://')
|
||||
}
|
||||
|
||||
function isRelativeImageSource(input: { src: string }) {
|
||||
return !input.src.startsWith('/') && !input.src.startsWith('//') && !input.src.match(/^[A-Za-z][A-Za-z0-9+.-]*:/)
|
||||
}
|
||||
|
||||
function isPersistableLinkDestination(input: { href: string }) {
|
||||
const href = decodeMobileHtmlEntities({ text: input.href })
|
||||
if (href.match(/[\n\r]/)) {
|
||||
return false
|
||||
}
|
||||
|
||||
return isRemoteLinkDestination({ href }) || isMailLinkDestination({ href }) || isRelativeLinkDestination({ href }) || isWikilinkDestination({ href })
|
||||
}
|
||||
|
||||
function isRemoteLinkDestination(input: { href: string }) {
|
||||
return input.href.startsWith('https://') || input.href.startsWith('http://')
|
||||
}
|
||||
|
||||
function isMailLinkDestination(input: { href: string }) {
|
||||
return input.href.startsWith('mailto:')
|
||||
}
|
||||
|
||||
function isRelativeLinkDestination(input: { href: string }) {
|
||||
return !input.href.startsWith('/') && !input.href.startsWith('//') && !input.href.match(/^[A-Za-z][A-Za-z0-9+.-]*:/)
|
||||
}
|
||||
|
||||
function isWikilinkDestination(input: { href: string }) {
|
||||
return input.href.startsWith('tolaria-note:') && input.href.length > 'tolaria-note:'.length
|
||||
}
|
||||
|
||||
function stripRemainingTags(value: string) {
|
||||
return value.replace(/<[^>]+>/g, '')
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseEditorMessage } from './mobileEditorMessages'
|
||||
|
||||
describe('mobile editor messages', () => {
|
||||
it('parses empty wikilink queries with cursor geometry', () => {
|
||||
expect(parseEditorMessage(JSON.stringify({
|
||||
frame: { bottom: 124, left: 48 },
|
||||
query: '',
|
||||
type: 'wikilinkQuery',
|
||||
}))).toEqual({
|
||||
frame: { bottom: 124, left: 48 },
|
||||
query: '',
|
||||
type: 'wikilinkQuery',
|
||||
})
|
||||
})
|
||||
|
||||
it('ignores invalid wikilink query geometry', () => {
|
||||
expect(parseEditorMessage(JSON.stringify({
|
||||
frame: { bottom: '124', left: 48 },
|
||||
query: 'roadmap',
|
||||
type: 'wikilinkQuery',
|
||||
}))).toEqual({
|
||||
frame: null,
|
||||
query: 'roadmap',
|
||||
type: 'wikilinkQuery',
|
||||
})
|
||||
})
|
||||
|
||||
it('parses hardware Tab list indentation messages', () => {
|
||||
expect(parseEditorMessage(JSON.stringify({
|
||||
direction: 'in',
|
||||
type: 'listIndent',
|
||||
}))).toEqual({
|
||||
direction: 'in',
|
||||
type: 'listIndent',
|
||||
})
|
||||
|
||||
expect(parseEditorMessage(JSON.stringify({
|
||||
direction: 'out',
|
||||
type: 'listIndent',
|
||||
}))).toEqual({
|
||||
direction: 'out',
|
||||
type: 'listIndent',
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects malformed list indentation messages', () => {
|
||||
expect(parseEditorMessage(JSON.stringify({
|
||||
direction: 'sideways',
|
||||
type: 'listIndent',
|
||||
}))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -1,88 +0,0 @@
|
||||
export type MobileEditorMessage =
|
||||
| { target: string; type: 'openWikilink' }
|
||||
| { command: 'fileNewNote'; type: 'shortcut' }
|
||||
| { direction: 'in' | 'out'; type: 'listIndent' }
|
||||
| { frame: MobileEditorWikilinkFrame | null; query: string | null; type: 'wikilinkQuery' }
|
||||
|
||||
export type MobileEditorWikilinkFrame = {
|
||||
bottom: number
|
||||
left: number
|
||||
}
|
||||
|
||||
export function parseEditorMessage(data: string): MobileEditorMessage | null {
|
||||
try {
|
||||
return normalizeEditorMessage(JSON.parse(data))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeEditorMessage(value: unknown): MobileEditorMessage | null {
|
||||
if (!isMessageRecord(value)) {
|
||||
return null
|
||||
}
|
||||
if (isWikilinkQueryMessage(value)) {
|
||||
return { frame: wikilinkFrame(value.frame), query: value.query, type: 'wikilinkQuery' }
|
||||
}
|
||||
if (isListIndentMessage(value)) {
|
||||
return { direction: value.direction, type: 'listIndent' }
|
||||
}
|
||||
if (value.type === 'openWikilink' && typeof value.target === 'string') {
|
||||
return { target: value.target, type: 'openWikilink' }
|
||||
}
|
||||
if (value.type === 'shortcut' && value.command === 'fileNewNote') {
|
||||
return { command: 'fileNewNote', type: 'shortcut' }
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function isMessageRecord(value: unknown): value is {
|
||||
command?: unknown
|
||||
direction?: unknown
|
||||
frame?: unknown
|
||||
query?: unknown
|
||||
target?: unknown
|
||||
type?: unknown
|
||||
} {
|
||||
return typeof value === 'object' && value !== null
|
||||
}
|
||||
|
||||
function isWikilinkQueryMessage(value: {
|
||||
frame?: unknown
|
||||
query?: unknown
|
||||
type?: unknown
|
||||
}): value is {
|
||||
frame?: unknown
|
||||
query: string | null
|
||||
type: 'wikilinkQuery'
|
||||
} {
|
||||
return value.type === 'wikilinkQuery'
|
||||
&& (typeof value.query === 'string' || value.query === null)
|
||||
}
|
||||
|
||||
function wikilinkFrame(value: unknown): MobileEditorWikilinkFrame | null {
|
||||
if (!isFrameRecord(value)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return { bottom: value.bottom, left: value.left }
|
||||
}
|
||||
|
||||
function isFrameRecord(value: unknown): value is MobileEditorWikilinkFrame {
|
||||
return typeof value === 'object'
|
||||
&& value !== null
|
||||
&& typeof (value as { bottom?: unknown }).bottom === 'number'
|
||||
&& typeof (value as { left?: unknown }).left === 'number'
|
||||
}
|
||||
|
||||
function isListIndentMessage(value: {
|
||||
direction?: unknown
|
||||
type?: unknown
|
||||
}): value is {
|
||||
direction: 'in' | 'out'
|
||||
type: 'listIndent'
|
||||
} {
|
||||
return value.type === 'listIndent'
|
||||
&& (value.direction === 'in' || value.direction === 'out')
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import {
|
||||
failedMobileEditorSaveState,
|
||||
idleMobileEditorSaveState,
|
||||
queuedMobileEditorSaveState,
|
||||
saveResultState,
|
||||
savingMobileEditorSaveState,
|
||||
} from './mobileEditorSaveState'
|
||||
|
||||
describe('mobile editor save state', () => {
|
||||
it('provides stable labels for direct save states', () => {
|
||||
expect(idleMobileEditorSaveState.label).toBe('Ready')
|
||||
expect(queuedMobileEditorSaveState.label).toBe('Edited')
|
||||
expect(savingMobileEditorSaveState.label).toBe('Saving')
|
||||
expect(failedMobileEditorSaveState.label).toBe('Save failed')
|
||||
})
|
||||
|
||||
it('derives visible state from save results', () => {
|
||||
expect(saveResultState({ status: 'saved', path: 'workflow.md' })).toEqual({
|
||||
state: 'saved',
|
||||
label: 'Saved',
|
||||
})
|
||||
expect(saveResultState({ status: 'blocked', reason: 'unsupportedEditorHtml' })).toEqual({
|
||||
state: 'blocked',
|
||||
label: 'Blocked',
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { MobileEditorDraftSaveResult } from './mobileEditorDraftSave'
|
||||
|
||||
export type MobileEditorSaveState =
|
||||
| {
|
||||
state: 'idle'
|
||||
label: 'Ready'
|
||||
}
|
||||
| {
|
||||
state: 'queued'
|
||||
label: 'Edited'
|
||||
}
|
||||
| {
|
||||
state: 'saving'
|
||||
label: 'Saving'
|
||||
}
|
||||
| {
|
||||
state: 'saved'
|
||||
label: 'Saved'
|
||||
}
|
||||
| {
|
||||
state: 'blocked'
|
||||
label: 'Blocked'
|
||||
}
|
||||
| {
|
||||
state: 'failed'
|
||||
label: 'Save failed'
|
||||
}
|
||||
|
||||
export const idleMobileEditorSaveState: MobileEditorSaveState = {
|
||||
state: 'idle',
|
||||
label: 'Ready',
|
||||
}
|
||||
|
||||
export const queuedMobileEditorSaveState: MobileEditorSaveState = {
|
||||
state: 'queued',
|
||||
label: 'Edited',
|
||||
}
|
||||
|
||||
export const savingMobileEditorSaveState: MobileEditorSaveState = {
|
||||
state: 'saving',
|
||||
label: 'Saving',
|
||||
}
|
||||
|
||||
export const failedMobileEditorSaveState: MobileEditorSaveState = {
|
||||
state: 'failed',
|
||||
label: 'Save failed',
|
||||
}
|
||||
|
||||
export function saveResultState(result: MobileEditorDraftSaveResult): MobileEditorSaveState {
|
||||
return result.status === 'saved'
|
||||
? { state: 'saved', label: 'Saved' }
|
||||
: { state: 'blocked', label: 'Blocked' }
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { decodeMobileHtmlEntities } from './mobileHtmlEntities'
|
||||
|
||||
type HtmlInput = {
|
||||
html: string
|
||||
}
|
||||
|
||||
type TableRow = {
|
||||
cells: string[]
|
||||
}
|
||||
|
||||
export function isMobileEditorTableBlock(input: HtmlInput) {
|
||||
return input.html.match(/^<table/i)
|
||||
}
|
||||
|
||||
export function canSerializeMobileEditorTable(input: HtmlInput) {
|
||||
const rows = tableRows(input)
|
||||
const columnCount = rows[0]?.cells.length ?? 0
|
||||
|
||||
return columnCount > 0 && rows.every((row) => row.cells.length === columnCount)
|
||||
}
|
||||
|
||||
export function mobileEditorTableMarkdown(input: HtmlInput) {
|
||||
const rows = tableRows(input)
|
||||
const header = rows[0]?.cells ?? []
|
||||
const body = rows.slice(1).map(tableRowMarkdown)
|
||||
|
||||
return [
|
||||
tableRowMarkdown({ cells: header }),
|
||||
tableSeparator({ columnCount: header.length }),
|
||||
...body,
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
function tableRows(input: HtmlInput) {
|
||||
return [...input.html.matchAll(/<tr(?:\s[^>]*)?>([\s\S]*?)<\/tr>/gi)]
|
||||
.map((match) => tableRow({ html: match[1] }))
|
||||
}
|
||||
|
||||
function tableRow(input: HtmlInput): TableRow {
|
||||
return {
|
||||
cells: [...input.html.matchAll(/<t[hd](?:\s[^>]*)?>([\s\S]*?)<\/t[hd]>/gi)]
|
||||
.map((match) => tableCellMarkdown({ html: match[1] })),
|
||||
}
|
||||
}
|
||||
|
||||
function tableCellMarkdown(input: HtmlInput) {
|
||||
return decodeMobileHtmlEntities({ text: stripCellTags(input).trim() })
|
||||
.replace(/\s+/g, ' ')
|
||||
.replace(/\|/g, '\\|')
|
||||
}
|
||||
|
||||
function tableRowMarkdown(input: TableRow) {
|
||||
return `| ${input.cells.join(' | ')} |`
|
||||
}
|
||||
|
||||
function tableSeparator(input: { columnCount: number }) {
|
||||
return tableRowMarkdown({ cells: Array.from({ length: input.columnCount }, () => '---') })
|
||||
}
|
||||
|
||||
function stripCellTags(input: HtmlInput) {
|
||||
return input.html.replace(/<br\s*\/?>/gi, ' ').replace(/<[^>]+>/g, '')
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
export const mobileEditorSetupScript = `
|
||||
document.documentElement.lang = navigator.language || "en";
|
||||
document.addEventListener("keydown", function(event) {
|
||||
if (isFileNewShortcut(event)) {
|
||||
event.preventDefault();
|
||||
postEditorMessage({ type: "shortcut", command: "fileNewNote" });
|
||||
return;
|
||||
}
|
||||
if (!isTabInsideEditor(event)) return;
|
||||
event.preventDefault();
|
||||
postEditorMessage({
|
||||
type: "listIndent",
|
||||
direction: event.shiftKey ? "out" : "in"
|
||||
});
|
||||
}, true);
|
||||
document.addEventListener("click", function(event) {
|
||||
var link = event.target && event.target.closest && event.target.closest("a[href^='tolaria-note:']");
|
||||
if (!link) return;
|
||||
event.preventDefault();
|
||||
postEditorMessage({
|
||||
type: "openWikilink",
|
||||
target: decodeURIComponent(String(link.getAttribute("href") || "").replace(/^tolaria-note:/, ""))
|
||||
});
|
||||
}, true);
|
||||
function isFileNewShortcut(event) {
|
||||
return (event.metaKey || event.ctrlKey)
|
||||
&& !event.altKey
|
||||
&& String(event.key).toLowerCase() === "n";
|
||||
}
|
||||
function isTabInsideEditor(event) {
|
||||
if (event.key !== "Tab") return false;
|
||||
var selection = window.getSelection();
|
||||
var node = selection && selection.anchorNode;
|
||||
return Boolean(node && containingEditor(node));
|
||||
}
|
||||
function containingEditor(node) {
|
||||
var editor = document.querySelector(".ProseMirror");
|
||||
var container = node.nodeType === 1 ? node : node.parentNode;
|
||||
return editor && container && editor.contains(container);
|
||||
}
|
||||
function activeWikilinkQuery() {
|
||||
var selection = window.getSelection();
|
||||
if (!isCollapsedTextSelection(selection)) return null;
|
||||
if (!containingEditor(selection.anchorNode)) return null;
|
||||
return wikilinkQueryBeforeCursor(selection);
|
||||
}
|
||||
function isCollapsedTextSelection(selection) {
|
||||
return Boolean(selection
|
||||
&& selection.anchorNode
|
||||
&& selection.anchorNode.nodeType === 3
|
||||
&& selection.rangeCount > 0
|
||||
&& selection.isCollapsed);
|
||||
}
|
||||
function wikilinkQueryBeforeCursor(selection) {
|
||||
var prefix = String(selection.anchorNode.textContent || "").slice(0, selection.anchorOffset);
|
||||
var start = prefix.lastIndexOf("[[");
|
||||
if (start < 0) return null;
|
||||
var query = cleanWikilinkQuery(prefix.slice(start + 2));
|
||||
if (query === null) return null;
|
||||
return {
|
||||
frame: wikilinkQueryFrame(selection),
|
||||
query: query
|
||||
};
|
||||
}
|
||||
function cleanWikilinkQuery(query) {
|
||||
return query.indexOf("]]") >= 0 || query.indexOf("\\n") >= 0 ? null : query;
|
||||
}
|
||||
function emitWikilinkQuery() {
|
||||
var activeQuery = activeWikilinkQuery();
|
||||
postEditorMessage({
|
||||
type: "wikilinkQuery",
|
||||
frame: activeQuery ? activeQuery.frame : null,
|
||||
query: activeQuery ? activeQuery.query : null
|
||||
});
|
||||
}
|
||||
function wikilinkQueryFrame(selection) {
|
||||
var range = selection.getRangeAt(0).cloneRange();
|
||||
var rect = range.getBoundingClientRect();
|
||||
if (hasVisibleFrame(rect)) {
|
||||
return {
|
||||
bottom: rect.bottom,
|
||||
left: rect.left
|
||||
};
|
||||
}
|
||||
return fallbackWikilinkQueryFrame(selection);
|
||||
}
|
||||
function fallbackWikilinkQueryFrame(selection) {
|
||||
var container = selection.anchorNode && selection.anchorNode.parentElement;
|
||||
var rect = container && container.getBoundingClientRect && container.getBoundingClientRect();
|
||||
return {
|
||||
bottom: rect ? rect.bottom : 0,
|
||||
left: rect ? rect.left : 0
|
||||
};
|
||||
}
|
||||
function hasVisibleFrame(rect) {
|
||||
if (!rect) return false;
|
||||
return Boolean(rect.bottom || rect.left);
|
||||
}
|
||||
function postEditorMessage(message) {
|
||||
window.ReactNativeWebView && window.ReactNativeWebView.postMessage(JSON.stringify(message));
|
||||
}
|
||||
document.addEventListener("keyup", emitWikilinkQuery, true);
|
||||
document.addEventListener("mouseup", emitWikilinkQuery, true);
|
||||
document.addEventListener("selectionchange", emitWikilinkQuery, true);
|
||||
true;
|
||||
`
|
||||
|
||||
export const mobileEditorCss = `
|
||||
* {
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", sans-serif !important;
|
||||
}
|
||||
|
||||
html,
|
||||
body,
|
||||
#root,
|
||||
.ProseMirror {
|
||||
color: #292825;
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", sans-serif;
|
||||
font-size: 18px;
|
||||
line-height: 1.55;
|
||||
}
|
||||
|
||||
.ProseMirror {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.ProseMirror h1 {
|
||||
font-family: inherit;
|
||||
font-size: 42px;
|
||||
font-weight: 760;
|
||||
letter-spacing: 0;
|
||||
line-height: 1.08;
|
||||
margin: 18px 0 28px;
|
||||
}
|
||||
|
||||
.ProseMirror p,
|
||||
.ProseMirror li,
|
||||
.ProseMirror blockquote {
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.ProseMirror a[href^="tolaria-note:"] {
|
||||
color: #3367f6;
|
||||
font-weight: 650;
|
||||
text-decoration: none;
|
||||
border-radius: 5px;
|
||||
background: #e8eeff;
|
||||
padding: 1px 4px;
|
||||
}
|
||||
`
|
||||
@@ -1,310 +0,0 @@
|
||||
import { Buffer } from 'buffer'
|
||||
import { createMobileVaultConfigFromMetadata } from './mobileVaultMetadata'
|
||||
import type { MobileVaultMetadata } from './mobileVaultMetadata'
|
||||
import type { ExpoMobileVaultFileInfo, ExpoMobileVaultFileSystem } from './mobileExpoVaultStorage'
|
||||
import type { PromiseFsClient } from 'isomorphic-git'
|
||||
|
||||
type MobileGitStat = {
|
||||
ctime: Date
|
||||
ctimeMs: number
|
||||
dev: number
|
||||
gid: number
|
||||
ino: number
|
||||
isDirectory: () => boolean
|
||||
isFile: () => boolean
|
||||
isSymbolicLink: () => boolean
|
||||
mode: number
|
||||
mtime: Date
|
||||
mtimeMs: number
|
||||
size: number
|
||||
uid: number
|
||||
}
|
||||
|
||||
type MobileGitReadOptions = 'utf8' | { encoding?: 'base64' | 'utf8' }
|
||||
type MobileGitWriteOptions = { encoding?: 'base64' | 'utf8' }
|
||||
type MobileGitFileData = string | Uint8Array
|
||||
type ExistingPathInput = {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
path: string
|
||||
rootUri: string
|
||||
}
|
||||
|
||||
export type MobileExpoGitFileSystemContext = {
|
||||
dir: string
|
||||
fs: PromiseFsClient
|
||||
}
|
||||
|
||||
export function createMobileExpoGitFileSystem({
|
||||
fileSystem,
|
||||
vault,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
vault: MobileVaultMetadata
|
||||
}): MobileExpoGitFileSystemContext {
|
||||
const rootUri = mobileExpoGitVaultRootUri({ fileSystem, vault })
|
||||
const dir = '/vault'
|
||||
|
||||
return {
|
||||
dir,
|
||||
fs: {
|
||||
promises: {
|
||||
chmod: async () => {},
|
||||
lstat: (path: string) => statPath({ fileSystem, path, rootUri }),
|
||||
mkdir: (path: string) => mkdirPath({ fileSystem, path, rootUri }),
|
||||
readFile: (path: string, options?: MobileGitReadOptions) => readFile({ fileSystem, options, path, rootUri }),
|
||||
readlink: async () => {
|
||||
throw createFileSystemError('ENOTSUP', 'Symbolic links are not supported in mobile vaults.')
|
||||
},
|
||||
readdir: (path: string) => readDirectory({ fileSystem, path, rootUri }),
|
||||
rmdir: (path: string) => removeDirectory({ fileSystem, path, rootUri }),
|
||||
stat: (path: string) => statPath({ fileSystem, path, rootUri }),
|
||||
symlink: async () => {
|
||||
throw createFileSystemError('ENOTSUP', 'Symbolic links are not supported in mobile vaults.')
|
||||
},
|
||||
unlink: (path: string) => unlinkPath({ fileSystem, path, rootUri }),
|
||||
writeFile: (path: string, data: MobileGitFileData, options?: MobileGitWriteOptions) =>
|
||||
writeFile({ data, fileSystem, options, path, rootUri }),
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function mobileExpoGitVaultRootUri({
|
||||
fileSystem,
|
||||
vault,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
vault: MobileVaultMetadata
|
||||
}) {
|
||||
if (!fileSystem.documentDirectory) {
|
||||
throw new Error('Expo FileSystem documentDirectory is unavailable')
|
||||
}
|
||||
|
||||
const vaultConfig = createMobileVaultConfigFromMetadata(vault)
|
||||
return appendUri({
|
||||
root: fileSystem.documentDirectory,
|
||||
segments: ['vaults', vaultConfig.storage.directoryName || vaultConfig.id],
|
||||
})
|
||||
}
|
||||
|
||||
async function mkdirPath({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
path: string
|
||||
rootUri: string
|
||||
}) {
|
||||
const uri = uriForPath({ path, rootUri })
|
||||
const info = await fileSystem.getInfoAsync(uri)
|
||||
if (info.exists && !info.isDirectory) {
|
||||
throw createFileSystemError('ENOTDIR', `Path is not a directory: ${path}`)
|
||||
}
|
||||
|
||||
if (!info.exists) {
|
||||
await fileSystem.makeDirectoryAsync(uri, { intermediates: true })
|
||||
}
|
||||
}
|
||||
|
||||
async function readDirectory({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: ExistingPathInput) {
|
||||
await existingDirectory({ fileSystem, path, rootUri })
|
||||
|
||||
return fileSystem.readDirectoryAsync(uriForPath({ path, rootUri }))
|
||||
}
|
||||
|
||||
async function readFile({
|
||||
fileSystem,
|
||||
options,
|
||||
path,
|
||||
rootUri,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
options?: MobileGitReadOptions
|
||||
path: string
|
||||
rootUri: string
|
||||
}) {
|
||||
const info = await existingInfo({ fileSystem, path, rootUri })
|
||||
if (info.isDirectory) {
|
||||
throw createFileSystemError('EISDIR', `Path is a directory: ${path}`)
|
||||
}
|
||||
|
||||
const uri = uriForPath({ path, rootUri })
|
||||
return readAsUtf8(options)
|
||||
? fileSystem.readAsStringAsync(uri, { encoding: 'utf8' })
|
||||
: Buffer.from(await fileSystem.readAsStringAsync(uri, { encoding: 'base64' }), 'base64')
|
||||
}
|
||||
|
||||
async function writeFile({
|
||||
data,
|
||||
fileSystem,
|
||||
options,
|
||||
path,
|
||||
rootUri,
|
||||
}: {
|
||||
data: MobileGitFileData
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
options?: MobileGitWriteOptions
|
||||
path: string
|
||||
rootUri: string
|
||||
}) {
|
||||
await ensureParentDirectory({ fileSystem, path, rootUri })
|
||||
|
||||
if (typeof data === 'string' && writeAsUtf8(options)) {
|
||||
await fileSystem.writeAsStringAsync(uriForPath({ path, rootUri }), data, { encoding: 'utf8' })
|
||||
return
|
||||
}
|
||||
|
||||
await fileSystem.writeAsStringAsync(
|
||||
uriForPath({ path, rootUri }),
|
||||
dataToBase64(data),
|
||||
{ encoding: 'base64' },
|
||||
)
|
||||
}
|
||||
|
||||
async function unlinkPath({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: ExistingPathInput) {
|
||||
await existingFile({ fileSystem, path, rootUri })
|
||||
|
||||
await fileSystem.deleteAsync(uriForPath({ path, rootUri }))
|
||||
}
|
||||
|
||||
async function removeDirectory({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: ExistingPathInput) {
|
||||
await existingDirectory({ fileSystem, path, rootUri })
|
||||
|
||||
await fileSystem.deleteAsync(uriForPath({ path, rootUri }))
|
||||
}
|
||||
|
||||
async function statPath({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
path: string
|
||||
rootUri: string
|
||||
}): Promise<MobileGitStat> {
|
||||
return statForInfo(await existingInfo({ fileSystem, path, rootUri }))
|
||||
}
|
||||
|
||||
async function existingInfo({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: ExistingPathInput) {
|
||||
const info = await fileSystem.getInfoAsync(uriForPath({ path, rootUri }))
|
||||
if (!info.exists) {
|
||||
throw createFileSystemError('ENOENT', `Path does not exist: ${path}`)
|
||||
}
|
||||
|
||||
return info
|
||||
}
|
||||
|
||||
async function existingDirectory(input: ExistingPathInput) {
|
||||
const info = await existingInfo(input)
|
||||
if (!info.isDirectory) {
|
||||
throw createFileSystemError('ENOTDIR', `Path is not a directory: ${input.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function existingFile(input: ExistingPathInput) {
|
||||
const info = await existingInfo(input)
|
||||
if (info.isDirectory) {
|
||||
throw createFileSystemError('EISDIR', `Path is a directory: ${input.path}`)
|
||||
}
|
||||
}
|
||||
|
||||
function statForInfo(info: ExpoMobileVaultFileInfo): MobileGitStat {
|
||||
const modifiedMs = Math.round((info.modificationTime ?? 0) * 1000)
|
||||
const modified = new Date(modifiedMs)
|
||||
const isDirectory = info.isDirectory === true
|
||||
|
||||
return {
|
||||
ctime: modified,
|
||||
ctimeMs: modifiedMs,
|
||||
dev: 0,
|
||||
gid: 0,
|
||||
ino: 0,
|
||||
isDirectory: () => isDirectory,
|
||||
isFile: () => !isDirectory,
|
||||
isSymbolicLink: () => false,
|
||||
mode: isDirectory ? 0o040000 : 0o100644,
|
||||
mtime: modified,
|
||||
mtimeMs: modifiedMs,
|
||||
size: info.size ?? 0,
|
||||
uid: 0,
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureParentDirectory({
|
||||
fileSystem,
|
||||
path,
|
||||
rootUri,
|
||||
}: {
|
||||
fileSystem: ExpoMobileVaultFileSystem
|
||||
path: string
|
||||
rootUri: string
|
||||
}) {
|
||||
const segments = normalizedSegments(path)
|
||||
const parentSegments = segments.slice(0, -1)
|
||||
if (parentSegments.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
await fileSystem.makeDirectoryAsync(appendUri({ root: rootUri, segments: parentSegments }), { intermediates: true })
|
||||
}
|
||||
|
||||
function uriForPath({ path, rootUri }: { path: string; rootUri: string }) {
|
||||
return appendUri({ root: rootUri, segments: normalizedSegments(path) })
|
||||
}
|
||||
|
||||
function normalizedSegments(path: string) {
|
||||
const pathWithoutRoot = path.replace(/^\/+vault\/?/, '')
|
||||
const segments = pathWithoutRoot.replaceAll('\\', '/').split('/').filter(Boolean)
|
||||
if (segments.some(isUnsafeSegment)) {
|
||||
throw createFileSystemError('EINVAL', `Unsafe mobile Git path: ${path}`)
|
||||
}
|
||||
|
||||
return segments
|
||||
}
|
||||
|
||||
function isUnsafeSegment(segment: string) {
|
||||
return segment === '.' || segment === '..' || segment.includes('/')
|
||||
}
|
||||
|
||||
function readAsUtf8(options?: MobileGitReadOptions) {
|
||||
return options === 'utf8' || (typeof options === 'object' && options.encoding === 'utf8')
|
||||
}
|
||||
|
||||
function writeAsUtf8(options?: MobileGitWriteOptions) {
|
||||
return options?.encoding === 'utf8'
|
||||
}
|
||||
|
||||
function dataToBase64(data: MobileGitFileData) {
|
||||
return typeof data === 'string'
|
||||
? Buffer.from(data, 'utf8').toString('base64')
|
||||
: Buffer.from(data).toString('base64')
|
||||
}
|
||||
|
||||
function appendUri(input: { root: string; segments: string[] }) {
|
||||
const base = input.root.replace(/\/+$/, '')
|
||||
const path = input.segments.filter(Boolean).join('/')
|
||||
|
||||
return path ? `${base}/${path}` : base
|
||||
}
|
||||
|
||||
function createFileSystemError(code: string, message: string) {
|
||||
const error = new Error(message)
|
||||
return Object.assign(error, { code })
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user