Compare commits

...

222 Commits

Author SHA1 Message Date
pinpox
4e17d9ec0f Revert "vars: retrieve generators for multiple machines"
This reverts commit 501d020562.
2025-09-01 15:00:21 +02:00
clan-bot
87ea942399 Merge pull request 'Update data-mesher' (#5044) from update-data-mesher into main 2025-09-01 07:49:03 +00:00
clan-bot
39a032a285 Update data-mesher 2025-09-01 05:00:37 +00:00
clan-bot
a06940e981 Merge pull request 'Update treefmt-nix in devFlake' (#5043) from update-devFlake-treefmt-nix into main 2025-08-31 20:13:10 +00:00
clan-bot
4aebfadc8a Merge pull request 'Update nixpkgs-dev in devFlake' (#5042) from update-devFlake-nixpkgs-dev into main 2025-08-31 20:11:27 +00:00
clan-bot
f45f26994e Merge pull request 'Update treefmt-nix' (#5041) from update-treefmt-nix into main 2025-08-31 20:11:10 +00:00
clan-bot
c777a1a2b9 Update treefmt-nix in devFlake 2025-08-31 20:01:38 +00:00
clan-bot
36fe7822f7 Update nixpkgs-dev in devFlake 2025-08-31 20:01:33 +00:00
clan-bot
0ccf3310f9 Update treefmt-nix 2025-08-31 20:01:10 +00:00
clan-bot
a8d6552caa Merge pull request 'Update nixos-facter-modules' (#5032) from update-nixos-facter-modules into main 2025-08-31 19:39:40 +00:00
hsjobeki
a131448dcf Merge pull request 'ui/scene: init move machine' (#5031) from ui-more-2 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5031
2025-08-31 15:22:32 +00:00
hsjobeki
14a52dbc2e Merge pull request 'api/modules: improve logic for builtin modules' (#5040) from fix-modules-spagetti-other into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5040
2025-08-31 15:12:31 +00:00
Johannes Kirschbauer
565391bd8c ui/modules: deduplicate information 2025-08-31 17:09:36 +02:00
Johannes Kirschbauer
9bffa2a774 ui/clanContext: simplify
Try to avoid classes for use cases like this
2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
e42a07423e ui/machineLabels: use troika for label rendering 2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
c5178ac16a ui/fonts: use ttf font for 3d texture rendering 2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
33791e06cd ui: cleanup unused code 2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
c7e3bf624e ui/scene: replace 2d labels 2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
ba027c2239 ui/scene: init move machine 2025-08-31 17:04:03 +02:00
Johannes Kirschbauer
25fdabee29 ui/menu: add simple context menu 2025-08-31 17:04:03 +02:00
clan-bot
de69c63ee3 Update nixos-facter-modules 2025-08-31 15:00:41 +00:00
Johannes Kirschbauer
b9573636d8 ui/modules: simplify ui logic 2025-08-31 15:58:39 +02:00
Johannes Kirschbauer
3862ad2a06 api/modules: add foreign key to instances 2025-08-31 15:58:39 +02:00
Johannes Kirschbauer
c447aec9d3 api/modules: improve logic for builtin modules 2025-08-31 15:58:39 +02:00
Johannes Kirschbauer
5137d19b0f nix_modules: fix and update None types 2025-08-31 15:58:39 +02:00
Johannes Kirschbauer
453f2649d3 clanInternals: expose builtin modules 2025-08-31 15:58:39 +02:00
Johannes Kirschbauer
58cfcf3d25 api/modules: delete instances.py duplicate 2025-08-31 15:58:39 +02:00
clan-bot
c260a97cc1 Merge pull request 'Update nixpkgs-dev in devFlake' (#5033) from update-devFlake-nixpkgs-dev into main 2025-08-31 13:49:44 +00:00
clan-bot
3eb64870b0 Update nixpkgs-dev in devFlake 2025-08-31 13:44:23 +00:00
Mic92
7412b958c6 Merge pull request 'disable state-version in right place' (#5038) from private-flake-2 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5038
2025-08-31 13:43:07 +00:00
Jörg Thalheim
a0c27194a6 disable state-version in right place 2025-08-31 15:37:25 +02:00
Mic92
3437af29cb Merge pull request 'vars: fix var name in error message' (#5037) from private-flake-2 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5037
2025-08-31 13:33:01 +00:00
Jörg Thalheim
0b1c12d2e5 flash-installer: disable state-version
We cannot have vars in here because it breaks:

```
  clan flash write --flake https://git.clan.lol/clan/clan-core/archive/main.tar.gz   --ssh-pubkey $HOME/.ssh/id_ed25519.pub   --keymap us   --language en_US.UTF-8   --disk main /dev/sdb   flash-installer
```
2025-08-31 15:26:04 +02:00
Jörg Thalheim
8620761bbd vars: fix var name in error message 2025-08-31 15:23:24 +02:00
Mic92
d793b6ca07 Merge pull request 'vars: improve error message when storing trying to store a var in a read-only flake' (#5036) from private-flake-2 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5036
2025-08-31 13:20:13 +00:00
Jörg Thalheim
17e9231657 vars: improve error message when storing trying to store a var in a read-only flake 2025-08-31 14:14:56 +02:00
Mic92
acc2674d79 Merge pull request 'fix: check if phases are non-default when installing' (#5024) from sachk/clan-core:main into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5024
2025-08-29 16:16:01 +00:00
Jörg Thalheim
c34a21a3bb install: make Step a String enum 2025-08-29 17:45:16 +02:00
Mic92
275bff23da Merge pull request 'zfs-latest: fix eval errors' (#5029) from zfs-latest into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5029
2025-08-29 15:26:58 +00:00
Sacha Korban
1a766a3447 fix: check if phases are non-default when running 2025-08-29 17:26:49 +02:00
Jörg Thalheim
c22844c83b zfs-latest: fix eval errors 2025-08-29 17:20:56 +02:00
clan-bot
5472ca0e21 Merge pull request 'Update nixpkgs-dev in devFlake' (#5028) from update-devFlake-nixpkgs-dev into main 2025-08-29 15:08:13 +00:00
clan-bot
ad890b0b6b Update nixpkgs-dev in devFlake 2025-08-29 15:01:35 +00:00
DavHau
a364b5ebf3 API/list_service_instances: add module metadata (#5023)
@hsjobeki

Co-authored-by: Johannes Kirschbauer <hsjobeki@gmail.com>
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5023
2025-08-29 13:14:19 +00:00
brianmcgee
d0134d131e Merge pull request 'feat(ui): display add machine in sidebar when machine list is empty' (#5027) from ui/refine-add-machine into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5027
2025-08-29 12:27:33 +00:00
Brian McGee
ccf0dace11 feat(ui): display add machine in sidebar when machine list is empty 2025-08-29 13:23:45 +01:00
hsjobeki
9977a903ce Merge pull request 'ui/scene: cursor and mode fixes' (#5026) from ui-more-2 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5026
2025-08-29 12:01:56 +00:00
Johannes Kirschbauer
dc9bf5068e ui/scene: make 'select' the default mode 2025-08-29 13:58:35 +02:00
Johannes Kirschbauer
6b4f79c9fa ui/scene: add different cursor type 2025-08-29 13:54:32 +02:00
brianmcgee
b2985b59e9 Merge pull request 'feat(ui): stop reloading sidebar when moving between machine' (#5025) from ui/stop-sidebar-pane-re-opening into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5025
2025-08-29 11:27:03 +00:00
Brian McGee
d4ac3b83ee feat(ui): stop reloading sidebar when moving between machine 2025-08-29 12:06:28 +01:00
hsjobeki
00bf55be5a Merge pull request 'ui/implement-add-machine-workflow' (#5021) from ui/implement-add-machine-workflow into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5021
2025-08-29 08:42:31 +00:00
Johannes Kirschbauer
851d6aaa89 ui/machines: hook up create machine with scene workflow 2025-08-29 10:39:05 +02:00
Johannes Kirschbauer
f007279bee ui: format and debug messages 2025-08-29 10:38:39 +02:00
Brian McGee
5a3381d9ff ui/machines: add machine workflow 2025-08-29 10:34:03 +02:00
clan-bot
83e51db2e7 Merge pull request 'Update nixpkgs-dev in devFlake' (#5022) from update-devFlake-nixpkgs-dev into main 2025-08-29 00:11:06 +00:00
clan-bot
4e4af8a52f Update nixpkgs-dev in devFlake 2025-08-29 00:01:29 +00:00
Brian McGee
54a8ec717e chore(ui): rename install workflow to InstallMachine 2025-08-28 22:44:27 +02:00
hsjobeki
d3e5e6edf1 Merge pull request 'ui/service: rewire to allow external selection' (#5020) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5020
2025-08-28 20:43:07 +00:00
Johannes Kirschbauer
a4277ad312 ui/service: rewire to allow external selection 2025-08-28 22:39:49 +02:00
Johannes Kirschbauer
8877f2d451 ui/scene: lift state signals to allow external access 2025-08-28 22:39:23 +02:00
Johannes Kirschbauer
9275b66bd9 ui/machine: remove unsued imports 2025-08-28 22:38:19 +02:00
Johannes Kirschbauer
6a964f37d5 ui/machineRepr: listen to highlight state 2025-08-28 22:38:19 +02:00
Johannes Kirschbauer
73f2a4f56f ui/hooks: add clickOutside hook 2025-08-28 22:37:34 +02:00
Johannes Kirschbauer
85fb0187ee ui/typography: add missing label xxs 2025-08-28 22:37:15 +02:00
Johannes Kirschbauer
db9812a08b ui/sidebar: remove unused imports 2025-08-28 22:37:05 +02:00
Johannes Kirschbauer
ca69530591 ui/search: fix divider and text styles 2025-08-28 22:36:50 +02:00
Johannes Kirschbauer
fc5b0e4113 ui/multisearch: make controlled for now 2025-08-28 22:36:21 +02:00
Johannes Kirschbauer
278af5f0f4 ui/queries: add instances query 2025-08-28 22:35:58 +02:00
Johannes Kirschbauer
e7baf25ff7 ui/toast: add toast temporarily 2025-08-28 22:35:33 +02:00
Johannes Kirschbauer
fada75144c ui/highlight: add global highlighter store 2025-08-28 22:35:15 +02:00
brianmcgee
803ef5476f Merge pull request 'feat(ui): disable button when loading state is active' (#5018) from ui/disable-button-when-loading into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5018
2025-08-28 16:00:57 +00:00
brianmcgee
016bd263d0 Merge pull request 'ui/refine-sidebar-sidepane' (#5017) from ui/refine-sidebar-sidepane into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5017
2025-08-28 15:44:27 +00:00
Brian McGee
f9143f8a5d feat(ui): disable button when loading state is active 2025-08-28 16:43:23 +01:00
Brian McGee
92eb27fcb1 feat(ui): reduce size of sidebar when selecting a machine 2025-08-28 16:40:47 +01:00
Brian McGee
0cc9b91ae8 fix(ui): quirks with sidebar sizing 2025-08-28 15:56:37 +01:00
hsjobeki
2ed3608e34 Merge pull request 'ui/clan: wire up service create' (#5016) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5016
2025-08-28 12:17:03 +00:00
Johannes Kirschbauer
a92a1a7dd1 ui/clan: wire up service create 2025-08-28 14:13:39 +02:00
Johannes Kirschbauer
9a903be6d4 ui/services: add submit handler to create the instance 2025-08-28 14:13:26 +02:00
Johannes Kirschbauer
adea270b27 ui/tagSelect: remove left over console.log 2025-08-28 14:13:05 +02:00
clan-bot
765eb142a5 Merge pull request 'Update nixpkgs-dev in devFlake' (#5014) from update-devFlake-nixpkgs-dev into main 2025-08-28 10:08:09 +00:00
clan-bot
faa1405d6b Update nixpkgs-dev in devFlake 2025-08-28 10:01:48 +00:00
hsjobeki
0c93aab818 Merge pull request 'ui/services: workflow init' (#5013) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5013
2025-08-28 08:19:01 +00:00
Johannes Kirschbauer
56923ae2c3 ui/services: workflow init 2025-08-28 10:11:15 +02:00
Johannes Kirschbauer
e2f64e1d40 ui/stepper: forward props in backButton 2025-08-28 10:10:52 +02:00
Johannes Kirschbauer
c574b84278 ui/tagSelect: simplify by requiring objects with value key 2025-08-28 10:10:25 +02:00
Johannes Kirschbauer
640f15d55e ui/search: remove portal, fix styling 2025-08-28 10:09:41 +02:00
Johannes Kirschbauer
789d326273 ui/queries: add list tags query 2025-08-28 10:09:03 +02:00
clan-bot
1763d85d91 Merge pull request 'Update nixpkgs-dev in devFlake' (#5011) from update-devFlake-nixpkgs-dev into main 2025-08-27 20:10:01 +00:00
clan-bot
082fa05083 Update nixpkgs-dev in devFlake 2025-08-27 20:01:45 +00:00
brianmcgee
9ed7190606 Merge pull request 'fix(ui): icon alignment in alerts' (#5008) from ui/fix-icon-misalignment into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5008
2025-08-27 16:33:29 +00:00
Brian McGee
6c22539dd4 fix(ui): icon alignment in alerts
Closes #5004
2025-08-27 17:30:08 +01:00
Luis Hebendanz
e6819ede61 Merge pull request 'docs/update: refactor machine update guide' (#4997) from docs-10 into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4997
2025-08-27 15:40:34 +00:00
Qubasa
186a760529 docs: fixup links to networking guide, improve introduction. 2025-08-27 17:37:15 +02:00
clan-bot
a84aee7b0c Merge pull request 'Update nixos-facter-modules' (#5007) from update-nixos-facter-modules into main 2025-08-27 15:10:12 +00:00
clan-bot
cab2fa44ba Update nixos-facter-modules 2025-08-27 15:00:55 +00:00
Mic92
5962149e55 Merge pull request 'remove diskId from existing templates' (#5006) from drop-diskid into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/5006
2025-08-27 13:31:23 +00:00
Jörg Thalheim
00f9d08a4b remove diskId from existing templates
we don't have a replacement yet, but at least this will work.
2025-08-27 15:24:59 +02:00
clan-bot
3d0c843308 Merge pull request 'Update nixpkgs-dev in devFlake' (#5003) from update-devFlake-nixpkgs-dev into main 2025-08-27 10:08:09 +00:00
clan-bot
847138472b Update nixpkgs-dev in devFlake 2025-08-27 10:01:50 +00:00
Johannes Kirschbauer
c7786a59fd docs/update: refactor machine update guide
Restructured page: core workflow first, advanced usage after.

Improved grammar, phrasing, and capitalization (Clan CLI, apostrophes).

Added warnings/notes for buildHost and CPU architecture.

Polished code snippets and CLI examples for clarity.
2025-08-27 10:26:53 +02:00
hsjobeki
3b2d357f10 Merge pull request 'api/modules: unify duplicate endpoints for {modules, instances}' (#4994) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4994
2025-08-27 07:13:46 +00:00
DavHau
a83dbf604c Merge pull request 'vars: always generate dependents' (#4996) from vars into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4996
2025-08-27 05:59:13 +00:00
DavHau
f77456a123 vars: simplify graph implementation, remove obsolete closure functions
- full_closure is obsolete since it is the same as calling requested_closure with the full list of generators.
- minimal_closure is obsolete as well. Since the recent addition of dependents to the closure via 3d2127ce1e it is essentially the same as the all_missing_closure
2025-08-27 12:50:59 +07:00
DavHau
6e4c3a638d vars: move graph tests to separate file 2025-08-27 11:47:46 +07:00
DavHau
3d2127ce1e vars: always generate dependents
Even for the minimal closure case (when a specific generator was picked), we should still force regeneration of all dependents, as otherwise we risk keeping outdated dependents from previous generations
2025-08-27 11:47:46 +07:00
DavHau
a4a5916fa2 vars: generate over multiple machines at once 2025-08-27 11:45:45 +07:00
Johannes Kirschbauer
f6727055cd api/modules: unify duplicate endpoints for {modules, instances} 2025-08-26 21:44:58 +02:00
hsjobeki
0517d87caa Merge pull request 'api/instances: add list service instances' (#4993) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4993
2025-08-26 16:52:53 +00:00
Johannes Kirschbauer
89e587592c api/instances: add list service instances 2025-08-26 18:47:08 +02:00
hsjobeki
439495d738 Merge pull request 'ui/search: fix height of overflow' (#4992) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4992
2025-08-26 16:46:29 +00:00
Johannes Kirschbauer
0b2fd681be ui/search: fix height of overflow 2025-08-26 18:43:09 +02:00
hsjobeki
41de615331 Merge pull request 'ui/services: add more features to components' (#4988) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4988
2025-08-26 16:40:51 +00:00
Johannes Kirschbauer
b7639b1d81 ui/services: fix some background colors 2025-08-26 18:35:43 +02:00
Johannes Kirschbauer
602879c9e4 ui/services: workflow select service 2025-08-26 18:35:43 +02:00
Johannes Kirschbauer
53e16242b9 ui/search: add loading state 2025-08-26 18:35:43 +02:00
Johannes Kirschbauer
24c5146763 ui/search: fix height calculate to avoid overlaying components 2025-08-26 18:35:43 +02:00
Johannes Kirschbauer
dca7aa0487 ui/modules: hook up list modules query 2025-08-26 18:35:43 +02:00
Johannes Kirschbauer
647bc4e4df api/list_modules: return a simpler list of modules 2025-08-26 18:35:43 +02:00
brianmcgee
1c80223fe3 Merge pull request 'feat(ui): remove light typography weight' (#4991) from misc/fixes into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4991
2025-08-26 16:18:21 +00:00
Brian McGee
7ac9b00398 feat(ui): remove light typography weight 2025-08-26 16:13:53 +01:00
brianmcgee
d37c9e3b04 Merge pull request 'feat(ui): refine remove clan button copy' (#4986) from ui/refine-remove-clan into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4986
2025-08-26 14:44:12 +00:00
Brian McGee
0fe9d0e157 feat(ui): refine remove clan button copy 2025-08-26 15:40:24 +01:00
Mic92
5479c767c1 Merge pull request 'try{300,301,400}: fix' (#4984) from checkout-update into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4984
2025-08-26 14:31:57 +00:00
brianmcgee
edc389ba4b Merge pull request 'feat(ui): change button font to normal instead of monospace' (#4985) from ui/change-button-font into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4985
2025-08-26 14:23:10 +00:00
Jörg Thalheim
4cb17d42e1 PLR2004: fix 2025-08-26 16:21:15 +02:00
Jörg Thalheim
f26499edb8 pyproject.toml: add descriptions to each rule 2025-08-26 16:21:15 +02:00
Jörg Thalheim
2857cb7ed8 remove various ignores that had no actual issue 2025-08-26 16:21:15 +02:00
Jörg Thalheim
3168fecd52 PT100: fix 2025-08-26 16:21:15 +02:00
Jörg Thalheim
24c20ff243 TRY400: fix 2025-08-26 16:21:15 +02:00
Jörg Thalheim
8ba8fda54b RUF100: fix 2025-08-26 16:21:15 +02:00
Brian McGee
0992a47b00 feat(ui): change button font to normal instead of monospace 2025-08-26 15:13:30 +01:00
Jörg Thalheim
d5b09f18ed RET504: fix 2025-08-26 15:55:23 +02:00
Jörg Thalheim
fb2fe36c87 SIM112: fix 2025-08-26 15:55:23 +02:00
hsjobeki
3db51887b1 Merge pull request 'ui/select machines/tags: add custom combobox' (#4983) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4983
2025-08-26 13:51:50 +00:00
Johannes Kirschbauer
24f3bcca57 ui/select: rename to tagSelect 2025-08-26 15:48:28 +02:00
Johannes Kirschbauer
85006c8103 ui/select machines/tags: add custom combobox
This just renders machines and tags as chips
onclick will open another combobox
2025-08-26 15:47:22 +02:00
Jörg Thalheim
db5571d623 SIM108: fix 2025-08-26 15:23:36 +02:00
Jörg Thalheim
d4bdaec586 SIM102: fix 2025-08-26 15:22:25 +02:00
Jörg Thalheim
cb9c8e5b5a try{300,301,400}: fix 2025-08-26 15:17:16 +02:00
Mic92
0a1802c341 Merge pull request 'github/repo-sync: v4 -> v5' (#4982) from checkout-update into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4982
2025-08-26 12:59:10 +00:00
Mic92
dfae1a4429 Merge pull request 'PLC0415: fix' (#4981) from ruff into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4981
2025-08-26 12:58:37 +00:00
Jörg Thalheim
c1dc73a21b github/repo-sync: v4 -> v5 2025-08-26 14:54:41 +02:00
Jörg Thalheim
8145740cc1 api: lazly load Api options 2025-08-26 14:48:20 +02:00
Jörg Thalheim
b2a54f5b0d PLC0415: fix 2025-08-26 14:46:42 +02:00
hsjobeki
9c9adc6e16 Merge pull request 'ui/tags: refactor generic children and icon' (#4960) from search into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4960
2025-08-26 12:14:41 +00:00
Johannes Kirschbauer
f7cde8eb0f ui/tags: refactor generic children and icon 2025-08-26 14:11:14 +02:00
DavHau
501d020562 vars: retrieve generators for multiple machines
This is necessary ground work for fixing regeneration behavior spanning over multiple machines
2025-08-26 18:55:54 +07:00
Mic92
a9bafd71e1 Merge pull request 'templates/list: we can compute the lenght of an dictionary directly' (#4980) from ruff into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4980
2025-08-26 11:45:44 +00:00
Mic92
166e4b8081 Merge pull request 'add feature: ask for vars input confirmation, and fail after 3 attempts. fixes accidental misinputs when typing passwords!' (#4920) from adeci-2xconfirm into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4920
2025-08-26 11:41:16 +00:00
Jörg Thalheim
c3eb40f17a templates/list: we can compute the lenght of an dictionary directly 2025-08-26 13:39:49 +02:00
Jörg Thalheim
7330285150 prompt/multiline: strip final newline just like hidden prompt 2025-08-26 13:35:12 +02:00
Luis Hebendanz
8cf8573c61 Merge pull request 'clan-app: Maybe fix the logging errror ValueError: I/O operation on closed file.' (#4974) from Qubasa/clan-core:fix_logging into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4974
2025-08-26 11:32:48 +00:00
Jörg Thalheim
5bfa0d7a9d prompt: catch EOF errors 2025-08-26 13:26:49 +02:00
adeci
8ea2dd9b72 add feature: ask for vars input confirmation, and fail after 3 attempts. fixes accidental misinputs when typing passwords! 2025-08-26 13:26:49 +02:00
Mic92
6efcade56a Merge pull request 'Enable "all" ruff lint fixes' (#4978) from ruff into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4978
2025-08-26 11:26:47 +00:00
Jörg Thalheim
6d2372be56 machines/update: fix incorrecct nixos-rebuild command 2025-08-26 13:11:43 +02:00
brianmcgee
626af4691b Merge pull request 'feat(ui): pin stepper buttons to the bottom' (#4979) from ui/pinned-stepper-buttons into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4979
2025-08-26 11:07:30 +00:00
Jörg Thalheim
63697ac4b1 various fixes 2025-08-26 13:07:22 +02:00
Brian McGee
0ebb1f0c66 feat(ui): pin stepper buttons to the bottom
Closes #4968
2025-08-26 12:02:28 +01:00
Jörg Thalheim
1dda60847e PLW0602: fix 2025-08-26 12:57:31 +02:00
Jörg Thalheim
a7bce4cb19 pyproject: enable all lints 2025-08-26 12:57:31 +02:00
Mic92
a5474bc25f Merge pull request 'ruff-7-misc' (#4939) from ruff-7-misc into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4939
2025-08-26 10:43:12 +00:00
Jörg Thalheim
f634b8f1fb merge-after-ci: move away from writePython3Bin
this is one is doing checks we don't want because we already have ruff.
2025-08-26 12:39:50 +02:00
brianmcgee
0ad40a0233 Merge pull request 'ui/refine-select-folder-onboarding' (#4977) from ui/refine-select-folder-onboarding into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4977
2025-08-26 10:30:23 +00:00
Luis Hebendanz
78abc36cd3 Merge pull request 'clan-cli: clan machines update-hardware-config now uses kexec, and supports non NixOS targets' (#4948) from Qubasa/clan-core:fix_update_hardware_config into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4948
2025-08-26 10:16:59 +00:00
Brian McGee
f5158b068f feat(ui): reduce size of sidebar pane
Make it clearer the distinction between parent and child panes.
2025-08-26 11:16:03 +01:00
Jörg Thalheim
e6066a6cb1 spawn_tor: catch OSError and wrap as ClanError 2025-08-26 12:12:29 +02:00
clan-bot
fc8b66effa Merge pull request 'Update nixpkgs-dev in devFlake' (#4972) from update-devFlake-nixpkgs-dev into main 2025-08-26 10:09:59 +00:00
Qubasa
16b92963fd clan-app: Maybe fix the logging errror ValueError: I/O operation on closed file. 2025-08-26 12:08:45 +02:00
Brian McGee
2ff3d871ac feat(ui): allow placing machines directly next to each other 2025-08-26 11:02:58 +01:00
clan-bot
108936ef07 Update nixpkgs-dev in devFlake 2025-08-26 10:01:48 +00:00
Jörg Thalheim
c45d4cfec9 D413/D212: fix 2025-08-26 12:01:47 +02:00
Jörg Thalheim
64217e1281 G001: fix 2025-08-26 12:01:47 +02:00
Jörg Thalheim
d1421bb534 EXE002: fix 2025-08-26 12:01:47 +02:00
Jörg Thalheim
ac20514a8e EXE001: fix 2025-08-26 12:01:47 +02:00
Jörg Thalheim
79c4e73a15 test_http_api: remove unused logging middleware 2025-08-26 12:01:47 +02:00
Jörg Thalheim
61a647b436 PLR1704: fix 2025-08-26 12:01:47 +02:00
Jörg Thalheim
c9a709783a BLE001: fix 2025-08-26 12:01:47 +02:00
Kenji Berthold
c55b369899 Merge pull request 'docs: Add edit button to documentation pages' (#4969) from kenji/ke-add-repo-url into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4969
2025-08-26 09:59:14 +00:00
Brian McGee
084b8bacd3 fix(ui): typos in install machine workflow 2025-08-26 10:52:52 +01:00
a-kenji
47ad7d8a95 docs: Add edit button to documentation pages
Closes: #4966
2025-08-26 11:52:08 +02:00
a-kenji
3798808013 docs: Fix edit uri 2025-08-26 11:51:53 +02:00
Brian McGee
43a39267f3 feat(ui): make the intention of the select folder button clearer in Onboarding 2025-08-26 10:44:42 +01:00
Mic92
db94ea2d2e Merge pull request 'Misc ruff fixes' (#4965) from ruff-foo into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4965
2025-08-26 09:44:06 +00:00
hsjobeki
f0533f9bba Merge pull request 'ui/scene: dont snap to occupied positions' (#4967) from fixes-ui into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4967
2025-08-26 09:43:59 +00:00
Johannes Kirschbauer
360048fd04 ui/scene: dont snap to occupied positions 2025-08-26 11:40:38 +02:00
Jörg Thalheim
8f8426de52 PGH003: fix 2025-08-26 11:36:38 +02:00
Qubasa
4bce390e64 clan-cli: clan machiens update-hardware-config now uses kexec, and supports non NixOS targets 2025-08-26 11:35:44 +02:00
DavHau
2b7837e2b6 Merge pull request 'GUI: add port option for ssh remote' (#4961) from dave into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4961
2025-08-26 09:33:26 +00:00
Jörg Thalheim
cbf9678534 flake/prefetch: Fix unconditional truthy string causes always-True 2025-08-26 11:07:57 +02:00
Jörg Thalheim
b38b10c9a6 automatic ruff fixes 2025-08-26 11:07:57 +02:00
Jörg Thalheim
31cbb7dc00 PLC0415: fix 2025-08-26 11:07:57 +02:00
hsjobeki
0fa4377793 Merge pull request 'ui/scene: add reload button' (#4962) from fixes-ui into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4962
2025-08-26 09:01:45 +00:00
Johannes Kirschbauer
7b0d10e8c2 ui/queries: remove annoying refetch interval, invalidate on change instead 2025-08-26 10:58:39 +02:00
Johannes Kirschbauer
bb41adab4b ui/scene: fix syncing remote and local state 2025-08-26 10:40:09 +02:00
DavHau
648aa7dc59 Merge pull request 'API: fix serialization of union types' (#4963) from serde into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4963
2025-08-26 08:26:13 +00:00
DavHau
3073969c92 vars/tests: add comments 2025-08-26 15:17:41 +07:00
DavHau
2f1dc3a33d API: fix serialization of union types
Due to this bug in serde.py, the run_generators API id not work for the frontend
2025-08-26 15:16:55 +07:00
Johannes Kirschbauer
b707dcea2d ui/scene: add reload button 2025-08-26 10:08:05 +02:00
Johannes Kirschbauer
4f0c8025b2 ui/queries: remove annoying refetch interval, invalidate on change instead 2025-08-26 10:07:41 +02:00
pinpox
b91bee537a Merge pull request 'Enable state-version in defaults' (#4711) from default-state-version into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4711
2025-08-26 07:49:46 +00:00
pinpox
7207a3e8cd Cleanup state-version test 2025-08-26 09:44:01 +02:00
pinpox
ac675a5af0 Merge pull request 'Add coredns module' (#4837) from coredns into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4837
2025-08-26 07:39:57 +00:00
pinpox
64caebde62 service/state-version: drop 2025-08-26 09:32:36 +02:00
pinpox
4934884e0c Enable state-version in defaults 2025-08-26 09:32:36 +02:00
pinpox
22cd9baee2 Merge pull request 'Improve inventory docs' (#4933) from inventory-docs into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4933
2025-08-26 07:32:23 +00:00
pinpox
84232b5355 Improve inventory docs 2025-08-26 09:29:25 +02:00
DavHau
5bc7c255c1 GUI: add port option for ssh remote
I need this for testing with a local VM, which ahs a different port than 22.

This also disables host key checking, as there is currently no workflow int he GUI which can handle a mismatch, which mismatches are common.
2025-08-26 13:28:27 +07:00
clan-bot
d11d83f699 Merge pull request 'Update clan-core-for-checks in devFlake' (#4959) from update-devFlake-clan-core-for-checks into main 2025-08-26 05:08:08 +00:00
clan-bot
2ef1b2a8fa Update clan-core-for-checks in devFlake 2025-08-26 05:01:46 +00:00
clan-bot
f7414d7e6e Merge pull request 'Update clan-core-for-checks in devFlake' (#4957) from update-devFlake-clan-core-for-checks into main 2025-08-26 00:08:04 +00:00
clan-bot
ab384150b2 Merge pull request 'Update nixpkgs-dev in devFlake' (#4958) from update-devFlake-nixpkgs-dev into main 2025-08-26 00:07:37 +00:00
clan-bot
0b6939ffee Update nixpkgs-dev in devFlake 2025-08-26 00:01:48 +00:00
clan-bot
bc6a1a9d17 Update clan-core-for-checks in devFlake 2025-08-26 00:01:28 +00:00
clan-bot
7055461cf0 Merge pull request 'Update clan-core-for-checks in devFlake' (#4956) from update-devFlake-clan-core-for-checks into main 2025-08-25 20:10:56 +00:00
clan-bot
a9564df6a9 Update clan-core-for-checks in devFlake 2025-08-25 20:01:26 +00:00
brianmcgee
e2dfc74d02 Merge pull request 'feat(ui): fix layout and size of install progress and done screens' (#4954) from ui/fix-install-modal-sizes into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4954
2025-08-25 16:55:48 +00:00
Brian McGee
326cb60aea feat(ui): fix layout and size of install progress and done screens 2025-08-25 17:51:20 +01:00
brianmcgee
68b264970a Merge pull request 'feat(ui): set loading status on update hardware report button in install workflow' (#4951) from ui/update-hardware-report-loading-state into main
Reviewed-on: https://git.clan.lol/clan/clan-core/pulls/4951
2025-08-25 16:46:16 +00:00
Brian McGee
1fa4ef82e9 feat(ui): set loading status on update hardware report button in install workflow 2025-08-25 17:32:15 +01:00
pinpox
ec70de406b Add coredns module 2025-08-21 10:29:54 +02:00
229 changed files with 5248 additions and 2174 deletions

View File

@@ -10,7 +10,7 @@ jobs:
if: github.repository_owner == 'clan-lol'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v5
with:
persist-credentials: false
- uses: actions/create-github-app-token@v2

View File

@@ -302,7 +302,8 @@
"test-install-machine-without-system",
"-i", ssh_conn.ssh_key,
"--option", "store", os.environ['CLAN_TEST_STORE'],
f"nonrootuser@localhost:{ssh_conn.host_port}"
"--target-host", f"nonrootuser@localhost:{ssh_conn.host_port}",
"--yes"
]
result = subprocess.run(clan_cmd, capture_output=True, cwd=flake_dir)
@@ -326,7 +327,9 @@
"test-install-machine-without-system",
"-i", ssh_conn.ssh_key,
"--option", "store", os.environ['CLAN_TEST_STORE'],
f"nonrootuser@localhost:{ssh_conn.host_port}"
"--target-host",
f"nonrootuser@localhost:{ssh_conn.host_port}",
"--yes"
]
result = subprocess.run(clan_cmd, capture_output=True, cwd=flake_dir)

View File

@@ -0,0 +1,68 @@
This module enables hosting clan-internal services easily, which can be resolved
inside your VPN. This allows defining a custom top-level domain (e.g. `.clan`)
and exposing endpoints from a machine to others, which will be
accessible under `http://<service>.clan` in your browser.
The service consists of two roles:
- A `server` role: This is the DNS-server that will be queried when trying to
resolve clan-internal services. It defines the top-level domain.
- A `default` role: This does two things. First, it sets up the nameservers so
thatclan-internal queries are resolved via the `server` machine, while
external queries are resolved as normal via DHCP. Second, it allows exposing
services (see example below).
## Example Usage
Here the machine `dnsserver` is designated as internal DNS-server for the TLD
`.foo`. `server01` will host an application that shall be reachable at
`http://one.foo` and `server02` is going to be reachable at `http://two.foo`.
`client` is any other machine that is part of the clan but does not host any
services.
When `client` tries to resolve `http://one.foo`, the DNS query will be
routed to `dnsserver`, which will answer with `192.168.1.3`. If it tries to
resolve some external domain (e.g. `https://clan.lol`), the query will not be
routed to `dnsserver` but resolved as before, via the nameservers advertised by
DHCP.
```nix
inventory = {
machines = {
dnsserver = { }; # 192.168.1.2
server01 = { }; # 192.168.1.3
server02 = { }; # 192.168.1.4
client = { }; # 192.168.1.5
};
instances = {
coredns = {
module.name = "@clan/coredns";
module.input = "self";
# Add the default role to all machines, including `client`
roles.default.tags.all = { };
# DNS server
roles.server.machines."dnsserver".settings = {
ip = "192.168.1.2";
tld = "foo";
};
# First service
roles.default.machines."server01".settings = {
ip = "192.168.1.3";
services = [ "one" ];
};
# Second service
roles.default.machines."server02".settings = {
ip = "192.168.1.4";
services = [ "two" ];
};
};
};
};
```

View File

@@ -0,0 +1,157 @@
{ ... }:
{
_class = "clan.service";
manifest.name = "coredns";
manifest.description = "Clan-internal DNS and service exposure";
manifest.categories = [ "Network" ];
manifest.readme = builtins.readFile ./README.md;
roles.server = {
interface =
{ lib, ... }:
{
options.tld = lib.mkOption {
type = lib.types.str;
default = "clan";
description = ''
Top-level domain for this instance. All services below this will be
resolved internally.
'';
};
options.ip = lib.mkOption {
type = lib.types.str;
# TODO: Set a default
description = "IP for the DNS to listen on";
};
};
perInstance =
{
roles,
settings,
...
}:
{
nixosModule =
{
lib,
pkgs,
...
}:
{
networking.firewall.allowedTCPPorts = [ 53 ];
networking.firewall.allowedUDPPorts = [ 53 ];
services.coredns =
let
# Get all service entries for one host
hostServiceEntries =
host:
lib.strings.concatStringsSep "\n" (
map (
service: "${service} IN A ${roles.default.machines.${host}.settings.ip} ; ${host}"
) roles.default.machines.${host}.settings.services
);
zonefile = pkgs.writeTextFile {
name = "db.${settings.tld}";
text = ''
$TTL 3600
@ IN SOA ns.${settings.tld}. admin.${settings.tld}. 1 7200 3600 1209600 3600
IN NS ns.${settings.tld}.
ns IN A ${settings.ip} ; DNS server
''
+ (lib.strings.concatStringsSep "\n" (
map (host: hostServiceEntries host) (lib.attrNames roles.default.machines)
));
};
in
{
enable = true;
config = ''
. {
forward . 1.1.1.1
cache 30
}
${settings.tld} {
file ${zonefile}
}
'';
};
};
};
};
roles.default = {
interface =
{ lib, ... }:
{
options.services = lib.mkOption {
type = lib.types.listOf lib.types.str;
default = [ ];
description = ''
Service endpoints this host exposes (without TLD). Each entry will
be resolved to <entry>.<tld> using the configured top-level domain.
'';
};
options.ip = lib.mkOption {
type = lib.types.str;
# TODO: Set a default
description = "IP on which the services will listen";
};
};
perInstance =
{ roles, ... }:
{
nixosModule =
{ lib, ... }:
{
networking.nameservers = map (m: "127.0.0.1:5353#${roles.server.machines.${m}.settings.tld}") (
lib.attrNames roles.server.machines
);
services.resolved.domains = map (m: "~${roles.server.machines.${m}.settings.tld}") (
lib.attrNames roles.server.machines
);
services.unbound = {
enable = true;
settings = {
server = {
port = 5353;
verbosity = 2;
interface = [ "127.0.0.1" ];
access-control = [ "127.0.0.0/8 allow" ];
do-not-query-localhost = "no";
domain-insecure = map (m: "${roles.server.machines.${m}.settings.tld}.") (
lib.attrNames roles.server.machines
);
};
# Default: forward everything else to DHCP-provided resolvers
forward-zone = [
{
name = ".";
forward-addr = "127.0.0.53@53"; # Forward to systemd-resolved
}
];
stub-zone = map (m: {
name = "${roles.server.machines.${m}.settings.tld}.";
stub-addr = "${roles.server.machines.${m}.settings.ip}";
}) (lib.attrNames roles.server.machines);
};
};
};
};
};
}

View File

@@ -3,14 +3,16 @@ let
module = lib.modules.importApply ./default.nix { };
in
{
clan.modules.state-version = module;
clan.modules = {
coredns = module;
};
perSystem =
{ ... }:
{
clan.nixosTests.state-version = {
clan.nixosTests.coredns = {
imports = [ ./tests/vm/default.nix ];
clan.modules."@clan/state-version" = module;
clan.modules."@clan/coredns" = module;
};
};
}

View File

@@ -0,0 +1,113 @@
{
...
}:
{
name = "coredns";
clan = {
directory = ./.;
test.useContainers = true;
inventory = {
machines = {
dns = { }; # 192.168.1.2
server01 = { }; # 192.168.1.3
server02 = { }; # 192.168.1.4
client = { }; # 192.168.1.1
};
instances = {
coredns = {
module.name = "@clan/coredns";
module.input = "self";
roles.default.tags.all = { };
# First service
roles.default.machines."server01".settings = {
ip = "192.168.1.3";
services = [ "one" ];
};
# Second service
roles.default.machines."server02".settings = {
ip = "192.168.1.4";
services = [ "two" ];
};
# DNS server
roles.server.machines."dns".settings = {
ip = "192.168.1.2";
tld = "foo";
};
};
};
};
};
nodes = {
dns =
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.net-tools ];
};
client =
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.net-tools ];
};
server01 = {
services.nginx = {
enable = true;
virtualHosts."one.foo" = {
locations."/" = {
return = "200 'test server response one'";
extraConfig = "add_header Content-Type text/plain;";
};
};
};
};
server02 = {
services.nginx = {
enable = true;
virtualHosts."two.foo" = {
locations."/" = {
return = "200 'test server response two'";
extraConfig = "add_header Content-Type text/plain;";
};
};
};
};
};
testScript = ''
import json
start_all()
machines = [server01, server02, dns, client]
for m in machines:
m.systemctl("start network-online.target")
for m in machines:
m.wait_for_unit("network-online.target")
# import time
# time.sleep(2333333)
# This should work, but is borken in tests i think? Instead we dig directly
# client.succeed("curl -k -v http://one.foo")
# client.succeed("curl -k -v http://two.foo")
answer = client.succeed("dig @192.168.1.2 one.foo")
assert "192.168.1.3" in answer, "IP not found"
answer = client.succeed("dig @192.168.1.2 two.foo")
assert "192.168.1.4" in answer, "IP not found"
'';
}

View File

@@ -1,37 +0,0 @@
This service generates the `system.stateVersion` of the nixos installation
automatically.
Possible values:
[system.stateVersion](https://search.nixos.org/options?channel=unstable&show=system.stateVersion&from=0&size=50&sort=relevance&type=packages&query=stateVersion)
## Usage
The following configuration will set `stateVersion` for all machines:
```
inventory.instances = {
state-version = {
module = {
name = "state-version";
input = "clan";
};
roles.default.tags.all = { };
};
```
## Migration
If you are already setting `system.stateVersion`, either let the automatic
generation happen, or trigger the generation manually for the machine. The
service will take the specified version, if one is already supplied through the
config.
To manually generate the version for a specified machine run:
```
clan vars generate [MACHINE]
```
If the setting was already set, you can then remove `system.stateVersion` from
your machine configuration. For new machines, just import the service as shown
above.

View File

@@ -1,50 +0,0 @@
{ ... }:
{
_class = "clan.service";
manifest.name = "clan-core/state-version";
manifest.description = "Automatically generate the state version of the nixos installation.";
manifest.categories = [ "System" ];
manifest.readme = builtins.readFile ./README.md;
roles.default = {
perInstance =
{ ... }:
{
nixosModule =
{
config,
lib,
...
}:
let
var = config.clan.core.vars.generators.state-version.files.version or { };
in
{
warnings = [
''
The clan.state-version service is deprecated and will be
removed on 2025-07-15 in favor of a nix option.
Please migrate your configuration to use `clan.core.settings.state-version.enable = true` instead.
''
];
system.stateVersion = lib.mkDefault (lib.removeSuffix "\n" var.value);
clan.core.vars.generators.state-version = {
files.version = {
secret = false;
value = lib.mkDefault config.system.nixos.release;
};
runtimeInputs = [ ];
script = ''
echo -n ${config.system.stateVersion} > "$out"/version
'';
};
};
};
};
}

View File

@@ -1,22 +0,0 @@
{ lib, ... }:
{
name = "service-state-version";
clan = {
directory = ./.;
inventory = {
machines.server = { };
instances.default = {
module.name = "@clan/state-version";
module.input = "self";
roles.default.machines."server" = { };
};
};
};
nodes.server = { };
testScript = lib.mkDefault ''
start_all()
'';
}

View File

@@ -12,6 +12,11 @@ import ipaddress
import sys
from pathlib import Path
# Constants for argument count validation
MIN_ARGS_BASE = 4
MIN_ARGS_CONTROLLER = 5
MIN_ARGS_PEER = 5
def hash_string(s: str) -> str:
"""Generate SHA256 hash of string."""
@@ -39,8 +44,7 @@ def generate_ula_prefix(instance_name: str) -> ipaddress.IPv6Network:
prefix = f"fd{prefix_bits:08x}"
prefix_formatted = f"{prefix[:4]}:{prefix[4:8]}::/40"
network = ipaddress.IPv6Network(prefix_formatted)
return network
return ipaddress.IPv6Network(prefix_formatted)
def generate_controller_subnet(
@@ -60,9 +64,7 @@ def generate_controller_subnet(
# The controller subnet is at base_prefix:controller_id::/56
base_int = int(base_network.network_address)
controller_subnet_int = base_int | (controller_id << (128 - 56))
controller_subnet = ipaddress.IPv6Network((controller_subnet_int, 56))
return controller_subnet
return ipaddress.IPv6Network((controller_subnet_int, 56))
def generate_peer_suffix(peer_name: str) -> str:
@@ -76,12 +78,11 @@ def generate_peer_suffix(peer_name: str) -> str:
suffix_bits = h[:16]
# Format as IPv6 suffix without leading colon
suffix = f"{suffix_bits[0:4]}:{suffix_bits[4:8]}:{suffix_bits[8:12]}:{suffix_bits[12:16]}"
return suffix
return f"{suffix_bits[0:4]}:{suffix_bits[4:8]}:{suffix_bits[8:12]}:{suffix_bits[12:16]}"
def main() -> None:
if len(sys.argv) < 4:
if len(sys.argv) < MIN_ARGS_BASE:
print(
"Usage: ipv6_allocator.py <output_dir> <instance_name> <controller|peer> <machine_name>",
)
@@ -95,7 +96,7 @@ def main() -> None:
base_network = generate_ula_prefix(instance_name)
if node_type == "controller":
if len(sys.argv) < 5:
if len(sys.argv) < MIN_ARGS_CONTROLLER:
print("Controller name required")
sys.exit(1)
@@ -111,7 +112,7 @@ def main() -> None:
(output_dir / "prefix").write_text(prefix_str)
elif node_type == "peer":
if len(sys.argv) < 5:
if len(sys.argv) < MIN_ARGS_PEER:
print("Peer name required")
sys.exit(1)

18
devFlake/flake.lock generated
View File

@@ -3,10 +3,10 @@
"clan-core-for-checks": {
"flake": false,
"locked": {
"lastModified": 1756133826,
"narHash": "sha256-In3u7UVSjPzX9u4Af9K/jVy4MMAZBzxByMe4GREpHBo=",
"lastModified": 1756166884,
"narHash": "sha256-skg4rwpbCjhpLlrv/Pndd43FoEgrJz98WARtGLhCSzo=",
"ref": "main",
"rev": "c4da43da0f583bd3cbcfd1f3acf74f9dc51b8fdd",
"rev": "f7414d7e6e58709af27b6fe16eb530278e81eaaf",
"shallow": true,
"type": "git",
"url": "https://git.clan.lol/clan/clan-core"
@@ -84,11 +84,11 @@
},
"nixpkgs-dev": {
"locked": {
"lastModified": 1756104823,
"narHash": "sha256-wRzHREXDOrbCjy+sqo4t3JoInbB2PuhXIUa8NWdh9tk=",
"lastModified": 1756662818,
"narHash": "sha256-Opggp4xiucQ5gBceZ6OT2vWAZOjQb3qULv39scGZ9Nw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "d7967bed5381e65208f4fb8d5502e3c36bb94759",
"rev": "2e6aeede9cb4896693434684bb0002ab2c0cfc09",
"type": "github"
},
"original": {
@@ -165,11 +165,11 @@
"nixpkgs": []
},
"locked": {
"lastModified": 1755934250,
"narHash": "sha256-CsDojnMgYsfshQw3t4zjRUkmMmUdZGthl16bXVWgRYU=",
"lastModified": 1756662192,
"narHash": "sha256-F1oFfV51AE259I85av+MAia221XwMHCOtZCMcZLK2Jk=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "74e1a52d5bd9430312f8d1b8b0354c92c17453e5",
"rev": "1aabc6c05ccbcbf4a635fb7a90400e44282f61c4",
"type": "github"
},
"original": {

View File

@@ -1,13 +1,11 @@
{
lib,
config,
...
}:
let
suffix = config.clan.core.vars.generators.disk-id.files.diskId.value;
mirrorBoot = idx: {
# suffix is to prevent disk name collisions
name = idx + suffix;
name = idx;
type = "disk";
device = "/dev/disk/by-id/${idx}";
content = {

View File

@@ -1,13 +1,11 @@
{
lib,
config,
...
}:
let
suffix = config.clan.core.vars.generators.disk-id.files.diskId.value;
mirrorBoot = idx: {
# suffix is to prevent disk name collisions
name = idx + suffix;
name = idx;
type = "disk";
device = "/dev/disk/by-id/${idx}";
content = {

View File

@@ -2,7 +2,7 @@ site_name: Clan Documentation
site_url: https://docs.clan.lol
repo_url: https://git.clan.lol/clan/clan-core/
repo_name: "_>"
edit_uri: _edit/main/docs/docs/
edit_uri: _edit/main/docs/site/
validation:
omitted_files: warn
@@ -94,6 +94,7 @@ nav:
- reference/clanServices/index.md
- reference/clanServices/admin.md
- reference/clanServices/borgbackup.md
- reference/clanServices/coredns.md
- reference/clanServices/data-mesher.md
- reference/clanServices/dyndns.md
- reference/clanServices/emergency-access.md
@@ -106,7 +107,6 @@ nav:
- reference/clanServices/monitoring.md
- reference/clanServices/packages.md
- reference/clanServices/sshd.md
- reference/clanServices/state-version.md
- reference/clanServices/syncthing.md
- reference/clanServices/trusted-nix-caches.md
- reference/clanServices/users.md
@@ -173,6 +173,7 @@ theme:
- content.code.annotate
- content.code.copy
- content.tabs.link
- content.action.edit
icon:
repo: fontawesome/brands/git
custom_dir: overrides

View File

@@ -48,7 +48,7 @@ CLAN_SERVICE_INTERFACE = os.environ.get("CLAN_SERVICE_INTERFACE")
CLAN_MODULES_VIA_SERVICE = os.environ.get("CLAN_MODULES_VIA_SERVICE")
OUT = os.environ.get("out")
OUT = os.environ.get("out") # noqa: SIM112
def sanitize(text: str) -> str:
@@ -551,8 +551,7 @@ def options_docs_from_tree(
return output
md = render_tree(root)
return md
return render_tree(root)
if __name__ == "__main__":

View File

@@ -1,16 +1,22 @@
# Using `clanServices`
# Using the Inventory
Clan's `clanServices` system is a composable way to define and deploy services across machines.
Clan's inventory system is a composable way to define and deploy services across
machines.
This guide shows how to **instantiate** a `clanService`, explains how service definitions are structured in your inventory, and how to pick or create services from modules exposed by flakes.
This guide shows how to **instantiate** a `clanService`, explains how service
definitions are structured in your inventory, and how to pick or create services
from modules exposed by flakes.
The term **Multi-host-modules** was introduced previously in the [nixus repository](https://github.com/infinisil/nixus) and represents a similar concept.
The term **Multi-host-modules** was introduced previously in the [nixus
repository](https://github.com/infinisil/nixus) and represents a similar
concept.
---
______________________________________________________________________
## Overview
Services are used in `inventory.instances`, and then they attach to *roles* and *machines* — meaning you decide which machines run which part of the service.
Services are used in `inventory.instances`, and assigned to *roles* and
*machines* -- meaning you decide which machines run which part of the service.
For example:
@@ -18,116 +24,135 @@ For example:
inventory.instances = {
borgbackup = {
roles.client.machines."laptop" = {};
roles.client.machines."server1" = {};
roles.client.machines."workstation" = {};
roles.server.machines."backup-box" = {};
};
}
```
This says: Run borgbackup as a *client* on my *laptop* and *server1*, and as a *server* on *backup-box*.”
This says: "Run borgbackup as a *client* on my *laptop* and *workstation*, and
as a *server* on *backup-box*". `client` and `server` are roles defined by the
`borgbackup` service.
## Module source specification
Each instance includes a reference to a **module specification** this is how Clan knows which service module to use and where it came from.
Usually one would just use `imports` but we needd to make the `module source` configurable via Python API.
By default it is not required to specify the `module`, in which case it defaults to the preprovided services of clan-core.
Each instance includes a reference to a **module specification** -- this is how
Clan knows which service module to use and where it came from.
---
## Override Example
It is not required to specify the `module.input` parameter, in which case it
defaults to the pre-provided services of clan-core. In a similar fashion, the
`module.name` parameter can also be omitted, it will default to the name of the
instance.
Example of instantiating a `borgbackup` service using `clan-core`:
```nix
inventory.instances = {
# Instance Name: Different name for this 'borgbackup' instance
borgbackup = {
# Since this is instances."borgbackup" the whole `module = { ... }` below is equivalent and optional.
module = {
name = "borgbackup"; # <-- Name of the module (optional)
input = "clan-core"; # <-- The flake input where the service is defined (optional)
};
borgbackup = { # <- Instance name
# This can be partially/fully specified,
# - If the instance name is not the name of the module
# - If the input is not clan-core
# module = {
# name = "borgbackup"; # Name of the module (optional)
# input = "clan-core"; # The flake input where the service is defined (optional)
# };
# Participation of the machines is defined via roles
# Right side needs to be an attribute set. Its purpose will become clear later
roles.client.machines."machine-a" = {};
roles.server.machines."backup-host" = {};
};
}
```
If you used `clan-core` as an input attribute for your flake:
## Module Settings
Each role might expose configurable options. See clan's [clanServices
reference](../reference/clanServices/index.md) for all available options.
Settings can be set in per-machine or per-role. The latter is applied to all
machines that are assigned to that role.
```nix
# ↓ module.input = "clan-core"
inputs.clan-core.url = "https://git.clan.lol/clan/clan-core/archive/main.tar.gz";
```
## Simplified Example
If only one instance is needed for a service and the service is a clan core service, the `module` definition can be omitted.
```nix
# Simplified way of specifying a single instance
inventory.instances = {
# instance name is `borgbackup` -> clan core module `borgbackup` will be loaded.
borgbackup = {
# Participation of the machines is defined via roles
# Right side needs to be an attribute set. Its purpose will become clear later
roles.client.machines."machine-a" = {};
roles.server.machines."backup-host" = {};
};
}
```
## Configuration Example
Each role might expose configurable options
See clan's [clanServices reference](../reference/clanServices/index.md) for available options
```nix
inventory.instances = {
borgbackup-example = {
module = {
name = "borgbackup";
input = "clan-core";
};
# Settings for 'machine-a'
roles.client.machines."machine-a" = {
# 'client' -Settings of 'machine-a'
settings = {
backupFolders = [
/home
/var
];
};
# ---------------------------
};
roles.server.machines."backup-host" = {};
# Settings for all machines of the role "server"
roles.server.settings = {
directory = "/var/lib/borgbackup";
};
};
}
```
## Tags
Multiple members can be defined using tags as follows
Tags can be used to assign multiple machines to a role at once. It can be thought of as a grouping mechanism.
For example using the `all` tag for services that you want to be configured on all
your machines is a common pattern.
The following example could be used to backup all your machines to a common
backup server
```nix
inventory.instances = {
borgbackup-example = {
module = {
name = "borgbackup";
input = "clan-core";
};
#
# The 'all' -tag targets all machines
roles.client.tags."all" = {};
# ---------------------------
borgbackup = {
# "All" machines are assigned to the borgbackup 'client' role
roles.client.tags = [ "all" ];
# But only one specific machine (backup-host) is assigned to the 'server' role
roles.server.machines."backup-host" = {};
};
}
```
## Sharing additional Nix configuration
Sometimes you need to add custom NixOS configuration alongside your clan
services. The `extraModules` option allows you to include additional NixOS
configuration that is applied for every machine assigned to that role.
There are multiple valid syntaxes for specifying modules:
```nix
inventory.instances = {
borgbackup = {
roles.client = {
# Direct module reference
extraModules = [ ../nixosModules/borgbackup.nix ];
# Or using self (needs to be json serializable)
# See next example, for a workaround.
extraModules = [ self.nixosModules.borgbackup ];
# Or inline module definition, (needs to be json compatible)
extraModules = [
{
# Your module configuration here
# ...
#
# If the module needs to contain non-serializable expressions:
imports = [ ./path/to/non-serializable.nix ];
}
];
};
};
}
```
## Picking a clanService
You can use services exposed by Clan's core module library, `clan-core`.
@@ -142,18 +167,19 @@ You can also author your own `clanService` modules.
You might expose your service module from your flake — this makes it easy for other people to also use your module in their clan.
---
______________________________________________________________________
## 💡 Tips for Working with clanServices
* You can add multiple inputs to your flake (`clan-core`, `your-org-modules`, etc.) to mix and match services.
* Each service instance is isolated by its key in `inventory.instances`, allowing you to deploy multiple versions or roles of the same service type.
* Roles can target different machines or be scoped dynamically.
- You can add multiple inputs to your flake (`clan-core`, `your-org-modules`, etc.) to mix and match services.
- Each service instance is isolated by its key in `inventory.instances`, allowing to deploy multiple versions or roles of the same service type.
- Roles can target different machines or be scoped dynamically.
---
______________________________________________________________________
## What's Next?
* [Author your own clanService →](../guides/services/community.md)
* [Migrate from clanModules →](../guides/migrations/migrate-inventory-services.md)
- [Author your own clanService →](../guides/services/community.md)
- [Migrate from clanModules →](../guides/migrations/migrate-inventory-services.md)
<!-- TODO: * [Understand the architecture →](../explanation/clan-architecture.md) -->

View File

@@ -1,12 +1,15 @@
# Update Your Machines
# Update Machines
Clan CLI enables you to remotely update your machines over SSH. This requires setting up a target address for each target machine.
The Clan command line interface enables you to update machines remotely over SSH.
In this guide we will teach you how to set a `targetHost` in Nix,
and how to define a remote builder for your machine closures.
### Setting `targetHost`
In your Nix files, set the `targetHost` to the reachable IP address of your new machine. This eliminates the need to specify `--target-host` with every command.
## Setting `targetHost`
Set the machines `targetHost` to the reachable IP address of the new machine.
This eliminates the need to specify `--target-host` in CLI commands.
```{.nix title="clan.nix" hl_lines="9"}
{
@@ -23,15 +26,42 @@ inventory.machines = {
# [...]
}
```
The use of `root@` in the target address implies SSH access as the `root` user.
Ensure that the root login is secured and only used when necessary.
## Multiple Target Hosts
### Setting a Build Host
You can now experiment with a new interface that allows you to define multiple `targetHost` addresses for different VPNs. Learn more and try it out in our [networking guide](../networking.md).
If the machine does not have enough resources to run the NixOS evaluation or build itself,
it is also possible to specify a build host instead.
During an update, the cli will ssh into the build host and run `nixos-rebuild` from there.
## Updating Machine Configurations
Execute the following command to update the specified machine:
```bash
clan machines update jon
```
All machines can be updated simultaneously by omitting the machine name:
```bash
clan machines update
```
---
## Advanced Usage
The following options are only needed for special cases, such as limited resources, mixed environments, or private flakes.
### Setting `buildHost`
If the machine does not have enough resources to run the NixOS **evaluation** or **build** itself,
it is also possible to specify a `buildHost` instead.
During an update, clan will ssh into the `buildHost` and run `nixos-rebuild` from there.
!!! Note
The `buildHost` option should be set directly within your machines Nix configuration, **not** under `inventory.machines`.
```{.nix hl_lines="5" .no-copy}
@@ -45,7 +75,11 @@ buildClan {
};
```
You can also override the build host via the command line:
### Overriding configuration with CLI flags
`buildHost` / `targetHost`, and other network settings can be temporarily overridden for a single command:
For the full list of flags refer to the [Clan CLI](../../reference/cli/index.md)
```bash
# Build on a remote host
@@ -56,23 +90,9 @@ clan machines update jon --build-host local
```
!!! Note
Make sure that the CPU architecture is the same for the buildHost as for the targetHost.
Example:
If you want to deploy to a macOS machine, your architecture is an ARM64-Darwin, that means you need a second macOS machine to build it.
Make sure the CPU architecture of the `buildHost` matches that of the `targetHost`
### Updating Machine Configurations
Execute the following command to update the specified machine:
```bash
clan machines update jon
```
You can also update all configured machines simultaneously by omitting the machine name:
```bash
clan machines update
```
For example, if deploying to a macOS machine with an ARM64-Darwin architecture, you need a second macOS machine with the same architecture to build it.
### Excluding a machine from `clan machine update`
@@ -96,14 +116,15 @@ This is useful for machines that are not always online or are not part of the re
### Uploading Flake Inputs
When updating remote machines, flake inputs are usually fetched by the build host.
However, if your flake inputs require authentication (e.g., private repositories),
you can use the `--upload-inputs` flag to upload all inputs from your local machine:
However, if flake inputs require authentication (e.g., private repositories),
Use the `--upload-inputs` flag to upload all inputs from your local machine:
```bash
clan machines update jon --upload-inputs
```
This is particularly useful when:
- Your flake references private Git repositories
- Authentication credentials are only available on your local machine
- The flake references private Git repositories
- Authentication credentials are only available on local machine
- The build host doesn't have access to certain network resources

View File

@@ -254,7 +254,7 @@ The following table shows the migration status of each deprecated clanModule:
| `data-mesher` | ✅ [Migrated](../../reference/clanServices/data-mesher.md) | |
| `deltachat` | ❌ Removed | |
| `disk-id` | ❌ Removed | |
| `dyndns` | [Being Migrated](https://git.clan.lol/clan/clan-core/pulls/4390) | |
| `dyndns` | [Migrated](../../reference/clanServices/dyndns.md) | |
| `ergochat` | ❌ Removed | |
| `garage` | ✅ [Migrated](../../reference/clanServices/garage.md) | |
| `golem-provider` | ❌ Removed | |
@@ -263,18 +263,18 @@ The following table shows the migration status of each deprecated clanModule:
| `iwd` | ❌ Removed | Use [wifi service](../../reference/clanServices/wifi.md) instead |
| `localbackup` | ✅ [Migrated](../../reference/clanServices/localbackup.md) | |
| `localsend` | ❌ Removed | |
| `machine-id` | ❌ Removed | Now an [option](../../reference/clan.core/settings.md) |
| `machine-id` | ✅ [Migrated](../../reference/clan.core/settings.md) | Now an [option](../../reference/clan.core/settings.md) |
| `matrix-synapse` | ✅ [Migrated](../../reference/clanServices/matrix-synapse.md) | |
| `moonlight` | ❌ Removed | |
| `mumble` | ❌ Removed | |
| `mycelium` | ✅ [Migrated](../../reference/clanServices/mycelium.md) | |
| `nginx` | ❌ Removed | |
| `packages` | ✅ [Migrated](../../reference/clanServices/packages.md) | |
| `postgresql` | ❌ Removed | Now an [option](../../reference/clan.core/settings.md) |
| `postgresql` | ✅ [Migrated](../../reference/clan.core/settings.md) | Now an [option](../../reference/clan.core/settings.md) |
| `root-password` | ✅ [Migrated](../../reference/clanServices/users.md) | See [migration guide](../../reference/clanServices/users.md#migration-from-root-password-module) |
| `single-disk` | ❌ Removed | |
| `sshd` | ✅ [Migrated](../../reference/clanServices/sshd.md) | |
| `state-version` | ✅ [Migrated](../../reference/clanServices/state-version.md) | |
| `state-version` | ✅ [Migrated](../../reference/clan.core/settings.md) | Now an [option](../../reference/clan.core/settings.md) |
| `static-hosts` | ❌ Removed | |
| `sunshine` | ❌ Removed | |
| `syncthing-static-peers` | ❌ Removed | |

View File

@@ -255,11 +255,50 @@ outputs = inputs: flake-parts.lib.mkFlake { inherit inputs; } ({self, lib, ...}:
})
```
The benefit of this approach is that downstream users can override the value of `myClan` by using `mkForce` or other priority modifiers.
The benefit of this approach is that downstream users can override the value of
`myClan` by using `mkForce` or other priority modifiers.
## Example: A machine-type service
Users often have different types of machines. These could be any classification
you like, for example "servers" and "desktops". Having such distictions, allows
reusing parts of your configuration that should be appplied to a class of
machines. Since this is such a common pattern, here is how to write such a
service.
For this example the we have to roles: `server` and `desktop`. Additionally, we
can use the `perMachine` section to add configuration to all machines regardless
of their type.
```nix title="machine-type.nix"
{
_class = "clan.service";
manifest.name = "machine-type";
roles.server.perInstance.nixosModule = ./server.nix;
roles.desktop.perInstance.nixosModule = ./desktop.nix;
perMachine.nixosModule = {
# Configuration for all machines (any type)
};
}
```
In the inventory we the assign machines to a type, e.g. by using tags
```nix title="flake.nix"
instnaces.machine-type = {
module.input = "self";
module.name = "@pinpox/machine-type";
roles.desktop.tags.desktop = { };
roles.server.tags.server = { };
};
```
---
## Further
## Further Reading
- [Reference Documentation for Service Authors](../../reference/clanServices/clan-service-author-interface.md)
- [Migration Guide from ClanModules to ClanServices](../../guides/migrations/migrate-inventory-services.md)

20
flake.lock generated
View File

@@ -13,11 +13,11 @@
]
},
"locked": {
"lastModified": 1756091210,
"narHash": "sha256-oEUEAZnLbNHi8ti4jY8x10yWcIkYoFc5XD+2hjmOS04=",
"rev": "eb831bca21476fa8f6df26cb39e076842634700d",
"lastModified": 1756695982,
"narHash": "sha256-dyLhOSDzxZtRgi5aj/OuaZJUsuvo+8sZ9CU/qieZ15c=",
"rev": "cc8f26e7e6c2dc985526ba59b286ae5a83168cdb",
"type": "tarball",
"url": "https://git.clan.lol/api/v1/repos/clan/data-mesher/archive/eb831bca21476fa8f6df26cb39e076842634700d.tar.gz"
"url": "https://git.clan.lol/api/v1/repos/clan/data-mesher/archive/cc8f26e7e6c2dc985526ba59b286ae5a83168cdb.tar.gz"
},
"original": {
"type": "tarball",
@@ -99,11 +99,11 @@
},
"nixos-facter-modules": {
"locked": {
"lastModified": 1756109073,
"narHash": "sha256-5pjFEziluVwJ0Z50h9laKfWbDluXuA5ada05xb/QiV4=",
"lastModified": 1756491981,
"narHash": "sha256-lXyDAWPw/UngVtQfgQ8/nrubs2r+waGEYIba5UX62+k=",
"owner": "nix-community",
"repo": "nixos-facter-modules",
"rev": "a1042c81126d9c9314c1eb1a7b89ab4d81b5dea7",
"rev": "c1b29520945d3e148cd96618c8a0d1f850965d8c",
"type": "github"
},
"original": {
@@ -181,11 +181,11 @@
]
},
"locked": {
"lastModified": 1755934250,
"narHash": "sha256-CsDojnMgYsfshQw3t4zjRUkmMmUdZGthl16bXVWgRYU=",
"lastModified": 1756662192,
"narHash": "sha256-F1oFfV51AE259I85av+MAia221XwMHCOtZCMcZLK2Jk=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "74e1a52d5bd9430312f8d1b8b0354c92c17453e5",
"rev": "1aabc6c05ccbcbf4a635fb7a90400e44282f61c4",
"type": "github"
},
"original": {

View File

@@ -245,6 +245,8 @@ in
in
{ config, ... }:
{
staticModules = clan-core.clan.modules;
distributedServices = clanLib.inventory.mapInstances {
inherit (clanConfig) inventory exportsModule;
inherit flakeInputs directory;

View File

@@ -23,6 +23,12 @@ let
};
in
{
options.staticModules = lib.mkOption {
readOnly = true;
type = lib.types.raw;
apply = moduleSet: lib.mapAttrs (inspectModule "<clan-core>") moduleSet;
};
options.modulesPerSource = lib.mkOption {
# { sourceName :: { moduleName :: {} }}
readOnly = true;

View File

@@ -324,14 +324,13 @@ class Machine:
# Always run command with shell opts
command = f"set -eo pipefail; source /etc/profile; set -xu; {command}"
proc = subprocess.run(
return subprocess.run(
self.nsenter_command(command),
timeout=timeout,
check=False,
stdout=subprocess.PIPE,
text=True,
)
return proc
def nested(
self,

View File

@@ -180,15 +180,15 @@ class CompositeLogger(AbstractLogger):
stack.enter_context(logger.nested(message, attributes))
yield
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
for logger in self.logger_list:
logger.info(*args, **kwargs)
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
for logger in self.logger_list:
logger.warning(*args, **kwargs)
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
for logger in self.logger_list:
logger.error(*args, **kwargs)
sys.exit(1)
@@ -245,13 +245,13 @@ class TerminalLogger(AbstractLogger):
toc = time.time()
self.log(f"(finished: {message}, in {toc - tic:.2f} seconds)")
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def print_serial_logs(self, enable: bool) -> None:
@@ -297,13 +297,13 @@ class XMLLogger(AbstractLogger):
self.xml.characters(message)
self.xml.endElement("line")
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def info(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def warning(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore
def error(self, *args: Any, **kwargs: Any) -> None: # type: ignore[no-untyped-def]
self.log(*args, **kwargs)
def log(self, message: str, attributes: dict[str, str] | None = None) -> None:

View File

@@ -8,6 +8,10 @@
{
imports = lib.optional (_class == "nixos") (
lib.mkIf config.clan.core.enableRecommendedDefaults {
# Enable automatic state-version generation.
clan.core.settings.state-version.enable = lib.mkDefault true;
# Use systemd during boot as well except:
# - systems with raids as this currently require manual configuration: https://github.com/NixOS/nixpkgs/issues/210210
# - for containers we currently rely on the `stage-2` init script that sets up our /etc
@@ -37,6 +41,7 @@
};
config = lib.mkIf config.clan.core.enableRecommendedDefaults {
# This disables the HTML manual and `nixos-help` command but leaves
# `man configuration.nix`
documentation.doc.enable = lib.mkDefault false;

View File

@@ -9,28 +9,11 @@
clan = {
directory = ./.;
# Workaround until we can use nodes.server = { };
modules."@clan/importer" = ../../../../clanServices/importer;
inventory = {
machines.server = { };
instances.importer = {
module.name = "@clan/importer";
module.input = "self";
roles.default.tags.all = { };
roles.default.extraModules = [
{
clan.core.settings.state-version.enable = true;
}
];
};
machines.server = {
clan.core.settings.state-version.enable = true;
};
};
# TODO: Broken. Use instead of importer after fixing.
# nodes.server = { };
# This is not an actual vm test, this is a workaround to
# generate the needed vars for the eval test.
testScript = "";

View File

@@ -16,6 +16,10 @@ from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Any
# Constants
NODE_ID_LENGTH = 10
NETWORK_ID_LENGTH = 16
class ClanError(Exception):
pass
@@ -55,8 +59,8 @@ class Identity:
def node_id(self) -> str:
nid = self.public.split(":")[0]
if len(nid) != 10:
msg = f"node_id must be 10 characters long, got {len(nid)}: {nid}"
if len(nid) != NODE_ID_LENGTH:
msg = f"node_id must be {NODE_ID_LENGTH} characters long, got {len(nid)}: {nid}"
raise ClanError(msg)
return nid
@@ -173,8 +177,8 @@ def create_identity() -> Identity:
def compute_zerotier_ip(network_id: str, identity: Identity) -> ipaddress.IPv6Address:
if len(network_id) != 16:
msg = f"network_id must be 16 characters long, got '{network_id}'"
if len(network_id) != NETWORK_ID_LENGTH:
msg = f"network_id must be {NETWORK_ID_LENGTH} characters long, got '{network_id}'"
raise ClanError(msg)
nwid = int(network_id, 16)
node_id = int(identity.node_id(), 16)

5
nixosModules/clanCore/zerotier/genmoon.py Normal file → Executable file
View File

@@ -6,9 +6,12 @@ import sys
from pathlib import Path
from tempfile import NamedTemporaryFile
# Constants
REQUIRED_ARGS = 4
def main() -> None:
if len(sys.argv) != 4:
if len(sys.argv) != REQUIRED_ARGS:
print("Usage: genmoon.py <moon.json> <endpoint.json> <moons.d>")
sys.exit(1)
moon_json_path = sys.argv[1]

View File

@@ -12,8 +12,14 @@ let
(builtins.match "linux_[0-9]+_[0-9]+" name) != null
&& (builtins.tryEval kernelPackages).success
&& (
(!isUnstable && !kernelPackages.zfs.meta.broken)
|| (isUnstable && !kernelPackages.zfs_unstable.meta.broken)
let
zfsPackage =
if isUnstable then
kernelPackages.zfs_unstable
else
kernelPackages.${pkgs.zfs.kernelModuleAttribute};
in
!(zfsPackage.meta.broken or false)
)
) pkgs.linuxKernel.packages;
latestKernelPackage = lib.last (
@@ -24,5 +30,5 @@ let
in
{
# Note this might jump back and worth as kernel get added or removed.
boot.kernelPackages = latestKernelPackage;
boot.kernelPackages = lib.mkIf (lib.meta.availableOn pkgs.hostPlatform pkgs.zfs) latestKernelPackage;
}

View File

@@ -5,7 +5,7 @@ from contextlib import ExitStack
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
from clan_lib.api import ApiResponse
from clan_lib.api import ApiError, ApiResponse, ErrorDataClass
from clan_lib.api.tasks import WebThread
from clan_lib.async_run import set_current_thread_opkey, set_should_cancel
@@ -43,7 +43,7 @@ class ApiBridge(ABC):
def process_request(self, request: BackendRequest) -> None:
"""Process an API request through the middleware chain."""
from .middleware import MiddlewareContext
from .middleware import MiddlewareContext # noqa: PLC0415
with ExitStack() as stack:
context = MiddlewareContext(
@@ -59,7 +59,7 @@ class ApiBridge(ABC):
f"{middleware.__class__.__name__} => {request.method_name}",
)
middleware.process(context)
except Exception as e:
except Exception as e: # noqa: BLE001
# If middleware fails, handle error
self.send_api_error_response(
request.op_key or "unknown",
@@ -75,8 +75,6 @@ class ApiBridge(ABC):
location: list[str],
) -> None:
"""Send an error response."""
from clan_lib.api import ApiError, ErrorDataClass
error_data = ErrorDataClass(
op_key=op_key,
status="error",

View File

@@ -91,7 +91,6 @@ def get_system_file(
def gtk_open_file(file_request: FileRequest, op_key: str) -> bool:
def returns(data: SuccessDataClass | ErrorDataClass) -> None:
global RESULT
RESULT[op_key] = data
def on_file_select(file_dialog: Gtk.FileDialog, task: Gio.Task) -> None:

View File

@@ -94,10 +94,10 @@ class LoggingMiddleware(Middleware):
if self.handler:
self.handler.root_logger.removeHandler(self.handler.new_handler)
self.handler.new_handler.close()
if self.log_f:
self.log_f.close()
if self.original_ctx:
set_async_ctx(self.original_ctx)
if self.log_f:
self.log_f.close()
# Register the logging context manager
self.register_context_manager(context, LoggingContextManager(log_file))

View File

@@ -1,5 +1,6 @@
import logging
import os
import time
from dataclasses import dataclass
from pathlib import Path
@@ -16,6 +17,7 @@ from clan_app.api.middleware import (
LoggingMiddleware,
MethodExecutionMiddleware,
)
from clan_app.deps.http.http_server import HttpApiServer
from clan_app.deps.webview.webview import Size, SizeHint, Webview
log = logging.getLogger(__name__)
@@ -64,8 +66,6 @@ def app_run(app_opts: ClanAppOptions) -> int:
# Start HTTP API server if requested
http_server = None
if app_opts.http_api:
from clan_app.deps.http.http_server import HttpApiServer
openapi_file = os.getenv("OPENAPI_FILE", None)
swagger_dist = os.getenv("SWAGGER_UI_DIST", None)
@@ -95,8 +95,6 @@ def app_run(app_opts: ClanAppOptions) -> int:
log.info("Press Ctrl+C to stop the server")
try:
# Keep the main thread alive
import time
while True:
time.sleep(1)
except KeyboardInterrupt:

View File

@@ -148,8 +148,8 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
self.send_header("Content-Type", content_type)
self.end_headers()
self.wfile.write(file_data)
except Exception as e:
log.error(f"Error reading Swagger file: {e!s}")
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
log.exception("Error reading Swagger file")
self.send_error(500, "Internal Server Error")
def _get_swagger_file_path(self, rel_path: str) -> Path:
@@ -191,13 +191,13 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
return file_data
def do_OPTIONS(self) -> None: # noqa: N802
def do_OPTIONS(self) -> None:
"""Handle CORS preflight requests."""
self.send_response_only(200)
self._send_cors_headers()
self.end_headers()
def do_GET(self) -> None: # noqa: N802
def do_GET(self) -> None:
"""Handle GET requests."""
parsed_url = urlparse(self.path)
path = parsed_url.path
@@ -211,7 +211,7 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
else:
self.send_api_error_response("info", "Not Found", ["http_bridge", "GET"])
def do_POST(self) -> None: # noqa: N802
def do_POST(self) -> None:
"""Handle POST requests."""
parsed_url = urlparse(self.path)
path = parsed_url.path
@@ -252,7 +252,7 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
gen_op_key = str(uuid.uuid4())
try:
self._handle_api_request(method_name, request_data, gen_op_key)
except Exception as e:
except RuntimeError as e:
log.exception(f"Error processing API request {method_name}")
self.send_api_error_response(
gen_op_key,
@@ -264,10 +264,10 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
"""Read and parse the request body. Returns None if there was an error."""
try:
content_length = int(self.headers.get("Content-Length", 0))
if content_length > 0:
body = self.rfile.read(content_length)
return json.loads(body.decode("utf-8"))
return {}
if content_length == 0:
return {}
body = self.rfile.read(content_length)
return json.loads(body.decode("utf-8"))
except json.JSONDecodeError:
self.send_api_error_response(
"post",
@@ -275,7 +275,7 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
["http_bridge", "POST", method_name],
)
return None
except Exception as e:
except (OSError, ValueError, UnicodeDecodeError) as e:
self.send_api_error_response(
"post",
f"Error reading request: {e!s}",
@@ -305,7 +305,7 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
op_key=op_key,
)
except Exception as e:
except (KeyError, TypeError, ValueError) as e:
self.send_api_error_response(
gen_op_key,
str(e),

View File

@@ -4,13 +4,11 @@ import json
import logging
import threading
import time
from unittest.mock import Mock
from urllib.request import Request, urlopen
import pytest
from clan_lib.api import MethodRegistry, tasks
from clan_lib.async_run import is_async_cancelled
from clan_lib.log_manager import LogManager
from clan_app.api.middleware import (
ArgumentParsingMiddleware,
@@ -53,31 +51,20 @@ def mock_api() -> MethodRegistry:
return api
@pytest.fixture
def mock_log_manager() -> Mock:
"""Create a mock log manager."""
log_manager = Mock(spec=LogManager)
log_manager.create_log_file.return_value.get_file_path.return_value = Mock()
log_manager.create_log_file.return_value.get_file_path.return_value.open.return_value = Mock()
return log_manager
@pytest.fixture
def http_bridge(
mock_api: MethodRegistry,
mock_log_manager: Mock,
) -> tuple[MethodRegistry, tuple]:
"""Create HTTP bridge dependencies for testing."""
middleware_chain = (
ArgumentParsingMiddleware(api=mock_api),
# LoggingMiddleware(log_manager=mock_log_manager),
MethodExecutionMiddleware(api=mock_api),
)
return mock_api, middleware_chain
@pytest.fixture
def http_server(mock_api: MethodRegistry, mock_log_manager: Mock) -> HttpApiServer:
def http_server(mock_api: MethodRegistry) -> HttpApiServer:
"""Create HTTP server with mock dependencies."""
server = HttpApiServer(
api=mock_api,
@@ -87,7 +74,6 @@ def http_server(mock_api: MethodRegistry, mock_log_manager: Mock) -> HttpApiServ
# Add middleware
server.add_middleware(ArgumentParsingMiddleware(api=mock_api))
# server.add_middleware(LoggingMiddleware(log_manager=mock_log_manager))
server.add_middleware(MethodExecutionMiddleware(api=mock_api))
# Bridge will be created automatically when accessed
@@ -114,7 +100,6 @@ class TestHttpBridge:
# The actual HTTP handling will be tested through the server integration tests
assert len(middleware_chain) == 2
assert isinstance(middleware_chain[0], ArgumentParsingMiddleware)
# assert isinstance(middleware_chain[1], LoggingMiddleware)
assert isinstance(middleware_chain[1], MethodExecutionMiddleware)
@@ -151,14 +136,14 @@ class TestHttpApiServer:
try:
# Test root endpoint
response = urlopen("http://127.0.0.1:8081/") # noqa: S310
response = urlopen("http://127.0.0.1:8081/")
data: dict = json.loads(response.read().decode())
assert data["body"]["status"] == "success"
assert data["body"]["data"]["message"] == "Clan API Server"
assert data["body"]["data"]["version"] == "1.0.0"
# Test methods endpoint
response = urlopen("http://127.0.0.1:8081/api/methods") # noqa: S310
response = urlopen("http://127.0.0.1:8081/api/methods")
data = json.loads(response.read().decode())
assert data["body"]["status"] == "success"
assert "test_method" in data["body"]["data"]["methods"]
@@ -194,7 +179,7 @@ class TestHttpApiServer:
try:
# Test 404 error
res = urlopen("http://127.0.0.1:8081/nonexistent") # noqa: S310
res = urlopen("http://127.0.0.1:8081/nonexistent")
assert res.status == 200
body = json.loads(res.read().decode())["body"]
assert body["status"] == "error"
@@ -259,7 +244,6 @@ class TestIntegration:
def test_full_request_flow(
self,
mock_api: MethodRegistry,
mock_log_manager: Mock,
) -> None:
"""Test complete request flow from server to bridge to middleware."""
server: HttpApiServer = HttpApiServer(
@@ -270,7 +254,6 @@ class TestIntegration:
# Add middleware
server.add_middleware(ArgumentParsingMiddleware(api=mock_api))
# server.add_middleware(LoggingMiddleware(log_manager=mock_log_manager))
server.add_middleware(MethodExecutionMiddleware(api=mock_api))
# Bridge will be created automatically when accessed
@@ -306,7 +289,6 @@ class TestIntegration:
def test_blocking_task(
self,
mock_api: MethodRegistry,
mock_log_manager: Mock,
) -> None:
shared_threads: dict[str, tasks.WebThread] = {}
tasks.BAKEND_THREADS = shared_threads
@@ -321,7 +303,6 @@ class TestIntegration:
# Add middleware
server.add_middleware(ArgumentParsingMiddleware(api=mock_api))
# server.add_middleware(LoggingMiddleware(log_manager=mock_log_manager))
server.add_middleware(MethodExecutionMiddleware(api=mock_api))
# Start server

View File

@@ -12,12 +12,11 @@ from clan_lib.api import MethodRegistry, message_queue
from clan_lib.api.tasks import WebThread
from ._webview_ffi import _encode_c_string, _webview_lib
from .webview_bridge import WebviewBridge
if TYPE_CHECKING:
from clan_app.api.middleware import Middleware
from .webview_bridge import WebviewBridge
log = logging.getLogger(__name__)
@@ -49,7 +48,7 @@ class Webview:
shared_threads: dict[str, WebThread] | None = None
# initialized later
_bridge: "WebviewBridge | None" = None
_bridge: WebviewBridge | None = None
_handle: Any | None = None
_callbacks: dict[str, Callable[..., Any]] = field(default_factory=dict)
_middleware: list["Middleware"] = field(default_factory=list)
@@ -81,7 +80,7 @@ class Webview:
msg = message_queue.get() # Blocks until available
js_code = f"window.notifyBus({json.dumps(msg)});"
self.eval(js_code)
except Exception as e:
except (json.JSONDecodeError, RuntimeError, AttributeError) as e:
print("Bridge notify error:", e)
sleep(0.01) # avoid busy loop
@@ -132,10 +131,8 @@ class Webview:
self._middleware.append(middleware)
def create_bridge(self) -> "WebviewBridge":
def create_bridge(self) -> WebviewBridge:
"""Create and initialize the WebviewBridge with current middleware."""
from .webview_bridge import WebviewBridge
# Use shared_threads if provided, otherwise let WebviewBridge use its default
if self.shared_threads is not None:
bridge = WebviewBridge(
@@ -211,7 +208,7 @@ class Webview:
try:
result = callback(*args)
success = True
except Exception as e:
except Exception as e: # noqa: BLE001
result = str(e)
success = False
self.return_(seq.decode(), 0 if success else 1, json.dumps(result))

View File

@@ -8,8 +8,6 @@ from clan_lib.api.tasks import WebThread
from clan_app.api.api_bridge import ApiBridge, BackendRequest, BackendResponse
from .webview import FuncStatus
if TYPE_CHECKING:
from .webview import Webview
@@ -32,6 +30,9 @@ class WebviewBridge(ApiBridge):
)
log.debug(f"Sending response: {serialized}")
# Import FuncStatus locally to avoid circular import
from .webview import FuncStatus # noqa: PLC0415
self.webview.return_(response._op_key, FuncStatus.SUCCESS, serialized) # noqa: SLF001
def handle_webview_call(

View File

@@ -48,6 +48,10 @@ let
url = "https://github.com/eigilnikolajsen/commit-mono/raw/0b3b192f035cdc8d1ea8ffb5463cc23d73d0b89f/src/fonts/fontlab/CommitMonoV143-VF.woff2";
hash = "sha256-80LKbD8ll+bA/NhLPz7WTTzlvbbQrxnRkNZFpVixzyk=";
};
commitMono_ttf = fetchurl {
url = "https://github.com/eigilnikolajsen/commit-mono/raw/0b3b192f035cdc8d1ea8ffb5463cc23d73d0b89f/src/fonts/fontlab/CommitMonoV143-VF.ttf";
hash = "sha256-mN6akBFjp2mBLDzy8bhtY6mKnO1nINdHqmZSaIQHw08=";
};
in
runCommand "" { } ''
@@ -62,4 +66,5 @@ runCommand "" { } ''
cp ${archivoSemi.semiBold} $out/ArchivoSemiCondensed-SemiBold.woff2
cp ${commitMono} $out/CommitMonoV143-VF.woff2
cp ${commitMono_ttf} $out/CommitMonoV143-VF.ttf
''

View File

@@ -23,6 +23,7 @@
"solid-js": "^1.9.7",
"solid-toast": "^0.5.0",
"three": "^0.176.0",
"troika-three-text": "^0.52.4",
"valibot": "^1.1.0"
},
"devDependencies": {
@@ -3807,6 +3808,15 @@
"node": ">=12.0.0"
}
},
"node_modules/bidi-js": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz",
"integrity": "sha512-RKshQI1R3YQ+n9YJz2QQ147P66ELpa1FQEg20Dk8oW9t2KgLbpDLLp9aGZ7y8WHSshDknG0bknqGw5/tyCs5tw==",
"license": "MIT",
"dependencies": {
"require-from-string": "^2.0.2"
}
},
"node_modules/binary-extensions": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz",
@@ -7528,6 +7538,15 @@
"node": ">=0.10.0"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
"integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
"license": "MIT",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/requires-port": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
@@ -8655,6 +8674,36 @@
"tree-kill": "cli.js"
}
},
"node_modules/troika-three-text": {
"version": "0.52.4",
"resolved": "https://registry.npmjs.org/troika-three-text/-/troika-three-text-0.52.4.tgz",
"integrity": "sha512-V50EwcYGruV5rUZ9F4aNsrytGdKcXKALjEtQXIOBfhVoZU9VAqZNIoGQ3TMiooVqFAbR1w15T+f+8gkzoFzawg==",
"license": "MIT",
"dependencies": {
"bidi-js": "^1.0.2",
"troika-three-utils": "^0.52.4",
"troika-worker-utils": "^0.52.0",
"webgl-sdf-generator": "1.1.1"
},
"peerDependencies": {
"three": ">=0.125.0"
}
},
"node_modules/troika-three-utils": {
"version": "0.52.4",
"resolved": "https://registry.npmjs.org/troika-three-utils/-/troika-three-utils-0.52.4.tgz",
"integrity": "sha512-NORAStSVa/BDiG52Mfudk4j1FG4jC4ILutB3foPnfGbOeIs9+G5vZLa0pnmnaftZUGm4UwSoqEpWdqvC7zms3A==",
"license": "MIT",
"peerDependencies": {
"three": ">=0.125.0"
}
},
"node_modules/troika-worker-utils": {
"version": "0.52.0",
"resolved": "https://registry.npmjs.org/troika-worker-utils/-/troika-worker-utils-0.52.0.tgz",
"integrity": "sha512-W1CpvTHykaPH5brv5VHLfQo9D1OYuo0cSBEUQFFT/nBUzM8iD6Lq2/tgG/f1OelbAS1WtaTPQzE5uM49egnngw==",
"license": "MIT"
},
"node_modules/ts-api-utils": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz",
@@ -9268,6 +9317,12 @@
"node": "20 || >=22"
}
},
"node_modules/webgl-sdf-generator": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/webgl-sdf-generator/-/webgl-sdf-generator-1.1.1.tgz",
"integrity": "sha512-9Z0JcMTFxeE+b2x1LJTdnaT8rT8aEp7MVxkNwoycNmJWwPdzoXzMh0BjJSh/AEFP+KPYZUli814h8bJZFIZ2jA==",
"license": "MIT"
},
"node_modules/webidl-conversions": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",

View File

@@ -80,6 +80,7 @@
"solid-js": "^1.9.7",
"solid-toast": "^0.5.0",
"three": "^0.176.0",
"troika-three-text": "^0.52.4",
"valibot": "^1.1.0"
},
"optionalDependencies": {

View File

@@ -5,10 +5,6 @@
@apply pl-3;
}
&.hasIcon svg.icon {
@apply relative top-0.5;
}
&.hasDismiss {
@apply pr-3;
}
@@ -35,6 +31,10 @@
&.noPadding {
@apply p-0;
}
svg {
@apply relative top-0.5;
}
}
.alertContent {

View File

@@ -68,6 +68,7 @@ export const Button = (props: ButtonProps) => {
},
)}
onClick={props.onClick}
disabled={props.disabled || props.loading}
{...other}
>
<Loader
@@ -90,7 +91,6 @@ export const Button = (props: ButtonProps) => {
<Typography
class="label"
hierarchy="label"
family="mono"
size={local.size || "default"}
inverted={local.hierarchy === "primary"}
weight="bold"

View File

@@ -0,0 +1,33 @@
.list {
display: flex;
width: 113px;
padding: 8px;
flex-direction: column;
align-items: flex-start;
border-radius: 5px;
border: 1px solid var(--clr-border-def-2, #d8e8eb);
background: var(--clr-bg-def-1, #fff);
box-shadow: 0 3px 8px 0 rgba(0, 0, 0, 0.24);
}
.item {
max-height: 28px;
height: 28px;
padding: 4px 8px;
cursor: pointer;
display: flex;
align-items: center;
align-self: stretch;
gap: 4px;
&:hover {
@apply bg-def-3;
border-radius: 2px;
}
&[aria-disabled="true"] {
cursor: not-allowed;
pointer-events: none;
}
}

View File

@@ -0,0 +1,61 @@
import { onCleanup, onMount } from "solid-js";
import styles from "./ContextMenu.module.css";
import { Typography } from "../Typography/Typography";
export const Menu = (props: {
x: number;
y: number;
onSelect: (option: "move") => void;
close: () => void;
intersect: string[];
}) => {
let ref: HTMLUListElement;
const handleClickOutside = (e: MouseEvent) => {
if (!ref.contains(e.target as Node)) {
props.close();
}
};
onMount(() => {
document.addEventListener("mousedown", handleClickOutside);
});
onCleanup(() =>
document.removeEventListener("mousedown", handleClickOutside),
);
const currentMachine = () => props.intersect.at(0) || null;
return (
<ul
ref={(el) => (ref = el)}
style={{
position: "absolute",
top: `${props.y}px`,
left: `${props.x}px`,
"z-index": 1000,
"pointer-events": "auto",
}}
class={styles.list}
>
<li
class={styles.item}
aria-disabled={!currentMachine()}
onClick={() => {
console.log("Move clicked", currentMachine());
props.onSelect("move");
props.close();
}}
>
<Typography
hierarchy="label"
size="s"
weight="bold"
color={currentMachine() ? "primary" : "quaternary"}
>
Move
</Typography>
</li>
</ul>
);
};

View File

@@ -164,17 +164,26 @@ export const MachineTags = (props: MachineTagsProps) => {
<For each={state.selectedOptions()}>
{(option) => (
<Tag
label={option.value}
inverted={props.inverted}
action={
option.disabled || props.disabled || props.readOnly
? undefined
: {
icon: "Close",
onClick: () => state.remove(option),
}
interactive={
!(option.disabled || props.disabled || props.readOnly)
}
/>
icon={({ inverted }) =>
option.disabled ||
props.disabled ||
props.readOnly ? undefined : (
<Icon
role="button"
icon={"Close"}
size="0.5rem"
inverted={inverted}
onClick={() => state.remove(option)}
/>
)
}
>
{option.value}
</Tag>
)}
</For>
<Show when={!props.readOnly}>

View File

@@ -25,7 +25,7 @@
.modal_body {
overflow-y: auto;
@apply rounded-b-md p-6 pt-4 bg-def-1 flex-grow;
@apply rounded-b-md p-4 pt-4 bg-def-1 flex-grow;
&[data-no-padding] {
@apply p-0;

View File

@@ -2,20 +2,33 @@ import Icon from "../Icon/Icon";
import { Button } from "../Button/Button";
import styles from "./Search.module.css";
import { Combobox } from "@kobalte/core/combobox";
import { createMemo, createSignal, For, JSX } from "solid-js";
import {
createEffect,
createMemo,
createSignal,
For,
JSX,
Match,
Switch,
} from "solid-js";
import { createVirtualizer, VirtualizerOptions } from "@tanstack/solid-virtual";
import { CollectionNode } from "@kobalte/core/*";
import cx from "classnames";
import { Loader } from "../Loader/Loader";
export interface Option {
value: string;
label: string;
disabled?: boolean;
}
export interface ItemRenderOptions {
selected: boolean;
disabled: boolean;
}
export interface SearchMultipleProps<T> {
values: T[]; // controlled values
onChange: (values: T[]) => void;
options: T[];
renderItem: (item: T, opts: ItemRenderOptions) => JSX.Element;
@@ -23,12 +36,17 @@ export interface SearchMultipleProps<T> {
placeholder?: string;
virtualizerOptions?: Partial<VirtualizerOptions<Element, Element>>;
height: string; // e.g. '14.5rem'
headerClass?: string;
headerChildren?: JSX.Element;
loading?: boolean;
loadingComponent?: JSX.Element;
divider?: boolean;
}
export function SearchMultiple<T extends Option>(
props: SearchMultipleProps<T>,
) {
// Controlled input value, to allow resetting the input itself
const [values, setValues] = createSignal<T[]>(props.initialValues || []);
// const [values, setValues] = createSignal<T[]>(props.initialValues || []);
const [inputValue, setInputValue] = createSignal<string>("");
let inputEl: HTMLInputElement;
@@ -54,30 +72,32 @@ export function SearchMultiple<T extends Option>(
return item?.rawValue?.value || `item-${index}`;
},
estimateSize: () => 42,
gap: 6,
gap: 0,
overscan: 5,
...props.virtualizerOptions,
});
return newVirtualizer;
});
createEffect(() => {
console.log("multi values:", props.values);
});
return (
<Combobox<T>
multiple
value={values()}
value={props.values}
onChange={(values) => {
setValues(() => values);
// setInputValue(value ? value.label : "");
// setValues(() => values);
console.log("onChange", values);
props.onChange(values);
}}
class={styles.searchContainer}
style={{ "--container-height": props.height }}
placement="bottom-start"
options={props.options}
optionValue="value"
optionTextValue="label"
optionLabel="label"
optionDisabled={"disabled"}
sameWidth={true}
open={true}
gutter={7}
@@ -89,69 +109,78 @@ export function SearchMultiple<T extends Option>(
triggerMode="manual"
noResetInputOnBlur={true}
>
<Combobox.Control<T> class={styles.searchHeader}>
<Combobox.Control<T>
class={cx(styles.searchHeader, props.headerClass || "bg-inv-3")}
>
{(state) => (
<div class={styles.inputContainer}>
<Icon icon="Search" color="quaternary" />
<Combobox.Input
ref={(el) => {
inputEl = el;
}}
class={styles.searchInput}
placeholder={props.placeholder}
value={inputValue()}
onChange={(e) => {
setInputValue(e.currentTarget.value);
}}
/>
<Button
type="reset"
hierarchy="primary"
size="s"
ghost
icon="CloseCircle"
onClick={() => {
state.clear();
setInputValue("");
<>
{props.headerChildren}
<div class={styles.inputContainer}>
<Icon icon="Search" color="quaternary" />
<Combobox.Input
ref={(el) => {
inputEl = el;
}}
class={styles.searchInput}
placeholder={props.placeholder}
value={inputValue()}
onChange={(e) => {
setInputValue(e.currentTarget.value);
}}
/>
<Button
type="reset"
hierarchy="primary"
size="s"
ghost
icon="CloseCircle"
onClick={() => {
state.clear();
setInputValue("");
// Dispatch an input event to notify combobox listeners
inputEl.dispatchEvent(
new Event("input", { bubbles: true, cancelable: true }),
);
}}
/>
</div>
// Dispatch an input event to notify combobox listeners
inputEl.dispatchEvent(
new Event("input", { bubbles: true, cancelable: true }),
);
}}
/>
</div>
</>
)}
</Combobox.Control>
<Combobox.Portal>
<Combobox.Content
class={styles.searchContent}
tabIndex={-1}
style={{ "--container-height": props.height }}
>
<Combobox.Listbox<T>
ref={(el) => {
listboxRef = el;
}}
style={{
height: "100%",
width: "100%",
overflow: "auto",
"overflow-y": "auto",
}}
scrollToItem={(key) => {
const idx = comboboxItems().findIndex(
(option) => option.rawValue.value === key,
);
virtualizer().scrollToIndex(idx);
}}
>
{(items) => {
// Update the virtualizer with the filtered items
const arr = Array.from(items());
setComboboxItems(arr);
<Combobox.Listbox<T>
ref={(el) => {
listboxRef = el;
}}
style={{
height: props.height,
width: "100%",
overflow: "auto",
"overflow-y": "auto",
}}
scrollToItem={(key) => {
const idx = comboboxItems().findIndex(
(option) => option.rawValue.value === key,
);
virtualizer().scrollToIndex(idx);
}}
class={styles.listbox}
>
{(items) => {
// Update the virtualizer with the filtered items
const arr = Array.from(items());
setComboboxItems(arr);
return (
return (
<Switch>
<Match when={props.loading}>
{props.loadingComponent ?? (
<div class="flex w-full justify-center py-2">
<Loader />
</div>
)}
</Match>
<Match when={!props.loading}>
<div
style={{
height: `${virtualizer().getTotalSize()}px`,
@@ -169,11 +198,16 @@ export function SearchMultiple<T extends Option>(
return null;
}
const isSelected = () =>
values().some((v) => v.value === item.rawValue.value);
props.values.some(
(v) => v.value === item.rawValue.value,
);
return (
<Combobox.Item
item={item}
class={styles.searchItem}
class={cx(
styles.searchItem,
props.divider && styles.hasDivider,
)}
style={{
position: "absolute",
top: 0,
@@ -185,17 +219,19 @@ export function SearchMultiple<T extends Option>(
>
{props.renderItem(item.rawValue, {
selected: isSelected(),
disabled: item.disabled,
})}
</Combobox.Item>
);
}}
</For>
</div>
);
}}
</Combobox.Listbox>
</Combobox.Content>
</Combobox.Portal>
</Match>
</Switch>
);
}}
</Combobox.Listbox>
{/* </Combobox.Content> */}
</Combobox>
);
}

View File

@@ -29,7 +29,7 @@
}
.searchHeader {
@apply bg-inv-3 flex gap-2 items-center p-2 rounded-md z-50;
@apply flex gap-2 items-center p-2 rounded-t-md z-50;
@apply px-3 pt-3 pb-2;
}
@@ -42,18 +42,33 @@
}
.searchItem {
&[data-highlighted],
&:focus,
&:focus-visible,
&:hover {
@apply bg-inv-acc-2;
@apply flex flex-col justify-center overflow-hidden;
&.hasDivider {
box-shadow: 0 1px 0 0 theme(colors.border.inv.2);
}
&:active {
@apply bg-inv-acc-3;
/* Next element is hovered */
&:has(+ &:hover) {
box-shadow: unset;
}
@apply flex flex-col justify-center;
&:not([aria-disabled="true"])[data-highlighted],
&:not([aria-disabled="true"]):focus,
&:not([aria-disabled="true"]):focus-visible,
&:not([aria-disabled="true"]):hover {
@apply bg-inv-acc-2 rounded-md;
box-shadow: unset;
}
&:not([aria-disabled="true"]):active {
@apply bg-inv-acc-3 rounded-md;
box-shadow: unset;
}
&[aria-disabled="true"] {
@apply cursor-not-allowed;
}
}
.searchContainer {
@@ -61,16 +76,14 @@
@apply rounded-lg;
height: var(--container-height, 14.5rem);
border: 1px solid #2b4647;
background:
linear-gradient(0deg, rgba(0, 0, 0, 0.18) 0%, rgba(0, 0, 0, 0.18) 100%),
linear-gradient(0deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.2) 100%),
linear-gradient(
180deg,
var(--clr-bg-inv-3, rgba(43, 70, 71, 0.79)) 0%,
var(--clr-bg-inv-4, rgba(32, 54, 55, 0.79)) 100%
theme(colors.bg.inv.2) 0%,
theme(colors.bg.inv.3) 100%
);
box-shadow:
@@ -78,10 +91,8 @@
0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.searchContent {
@apply px-3;
height: var(--container-height, 14.5rem);
padding-bottom: 4rem;
.listbox {
@apply px-3 pt-3.5;
}
@keyframes contentHide {

View File

@@ -9,7 +9,7 @@ import {
SearchMultiple,
SearchMultipleProps,
} from "./MultipleSearch";
import { JSX, Show } from "solid-js";
import { Show } from "solid-js";
const meta = {
title: "Components/Search",
@@ -55,8 +55,8 @@ function generateModules(count: number): Module[] {
modules.push({
value: `lolcat/module-${i + 1}`,
label: `Module ${i + 1}`,
description: `${greek[i % greek.length]}#${i + 1}`,
input: "lolcat",
description: `${greek[i % greek.length]}#${i + 1} this is a very long description to test text wrapping in the search component`,
input: "lolcat-flake-part-from-nixpkgs-via-nix-via-clan-flake",
});
}
@@ -72,12 +72,13 @@ export interface Module {
export const Default: Story = {
args: {
height: "14.5rem",
// Test with lots of modules
options: generateModules(1000),
renderItem: (item: Module) => {
return (
<div class="flex items-center justify-between gap-2 rounded-md px-2 py-1 pr-4">
<div class="flex size-8 items-center justify-center rounded-md bg-white">
<div class="flex size-8 shrink-0 items-center justify-center rounded-md bg-white">
<Icon icon="Code" />
</div>
<div class="flex w-full flex-col">
@@ -94,8 +95,12 @@ export const Default: Story = {
inverted
class="flex justify-between"
>
<span>{item.description}</span>
<span>by {item.input}</span>
<span class="inline-block max-w-72 truncate align-middle">
{item.description}
</span>
<span class="inline-block max-w-20 truncate align-middle">
by {item.input}
</span>
</Typography>
</div>
</div>
@@ -104,7 +109,7 @@ export const Default: Story = {
},
render: (args: SearchProps<Module>) => {
return (
<div class="absolute bottom-1/3 w-3/4 px-3">
<div class="fixed bottom-10 left-1/2 mb-2 w-[30rem] -translate-x-1/2">
<Search<Module>
{...args}
onChange={(module) => {
@@ -117,32 +122,43 @@ export const Default: Story = {
},
};
export const Loading: Story = {
args: {
height: "14.5rem",
// Test with lots of modules
loading: true,
options: [],
renderItem: () => <span></span>,
},
render: (args: SearchProps<Module>) => {
return (
<div class="absolute bottom-1/3 w-3/4 px-3">
<Search<Module>
{...args}
onChange={(module) => {
// Go to the module configuration
}}
/>
</div>
);
},
};
type MachineOrTag =
| {
value: string;
label: string;
type: "machine";
disabled?: boolean;
}
| {
members: string[];
value: string;
label: string;
disabled?: boolean;
type: "tag";
};
interface WrapIfProps {
condition: boolean;
wrapper: (children: JSX.Element) => JSX.Element;
children: JSX.Element;
}
const WrapIf = (props: WrapIfProps) => {
if (props.condition) {
return props.wrapper(props.children);
} else {
return props.children;
}
};
const machinesAndTags: MachineOrTag[] = [
{ value: "machine-1", label: "Machine 1", type: "machine" },
{ value: "machine-2", label: "Machine 2", type: "machine" },
@@ -183,7 +199,13 @@ export const Multiple: Story = {
</Show>
</Combobox.ItemIndicator>
<Combobox.ItemLabel class="flex items-center gap-2">
<Typography hierarchy="body" size="s" weight="medium" inverted>
<Typography
hierarchy="body"
size="s"
weight="medium"
inverted
color={opts.disabled ? "quaternary" : "primary"}
>
{item.label}
</Typography>
<Show when={item.type === "tag" && item}>
@@ -216,6 +238,7 @@ export const Multiple: Story = {
<div class="absolute bottom-1/3 w-3/4 px-3">
<SearchMultiple<MachineOrTag>
{...args}
divider
height="20rem"
virtualizerOptions={{
estimateSize: () => 38,

View File

@@ -2,20 +2,29 @@ import Icon from "../Icon/Icon";
import { Button } from "../Button/Button";
import styles from "./Search.module.css";
import { Combobox } from "@kobalte/core/combobox";
import { createMemo, createSignal, For, JSX } from "solid-js";
import { createMemo, createSignal, For, JSX, Match, Switch } from "solid-js";
import { createVirtualizer } from "@tanstack/solid-virtual";
import { CollectionNode } from "@kobalte/core/*";
import { Loader } from "../Loader/Loader";
import cx from "classnames";
export interface Option {
value: string;
label: string;
disabled?: boolean;
}
export interface SearchProps<T> {
onChange: (value: T | null) => void;
options: T[];
renderItem: (item: T) => JSX.Element;
renderItem: (item: T, opts: { disabled: boolean }) => JSX.Element;
loading?: boolean;
loadingComponent?: JSX.Element;
headerClass?: string;
height: string; // e.g. '14.5rem'
divider?: boolean;
}
export function Search<T extends Option>(props: SearchProps<T>) {
// Controlled input value, to allow resetting the input itself
const [value, setValue] = createSignal<T | null>(null);
@@ -59,13 +68,14 @@ export function Search<T extends Option>(props: SearchProps<T>) {
setInputValue(value ? value.label : "");
props.onChange(value);
}}
class={styles.searchContainer}
class={cx(styles.searchContainer, props.divider && styles.hasDivider)}
placement="bottom-start"
options={props.options}
optionValue="value"
optionTextValue="label"
optionLabel="label"
placeholder="Search a service"
optionDisabled={"disabled"}
sameWidth={true}
open={true}
gutter={7}
@@ -77,7 +87,9 @@ export function Search<T extends Option>(props: SearchProps<T>) {
triggerMode="manual"
noResetInputOnBlur={true}
>
<Combobox.Control<T> class={styles.searchHeader}>
<Combobox.Control<T>
class={cx(styles.searchHeader, props.headerClass || "bg-inv-3")}
>
{(state) => (
<div class={styles.inputContainer}>
<Icon icon="Search" color="quaternary" />
@@ -111,31 +123,39 @@ export function Search<T extends Option>(props: SearchProps<T>) {
</div>
)}
</Combobox.Control>
<Combobox.Portal>
<Combobox.Content class={styles.searchContent} tabIndex={-1}>
<Combobox.Listbox<T>
ref={(el) => {
listboxRef = el;
}}
style={{
height: "100%",
width: "100%",
overflow: "auto",
"overflow-y": "auto",
}}
scrollToItem={(key) => {
const idx = comboboxItems().findIndex(
(option) => option.rawValue.value === key,
);
virtualizer().scrollToIndex(idx);
}}
>
{(items) => {
// Update the virtualizer with the filtered items
const arr = Array.from(items());
setComboboxItems(arr);
<Combobox.Listbox<T>
ref={(el) => {
listboxRef = el;
}}
style={{
height: props.height,
width: "100%",
overflow: "auto",
"overflow-y": "auto",
}}
class={styles.listbox}
scrollToItem={(key) => {
const idx = comboboxItems().findIndex(
(option) => option.rawValue.value === key,
);
virtualizer().scrollToIndex(idx);
}}
>
{(items) => {
// Update the virtualizer with the filtered items
const arr = Array.from(items());
setComboboxItems(arr);
return (
return (
<Switch>
<Match when={props.loading}>
{props.loadingComponent ?? (
<div class="flex w-full justify-center py-2">
<Loader />
</div>
)}
</Match>
<Match when={!props.loading}>
<div
style={{
height: `${virtualizer().getTotalSize()}px`,
@@ -165,17 +185,19 @@ export function Search<T extends Option>(props: SearchProps<T>) {
transform: `translateY(${virtualRow.start}px)`,
}}
>
{props.renderItem(item.rawValue)}
{props.renderItem(item.rawValue, {
disabled: item.disabled,
})}
</Combobox.Item>
);
}}
</For>
</div>
);
}}
</Combobox.Listbox>
</Combobox.Content>
</Combobox.Portal>
</Match>
</Switch>
);
}}
</Combobox.Listbox>
</Combobox>
);
}

View File

@@ -0,0 +1,20 @@
.trigger {
@apply rounded-md bg-inv-4 w-full min-h-11;
&:focus,
&:hover {
@apply outline outline-def-1 outline-1;
background:
linear-gradient(
90deg,
var(--clr-bg-inv-acc-3, #2c4347) 0%,
var(--clr-bg-inv-acc-2, #4f747a) 100%
),
var(--clr-bg-inv-4, #203637);
box-shadow: 0 0 0 2px var(--clr-bg-inv-acc-4, #162324) inset;
}
&.open {
@apply bg-inv-acc-4;
}
}

View File

@@ -0,0 +1,62 @@
import { Meta, StoryObj } from "@kachurun/storybook-solid";
import { TagSelect, TagSelectProps } from "./TagSelect";
import { Tag } from "../Tag/Tag";
import Icon from "../Icon/Icon";
import { createSignal } from "solid-js";
const meta = {
title: "Components/Custom/SelectStepper",
component: TagSelect,
} satisfies Meta<TagSelectProps<string>>;
export default meta;
interface Item {
value: string;
label: string;
}
type Story = StoryObj<TagSelectProps<Item>>;
const Item = (item: Item) => (
<Tag
inverted
icon={(tag) => (
<Icon icon={"Machine"} size="0.5rem" inverted={tag.inverted} />
)}
>
{item.label}
</Tag>
);
export const Default: Story = {
args: {
renderItem: Item,
label: "Peer",
options: [
{ value: "foo", label: "Foo" },
{ value: "bar", label: "Bar" },
{ value: "baz", label: "Baz" },
{ value: "qux", label: "Qux" },
{ value: "quux", label: "Quux" },
{ value: "corge", label: "Corge" },
{ value: "grault", label: "Grault" },
],
} satisfies Partial<TagSelectProps<Item>>,
render: (args: TagSelectProps<Item>) => {
const [state, setState] = createSignal<Item[]>([]);
return (
<TagSelect<Item>
{...args}
values={state()}
onClick={() => {
console.log("Clicked, current values:");
setState(() => [
{ value: "baz", label: "Baz" },
{ value: "qux", label: "Qux" },
]);
}}
/>
);
},
};

View File

@@ -0,0 +1,85 @@
import Icon from "../Icon/Icon";
import { Typography } from "../Typography/Typography";
import { For, JSX, Show } from "solid-js";
import styles from "./TagSelect.module.css";
import { Combobox } from "@kobalte/core/combobox";
import { Button } from "../Button/Button";
// Base props common to both modes
export interface TagSelectProps<T> {
onClick: () => void;
label: string;
values: T[];
options: T[];
renderItem: (item: T) => JSX.Element;
}
/**
* Shallowly interactive field for selecting multiple tags / machines.
* It does only handle click and focus interactions
* Displays the selected items as tags
*/
export function TagSelect<T extends { value: unknown }>(
props: TagSelectProps<T>,
) {
const optionValue = "value";
return (
<div class="flex flex-col gap-1.5">
<div class="flex w-full items-center gap-2 px-1.5 py-0">
<Typography
hierarchy="label"
weight="medium"
class="flex gap-2 uppercase"
size="xs"
inverted
color="secondary"
>
{props.label}
</Typography>
<Icon icon="Info" color="tertiary" inverted size={11} />
<Button
icon="Settings"
hierarchy="primary"
ghost
class="ml-auto"
size="xs"
/>
</div>
<Combobox<T>
multiple
optionValue={optionValue}
value={props.values}
options={props.options}
allowsEmptyCollection
class="w-full"
>
<Combobox.Control<T> aria-label="Fruits">
{(state) => {
return (
<Combobox.Trigger
tabIndex={1}
class={styles.trigger}
onClick={props.onClick}
>
<div class="flex flex-wrap items-center gap-2 px-2 py-3">
<Icon icon="Search" color="quaternary" inverted />
<Show when={state.selectedOptions().length === 0}>
<Typography
color="tertiary"
inverted
hierarchy="body"
size="s"
>
Select
</Typography>
</Show>
<For each={state.selectedOptions()}>{props.renderItem}</For>
</div>
</Combobox.Trigger>
);
}}
</Combobox.Control>
</Combobox>
</div>
);
}

View File

@@ -1,7 +1,3 @@
.sidebar {
@apply w-60 border-none z-10;
.body {
@apply pt-4 pb-3 px-2;
}
@apply w-60 border-none z-10 h-full flex flex-col;
}

View File

@@ -2,6 +2,7 @@ import styles from "./Sidebar.module.css";
import { SidebarHeader } from "@/src/components/Sidebar/SidebarHeader";
import { SidebarBody } from "@/src/components/Sidebar/SidebarBody";
import cx from "classnames";
import { splitProps } from "solid-js";
export interface LinkProps {
path: string;
@@ -19,10 +20,12 @@ export interface SidebarProps {
}
export const Sidebar = (props: SidebarProps) => {
const [bodyProps] = splitProps(props, ["staticSections"]);
return (
<div class={cx(styles.sidebar, props.class)}>
<SidebarHeader />
<SidebarBody class={cx(styles.body)} {...props} />
<SidebarBody {...bodyProps} />
</div>
);
};

View File

@@ -3,12 +3,13 @@ import { A } from "@solidjs/router";
import { Accordion } from "@kobalte/core/accordion";
import Icon from "../Icon/Icon";
import { Typography } from "@/src/components/Typography/Typography";
import { For, useContext } from "solid-js";
import { For, Show, useContext } from "solid-js";
import { MachineStatus } from "@/src/components/MachineStatus/MachineStatus";
import { buildMachinePath, useClanURI } from "@/src/hooks/clan";
import { useMachineStateQuery } from "@/src/hooks/queries";
import { SidebarProps } from "./Sidebar";
import { ClanContext } from "@/src/routes/Clan/Clan";
import { Button } from "../Button/Button";
import { useClanContext } from "@/src/routes/Clan/Clan";
interface MachineProps {
clanURI: string;
@@ -58,10 +59,7 @@ const MachineRoute = (props: MachineProps) => {
export const SidebarBody = (props: SidebarProps) => {
const clanURI = useClanURI();
const ctx = useContext(ClanContext);
if (!ctx) {
throw new Error("ClanContext not found");
}
const ctx = useClanContext();
const sectionLabels = (props.staticSections || []).map(
(section) => section.title,
@@ -71,6 +69,15 @@ export const SidebarBody = (props: SidebarProps) => {
// we want them all to be open by default
const defaultAccordionValues = ["your-machines", ...sectionLabels];
const machines = () => {
if (!ctx.machinesQuery.isSuccess) {
return {};
}
const result = ctx.machinesQuery.data;
return Object.keys(result).length > 0 ? result : undefined;
};
return (
<div class="sidebar-body">
<Accordion
@@ -100,18 +107,42 @@ export const SidebarBody = (props: SidebarProps) => {
</Accordion.Trigger>
</Accordion.Header>
<Accordion.Content class="content">
<nav>
<For each={Object.entries(ctx.machinesQuery.data || {})}>
{([id, machine]) => (
<MachineRoute
clanURI={clanURI}
machineID={id}
name={machine.name || id}
serviceCount={0}
/>
)}
</For>
</nav>
<Show
when={machines()}
fallback={
<div class="flex w-full flex-col items-center justify-center gap-2.5">
<Typography
hierarchy="body"
size="s"
weight="medium"
inverted
>
No machines yet
</Typography>
<Button
hierarchy="primary"
size="s"
startIcon="Machine"
onClick={() => ctx.setShowAddMachine(true)}
>
Add machine
</Button>
</div>
}
>
<nav>
<For each={Object.entries(machines()!)}>
{([id, machine]) => (
<MachineRoute
clanURI={clanURI}
machineID={id}
name={machine.name || id}
serviceCount={0}
/>
)}
</For>
</nav>
</Show>
</Accordion.Content>
</Accordion.Item>

View File

@@ -3,12 +3,12 @@ import Icon from "@/src/components/Icon/Icon";
import { DropdownMenu } from "@kobalte/core/dropdown-menu";
import { useNavigate } from "@solidjs/router";
import { Typography } from "../Typography/Typography";
import { createSignal, For, Show, Suspense, useContext } from "solid-js";
import { createSignal, For, Show, Suspense } from "solid-js";
import { navigateToOnboarding } from "@/src/hooks/clan";
import { setActiveClanURI } from "@/src/stores/clan";
import { Button } from "../Button/Button";
import { ClanContext } from "@/src/routes/Clan/Clan";
import { ClanSettingsModal } from "@/src/modals/ClanSettingsModal/ClanSettingsModal";
import { useClanContext } from "@/src/routes/Clan/Clan";
export const SidebarHeader = () => {
const navigate = useNavigate();
@@ -17,11 +17,7 @@ export const SidebarHeader = () => {
const [showSettings, setShowSettings] = createSignal(false);
// get information about the current active clan
const ctx = useContext(ClanContext);
if (!ctx) {
throw new Error("SidebarContext not found");
}
const ctx = useClanContext();
const clanChar = () =>
ctx?.activeClanQuery?.data?.details.name.charAt(0).toUpperCase();

View File

@@ -1,10 +1,10 @@
div.sidebar-pane {
@apply border-none z-10;
@apply flex flex-col border-none z-20 h-full;
animation: sidebarPaneShow 250ms ease-in forwards;
&.open {
@apply w-60;
@apply w-72;
}
&.closing {
@@ -90,7 +90,7 @@ div.sidebar-pane {
@apply opacity-100;
}
100% {
@apply w-60;
@apply w-72;
}
}

View File

@@ -9,7 +9,7 @@ export interface SidebarPaneProps {
class?: string;
title: string;
onClose: () => void;
subHeader?: () => JSX.Element;
subHeader?: JSX.Element;
children: JSX.Element;
}
@@ -43,7 +43,7 @@ export const SidebarPane = (props: SidebarPaneProps) => {
</KButton>
</div>
<Show when={props.subHeader}>
<div class="sub-header">{props.subHeader!()}</div>
<div class="sub-header">{props.subHeader}</div>
</Show>
<div class="body">{props.children}</div>
</div>

View File

@@ -1,5 +1,5 @@
div.sidebar-section {
@apply flex flex-col gap-2 w-full h-fit;
@apply flex flex-col gap-2 w-full h-full;
& > div.header {
@apply flex items-center justify-between px-1.5;

View File

@@ -17,7 +17,6 @@ export const SidebarSection = (props: SidebarSectionProps) => {
hierarchy="label"
size="xs"
family="mono"
weight="light"
transform="uppercase"
color="tertiary"
inverted={true}

View File

@@ -73,7 +73,6 @@ export function SidebarSectionForm<
hierarchy="label"
size="xs"
family="mono"
weight="light"
transform="uppercase"
color="tertiary"
inverted

View File

@@ -1,6 +1,6 @@
import { createSignal, Show } from "solid-js";
import { Button } from "@/src/components/Button/Button";
import { InstallModal } from "@/src/workflows/Install/install";
import { InstallModal } from "@/src/workflows/InstallMachine/InstallMachine";
import { useMachineName } from "@/src/hooks/clan";
import { useMachineStateQuery } from "@/src/hooks/queries";
import styles from "./SidebarSectionInstall.module.css";

View File

@@ -19,7 +19,9 @@ span.tag {
&.has-action {
@apply pr-1.5;
}
&.is-interactive {
&:hover {
@apply bg-def-acc-3;
}

View File

@@ -1,6 +1,7 @@
import { Tag, TagProps } from "@/src/components/Tag/Tag";
import { Meta, type StoryContext, StoryObj } from "@kachurun/storybook-solid";
import { expect, fn } from "storybook/test";
import { fn } from "storybook/test";
import Icon from "../Icon/Icon";
const meta: Meta<TagProps> = {
title: "Components/Tag",
@@ -13,27 +14,44 @@ type Story = StoryObj<TagProps>;
export const Default: Story = {
args: {
label: "Label",
children: "Label",
},
};
const IconAction = ({
inverted,
handleActionClick,
}: {
inverted: boolean;
handleActionClick: () => void;
}) => (
<Icon
role="button"
icon={"Close"}
size="0.5rem"
onClick={() => {
console.log("icon clicked");
handleActionClick();
fn();
}}
inverted={inverted}
/>
);
export const WithAction: Story = {
args: {
...Default.args,
action: {
icon: "Close",
onClick: fn(),
},
icon: IconAction,
interactive: true,
},
play: async ({ canvas, step, userEvent, args }: StoryContext) => {
await userEvent.click(canvas.getByRole("button"));
await expect(args.action.onClick).toHaveBeenCalled();
// await expect(args.icon.onClick).toHaveBeenCalled();
},
};
export const Inverted: Story = {
args: {
label: "Label",
children: "Label",
inverted: true,
},
};

View File

@@ -2,18 +2,19 @@ import "./Tag.css";
import cx from "classnames";
import { Typography } from "@/src/components/Typography/Typography";
import { createSignal, Show } from "solid-js";
import Icon, { IconVariant } from "../Icon/Icon";
import { createSignal, JSX } from "solid-js";
export interface TagAction {
icon: IconVariant;
onClick: () => void;
interface IconActionProps {
inverted: boolean;
handleActionClick: () => void;
}
export interface TagProps {
label: string;
action?: TagAction;
export interface TagProps extends JSX.HTMLAttributes<HTMLSpanElement> {
children?: JSX.Element;
icon?: (state: IconActionProps) => JSX.Element;
inverted?: boolean;
interactive?: boolean;
class?: string;
}
export const Tag = (props: TagProps) => {
@@ -23,7 +24,6 @@ export const Tag = (props: TagProps) => {
const handleActionClick = () => {
setIsActive(true);
props.action?.onClick();
setTimeout(() => setIsActive(false), 150);
};
@@ -32,23 +32,18 @@ export const Tag = (props: TagProps) => {
class={cx("tag", {
inverted: inverted(),
active: isActive(),
"has-action": props.action,
"has-icon": props.icon,
"is-interactive": props.interactive,
class: props.class,
})}
aria-label={props.label}
aria-readonly={!props.action}
>
<Typography hierarchy="label" size="xs" inverted={inverted()}>
{props.label}
{props.children}
</Typography>
<Show when={props.action}>
<Icon
role="button"
icon={props.action!.icon}
size="0.5rem"
inverted={inverted()}
onClick={handleActionClick}
/>
</Show>
{props.icon?.({
inverted: inverted(),
handleActionClick,
})}
</span>
);
};

View File

@@ -15,7 +15,7 @@ export const TagGroup = (props: TagGroupProps) => {
return (
<div class={cx("tag-group", props.class, { inverted: inverted() })}>
<For each={props.labels}>
{(label) => <Tag label={label} inverted={inverted()} />}
{(label) => <Tag inverted={inverted()}>{label}</Tag>}
</For>
</div>
);

View File

@@ -1,9 +1,5 @@
/* Body */
.typography {
&.weight-light {
font-weight: 300;
}
&.weight-normal {
font-weight: 400;
}
@@ -71,6 +67,12 @@
line-height: normal;
letter-spacing: 0.008125rem;
}
&.size-xxs {
font-size: 0.75rem;
line-height: 1;
/* letter-spacing: 0.008125rem; */
}
}
&.family-mono {
@@ -93,6 +95,11 @@
line-height: normal;
letter-spacing: normal;
}
&.size-xxs {
font-size: 0.75rem;
line-height: 1;
/* letter-spacing: 0.008125rem; */
}
}
}

View File

@@ -6,7 +6,7 @@ import { Color, fgClass } from "@/src/components/colors";
export type Tag = "span" | "p" | "h1" | "h2" | "h3" | "h4" | "div";
export type Hierarchy = "body" | "title" | "headline" | "label" | "teaser";
export type Weight = "normal" | "medium" | "bold" | "light";
export type Weight = "normal" | "medium" | "bold";
export type Family = "regular" | "condensed" | "mono";
export type Transform = "uppercase" | "lowercase" | "capitalize";
@@ -87,7 +87,6 @@ const weightMap: Record<Weight, string> = {
normal: "weight-normal",
medium: "weight-medium",
bold: "weight-bold",
light: "weight-light",
};
interface _TypographyProps<H extends Hierarchy> {

View File

@@ -42,6 +42,7 @@ export const DefaultQueryClient = new QueryClient({
},
});
export type MachinesQuery = ReturnType<typeof useMachinesQuery>;
export const useMachinesQuery = (clanURI: string) => {
const client = useApiClient();
@@ -117,11 +118,32 @@ export const useMachineQuery = (clanURI: string, machineName: string) => {
}));
};
export type TagsQuery = ReturnType<typeof useTags>;
export const useTags = (clanURI: string) => {
const client = useApiClient();
return useQuery(() => ({
queryKey: ["clans", encodeBase64(clanURI), "tags"],
queryFn: async () => {
const apiCall = client.fetch("list_tags", {
flake: {
identifier: clanURI,
},
});
const result = await apiCall.result;
if (result.status === "error") {
throw new Error("Error fetching tags: " + result.errors[0].message);
}
return result.data;
},
}));
};
export const useMachineStateQuery = (clanURI: string, machineName: string) => {
const client = useApiClient();
return useQuery<MachineState>(() => ({
queryKey: ["clans", encodeBase64(clanURI), "machine", machineName, "state"],
refetchInterval: 1000 * 60, // poll every 60 seconds
staleTime: 60_000, // 1 minute stale time
queryFn: async () => {
const apiCall = client.fetch("get_machine_state", {
machine: {
@@ -456,3 +478,53 @@ export const useMachineGenerators = (
},
}));
};
export type ServiceModulesQuery = ReturnType<typeof useServiceModules>;
export type ServiceModules = SuccessData<"list_service_modules">;
export const useServiceModules = (clanUri: string) => {
const client = useApiClient();
return useQuery(() => ({
queryKey: ["clans", encodeBase64(clanUri), "service_modules"],
queryFn: async () => {
const call = client.fetch("list_service_modules", {
flake: {
identifier: clanUri,
},
});
const result = await call.result;
if (result.status === "error") {
// todo should we create some specific error types?
console.error("Error fetching clan details:", result.errors);
throw new Error(result.errors[0].message);
}
return result.data;
},
}));
};
export type ServiceInstancesQuery = ReturnType<typeof useServiceInstances>;
export type ServiceInstances = SuccessData<"list_service_instances">;
export const useServiceInstances = (clanUri: string) => {
const client = useApiClient();
return useQuery(() => ({
queryKey: ["clans", encodeBase64(clanUri), "service_instances"],
queryFn: async () => {
const call = client.fetch("list_service_instances", {
flake: {
identifier: clanUri,
},
});
const result = await call.result;
if (result.status === "error") {
// todo should we create some specific error types?
console.error("Error fetching clan details:", result.errors);
throw new Error(result.errors[0].message);
}
return result.data;
},
}));
};

View File

@@ -0,0 +1,15 @@
import { onCleanup } from "solid-js";
export function useClickOutside(
el: () => HTMLElement | undefined,
handler: (e: MouseEvent) => void,
) {
const listener = (e: MouseEvent) => {
const element = el();
if (element && !element.contains(e.target as Node)) {
handler(e);
}
};
document.addEventListener("mousedown", listener);
onCleanup(() => document.removeEventListener("mousedown", listener));
}

View File

@@ -10,6 +10,7 @@ import { SolidQueryDevtools } from "@tanstack/solid-query-devtools";
import { ApiClientProvider } from "./hooks/ApiClient";
import { callApi } from "./hooks/api";
import { DefaultQueryClient } from "@/src/hooks/queries";
import { Toaster } from "solid-toast";
const root = document.getElementById("app");
@@ -25,6 +26,8 @@ if (import.meta.env.DEV) {
render(
() => (
<ApiClientProvider client={{ fetch: callApi }}>
{/* Temporary solution */}
<Toaster toastOptions={{}} />
<QueryClientProvider client={DefaultQueryClient}>
{import.meta.env.DEV && <SolidQueryDevtools initialIsOpen={true} />}
<Router root={Layout}>{Routes}</Router>

View File

@@ -199,7 +199,7 @@ export const ClanSettingsModal = (props: ClanSettingsModalProps) => {
disabled={removeDisabled()}
onClick={onRemove}
>
Remove
Remove Clan
</Button>
</div>
</div>

View File

@@ -7,9 +7,38 @@
@apply min-w-96;
}
.sidebar {
@apply absolute left-4 top-10 w-60;
@apply min-h-96;
.sidebarContainer {
@apply absolute left-4 top-4 w-60 z-10;
height: calc(100vh - 2rem);
height: calc(100vh - 8rem);
animation: sidebarNoMachine 250ms ease-in-out;
&.machineSelected {
@apply top-16;
height: calc(100vh - 8rem);
animation: sidebarMachine 250ms ease-in-out;
}
}
@keyframes sidebarNoMachine {
0% {
@apply top-16;
height: calc(100vh - 8rem);
}
100% {
@apply top-4;
height: calc(100vh - 2rem);
}
}
@keyframes sidebarMachine {
0% {
@apply top-4;
height: calc(100vh - 2rem);
}
100% {
@apply top-16;
height: calc(100vh - 8rem);
}
}

View File

@@ -11,11 +11,13 @@ import {
useContext,
} from "solid-js";
import {
buildClanPath,
buildMachinePath,
maybeUseMachineName,
useClanURI,
useMachineName,
} from "@/src/hooks/clan";
import { CubeScene } from "@/src/scene/cubes";
import { CubeScene, setWorldMode, worldMode } from "@/src/scene/cubes";
import {
ClanDetails,
MachinesQueryResult,
@@ -23,19 +25,21 @@ import {
useClanListQuery,
useMachinesQuery,
} from "@/src/hooks/queries";
import { callApi } from "@/src/hooks/api";
import { clanURIs, setStore, store } from "@/src/stores/clan";
import { produce } from "solid-js/store";
import { Button } from "@/src/components/Button/Button";
import { Splash } from "@/src/scene/splash";
import cx from "classnames";
import styles from "./Clan.module.css";
import { Modal } from "@/src/components/Modal/Modal";
import { TextInput } from "@/src/components/Form/TextInput";
import { createForm, FieldValues, reset } from "@modular-forms/solid";
import { Sidebar } from "@/src/components/Sidebar/Sidebar";
import { UseQueryResult } from "@tanstack/solid-query";
import { ListClansModal } from "@/src/modals/ListClansModal/ListClansModal";
import {
ServiceWorkflow,
SubmitServiceHandler,
} from "@/src/workflows/Service/Service";
import { useApiClient } from "@/src/hooks/ApiClient";
import toast from "solid-toast";
import { AddMachine } from "@/src/workflows/AddMachine/AddMachine";
interface ClanContextProps {
clanURI: string;
@@ -46,45 +50,43 @@ interface ClanContextProps {
isLoading(): boolean;
isError(): boolean;
showAddMachine(): boolean;
setShowAddMachine(value: boolean): void;
}
class DefaultClanContext implements ClanContextProps {
public readonly clanURI: string;
function createClanContext(
clanURI: string,
machinesQuery: MachinesQueryResult,
activeClanQuery: UseQueryResult<ClanDetails>,
otherClanQueries: UseQueryResult<ClanDetails>[],
) {
const [showAddMachine, setShowAddMachine] = createSignal(false);
const allClansQueries = [activeClanQuery, ...otherClanQueries];
const allQueries = [machinesQuery, ...allClansQueries];
public readonly activeClanQuery: UseQueryResult<ClanDetails>;
public readonly otherClanQueries: UseQueryResult<ClanDetails>[];
public readonly allClansQueries: UseQueryResult<ClanDetails>[];
public readonly machinesQuery: MachinesQueryResult;
allQueries: UseQueryResult[];
constructor(
clanURI: string,
machinesQuery: MachinesQueryResult,
activeClanQuery: UseQueryResult<ClanDetails>,
otherClanQueries: UseQueryResult<ClanDetails>[],
) {
this.clanURI = clanURI;
this.machinesQuery = machinesQuery;
this.activeClanQuery = activeClanQuery;
this.otherClanQueries = otherClanQueries;
this.allClansQueries = [activeClanQuery, ...otherClanQueries];
this.allQueries = [machinesQuery, activeClanQuery, ...otherClanQueries];
}
isLoading(): boolean {
return this.allQueries.some((q) => q.isLoading);
}
isError(): boolean {
return this.activeClanQuery.isError;
}
return {
clanURI,
machinesQuery,
activeClanQuery,
otherClanQueries,
allClansQueries,
isLoading: () => allQueries.some((q) => q.isLoading),
isError: () => activeClanQuery.isError,
showAddMachine,
setShowAddMachine,
};
}
export const ClanContext = createContext<ClanContextProps>();
const ClanContext = createContext<ClanContextProps>();
export const useClanContext = () => {
const ctx = useContext(ClanContext);
if (!ctx) {
throw new Error("ClanContext not found");
}
return ctx;
};
export const Clan: Component<RouteSectionProps> = (props) => {
const clanURI = useClanURI();
@@ -103,122 +105,47 @@ export const Clan: Component<RouteSectionProps> = (props) => {
const machinesQuery = useMachinesQuery(clanURI);
const ctx = createClanContext(
clanURI,
machinesQuery,
activeClanQuery,
otherClanQueries,
);
return (
<ClanContext.Provider
value={
new DefaultClanContext(
clanURI,
machinesQuery,
activeClanQuery,
otherClanQueries,
)
}
>
<Sidebar class={cx(styles.sidebar)} />
<ClanContext.Provider value={ctx}>
<div
class={cx(styles.sidebarContainer, {
[styles.machineSelected]: useMachineName(),
})}
>
<Sidebar />
</div>
{props.children}
<ClanSceneController {...props} />
</ClanContext.Provider>
);
};
interface CreateFormValues extends FieldValues {
name: string;
}
interface MockProps {
onClose: () => void;
onSubmit: (formValues: CreateFormValues) => void;
}
const MockCreateMachine = (props: MockProps) => {
const [form, { Form, Field, FieldArray }] = createForm<CreateFormValues>();
return (
<Modal
open={true}
onClose={() => {
reset(form);
props.onClose();
}}
class={cx(styles.createModal)}
title="Create Machine"
>
<Form class="flex flex-col" onSubmit={props.onSubmit}>
<Field name="name">
{(field, props) => (
<>
<TextInput
{...field}
label="Name"
size="s"
required={true}
input={{ ...props, placeholder: "name", autofocus: true }}
/>
</>
)}
</Field>
<div class="mt-4 flex w-full items-center justify-end gap-4">
<Button size="s" hierarchy="secondary" onClick={props.onClose}>
Cancel
</Button>
<Button size="s" type="submit" hierarchy="primary" onClick={close}>
Create
</Button>
</div>
</Form>
</Modal>
);
};
const ClanSceneController = (props: RouteSectionProps) => {
const ctx = useContext(ClanContext);
if (!ctx) {
throw new Error("ClanContext not found");
}
const ctx = useClanContext();
const navigate = useNavigate();
const [dialogHandlers, setDialogHandlers] = createSignal<{
const [showService, setShowService] = createSignal(false);
const [currentPromise, setCurrentPromise] = createSignal<{
resolve: ({ id }: { id: string }) => void;
reject: (err: unknown) => void;
} | null>(null);
const onCreate = async (): Promise<{ id: string }> => {
return new Promise((resolve, reject) => {
setShowModal(true);
setDialogHandlers({ resolve, reject });
ctx.setShowAddMachine(true);
setCurrentPromise({ resolve, reject });
});
};
const sendCreate = async (values: CreateFormValues) => {
const api = callApi("create_machine", {
opts: {
clan_dir: {
identifier: ctx.clanURI,
},
machine: {
name: values.name,
},
},
});
const res = await api.result;
if (res.status === "error") {
// TODO: Handle displaying errors
console.error("Error creating machine:");
// Important: rejects the promise
throw new Error(res.errors[0].message);
}
// trigger a refetch of the machines query
ctx.machinesQuery.refetch();
return { id: values.name };
};
const [showModal, setShowModal] = createSignal(false);
const [loadingError, setLoadingError] = createSignal<
{ title: string; description: string } | undefined
>();
@@ -246,6 +173,8 @@ const ClanSceneController = (props: RouteSectionProps) => {
const selected = ids.values().next().value;
if (selected) {
navigate(buildMachinePath(ctx.clanURI, selected));
} else {
navigate(buildClanPath(ctx.clanURI));
}
};
@@ -265,27 +194,64 @@ const ClanSceneController = (props: RouteSectionProps) => {
}),
);
const client = useApiClient();
const handleSubmitService: SubmitServiceHandler = async (
instance,
action,
) => {
console.log(action, "Instance", instance);
if (action !== "create") {
toast.error("Only creating new services is supported");
return;
}
const call = client.fetch("create_service_instance", {
flake: {
identifier: ctx.clanURI,
},
module_ref: instance.module,
roles: instance.roles,
});
const result = await call.result;
if (result.status === "error") {
toast.error("Error creating service instance");
console.error("Error creating service instance", result.errors);
}
toast.success("Created");
setShowService(false);
setWorldMode("select");
};
createEffect(
on(worldMode, (mode) => {
if (mode === "service") {
setShowService(true);
} else {
// TODO: request soft close instead of forced close
setShowService(false);
}
}),
);
return (
<>
<Show when={loadingError()}>
<ListClansModal error={loadingError()} />
</Show>
<Show when={showModal()}>
<MockCreateMachine
onClose={() => {
setShowModal(false);
dialogHandlers()?.reject(new Error("User cancelled"));
}}
onSubmit={async (values) => {
try {
const result = await sendCreate(values);
dialogHandlers()?.resolve(result);
setShowModal(false);
} catch (err) {
dialogHandlers()?.reject(err);
setShowModal(false);
<Show when={ctx.showAddMachine()}>
<AddMachine
onCreated={async (id) => {
const promise = currentPromise();
if (promise) {
await ctx.machinesQuery.refetch();
promise.resolve({ id });
setCurrentPromise(null);
}
}}
onClose={() => {
ctx.setShowAddMachine(false);
}}
/>
</Show>
<div
@@ -301,22 +267,39 @@ const ClanSceneController = (props: RouteSectionProps) => {
onSelect={onMachineSelect}
isLoading={ctx.isLoading()}
cubesQuery={ctx.machinesQuery}
toolbarPopup={
<Show when={showService()}>
<ServiceWorkflow
handleSubmit={handleSubmitService}
onClose={() => {
setShowService(false);
setWorldMode("select");
currentPromise()?.resolve({ id: "0" });
}}
/>
</Show>
}
onCreate={onCreate}
clanURI={ctx.clanURI}
sceneStore={() => store.sceneData?.[ctx.clanURI]}
setMachinePos={(machineId: string, pos: [number, number]) => {
setMachinePos={(machineId: string, pos: [number, number] | null) => {
console.log("calling setStore", machineId, pos);
setStore(
produce((s) => {
if (!s.sceneData) {
s.sceneData = {};
}
if (!s.sceneData[ctx.clanURI]) {
s.sceneData[ctx.clanURI] = {};
}
if (!s.sceneData[ctx.clanURI][machineId]) {
s.sceneData[ctx.clanURI][machineId] = { position: pos };
if (!s.sceneData) s.sceneData = {};
if (!s.sceneData[ctx.clanURI]) s.sceneData[ctx.clanURI] = {};
if (pos === null) {
// Remove the machine entry if pos is null
Reflect.deleteProperty(s.sceneData[ctx.clanURI], machineId);
if (Object.keys(s.sceneData[ctx.clanURI]).length === 0) {
Reflect.deleteProperty(s.sceneData, ctx.clanURI);
}
} else {
s.sceneData[ctx.clanURI][machineId].position = pos;
// Set or update the machine position
s.sceneData[ctx.clanURI][machineId] = { position: pos };
}
}),
);

View File

@@ -1,6 +1,5 @@
.sidebarPane {
@apply absolute left-[16.5rem] top-12 w-64;
@apply min-h-96;
.sidebarPaneContainer {
@apply absolute left-[16.5rem] top-4 w-64 z-20;
height: calc(100vh - 10rem);
height: calc(100vh - 2rem);
}

View File

@@ -9,7 +9,6 @@ import { callApi } from "@/src/hooks/api";
import { SidebarMachineStatus } from "@/src/components/Sidebar/SidebarMachineStatus";
import { SidebarSectionInstall } from "@/src/components/Sidebar/SidebarSectionInstall";
import cx from "classnames";
import styles from "./Machine.module.css";
export const Machine = (props: RouteSectionProps) => {
@@ -21,7 +20,8 @@ export const Machine = (props: RouteSectionProps) => {
navigateToClan(navigate, clanURI);
};
const sidebarPane = (machineName: string) => {
const sections = () => {
const machineName = useMachineName();
const machineQuery = useMachineQuery(clanURI, machineName);
// we have to update the whole machine model rather than just the sub fields that were changed
@@ -52,24 +52,35 @@ export const Machine = (props: RouteSectionProps) => {
const sectionProps = { clanURI, machineName, onSubmit, machineQuery };
return (
<SidebarPane
class={cx(styles.sidebarPane)}
title={machineName}
onClose={onClose}
subHeader={() => (
<SidebarMachineStatus clanURI={clanURI} machineName={machineName} />
)}
>
<SidebarSectionInstall clanURI={clanURI} machineName={machineName} />
<>
<SidebarSectionInstall
clanURI={clanURI}
machineName={useMachineName()}
/>
<SectionGeneral {...sectionProps} />
<SectionTags {...sectionProps} />
</SidebarPane>
</>
);
};
return (
<Show when={useMachineName()} keyed>
{sidebarPane(useMachineName())}
<Show when={useMachineName()}>
<div class={styles.sidebarPaneContainer}>
<SidebarPane
title={useMachineName()}
onClose={onClose}
subHeader={
<Show when={useMachineName()} keyed>
<SidebarMachineStatus
clanURI={clanURI}
machineName={useMachineName()}
/>
</Show>
}
>
{sections()}
</SidebarPane>
</div>
</Show>
);
};

View File

@@ -163,7 +163,7 @@ const welcome = (props: {
loading={loading()}
onClick={selectFolder}
>
Select folder
Select existing Clan
</Button>
</div>
);

View File

@@ -5,12 +5,13 @@ import { SceneData } from "../stores/clan";
import { MachinesQueryResult } from "../hooks/queries";
import { ObjectRegistry } from "./ObjectRegistry";
import { renderLoop } from "./RenderLoop";
import { highlightGroups } from "./highlightStore";
function keyFromPos(pos: [number, number]): string {
return `${pos[0]},${pos[1]}`;
}
const CUBE_SPACING = 2;
const CUBE_SPACING = 1;
export class MachineManager {
public machines = new Map<string, MachineRepr>();
@@ -25,50 +26,75 @@ export class MachineManager {
machinePositionsSignal: Accessor<SceneData>,
machinesQueryResult: MachinesQueryResult,
selectedIds: Accessor<Set<string>>,
setMachinePos: (id: string, position: [number, number]) => void,
setMachinePos: (id: string, position: [number, number] | null) => void,
camera: THREE.Camera,
) {
this.machinePositionsSignal = machinePositionsSignal;
this.disposeRoot = createRoot((disposeEffects) => {
createEffect(() => {
const machines = machinePositionsSignal();
Object.entries(machines).forEach(([id, data]) => {
const machineRepr = new MachineRepr(
scene,
registry,
new THREE.Vector2(data.position[0], data.position[1]),
id,
selectedIds,
);
this.machines.set(id, machineRepr);
scene.add(machineRepr.group);
});
renderLoop.requestRender();
});
// Push positions of previously existing machines to the scene
// TODO: Maybe we should do this in some post query hook?
//
// Effect 1: sync query → store (positions)
//
createEffect(() => {
if (!machinesQueryResult.data) return;
const actualMachines = Object.keys(machinesQueryResult.data);
const actualIds = Object.keys(machinesQueryResult.data);
const machinePositions = machinePositionsSignal();
const placed: Set<string> = machinePositions
? new Set(Object.keys(machinePositions))
: new Set();
const nonPlaced = actualMachines.filter((m) => !placed.has(m));
// Push not explizitly placed machines to the scene
// TODO: Make the user place them manually
// We just calculate some next free position
for (const id of nonPlaced) {
console.log("adding", id);
const position = this.nextGridPos();
setMachinePos(id, position);
// Remove stale
for (const id of Object.keys(machinePositions)) {
if (!actualIds.includes(id)) {
console.log("Removing stale machine", id);
setMachinePos(id, null);
}
}
// Add missing
for (const id of actualIds) {
if (!machinePositions[id]) {
const pos = this.nextGridPos();
setMachinePos(id, pos);
}
}
});
//
// Effect 2: sync store → scene
//
createEffect(() => {
const positions = machinePositionsSignal();
if (!positions) return;
// Remove machines from scene
for (const [id, repr] of this.machines) {
if (!Object.keys(positions).includes(id)) {
repr.dispose(scene);
this.machines.delete(id);
}
}
// Add or update machines
for (const [id, data] of Object.entries(positions)) {
let repr = this.machines.get(id);
if (!repr) {
repr = new MachineRepr(
scene,
registry,
new THREE.Vector2(data.position[0], data.position[1]),
id,
selectedIds,
highlightGroups,
camera,
);
this.machines.set(id, repr);
scene.add(repr.group);
} else {
repr.setPosition(
new THREE.Vector2(data.position[0], data.position[1]),
);
}
}
renderLoop.requestRender();
});
return disposeEffects;

View File

@@ -3,6 +3,9 @@ import { ObjectRegistry } from "./ObjectRegistry";
import { CSS2DObject } from "three/examples/jsm/renderers/CSS2DRenderer.js";
import { Accessor, createEffect, createRoot, on } from "solid-js";
import { renderLoop } from "./RenderLoop";
// @ts-expect-error: No types for troika-three-text
import { Text } from "troika-three-text";
import ttf from "../../.fonts/CommitMonoV143-VF.ttf";
// Constants
const BASE_SIZE = 0.9;
@@ -13,6 +16,7 @@ const CUBE_COLOR = 0xe2eff0;
const CUBE_EMISSIVE = 0x303030;
const CUBE_SELECTED_COLOR = 0x4b6767;
const HIGHLIGHT_COLOR = 0x00ee66;
const BASE_COLOR = 0xdbeaeb;
const BASE_EMISSIVE = 0x0c0c0c;
@@ -27,6 +31,7 @@ export class MachineRepr {
private baseMesh: THREE.Mesh;
private geometry: THREE.BoxGeometry;
private material: THREE.MeshPhongMaterial;
private camera: THREE.Camera;
private disposeRoot: () => void;
@@ -36,8 +41,11 @@ export class MachineRepr {
position: THREE.Vector2,
id: string,
selectedSignal: Accessor<Set<string>>,
highlightGroups: Record<string, Set<string>>, // Reactive store
camera: THREE.Camera,
) {
this.id = id;
this.camera = camera;
this.geometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
this.material = new THREE.MeshPhongMaterial({
color: CUBE_COLOR,
@@ -60,7 +68,6 @@ export class MachineRepr {
this.baseMesh.name = "base";
const label = this.createLabel(id);
this.cubeMesh.add(label);
const shadowPlaneMaterial = new THREE.MeshStandardMaterial({
color: BASE_COLOR, // any color you like
@@ -80,6 +87,7 @@ export class MachineRepr {
shadowPlane.position.set(0, BASE_HEIGHT + 0.0001, 0);
this.group = new THREE.Group();
this.group.add(label);
this.group.add(this.cubeMesh);
this.group.add(this.baseMesh);
this.group.add(shadowPlane);
@@ -89,23 +97,38 @@ export class MachineRepr {
this.disposeRoot = createRoot((disposeEffects) => {
createEffect(
on(selectedSignal, (selectedIds) => {
const isSelected = selectedIds.has(this.id);
// Update cube
(this.cubeMesh.material as THREE.MeshPhongMaterial).color.set(
isSelected ? CUBE_SELECTED_COLOR : CUBE_COLOR,
);
on(
[selectedSignal, () => Object.entries(highlightGroups)],
([selectedIds, groups]) => {
const isSelected = selectedIds.has(this.id);
const highlightedGroups = groups
.filter(([, ids]) => ids.has(this.id))
.map(([name]) => name);
// Update base
(this.baseMesh.material as THREE.MeshPhongMaterial).color.set(
isSelected ? BASE_SELECTED_COLOR : BASE_COLOR,
);
(this.baseMesh.material as THREE.MeshPhongMaterial).emissive.set(
isSelected ? BASE_SELECTED_EMISSIVE : BASE_EMISSIVE,
);
// console.log("MachineRepr effect", id, highlightedGroups);
// Update cube
(this.cubeMesh.material as THREE.MeshPhongMaterial).color.set(
isSelected ? CUBE_SELECTED_COLOR : CUBE_COLOR,
);
renderLoop.requestRender();
}),
// Update base
(this.baseMesh.material as THREE.MeshPhongMaterial).color.set(
isSelected ? BASE_SELECTED_COLOR : BASE_COLOR,
);
// TOOD: Find a different way to show both selected & highlighted
// I.e. via outline or pulsing
// selected > highlighted > normal
(this.baseMesh.material as THREE.MeshPhongMaterial).emissive.set(
highlightedGroups.length > 0 ? HIGHLIGHT_COLOR : 0x000000,
);
// (this.baseMesh.material as THREE.MeshPhongMaterial).emissive.set(
// isSelected ? BASE_SELECTED_EMISSIVE : BASE_EMISSIVE,
// );
renderLoop.requestRender();
},
),
);
return disposeEffects;
@@ -121,6 +144,11 @@ export class MachineRepr {
});
}
public setPosition(position: THREE.Vector2) {
this.group.position.set(position.x, 0, position.y);
renderLoop.requestRender();
}
private createCubeBase(
color: THREE.ColorRepresentation,
emissive: THREE.ColorRepresentation,
@@ -139,12 +167,27 @@ export class MachineRepr {
}
private createLabel(id: string) {
const div = document.createElement("div");
div.className = "machine-label";
div.textContent = id;
const label = new CSS2DObject(div);
label.position.set(0, CUBE_SIZE + 0.1, 0);
return label;
const text = new Text();
text.text = id;
text.font = ttf;
// text.font = ".fonts/CommitMonoV143-VF.woff2"; // <-- normal web font, not JSON
text.fontSize = 0.15; // relative to your cube size
text.color = 0x000000; // any THREE.Color
text.anchorX = "center"; // horizontal centering
text.anchorY = "bottom"; // baseline aligns to cube top
text.position.set(0, CUBE_SIZE + 0.05, 0);
// If you want it to always face camera:
text.userData.isLabel = true;
text.outlineWidth = 0.005;
text.outlineColor = 0x333333;
text.quaternion.copy(this.camera.quaternion);
// Re-render on text changes
text.sync(() => {
renderLoop.requestRender();
});
return text;
}
dispose(scene: THREE.Scene) {
@@ -154,6 +197,14 @@ export class MachineRepr {
this.geometry.dispose();
this.material.dispose();
for (const child of this.cubeMesh.children) {
if (child instanceof THREE.Mesh)
(child.material as THREE.Material).dispose();
if (child instanceof CSS2DObject) child.element.remove();
if (child instanceof THREE.Object3D) child.remove();
}
(this.baseMesh.material as THREE.Material).dispose();
}
}

View File

@@ -1,7 +1,7 @@
import { Scene, Camera, WebGLRenderer } from "three";
import { MapControls } from "three/examples/jsm/controls/MapControls.js";
import { CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer.js";
import * as THREE from "three";
/**
* Private class to manage the render loop
* @internal
@@ -93,6 +93,18 @@ class RenderLoop {
this.renderer.render(this.bgScene, this.bgCamera);
this.renderer.render(this.scene, this.camera);
this.scene.traverse((obj) => {
if (obj.userData.isLabel) {
(obj as THREE.Mesh).quaternion.copy(this.camera.quaternion);
}
// if (obj.userData.isLabel) {
// const camPos = new THREE.Vector3();
// this.camera.getWorldPosition(camPos);
// obj.lookAt(new THREE.Vector3(camPos.x, obj.position.y, camPos.z));
// }
});
this.labelRenderer.render(this.scene, this.camera);
}

View File

@@ -1,9 +1,10 @@
.cubes-scene-container {
width: 100%;
height: 100vh;
cursor: pointer;
}
/* <div class="absolute bottom-4 left-1/2 flex -translate-x-1/2 flex-col items-center">
<Show when={show()}> */
.toolbar-container {
@apply absolute bottom-10 z-10 w-full;
@apply flex justify-center items-center;

View File

@@ -1,4 +1,12 @@
import { createSignal, createEffect, onCleanup, onMount, on } from "solid-js";
import {
createSignal,
createEffect,
onCleanup,
onMount,
on,
JSX,
Show,
} from "solid-js";
import "./cubes.css";
import * as THREE from "three";
@@ -8,12 +16,36 @@ import { CSS2DRenderer } from "three/examples/jsm/renderers/CSS2DRenderer.js";
import { Toolbar } from "../components/Toolbar/Toolbar";
import { ToolbarButton } from "../components/Toolbar/ToolbarButton";
import { Divider } from "../components/Divider/Divider";
import { MachinesQueryResult } from "../hooks/queries";
import { MachinesQueryResult, useMachinesQuery } from "../hooks/queries";
import { SceneData } from "../stores/clan";
import { Accessor } from "solid-js";
import { renderLoop } from "./RenderLoop";
import { ObjectRegistry } from "./ObjectRegistry";
import { MachineManager } from "./MachineManager";
import cx from "classnames";
import { Portal } from "solid-js/web";
import { Menu } from "../components/ContextMenu/ContextMenu";
import { clearHighlight, setHighlightGroups } from "./highlightStore";
function intersectMachines(
event: MouseEvent,
renderer: THREE.WebGLRenderer,
camera: THREE.Camera,
machineManager: MachineManager,
raycaster: THREE.Raycaster,
): string[] {
const rect = renderer.domElement.getBoundingClientRect();
const mouse = new THREE.Vector2(
((event.clientX - rect.left) / rect.width) * 2 - 1,
-((event.clientY - rect.top) / rect.height) * 2 + 1,
);
raycaster.setFromCamera(mouse, camera);
const intersects = raycaster.intersectObjects(
Array.from(machineManager.machines.values().map((m) => m.group)),
);
return intersects.map((i) => i.object.userData.id);
}
function garbageCollectGroup(group: THREE.Group) {
for (const child of group.children) {
@@ -31,14 +63,45 @@ function garbageCollectGroup(group: THREE.Group) {
group.clear(); // Clear the group
}
// Can be imported by others via wrappers below
// Global signal for last clicked machine
const [lastClickedMachine, setLastClickedMachine] = createSignal<string | null>(
null,
);
// Exported so others could also emit the signal if needed
// And for testing purposes
export function emitMachineClick(id: string | null) {
setLastClickedMachine(id);
if (id) {
// Clear after a short delay to allow re-clicking the same machine
setTimeout(() => {
setLastClickedMachine(null);
}, 100);
}
}
/** Hook for components to subscribe */
export function useMachineClick() {
return lastClickedMachine;
}
/*Gloabl signal*/
const [worldMode, setWorldMode] = createSignal<
"default" | "select" | "service" | "create" | "move"
>("select");
export { worldMode, setWorldMode };
export function CubeScene(props: {
cubesQuery: MachinesQueryResult;
onCreate: () => Promise<{ id: string }>;
selectedIds: Accessor<Set<string>>;
onSelect: (v: Set<string>) => void;
sceneStore: Accessor<SceneData>;
setMachinePos: (machineId: string, pos: [number, number]) => void;
setMachinePos: (machineId: string, pos: [number, number] | null) => void;
isLoading: boolean;
clanURI: string;
toolbarPopup?: JSX.Element;
}) {
let container: HTMLDivElement;
let scene: THREE.Scene;
@@ -49,7 +112,7 @@ export function CubeScene(props: {
let controls: MapControls;
// Raycaster for clicking
const raycaster = new THREE.Raycaster();
let initBase: THREE.Mesh | undefined;
let actionBase: THREE.Mesh | undefined;
// Create background scene
const bgScene = new THREE.Scene();
@@ -63,8 +126,8 @@ export function CubeScene(props: {
const [positionMode, setPositionMode] = createSignal<"grid" | "circle">(
"grid",
);
const [worldMode, setWorldMode] = createSignal<"view" | "create">("view");
// Managed by controls
const [isDragging, setIsDragging] = createSignal(false);
const [cursorPosition, setCursorPosition] = createSignal<[number, number]>();
@@ -72,9 +135,13 @@ export function CubeScene(props: {
position: { x: 0, y: 0, z: 0 },
spherical: { radius: 0, theta: 0, phi: 0 },
});
// Context menu state
const [contextOpen, setContextOpen] = createSignal(false);
const [menuPos, setMenuPos] = createSignal<{ x: number; y: number }>();
const [menuIntersection, setMenuIntersection] = createSignal<string[]>([]);
// Grid configuration
const GRID_SIZE = 2;
const GRID_SIZE = 1;
const BASE_SIZE = 0.9; // Height of the cube above the ground
const CUBE_SIZE = BASE_SIZE / 1.5; //
@@ -87,8 +154,10 @@ export function CubeScene(props: {
const BASE_COLOR = 0xecfdff;
const BASE_EMISSIVE = 0x0c0c0c;
const CREATE_BASE_COLOR = 0x636363;
const ACTION_BASE_COLOR = 0x636363;
const CREATE_BASE_EMISSIVE = 0xc5fad7;
const MOVE_BASE_EMISSIVE = 0xb2d7ff;
function createCubeBase(
cube_pos: [number, number, number],
@@ -109,12 +178,6 @@ export function CubeScene(props: {
return base;
}
function toggleSelection(id: string) {
const next = new Set<string>();
next.add(id);
props.onSelect(next);
}
const initialCameraPosition = { x: 20, y: 20, z: 20 };
const initialSphericalCameraPosition = new THREE.Spherical();
initialSphericalCameraPosition.setFromVector3(
@@ -212,7 +275,8 @@ export function CubeScene(props: {
controls = new MapControls(camera, renderer.domElement);
controls.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.mouseButtons.RIGHT = null;
controls.enableRotate = false;
// controls.rotateSpeed = -0.8;
// controls.enableRotate = false;
controls.minZoom = 1.2;
controls.maxZoom = 3.5;
controls.addEventListener("change", () => {
@@ -236,6 +300,13 @@ export function CubeScene(props: {
bgCamera,
);
controls.addEventListener("start", (e) => {
setIsDragging(true);
});
controls.addEventListener("end", (e) => {
setIsDragging(false);
});
// Lighting
const ambientLight = new THREE.AmbientLight(0xd9f2f7, 0.72);
scene.add(ambientLight);
@@ -303,15 +374,15 @@ export function CubeScene(props: {
);
// Important create CubeBase depends on sharedBaseGeometry
initBase = createCubeBase(
actionBase = createCubeBase(
[1, BASE_HEIGHT / 2, 1],
1,
CREATE_BASE_COLOR,
ACTION_BASE_COLOR,
CREATE_BASE_EMISSIVE,
);
initBase.visible = false;
actionBase.visible = false;
scene.add(initBase);
scene.add(actionBase);
// const spherical = new THREE.Spherical();
// spherical.setFromVector3(camera.position);
@@ -340,9 +411,9 @@ export function CubeScene(props: {
createEffect(
on(worldMode, (mode) => {
if (mode === "create") {
initBase!.visible = true;
actionBase!.visible = true;
} else {
initBase!.visible = false;
actionBase!.visible = false;
}
renderLoop.requestRender();
}),
@@ -357,10 +428,11 @@ export function CubeScene(props: {
props.cubesQuery,
props.selectedIds,
props.setMachinePos,
camera,
);
// Click handler:
// - Select/deselects a cube in "view" mode
// - Select/deselects a cube in mode
// - Creates a new cube in "create" mode
const onClick = (event: MouseEvent) => {
if (worldMode() === "create") {
@@ -379,11 +451,21 @@ export function CubeScene(props: {
console.error("Error creating cube:", error);
})
.finally(() => {
if (initBase) initBase.visible = false;
if (actionBase) actionBase.visible = false;
setWorldMode("view");
setWorldMode("default");
});
}
if (worldMode() === "move") {
console.log("sanpped");
const currId = menuIntersection().at(0);
const pos = cursorPosition();
if (!currId || !pos) return;
props.setMachinePos(currId, pos);
setWorldMode("select");
clearHighlight("move");
}
const rect = renderer.domElement.getBoundingClientRect();
const mouse = new THREE.Vector2(
@@ -399,9 +481,14 @@ export function CubeScene(props: {
if (intersects.length > 0) {
console.log("Clicked on cube:", intersects);
const id = intersects[0].object.userData.id;
toggleSelection(id);
if (worldMode() === "select") props.onSelect(new Set<string>([id]));
emitMachineClick(id); // notify subscribers
} else {
props.onSelect(new Set<string>()); // Clear selection if clicked outside cubes
emitMachineClick(null);
if (worldMode() === "select") props.onSelect(new Set<string>());
}
};
@@ -432,18 +519,28 @@ export function CubeScene(props: {
renderLoop.requestRender();
};
const handleMouseDown = (e: MouseEvent) => {
if (e.button === 2) {
e.preventDefault();
e.stopPropagation();
const intersection = intersectMachines(
e,
renderer,
camera,
machineManager,
raycaster,
);
if (!intersection.length) return;
setMenuIntersection(intersection);
setMenuPos({ x: e.clientX, y: e.clientY });
setContextOpen(true);
}
};
renderer.domElement.addEventListener("mousedown", handleMouseDown);
renderer.domElement.addEventListener("mousemove", onMouseMove);
window.addEventListener("resize", handleResize);
// For debugging,
// TODO: Remove in production
window.addEventListener(
"contextmenu",
(e) => {
e.stopPropagation();
},
{ capture: true },
);
// Initial render
renderLoop.requestRender();
@@ -470,12 +567,12 @@ export function CubeScene(props: {
renderer.domElement.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("resize", handleResize);
if (initBase) {
initBase.geometry.dispose();
if (Array.isArray(initBase.material)) {
initBase.material.forEach((material) => material.dispose());
if (actionBase) {
actionBase.geometry.dispose();
if (Array.isArray(actionBase.material)) {
actionBase.material.forEach((material) => material.dispose());
} else {
initBase.material.dispose();
actionBase.material.dispose();
}
}
@@ -491,10 +588,18 @@ export function CubeScene(props: {
renderLoop.requestRender();
};
const onMouseMove = (event: MouseEvent) => {
if (worldMode() !== "create") return;
if (!initBase) return;
if (!(worldMode() === "create" || worldMode() === "move")) return;
if (!actionBase) return;
initBase.visible = true;
console.log("Mouse move in create/move mode");
actionBase.visible = true;
(actionBase.material as THREE.MeshPhongMaterial).emissive.set(
worldMode() === "create" ? CREATE_BASE_EMISSIVE : MOVE_BASE_EMISSIVE,
);
// Calculate mouse position in normalized device coordinates
// (-1 to +1) for both components
const rect = renderer.domElement.getBoundingClientRect();
const mouse = new THREE.Vector2(
@@ -505,6 +610,7 @@ export function CubeScene(props: {
const intersects = raycaster.intersectObject(floor);
if (intersects.length > 0) {
const point = intersects[0].point;
// Snap to grid
const snapped = new THREE.Vector3(
Math.round(point.x / GRID_SIZE) * GRID_SIZE,
@@ -512,35 +618,76 @@ export function CubeScene(props: {
Math.round(point.z / GRID_SIZE) * GRID_SIZE,
);
// Skip snapping if there's already a cube at this position
if (props.sceneStore()) {
const positions = Object.values(props.sceneStore());
const intersects = positions.some(
(p) => p.position[0] === snapped.x && p.position[1] === snapped.z,
);
if (intersects) {
return;
}
}
if (
Math.abs(initBase.position.x - snapped.x) > 0.01 ||
Math.abs(initBase.position.z - snapped.z) > 0.01
Math.abs(actionBase.position.x - snapped.x) > 0.01 ||
Math.abs(actionBase.position.z - snapped.z) > 0.01
) {
// Only request render if the position actually changed
initBase.position.set(snapped.x, 0, snapped.z);
actionBase.position.set(snapped.x, 0, snapped.z);
setCursorPosition([snapped.x, snapped.z]); // Update next position for cube creation
renderLoop.requestRender();
}
}
};
const handleMenuSelect = (mode: "move") => {
setWorldMode(mode);
setHighlightGroups({ move: new Set(menuIntersection()) });
console.log("Menu selected, new World mode", worldMode());
};
const machinesQuery = useMachinesQuery(props.clanURI);
return (
<>
<div class="cubes-scene-container" ref={(el) => (container = el)} />
<Show when={contextOpen()}>
<Portal mount={document.body}>
<Menu
onSelect={handleMenuSelect}
intersect={menuIntersection()}
x={menuPos()!.x - 10}
y={menuPos()!.y - 10}
close={() => setContextOpen(false)}
/>
</Portal>
</Show>
<div
class={cx(
"cubes-scene-container",
worldMode() === "default" && "cursor-no-drop",
worldMode() === "select" && "cursor-pointer",
worldMode() === "service" && "cursor-pointer",
worldMode() === "create" && "cursor-cell",
isDragging() && "!cursor-grabbing",
)}
ref={(el) => (container = el)}
/>
<div class="toolbar-container">
<div class="absolute bottom-full left-1/2 mb-2 -translate-x-1/2">
{props.toolbarPopup}
</div>
<Toolbar>
<ToolbarButton
description="Select machine"
name="Select"
icon="Cursor"
onClick={() => setWorldMode("view")}
selected={worldMode() === "view"}
onClick={() => setWorldMode("select")}
selected={worldMode() === "select"}
/>
<ToolbarButton
description="Create new machine"
name="new-machine"
icon="NewMachine"
disabled={positionMode() === "circle"}
onClick={onAddClick}
selected={worldMode() === "create"}
/>
@@ -548,24 +695,18 @@ export function CubeScene(props: {
<ToolbarButton
description="Add new Service"
name="modules"
icon="Modules"
icon="Services"
selected={worldMode() === "service"}
onClick={() => {
if (positionMode() === "grid") {
setPositionMode("circle");
setWorldMode("view");
grid.visible = false;
} else {
setPositionMode("grid");
grid.visible = true;
}
renderLoop.requestRender();
setWorldMode("service");
}}
/>
{/* <ToolbarButton
description="Delete Machine"
name="delete"
icon="Trash"
/> */}
<ToolbarButton
icon="Update"
name="Reload"
description="Reload machines"
onClick={() => machinesQuery.refetch()}
/>
</Toolbar>
</div>
</>

View File

@@ -0,0 +1,42 @@
// highlightStore.ts
import { createStore, produce } from "solid-js/store";
// groups: { [groupName: string]: Set<nodeId> }
const [highlightGroups, setHighlightGroups] = createStore<
Record<string, Set<string>>
>({});
// Add highlight
export function highlight(group: string, nodeId: string) {
setHighlightGroups(group, (prev = new Set()) => {
const next = new Set(prev);
next.add(nodeId);
return next;
});
}
// Remove highlight
export function unhighlight(group: string, nodeId: string) {
setHighlightGroups(group, (prev = new Set()) => {
const next = new Set(prev);
next.delete(nodeId);
return next;
});
}
// Clear group
export function clearHighlight(group: string) {
setHighlightGroups(group, () => new Set());
}
export function clearAllHighlights() {
setHighlightGroups(
produce((s) => {
for (const key of Object.keys(s)) {
Reflect.deleteProperty(s, key);
}
}),
);
}
export { highlightGroups, setHighlightGroups };

View File

@@ -0,0 +1,119 @@
import type { Meta, StoryContext, StoryObj } from "@kachurun/storybook-solid";
import { AddMachine } from "@/src/workflows/AddMachine/AddMachine";
import {
createMemoryHistory,
MemoryRouter,
RouteDefinition,
} from "@solidjs/router";
import { QueryClient, QueryClientProvider } from "@tanstack/solid-query";
import { ApiClientProvider, Fetcher } from "@/src/hooks/ApiClient";
import {
ApiCall,
OperationNames,
OperationResponse,
SuccessQuery,
} from "@/src/hooks/api";
type ResultDataMap = {
[K in OperationNames]: SuccessQuery<K>["data"];
};
const mockFetcher: Fetcher = <K extends OperationNames>(
name: K,
_args: unknown,
): ApiCall<K> => {
// TODO: Make this configurable for every story
const resultData: Partial<ResultDataMap> = {
list_machines: {
pandora: {
name: "pandora",
},
enceladus: {
name: "enceladus",
},
dione: {
name: "dione",
},
},
};
return {
uuid: "mock",
cancel: () => Promise.resolve(),
result: new Promise((resolve) => {
setTimeout(() => {
resolve({
op_key: "1",
status: "success",
data: resultData[name],
} as OperationResponse<K>);
}, 1500);
}),
};
};
const meta: Meta<typeof AddMachine> = {
title: "workflows/add-machine",
component: AddMachine,
decorators: [
(Story: StoryObj, context: StoryContext) => {
const Routes: RouteDefinition[] = [
{
path: "/clans/:clanURI",
component: () => (
<div class="w-[600px]">
<Story />
</div>
),
},
];
const history = createMemoryHistory();
history.set({ value: "/clans/dGVzdA==", replace: true });
const queryClient = new QueryClient();
return (
<ApiClientProvider client={{ fetch: mockFetcher }}>
<QueryClientProvider client={queryClient}>
<MemoryRouter
root={(props) => {
console.debug("Rendering MemoryRouter root with props:", props);
return props.children;
}}
history={history}
>
{Routes}
</MemoryRouter>
</QueryClientProvider>
</ApiClientProvider>
);
},
],
};
export default meta;
type Story = StoryObj<typeof AddMachine>;
export const General: Story = {
args: {},
};
export const Host: Story = {
args: {
initialStep: "host",
},
};
export const Tags: Story = {
args: {
initialStep: "tags",
},
};
export const Progress: Story = {
args: {
initialStep: "progress",
},
};

View File

@@ -0,0 +1,136 @@
import {
createStepper,
defineSteps,
StepperProvider,
useStepper,
} from "@/src/hooks/stepper";
import {
GeneralForm,
StepGeneral,
} from "@/src/workflows/AddMachine/StepGeneral";
import { Modal } from "@/src/components/Modal/Modal";
import cx from "classnames";
import { Dynamic } from "solid-js/web";
import { Show } from "solid-js";
import { Typography } from "@/src/components/Typography/Typography";
import { StepHost } from "@/src/workflows/AddMachine/StepHost";
import { StepTags } from "@/src/workflows/AddMachine/StepTags";
import { StepProgress } from "./StepProgress";
interface AddMachineStepperProps {
onDone: () => void;
}
const AddMachineStepper = (props: AddMachineStepperProps) => {
const stepSignal = useStepper<AddMachineSteps>();
return (
<Dynamic
component={stepSignal.currentStep().content}
onDone={props.onDone}
/>
);
};
export interface AddMachineProps {
onClose: () => void;
onCreated: (id: string) => void;
initialStep?: AddMachineSteps[number]["id"];
}
export interface AddMachineStoreType {
general: GeneralForm;
deploy: {
targetHost: string;
};
tags: {
tags: string[];
};
onCreated: (id: string) => void;
error?: string;
}
const steps = defineSteps([
{
id: "general",
title: "General",
content: StepGeneral,
},
{
id: "host",
title: "Host",
content: StepHost,
},
{
id: "tags",
title: "Tags",
content: StepTags,
},
{
id: "progress",
title: "Creating...",
content: StepProgress,
isSplash: true,
},
] as const);
export type AddMachineSteps = typeof steps;
export const AddMachine = (props: AddMachineProps) => {
const stepper = createStepper(
{
steps,
},
{
initialStep: props.initialStep || "general",
initialStoreData: { onCreated: props.onCreated },
},
);
const MetaHeader = () => {
const title = stepper.currentStep().title;
return (
<Show when={title}>
<Typography
hierarchy="label"
family="mono"
size="default"
weight="medium"
>
{title}
</Typography>
</Show>
);
};
const sizeClasses = () => {
const defaultClass = "max-w-3xl h-fit";
const currentStep = stepper.currentStep();
if (!currentStep) {
return defaultClass;
}
switch (currentStep.id) {
default:
return defaultClass;
}
};
return (
<StepperProvider stepper={stepper}>
<Modal
class={cx("w-screen", sizeClasses())}
title="Add Machine"
onClose={props.onClose}
open={true}
// @ts-expect-error some steps might not have
metaHeader={stepper.currentStep()?.title ? <MetaHeader /> : undefined}
// @ts-expect-error some steps might not have
disablePadding={stepper.currentStep()?.isSplash}
>
<AddMachineStepper onDone={() => props.onClose()} />
</Modal>
</StepperProvider>
);
};

View File

@@ -0,0 +1,176 @@
import { NextButton, StepLayout } from "@/src/workflows/Steps";
import * as v from "valibot";
import { getStepStore, useStepper } from "@/src/hooks/stepper";
import {
clearError,
createForm,
FieldValues,
getError,
getErrors,
setError,
SubmitHandler,
valiForm,
} from "@modular-forms/solid";
import {
AddMachineSteps,
AddMachineStoreType,
} from "@/src/workflows/AddMachine/AddMachine";
import { Fieldset } from "@/src/components/Form/Fieldset";
import { TextInput } from "@/src/components/Form/TextInput";
import { Divider } from "@/src/components/Divider/Divider";
import { TextArea } from "@/src/components/Form/TextArea";
import { Select } from "@/src/components/Select/Select";
import { Show } from "solid-js";
import { Alert } from "@/src/components/Alert/Alert";
import { useMachinesQuery } from "@/src/hooks/queries";
import { useClanURI } from "@/src/hooks/clan";
const PlatformOptions = [
{ label: "NixOS", value: "nixos" },
{ label: "Darwin", value: "darwin" },
];
const GeneralSchema = v.object({
name: v.pipe(
v.string("Name must be a string"),
v.nonEmpty("Please enter a machine name"),
v.regex(
new RegExp(/^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$/),
"Name must be a valid hostname e.g. alphanumeric characters and - only",
),
),
description: v.optional(v.string("Description must be a string")),
machineClass: v.pipe(v.string(), v.nonEmpty()),
});
export interface GeneralForm extends FieldValues {
machineClass: "nixos" | "darwin";
name: string;
description?: string;
}
export const StepGeneral = () => {
const stepSignal = useStepper<AddMachineSteps>();
const [store, set] = getStepStore<AddMachineStoreType>(stepSignal);
const clanURI = useClanURI();
const machines = useMachinesQuery(clanURI);
const machineNames = () => {
if (!machines.isSuccess) {
return [];
}
return Object.keys(machines.data || {});
};
const [formStore, { Form, Field }] = createForm<GeneralForm>({
validate: valiForm(GeneralSchema),
initialValues: { ...store.general, machineClass: "nixos" },
});
const handleSubmit: SubmitHandler<GeneralForm> = (values, event) => {
if (machineNames().includes(values.name)) {
setError(
formStore,
"name",
`A machine named '${values.name}' already exists. Please choose a different one.`,
);
return;
}
clearError(formStore, "name");
set("general", (s) => ({
...s,
...values,
}));
stepSignal.next();
};
const formError = () => {
const errors = getErrors(formStore);
return errors.name || errors.description || errors.machineClass;
};
return (
<Form onSubmit={handleSubmit} class="h-full">
<StepLayout
body={
<div class="flex flex-col gap-2">
<Show when={formError()}>
<Alert
type="error"
icon="WarningFilled"
title="Error"
description={formError()}
/>
</Show>
<Fieldset>
<Field name="name">
{(field, input) => (
<TextInput
{...field}
value={field.value}
label="Name"
required
orientation="horizontal"
input={{
...input,
placeholder: "A unique machine name.",
}}
validationState={
getError(formStore, "name") ? "invalid" : "valid"
}
/>
)}
</Field>
<Divider />
<Field name="description">
{(field, input) => (
<TextArea
{...field}
value={field.value}
label="Description"
orientation="horizontal"
input={{
...input,
placeholder: "A short description of the machine.",
}}
validationState={
getError(formStore, "description") ? "invalid" : "valid"
}
/>
)}
</Field>
</Fieldset>
<Fieldset>
<Field name="machineClass">
{(field, props) => (
<Select
zIndex={100}
{...props}
value={field.value}
error={field.error}
required
label={{
label: "Platform",
}}
options={PlatformOptions}
name={field.name}
/>
)}
</Field>
</Fieldset>
</div>
}
footer={
<div class="flex justify-end">
<NextButton type="submit" />
</div>
}
/>
</Form>
);
};

View File

@@ -0,0 +1,76 @@
import { BackButton, NextButton, StepLayout } from "@/src/workflows/Steps";
import * as v from "valibot";
import { getStepStore, useStepper } from "@/src/hooks/stepper";
import {
createForm,
getError,
SubmitHandler,
valiForm,
} from "@modular-forms/solid";
import {
AddMachineSteps,
AddMachineStoreType,
} from "@/src/workflows/AddMachine/AddMachine";
import { Fieldset } from "@/src/components/Form/Fieldset";
import { TextInput } from "@/src/components/Form/TextInput";
const HostSchema = v.object({
targetHost: v.pipe(v.string("Name must be a string")),
});
type HostForm = v.InferInput<typeof HostSchema>;
export const StepHost = () => {
const stepSignal = useStepper<AddMachineSteps>();
const [store, set] = getStepStore<AddMachineStoreType>(stepSignal);
const [formStore, { Form, Field }] = createForm<HostForm>({
validate: valiForm(HostSchema),
initialValues: store.deploy,
});
const handleSubmit: SubmitHandler<HostForm> = (values, event) => {
set("deploy", (s) => ({
...s,
...values,
}));
stepSignal.next();
};
return (
<Form onSubmit={handleSubmit} class="h-full">
<StepLayout
body={
<div class="flex flex-col gap-2">
<Fieldset>
<Field name="targetHost">
{(field, input) => (
<TextInput
{...field}
value={field.value}
label="Target"
orientation="horizontal"
input={{
...input,
placeholder: "root@flashinstaller.local",
}}
validationState={
getError(formStore, "targetHost") ? "invalid" : "valid"
}
/>
)}
</Field>
</Fieldset>
</div>
}
footer={
<div class="flex justify-between">
<BackButton />
<NextButton type="submit" />
</div>
}
/>
</Form>
);
};

View File

@@ -0,0 +1,40 @@
import { getStepStore, useStepper } from "@/src/hooks/stepper";
import {
AddMachineSteps,
AddMachineStoreType,
} from "@/src/workflows/AddMachine/AddMachine";
import { Loader } from "@/src/components/Loader/Loader";
import { Typography } from "@/src/components/Typography/Typography";
import { Show } from "solid-js";
import { Alert } from "@/src/components/Alert/Alert";
export interface StepProgressProps {
onDone: () => void;
}
export const StepProgress = (props: StepProgressProps) => {
const stepSignal = useStepper<AddMachineSteps>();
const [store, set] = getStepStore<AddMachineStoreType>(stepSignal);
return (
<div class="flex flex-col items-center justify-center gap-2.5 px-6 pb-7 pt-4">
<Show
when={store.error}
fallback={
<>
<Loader class="size-8" />
<Typography hierarchy="body" size="s" weight="medium" family="mono">
{store.general?.name} is being created
</Typography>
</>
}
>
<Alert
type="error"
title="There was an error"
description={store.error}
/>
</Show>
</div>
);
};

View File

@@ -0,0 +1,101 @@
import { BackButton, StepLayout } from "@/src/workflows/Steps";
import * as v from "valibot";
import { getStepStore, useStepper } from "@/src/hooks/stepper";
import { createForm, SubmitHandler, valiForm } from "@modular-forms/solid";
import {
AddMachineSteps,
AddMachineStoreType,
} from "@/src/workflows/AddMachine/AddMachine";
import { Fieldset } from "@/src/components/Form/Fieldset";
import { MachineTags } from "@/src/components/Form/MachineTags";
import { Button } from "@/src/components/Button/Button";
import { useApiClient } from "@/src/hooks/ApiClient";
import { useClanURI } from "@/src/hooks/clan";
const TagsSchema = v.object({
tags: v.array(v.string()),
});
type TagsForm = v.InferInput<typeof TagsSchema>;
export const StepTags = (props: { onDone: () => void }) => {
const stepSignal = useStepper<AddMachineSteps>();
const [store, set] = getStepStore<AddMachineStoreType>(stepSignal);
const [formStore, { Form, Field }] = createForm<TagsForm>({
validate: valiForm(TagsSchema),
initialValues: store.tags,
});
const apiClient = useApiClient();
const clanURI = useClanURI();
const handleSubmit: SubmitHandler<TagsForm> = async (values, event) => {
set("tags", (s) => ({
...s,
...values,
}));
const call = apiClient.fetch("create_machine", {
opts: {
clan_dir: {
identifier: clanURI,
},
machine: {
...store.general,
...store.tags,
deploy: store.deploy,
},
},
});
stepSignal.next();
const result = await call.result;
if (result.status == "error") {
// setError(result.errors[0].message);
}
if (result.status == "success") {
console.log("Machine creation was successful");
if (store.general) {
store.onCreated(store.general.name);
}
}
props.onDone();
};
return (
<Form onSubmit={handleSubmit} class="h-full">
<StepLayout
body={
<div class="flex flex-col gap-2">
<Fieldset>
<Field name="tags" type="string[]">
{(field, input) => (
<MachineTags
{...field}
required
orientation="horizontal"
defaultValue={field.value}
defaultOptions={[]}
input={input}
/>
)}
</Field>
</Fieldset>
</div>
}
footer={
<div class="flex justify-between">
<BackButton />
<Button hierarchy="primary" type="submit" endIcon="Flash">
Create Machine
</Button>
</div>
}
/>
</Form>
);
};

View File

@@ -1,5 +1,5 @@
import type { Meta, StoryContext, StoryObj } from "@kachurun/storybook-solid";
import { InstallModal } from "./install";
import { InstallModal } from "./InstallMachine";
import {
createMemoryHistory,
MemoryRouter,

View File

@@ -52,6 +52,7 @@ export interface InstallStoreType {
};
install: {
targetHost: string;
port?: string;
machineName: string;
mainDisk: string;
// ...TODO Vars
@@ -96,6 +97,8 @@ export const InstallModal = (props: InstallModalProps) => {
switch (currentStep.id) {
case "create:progress":
case "create:done":
case "install:progress":
case "install:done":
return currentStep.class;
default:

View File

@@ -1,5 +1,5 @@
import { defineSteps, useStepper } from "@/src/hooks/stepper";
import { InstallSteps } from "../install";
import { InstallSteps } from "../InstallMachine";
import { Button } from "@/src/components/Button/Button";
import { StepLayout } from "../../Steps";
import { NavSection } from "@/src/components/NavSection/NavSection";
@@ -13,7 +13,7 @@ const ChoiceLocalOrRemote = () => {
onClick={() => stepSignal.setActiveStep("local:choice")}
/>
<NavSection
label="The Machine is remote and i have ssh access to it"
label="The machine is remote and I have ssh access to it"
onClick={() => stepSignal.setActiveStep("install:address")}
/>
</div>

View File

@@ -6,7 +6,7 @@ import {
valiForm,
} from "@modular-forms/solid";
import * as v from "valibot";
import { InstallSteps, InstallStoreType } from "../install";
import { InstallSteps, InstallStoreType } from "../InstallMachine";
import { Fieldset } from "@/src/components/Form/Fieldset";
import { HostFileInput } from "@/src/components/Form/HostFileInput";
import { Select } from "@/src/components/Select/Select";
@@ -24,8 +24,8 @@ import cx from "classnames";
const Prose = () => (
<StepLayout
body={
<>
<div class="flex h-36 w-full flex-col justify-center gap-3 rounded-md px-4 py-6 text-fg-inv-1 outline-2 outline-bg-def-acc-3 bg-inv-4">
<div class="flex flex-col gap-4">
<div class="flex h-36 w-full flex-col justify-center gap-3 rounded-md p-4 text-fg-inv-1 outline-2 outline-bg-def-acc-3 bg-inv-4">
<div class="flex flex-col gap-3">
<Typography
hierarchy="label"
@@ -74,7 +74,7 @@ const Prose = () => (
</Typography>
</div>
</div>
</>
</div>
}
footer={<StepFooter nextText="start" />}
/>

View File

@@ -11,7 +11,11 @@ import {
import { Fieldset } from "@/src/components/Form/Fieldset";
import * as v from "valibot";
import { getStepStore, useStepper } from "@/src/hooks/stepper";
import { InstallSteps, InstallStoreType, PromptValues } from "../install";
import {
InstallSteps,
InstallStoreType,
PromptValues,
} from "../InstallMachine";
import { TextInput } from "@/src/components/Form/TextInput";
import { Alert } from "@/src/components/Alert/Alert";
import { createSignal, For, Match, Show, Switch } from "solid-js";
@@ -44,6 +48,12 @@ const ConfigureAdressSchema = v.object({
v.string("Please set a target host."),
v.nonEmpty("Please set a target host."),
),
port: v.optional(
v.pipe(
v.string(),
v.transform((val) => (val === "" ? undefined : val)),
),
),
});
type ConfigureAdressForm = v.InferInput<typeof ConfigureAdressSchema>;
@@ -56,6 +66,7 @@ const ConfigureAddress = () => {
validate: valiForm(ConfigureAdressSchema),
initialValues: {
targetHost: store.install?.targetHost,
port: store.install?.port,
},
});
@@ -69,7 +80,11 @@ const ConfigureAddress = () => {
event,
) => {
console.log("targetHost set", values);
set("install", (s) => ({ ...s, targetHost: values.targetHost }));
set("install", (s) => ({
...s,
targetHost: values.targetHost,
port: values.port,
}));
// Here you would typically trigger the ISO creation process
stepSignal.next();
@@ -81,10 +96,18 @@ const ConfigureAddress = () => {
return;
}
const portValue = getValue(formStore, "port");
const port = portValue ? parseInt(portValue, 10) : undefined;
setLoading(true);
const call = client.fetch("check_machine_ssh_login", {
remote: {
address,
...(port && { port }),
ssh_options: {
StrictHostKeyChecking: "no",
UserKnownHostsFile: "/dev/null",
},
},
});
const result = await call.result;
@@ -121,6 +144,25 @@ const ConfigureAddress = () => {
/>
)}
</Field>
<Field name="port">
{(field, props) => (
<TextInput
{...field}
label="SSH Port"
description="SSH port (default: 22)"
value={field.value}
orientation="horizontal"
validationState={
getError(formStore, "port") ? "invalid" : "valid"
}
input={{
...props,
placeholder: "22",
type: "number",
}}
/>
)}
</Field>
</Fieldset>
</div>
}
@@ -166,23 +208,41 @@ const CheckHardware = () => {
const client = useApiClient();
const [updatingHardwareReport, setUpdatingHardwareReport] =
createSignal(false);
const handleUpdateSummary = async () => {
// TODO: Debounce
const call = client.fetch("run_machine_hardware_info", {
target_host: {
address: store.install.targetHost,
},
opts: {
machine: {
flake: {
identifier: clanUri,
setUpdatingHardwareReport(true);
const port = store.install.port
? parseInt(store.install.port, 10)
: undefined;
try {
// TODO: Debounce
const call = client.fetch("run_machine_hardware_info", {
target_host: {
address: store.install.targetHost,
...(port && { port }),
ssh_options: {
StrictHostKeyChecking: "no",
UserKnownHostsFile: "/dev/null",
},
name: store.install.machineName,
},
},
});
await call.result;
hardwareQuery.refetch();
opts: {
machine: {
flake: {
identifier: clanUri,
},
name: store.install.machineName,
},
},
});
await call.result;
await hardwareQuery.refetch();
} finally {
setUpdatingHardwareReport(false);
}
};
const reportExists = () => hardwareQuery?.data?.hardware_config !== "none";
@@ -197,12 +257,12 @@ const CheckHardware = () => {
Hardware Report
</Typography>
<Button
disabled={hardwareQuery.isLoading}
disabled={hardwareQuery.isLoading || updatingHardwareReport()}
hierarchy="secondary"
startIcon="Report"
onClick={handleUpdateSummary}
class="flex gap-3"
loading={hardwareQuery.isFetching}
loading={hardwareQuery.isFetching || updatingHardwareReport()}
>
Update hardware report
</Button>
@@ -574,6 +634,10 @@ const InstallSummary = () => {
}));
await runGenerators.result; // Wait for the generators to run
const port = store.install.port
? parseInt(store.install.port, 10)
: undefined;
const runInstall = client.fetch("run_machine_install", {
opts: {
machine: {
@@ -585,6 +649,11 @@ const InstallSummary = () => {
},
target_host: {
address: store.install.targetHost,
...(port && { port }),
ssh_options: {
StrictHostKeyChecking: "no",
UserKnownHostsFile: "/dev/null",
},
},
});
set("install", (s) => ({
@@ -609,6 +678,14 @@ const InstallSummary = () => {
<Orienter orientation="horizontal">
<Display label="Address" value={store.install.targetHost} />
</Orienter>
{store.install.port && (
<>
<Divider orientation="horizontal" />
<Orienter orientation="horizontal">
<Display label="SSH Port" value={store.install.port} />
</Orienter>
</>
)}
</Fieldset>
<Fieldset legend="Disk">
<Orienter orientation="horizontal">
@@ -658,13 +735,13 @@ const InstallProgress = () => {
);
return (
<div class="relative flex size-full flex-col items-center justify-center bg-inv-4">
<div class="relative flex size-full flex-col items-center justify-end bg-inv-4">
<img
src="/logos/usb-stick-min.png"
alt="usb logo"
class="absolute top-2 z-0"
/>
<div class="z-10 mb-6 flex w-full max-w-md flex-col items-center gap-3 fg-inv-1">
<div class="z-10 mb-6 flex w-full max-w-md flex-col items-center gap-2 fg-inv-1">
<Typography
hierarchy="title"
size="default"
@@ -796,10 +873,12 @@ export const installSteps = [
id: "install:progress",
content: InstallProgress,
isSplash: true,
class: "max-w-[30rem] h-[18rem]",
},
{
id: "install:done",
content: InstallDone,
isSplash: true,
class: "max-w-[30rem] h-[18rem]",
},
] as const;

View File

@@ -0,0 +1,35 @@
.content {
@apply px-3 flex flex-col gap-5 py-6;
border: 1px solid #2e4a4b;
background:
linear-gradient(0deg, rgba(0, 0, 0, 0.2) 0%, rgba(0, 0, 0, 0.2) 100%),
linear-gradient(
180deg,
theme(colors.bg.inv.2) 0%,
theme(colors.bg.inv.3) 100%
);
box-shadow:
0 10px 15px -3px rgba(0, 0, 0, 0.1),
0 4px 6px -2px rgba(0, 0, 0, 0.05);
}
.header {
@apply py-2 pl-3 pr-2 flex gap-2.5 w-full items-center;
border-radius: 8px 8px 0 0;
border-bottom: 1px solid #2e4a4b;
}
.footer {
@apply py-3 px-4 flex justify-end w-full;
border-radius: 0 0 8px 8px;
border-top: 1px solid #2e4a4b;
}
.backgroundAlt {
background: linear-gradient(
90deg,
theme(colors.bg.inv.3) 0%,
theme(colors.bg.inv.4) 100%
);
}

Some files were not shown because too many files have changed in this diff Show More