Merge pull request 'Clan-app: Add loading animations & improve async data handling' (#1854) from hsjobeki/clan-core:hsjobeki-main into main

This commit is contained in:
clan-bot
2024-08-07 10:24:56 +00:00
15 changed files with 566 additions and 404 deletions

View File

@@ -40,7 +40,7 @@ def inspect_flake(flake_url: str | Path, machine_name: str) -> FlakeConfig:
system = config["system"] system = config["system"]
# Check if the machine exists # Check if the machine exists
machines: list[str] = list_nixos_machines(flake_url, False) machines: list[str] = list_nixos_machines(flake_url)
if machine_name not in machines: if machine_name not in machines:
raise ClanError( raise ClanError(
f"Machine {machine_name} not found in {flake_url}. Available machines: {', '.join(machines)}" f"Machine {machine_name} not found in {flake_url}. Available machines: {', '.join(machines)}"

View File

@@ -13,15 +13,13 @@ log = logging.getLogger(__name__)
@API.register @API.register
def list_inventory_machines( def list_inventory_machines(flake_url: str | Path) -> dict[str, Machine]:
flake_url: str | Path, debug: bool = False
) -> dict[str, Machine]:
inventory = load_inventory_eval(flake_url) inventory = load_inventory_eval(flake_url)
return inventory.machines return inventory.machines
@API.register @API.register
def list_nixos_machines(flake_url: str | Path, debug: bool = False) -> list[str]: def list_nixos_machines(flake_url: str | Path) -> list[str]:
cmd = nix_eval( cmd = nix_eval(
[ [
f"{flake_url}#nixosConfigurations", f"{flake_url}#nixosConfigurations",
@@ -42,7 +40,7 @@ def list_nixos_machines(flake_url: str | Path, debug: bool = False) -> list[str]
def list_command(args: argparse.Namespace) -> None: def list_command(args: argparse.Namespace) -> None:
flake_path = args.flake.path flake_path = args.flake.path
for name in list_nixos_machines(flake_path, args.debug): for name in list_nixos_machines(flake_path):
print(name) print(name)

View File

@@ -7,9 +7,6 @@ import { makePersisted } from "@solid-primitives/storage";
// Some global state // Some global state
const [route, setRoute] = createSignal<Route>("machines"); const [route, setRoute] = createSignal<Route>("machines");
createEffect(() => {
console.log(route());
});
export { route, setRoute }; export { route, setRoute };

View File

@@ -69,6 +69,11 @@ export const routes = {
label: "diskConfig", label: "diskConfig",
icon: "disk", icon: "disk",
}, },
"machines/edit": {
child: CreateMachine,
label: "Edit Machine",
icon: "edit",
},
}; };
interface RouterProps { interface RouterProps {

View File

@@ -123,7 +123,7 @@ export const callApi = <K extends OperationNames>(
return new Promise<OperationResponse<K>>((resolve) => { return new Promise<OperationResponse<K>>((resolve) => {
const id = nanoid(); const id = nanoid();
pyApi[method].receive((response) => { pyApi[method].receive((response) => {
console.log("Received response: ", { response }); console.log(method, "Received response: ", { response });
resolve(response); resolve(response);
}, id); }, id);
@@ -136,7 +136,6 @@ const deserialize =
(str: string) => { (str: string) => {
try { try {
const r = JSON.parse(str) as T; const r = JSON.parse(str) as T;
console.log("Received: ", r);
fn(r); fn(r);
} catch (e) { } catch (e) {
console.log("Error parsing JSON: ", e); console.log("Error parsing JSON: ", e);

View File

@@ -0,0 +1,91 @@
import cx from "classnames";
import { createMemo, JSX, Show, splitProps } from "solid-js";
interface FileInputProps {
ref: (element: HTMLInputElement) => void;
name: string;
value?: File[] | File;
onInput: JSX.EventHandler<HTMLInputElement, InputEvent>;
onClick: JSX.EventHandler<HTMLInputElement, Event>;
onChange: JSX.EventHandler<HTMLInputElement, Event>;
onBlur: JSX.EventHandler<HTMLInputElement, FocusEvent>;
accept?: string;
required?: boolean;
multiple?: boolean;
class?: string;
label?: string;
error?: string;
}
/**
* File input field that users can click or drag files into. Various
* decorations can be displayed in or around the field to communicate the entry
* requirements.
*/
export function FileInput(props: FileInputProps) {
// Split input element props
const [, inputProps] = splitProps(props, [
"class",
"value",
"label",
"error",
]);
// Create file list
const getFiles = createMemo(() =>
props.value
? Array.isArray(props.value)
? props.value
: [props.value]
: [],
);
return (
<div class={cx("form-control w-full", props.class)}>
<div class="label">
<span
class="label-text block"
classList={{
"after:ml-0.5 after:text-primary after:content-['*']":
props.required,
}}
>
{props.label}
</span>
</div>
<div
class={cx(
"relative flex min-h-[96px] w-full items-center justify-center rounded-2xl border-[3px] border-dashed p-8 text-center focus-within:ring-4 md:min-h-[112px] md:text-lg lg:min-h-[128px] lg:p-10 lg:text-xl",
!getFiles().length && "text-slate-500",
props.error
? "border-red-500/25 focus-within:border-red-500/50 focus-within:ring-red-500/10 hover:border-red-500/40 dark:border-red-400/25 dark:focus-within:border-red-400/50 dark:focus-within:ring-red-400/10 dark:hover:border-red-400/40"
: "border-slate-200 focus-within:border-sky-500/50 focus-within:ring-sky-500/10 hover:border-slate-300 dark:border-slate-800 dark:focus-within:border-sky-400/50 dark:focus-within:ring-sky-400/10 dark:hover:border-slate-700",
)}
>
<Show
when={getFiles().length}
fallback={<>Click to select file{props.multiple && "s"}</>}
>
Selected file{props.multiple && "s"}:{" "}
{getFiles()
.map(({ name }) => name)
.join(", ")}
</Show>
<input
{...inputProps}
// Disable drag n drop
onDrop={(e) => e.preventDefault()}
class="absolute size-full cursor-pointer opacity-0"
type="file"
id={props.name}
aria-invalid={!!props.error}
aria-errormessage={`${props.name}-error`}
/>
{props.error && (
<span class="label-text-alt font-bold text-error">{props.error}</span>
)}
</div>
</div>
);
}

View File

@@ -1,86 +1,67 @@
import { createSignal, Match, Show, Switch } from "solid-js"; import { Accessor, createEffect, Show } from "solid-js";
import { ErrorData, pyApi, SuccessData } from "../api"; import { SuccessData } from "../api";
import { Menu } from "./Menu";
import { setRoute } from "../App";
type MachineDetails = SuccessData<"list_inventory_machines">["data"][string]; type MachineDetails = SuccessData<"list_inventory_machines">["data"][string];
interface MachineListItemProps { interface MachineListItemProps {
name: string; name: string;
info?: MachineDetails; info?: MachineDetails;
nixOnly?: boolean;
} }
type HWInfo = Record<string, SuccessData<"show_machine_hardware_info">["data"]>;
type DeploymentInfo = Record<
string,
SuccessData<"show_machine_deployment_target">["data"]
>;
type MachineErrors = Record<string, ErrorData<"show_machine">["errors"]>;
const [hwInfo, setHwInfo] = createSignal<HWInfo>({});
const [deploymentInfo, setDeploymentInfo] = createSignal<DeploymentInfo>({});
const [errors, setErrors] = createSignal<MachineErrors>({});
// pyApi.show_machine_hardware_info.receive((r) => {
// const { op_key } = r;
// if (r.status === "error") {
// console.error(r.errors);
// if (op_key) {
// setHwInfo((d) => ({ ...d, [op_key]: { system: null } }));
// }
// return;
// }
// if (op_key) {
// setHwInfo((d) => ({ ...d, [op_key]: r.data }));
// }
// });
// pyApi.show_machine_deployment_target.receive((r) => {
// const { op_key } = r;
// if (r.status === "error") {
// console.error(r.errors);
// if (op_key) {
// setDeploymentInfo((d) => ({ ...d, [op_key]: null }));
// }
// return;
// }
// if (op_key) {
// setDeploymentInfo((d) => ({ ...d, [op_key]: r.data }));
// }
// });
export const MachineListItem = (props: MachineListItemProps) => { export const MachineListItem = (props: MachineListItemProps) => {
const { name, info } = props; const { name, info, nixOnly } = props;
return ( return (
<li> <li>
<div class="card card-side m-2 bg-base-100 shadow-lg"> <div class="card card-side m-2 bg-base-200">
<figure class="pl-2"> <figure class="pl-2">
<span class="material-icons content-center text-5xl"> <span
class="material-icons content-center text-5xl"
classList={{
"text-neutral-500": nixOnly,
}}
>
devices_other devices_other
</span> </span>
</figure> </figure>
<div class="card-body flex-row justify-between"> <div class="card-body flex-row justify-between ">
<div class="flex flex-col"> <div class="flex flex-col">
<h2 class="card-title">{name}</h2> <h2
class="card-title"
classList={{
"text-neutral-500": nixOnly,
}}
>
{name}
</h2>
<div class="text-slate-600"> <div class="text-slate-600">
<Show when={info}>{(d) => d()?.description}</Show> <Show when={info}>{(d) => d()?.description}</Show>
</div> </div>
<div class="flex flex-row flex-wrap gap-4 py-2"></div> <div class="flex flex-row flex-wrap gap-4 py-2"></div>
{/* Show only the first error at the bottom */}
<Show when={errors()[name]?.[0]}>
{(error) => (
<div class="badge badge-error py-4">
Error: {error().message}: {error().description}
</div>
)}
</Show>
</div> </div>
<div> <div>
<button class="btn btn-ghost"> <Menu
<span class="material-icons">more_vert</span> popoverid={`menu-${props.name}`}
</button> label={<span class="material-icons">more_vert</span>}
>
<ul class="menu z-[1] w-52 rounded-box bg-base-100 p-2 shadow">
<li>
<a
onClick={() => {
setRoute("machines/edit");
}}
>
Edit
</a>
</li>
<li>
<a>Deploy</a>
</li>
</ul>
</Menu>
</div> </div>
</div> </div>
</div> </div>

View File

@@ -0,0 +1,84 @@
import { children, Component, createSignal, type JSX } from "solid-js";
import { useFloating } from "@/src/floating";
import {
autoUpdate,
flip,
hide,
offset,
Placement,
shift,
} from "@floating-ui/dom";
import cx from "classnames";
interface MenuProps {
/**
* Used by the html API to associate the popover with the dispatcher button
*/
popoverid: string;
label: JSX.Element;
children?: JSX.Element;
buttonProps?: JSX.ButtonHTMLAttributes<HTMLButtonElement>;
buttonClass?: string;
/**
* @default "bottom"
*/
placement?: Placement;
}
export const Menu = (props: MenuProps) => {
const c = children(() => props.children);
const [reference, setReference] = createSignal<HTMLElement>();
const [floating, setFloating] = createSignal<HTMLElement>();
// `position` is a reactive object.
const position = useFloating(reference, floating, {
placement: "bottom",
// pass options. Ensure the cleanup function is returned.
whileElementsMounted: (reference, floating, update) =>
autoUpdate(reference, floating, update, {
animationFrame: true,
}),
middleware: [
offset(5),
shift(),
flip(),
hide({
strategy: "referenceHidden",
}),
],
});
return (
<div>
<button
popovertarget={props.popoverid}
popovertargetaction="toggle"
ref={setReference}
class={cx(
"btn btn-ghost btn-outline join-item btn-sm",
props.buttonClass,
)}
{...props.buttonProps}
>
{props.label}
</button>
<div
popover="auto"
id={props.popoverid}
ref={setFloating}
style={{
margin: 0,
position: position.strategy,
top: `${position.y ?? 0}px`,
left: `${position.x ?? 0}px`,
}}
class="bg-transparent"
>
{c()}
</div>
</div>
);
};

View File

@@ -0,0 +1,48 @@
import { FieldValues, FormStore, ResponseData } from "@modular-forms/solid";
import { type JSX } from "solid-js";
interface SelectInputProps<T extends FieldValues, R extends ResponseData> {
formStore: FormStore<T, R>;
value: string;
options: JSX.Element;
selectProps: JSX.HTMLAttributes<HTMLSelectElement>;
label: JSX.Element;
error?: string;
required?: boolean;
}
export function SelectInput<T extends FieldValues, R extends ResponseData>(
props: SelectInputProps<T, R>,
) {
return (
<label
class="form-control w-full"
aria-disabled={props.formStore.submitting}
>
<div class="label">
<span
class="label-text block"
classList={{
"after:ml-0.5 after:text-primary after:content-['*']":
props.required,
}}
>
{props.label}
</span>
</div>
<select
{...props.selectProps}
required={props.required}
class="select select-bordered w-full"
value={props.value}
>
{props.options}
</select>
{props.error && (
<span class="label-text-alt font-bold text-error">{props.error}</span>
)}
</label>
);
}

View File

@@ -0,0 +1,54 @@
import { FieldValues, FormStore, ResponseData } from "@modular-forms/solid";
import { type JSX } from "solid-js";
interface TextInputProps<T extends FieldValues, R extends ResponseData> {
formStore: FormStore<T, R>;
value: string;
inputProps: JSX.HTMLAttributes<HTMLInputElement>;
label: JSX.Element;
error?: string;
required?: boolean;
inlineLabel?: JSX.Element;
}
export function TextInput<T extends FieldValues, R extends ResponseData>(
props: TextInputProps<T, R>,
) {
return (
<label
class="form-control w-full"
aria-disabled={props.formStore.submitting}
>
<div class="label">
<span
class="label-text block"
classList={{
"after:ml-0.5 after:text-primary after:content-['*']":
props.required,
}}
>
{props.label}
</span>
</div>
<div class="input input-bordered flex items-center gap-2">
{props.inlineLabel}
<input
{...props.inputProps}
value={props.value}
type="text"
class="grow"
classList={{
"input-disabled": props.formStore.submitting,
}}
placeholder="name"
required
disabled={props.formStore.submitting}
/>
</div>
{props.error && (
<span class="label-text-alt font-bold text-error">{props.error}</span>
)}
</label>
);
}

View File

@@ -1,7 +1,7 @@
import { createQuery } from "@tanstack/solid-query"; import { createQuery } from "@tanstack/solid-query";
import { activeURI, setRoute } from "../App"; import { activeURI, setRoute } from "../App";
import { callApi } from "../api"; import { callApi } from "../api";
import { Accessor, createEffect, Show } from "solid-js"; import { Accessor, Show } from "solid-js";
interface HeaderProps { interface HeaderProps {
clan_dir: Accessor<string | null>; clan_dir: Accessor<string | null>;
@@ -34,7 +34,14 @@ export const Header = (props: HeaderProps) => {
</span> </span>
</div> </div>
<div class="flex-1"> <div class="flex-1">
<Show when={!query.isFetching && query.data}> <Show when={query.isLoading && !query.data}>
<div class="skeleton mx-4 size-11 rounded-full"></div>
<span class="flex flex-col gap-2">
<div class="skeleton h-3 w-32"></div>
<div class="skeleton h-3 w-40"></div>
</span>
</Show>
<Show when={query.data}>
{(meta) => ( {(meta) => (
<div class="tooltip tooltip-right" data-tip={activeURI()}> <div class="tooltip tooltip-right" data-tip={activeURI()}>
<div class="avatar placeholder online mx-4"> <div class="avatar placeholder online mx-4">
@@ -46,7 +53,7 @@ export const Header = (props: HeaderProps) => {
)} )}
</Show> </Show>
<span class="flex flex-col"> <span class="flex flex-col">
<Show when={!query.isFetching && query.data}> <Show when={query.data}>
{(meta) => [ {(meta) => [
<span class="text-primary">{meta().name}</span>, <span class="text-primary">{meta().name}</span>,
<span class="text-neutral">{meta()?.description}</span>, <span class="text-neutral">{meta()?.description}</span>,

View File

@@ -1,12 +1,11 @@
import { callApi, OperationResponse } from "@/src/api"; import { callApi, OperationResponse } from "@/src/api";
import { import { FileInput } from "@/src/components/FileInput";
createForm, import { SelectInput } from "@/src/components/SelectInput";
required, import { TextInput } from "@/src/components/TextInput";
FieldValues, import { createForm, required, FieldValues } from "@modular-forms/solid";
setValue,
} from "@modular-forms/solid";
import { createQuery } from "@tanstack/solid-query"; import { createQuery } from "@tanstack/solid-query";
import { createEffect, createSignal, For } from "solid-js"; import { For } from "solid-js";
import toast from "solid-toast";
interface FlashFormValues extends FieldValues { interface FlashFormValues extends FieldValues {
machine: { machine: {
@@ -16,58 +15,32 @@ interface FlashFormValues extends FieldValues {
disk: string; disk: string;
language: string; language: string;
keymap: string; keymap: string;
sshKeys: string[]; sshKeys: File[];
} }
type BlockDevices = Extract<
OperationResponse<"show_block_devices">,
{ status: "success" }
>["data"]["blockdevices"];
export const Flash = () => { export const Flash = () => {
const [formStore, { Form, Field }] = createForm<FlashFormValues>({}); const [formStore, { Form, Field }] = createForm<FlashFormValues>({
const [sshKeys, setSshKeys] = createSignal<string[]>([]); initialValues: {
const [isFlashing, setIsFlashing] = createSignal(false); machine: {
flake: "git+https://git.clan.lol/clan/clan-core",
const selectSshPubkey = async () => { devicePath: "flash-installer",
try { },
const loc = await callApi("open_file", { language: "en_US.UTF-8",
file_request: { keymap: "en",
title: "Select SSH Key", },
mode: "open_multiple_files",
filters: { patterns: ["*.pub"] },
initial_folder: "~/.ssh",
},
});
console.log({ loc }, loc.status);
if (loc.status === "success" && loc.data) {
setSshKeys(loc.data);
return loc.data;
}
} catch (e) {
//
}
};
// Create an effect that updates the form when externalUsername changes
createEffect(() => {
const newSshKeys = sshKeys();
if (newSshKeys) {
setValue(formStore, "sshKeys", newSshKeys);
}
}); });
const { data: devices, isFetching } = createQuery(() => ({ const deviceQuery = createQuery(() => ({
queryKey: ["block_devices"], queryKey: ["block_devices"],
queryFn: async () => { queryFn: async () => {
const result = await callApi("show_block_devices", {}); const result = await callApi("show_block_devices", {});
if (result.status === "error") throw new Error("Failed to fetch data"); if (result.status === "error") throw new Error("Failed to fetch data");
return result.data; return result.data;
}, },
staleTime: 1000 * 60 * 2, // 1 minutes staleTime: 1000 * 60 * 1, // 1 minutes
})); }));
const { data: keymaps, isFetching: isFetchingKeymaps } = createQuery(() => ({ const keymapQuery = createQuery(() => ({
queryKey: ["list_keymaps"], queryKey: ["list_keymaps"],
queryFn: async () => { queryFn: async () => {
const result = await callApi("list_possible_keymaps", {}); const result = await callApi("list_possible_keymaps", {});
@@ -77,20 +50,46 @@ export const Flash = () => {
staleTime: 1000 * 60 * 15, // 15 minutes staleTime: 1000 * 60 * 15, // 15 minutes
})); }));
const { data: languages, isFetching: isFetchingLanguages } = createQuery( const langQuery = createQuery(() => ({
() => ({ queryKey: ["list_languages"],
queryKey: ["list_languages"], queryFn: async () => {
queryFn: async () => { const result = await callApi("list_possible_languages", {});
const result = await callApi("list_possible_languages", {}); if (result.status === "error") throw new Error("Failed to fetch data");
if (result.status === "error") throw new Error("Failed to fetch data"); return result.data;
return result.data; },
staleTime: 1000 * 60 * 15, // 15 minutes
}));
/**
* Opens the custom file dialog
* Returns a native FileList to allow interaction with the native input type="file"
*/
const selectSshKeys = async (): Promise<FileList> => {
const dataTransfer = new DataTransfer();
const response = await callApi("open_file", {
file_request: {
title: "Select SSH Key",
mode: "open_multiple_files",
filters: { patterns: ["*.pub"] },
initial_folder: "~/.ssh",
}, },
staleTime: 1000 * 60 * 15, // 15 minutes });
}), if (response.status === "success" && response.data) {
); // Add synthetic files to the DataTransfer object
// FileList cannot be instantiated directly.
response.data.forEach((filename) => {
dataTransfer.items.add(new File([], filename));
});
}
return dataTransfer.files;
};
const handleSubmit = async (values: FlashFormValues) => { const handleSubmit = async (values: FlashFormValues) => {
setIsFlashing(true); console.log(
"Submit SSH Keys:",
values.sshKeys.map((file) => file.name),
);
try { try {
await callApi("flash_machine", { await callApi("flash_machine", {
machine: { machine: {
@@ -104,16 +103,15 @@ export const Flash = () => {
system_config: { system_config: {
language: values.language, language: values.language,
keymap: values.keymap, keymap: values.keymap,
ssh_keys_path: values.sshKeys, ssh_keys_path: values.sshKeys.map((file) => file.name),
}, },
dry_run: false, dry_run: false,
write_efi_boot_entries: false, write_efi_boot_entries: false,
debug: false, debug: false,
}); });
} catch (error) { } catch (error) {
toast.error(`Error could not flash disk: ${error}`);
console.error("Error submitting form:", error); console.error("Error submitting form:", error);
} finally {
setIsFlashing(false);
} }
}; };
@@ -126,24 +124,15 @@ export const Flash = () => {
> >
{(field, props) => ( {(field, props) => (
<> <>
<label class="input input-bordered flex items-center gap-2"> <TextInput
<span class="material-icons">file_download</span> formStore={formStore}
<input inputProps={props}
type="text" label="Installer (flake URL)"
class="grow" value={String(field.value)}
//placeholder="machine.flake" inlineLabel={<span class="material-icons">file_download</span>}
value="git+https://git.clan.lol/clan/clan-core" error={field.error}
required required
{...props} />
/>
</label>
<div class="label">
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</> </>
)} )}
</Field> </Field>
@@ -153,155 +142,125 @@ export const Flash = () => {
> >
{(field, props) => ( {(field, props) => (
<> <>
<label class="input input-bordered flex items-center gap-2"> <TextInput
<span class="material-icons">devices</span> formStore={formStore}
<input inputProps={props}
type="text" label="Installer Image (attribute name)"
class="grow" value={String(field.value)}
value="flash-installer" inlineLabel={<span class="material-icons">devices</span>}
required error={field.error}
{...props} required
/> />
</label>
<div class="label">
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</> </>
)} )}
</Field> </Field>
<Field name="disk" validate={[required("This field is required")]}> <Field name="disk" validate={[required("This field is required")]}>
{(field, props) => ( {(field, props) => (
<> <SelectInput
<label class="form-control input-bordered flex w-full items-center gap-2"> formStore={formStore}
<select selectProps={props}
required label="Flash Disk"
class="select select-bordered w-full" value={String(field.value)}
{...props} error={field.error}
> required
options={
<>
<option value="" disabled> <option value="" disabled>
Select a disk Select a disk
</option> </option>
<For each={devices?.blockdevices}> <For each={deviceQuery.data?.blockdevices}>
{(device) => ( {(device) => (
<option value={device.path}> <option value={device.path}>
{device.path} -- {device.size} bytes {device.path} -- {device.size} bytes
</option> </option>
)} )}
</For> </For>
</select> </>
<div class="label"> }
{isFetching && ( />
<span class="label-text-alt">
<span class="loading loading-bars"></span>
</span>
)}
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</label>
</>
)} )}
</Field> </Field>
<Field name="language" validate={[required("This field is required")]}> <Field name="language" validate={[required("This field is required")]}>
{(field, props) => ( {(field, props) => (
<> <>
<label class="form-control input-bordered flex w-full items-center gap-2"> <SelectInput
<select formStore={formStore}
required selectProps={props}
class="select select-bordered w-full" label="Language"
{...props} value={String(field.value)}
> error={field.error}
<option>en_US.UTF-8</option> required
<For each={languages}> options={
<For each={langQuery.data}>
{(language) => <option value={language}>{language}</option>} {(language) => <option value={language}>{language}</option>}
</For> </For>
</select> }
<div class="label"> />
{isFetchingLanguages && (
<span class="label-text-alt">
<span class="loading loading-bars">en_US.UTF-8</span>
</span>
)}
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</label>
</> </>
)} )}
</Field> </Field>
<Field name="keymap" validate={[required("This field is required")]}> <Field name="keymap" validate={[required("This field is required")]}>
{(field, props) => ( {(field, props) => (
<> <>
<label class="form-control input-bordered flex w-full items-center gap-2"> <SelectInput
<select formStore={formStore}
required selectProps={props}
class="select select-bordered w-full" label="Keymap"
{...props} value={String(field.value)}
> error={field.error}
<option>en</option> required
<For each={keymaps}> options={
<For each={keymapQuery.data}>
{(keymap) => <option value={keymap}>{keymap}</option>} {(keymap) => <option value={keymap}>{keymap}</option>}
</For> </For>
</select> }
<div class="label"> />
{isFetchingKeymaps && (
<span class="label-text-alt">
<span class="loading loading-bars"></span>
</span>
)}
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</label>
</> </>
)} )}
</Field> </Field>
<Field name="sshKeys" validate={[]} type="string[]">
<Field name="sshKeys" type="File[]">
{(field, props) => ( {(field, props) => (
<> <>
<label class="input input-bordered flex items-center gap-2"> <FileInput
<span class="material-icons">key</span> {...props}
<input onClick={async (event) => {
type="text" event.preventDefault(); // Prevent the native file dialog from opening
class="grow" const input = event.target;
placeholder="Select SSH Key" const files = await selectSshKeys();
value={field.value ? field.value.join(", ") : ""}
readOnly // Set the files
onClick={() => selectSshPubkey()} Object.defineProperty(input, "files", {
required value: files,
{...props} writable: true,
/> });
</label> // Define the files property on the input element
<div class="label"> const changeEvent = new Event("input", {
{field.error && ( bubbles: true,
<span class="label-text-alt font-bold text-error"> cancelable: true,
{field.error} });
</span> input.dispatchEvent(changeEvent);
)} }}
</div> value={field.value}
error={field.error}
label="Authorized SSH Keys"
multiple
required
/>
</> </>
)} )}
</Field> </Field>
<button class="btn btn-error" type="submit" disabled={isFlashing()}> <button
{isFlashing() ? ( class="btn btn-error"
type="submit"
disabled={formStore.submitting}
>
{formStore.submitting ? (
<span class="loading loading-spinner"></span> <span class="loading loading-spinner"></span>
) : ( ) : (
<span class="material-icons">bolt</span> <span class="material-icons">bolt</span>
)} )}
{isFlashing() ? "Flashing..." : "Flash Installer"} {formStore.submitting ? "Flashing..." : "Flash Installer"}
</button> </button>
</Form> </Form>
</div> </div>

View File

@@ -1,7 +1,8 @@
import { callApi, OperationArgs, pyApi, OperationResponse } from "@/src/api"; import { callApi, OperationArgs, pyApi, OperationResponse } from "@/src/api";
import { activeURI, setRoute } from "@/src/App"; import { activeURI, setRoute } from "@/src/App";
import { TextInput } from "@/src/components/TextInput";
import { createForm, required, reset } from "@modular-forms/solid"; import { createForm, required, reset } from "@modular-forms/solid";
import { createQuery } from "@tanstack/solid-query"; import { createQuery, useQueryClient } from "@tanstack/solid-query";
import { Match, Switch } from "solid-js"; import { Match, Switch } from "solid-js";
import toast from "solid-toast"; import toast from "solid-toast";
@@ -23,9 +24,7 @@ export function CreateMachine() {
}, },
}); });
const { refetch: refetchMachines } = createQuery(() => ({ const queryClient = useQueryClient();
queryKey: [activeURI(), "list_inventory_machines"],
}));
const handleSubmit = async (values: CreateMachineForm) => { const handleSubmit = async (values: CreateMachineForm) => {
const active_dir = activeURI(); const active_dir = activeURI();
@@ -46,7 +45,10 @@ export function CreateMachine() {
if (response.status === "success") { if (response.status === "success") {
toast.success(`Successfully created ${values.machine.name}`); toast.success(`Successfully created ${values.machine.name}`);
reset(formStore); reset(formStore);
refetchMachines();
queryClient.invalidateQueries({
queryKey: [activeURI(), "list_machines"],
});
setRoute("machines"); setRoute("machines");
} else { } else {
toast.error( toast.error(
@@ -56,93 +58,44 @@ export function CreateMachine() {
}; };
return ( return (
<div class="px-1"> <div class="px-1">
Create new Machine <span class="px-2">Create new Machine</span>
<button
onClick={() => {
reset(formStore);
}}
>
reset
</button>
<Form onSubmit={handleSubmit}> <Form onSubmit={handleSubmit}>
<Field <Field
name="machine.name" name="machine.name"
validate={[required("This field is required")]} validate={[required("This field is required")]}
> >
{(field, props) => ( {(field, props) => (
<> <TextInput
<label inputProps={props}
class="input input-bordered flex items-center gap-2" formStore={formStore}
classList={{ value={`${field.value}`}
"input-disabled": formStore.submitting, label={"name"}
}} error={field.error}
> required
<input />
{...props}
value={field.value}
type="text"
class="grow"
placeholder="name"
required
disabled={formStore.submitting}
/>
</label>
<div class="label">
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</>
)} )}
</Field> </Field>
<Field name="machine.description"> <Field name="machine.description">
{(field, props) => ( {(field, props) => (
<> <TextInput
<label inputProps={props}
class="input input-bordered flex items-center gap-2" formStore={formStore}
classList={{ value={`${field.value}`}
"input-disabled": formStore.submitting, label={"description"}
}} error={field.error}
> />
<input
value={String(field.value)}
type="text"
class="grow"
placeholder="description"
required
{...props}
/>
</label>
<div class="label">
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div>
</>
)} )}
</Field> </Field>
<Field name="machine.deploy.targetHost"> <Field name="machine.deploy.targetHost">
{(field, props) => ( {(field, props) => (
<> <>
<label <TextInput
class="input input-bordered flex items-center gap-2" inputProps={props}
classList={{ formStore={formStore}
"input-disabled": formStore.submitting, value={`${field.value}`}
}} label={"Deployment target"}
> error={field.error}
<input />
value={String(field.value)}
type="text"
class="grow"
placeholder="root@flash-installer.local"
required
{...props}
/>
</label>
<div class="label"> <div class="label">
<span class="label-text-alt text-neutral"> <span class="label-text-alt text-neutral">
Must be set before deployment for the following tasks: Must be set before deployment for the following tasks:
@@ -158,11 +111,6 @@ export function CreateMachine() {
</li> </li>
</ul> </ul>
</span> </span>
{field.error && (
<span class="label-text-alt font-bold text-error">
{field.error}
</span>
)}
</div> </div>
</> </>
)} )}

View File

@@ -3,43 +3,28 @@ import { activeURI, setRoute } from "@/src/App";
import { callApi, OperationResponse } from "@/src/api"; import { callApi, OperationResponse } from "@/src/api";
import toast from "solid-toast"; import toast from "solid-toast";
import { MachineListItem } from "@/src/components/MachineListItem"; import { MachineListItem } from "@/src/components/MachineListItem";
import { createQuery } from "@tanstack/solid-query"; import {
createQueries,
createQuery,
useQueryClient,
} from "@tanstack/solid-query";
type MachinesModel = Extract< type MachinesModel = Extract<
OperationResponse<"list_inventory_machines">, OperationResponse<"list_inventory_machines">,
{ status: "success" } { status: "success" }
>["data"]; >["data"];
type ExtendedMachine = MachinesModel & {
nixOnly: boolean;
};
export const MachineListView: Component = () => { export const MachineListView: Component = () => {
const { const queryClient = useQueryClient();
data: nixosMachines,
isFetching: isLoadingNixos, const inventoryQuery = createQuery<MachinesModel>(() => ({
refetch: refetchNixos, queryKey: [activeURI(), "list_machines", "inventory"],
} = createQuery<string[]>(() => ({ placeholderData: {},
queryKey: [activeURI(), "list_nixos_machines"], enabled: !!activeURI(),
queryFn: async () => {
const uri = activeURI();
if (uri) {
const response = await callApi("list_nixos_machines", {
flake_url: uri,
});
if (response.status === "error") {
toast.error("Failed to fetch data");
} else {
return response.data;
}
}
return [];
},
staleTime: 1000 * 60 * 5,
}));
const {
data: inventoryMachines,
isFetching: isLoadingInventory,
refetch: refetchInventory,
} = createQuery<MachinesModel>(() => ({
queryKey: [activeURI(), "list_inventory_machines"],
initialData: {},
queryFn: async () => { queryFn: async () => {
const uri = activeURI(); const uri = activeURI();
if (uri) { if (uri) {
@@ -54,26 +39,43 @@ export const MachineListView: Component = () => {
} }
return {}; return {};
}, },
staleTime: 1000 * 60 * 5, }));
const nixosQuery = createQuery<string[]>(() => ({
queryKey: [activeURI(), "list_machines", "nixos"],
enabled: !!activeURI(),
placeholderData: [],
queryFn: async () => {
const uri = activeURI();
if (uri) {
const response = await callApi("list_nixos_machines", {
flake_url: uri,
});
if (response.status === "error") {
toast.error("Failed to fetch data");
} else {
return response.data;
}
}
return [];
},
})); }));
const refresh = async () => { const refresh = async () => {
refetchInventory(); queryClient.invalidateQueries({
refetchNixos(); // Invalidates the cache for of all types of machine list at once
queryKey: [activeURI(), "list_machines"],
});
}; };
const unpackedMachines = () => Object.entries(inventoryMachines); const inventoryMachines = () => Object.entries(inventoryQuery.data || {});
const nixOnlyMachines = () => const nixOnlyMachines = () =>
nixosMachines?.filter( nixosQuery.data?.filter(
(name) => !unpackedMachines().some(([key, machine]) => key === name), (name) => !inventoryMachines().some(([key, machine]) => key === name),
); );
createEffect(() => {
console.log(nixOnlyMachines(), unpackedMachines());
});
return ( return (
<div class="max-w-screen-lg"> <div>
<div class="tooltip tooltip-bottom" data-tip="Open Clan"></div> <div class="tooltip tooltip-bottom" data-tip="Open Clan"></div>
<div class="tooltip tooltip-bottom" data-tip="Refresh"> <div class="tooltip tooltip-bottom" data-tip="Refresh">
<button class="btn btn-ghost" onClick={() => refresh()}> <button class="btn btn-ghost" onClick={() => refresh()}>
@@ -86,7 +88,7 @@ export const MachineListView: Component = () => {
</button> </button>
</div> </div>
<Switch> <Switch>
<Match when={isLoadingInventory}> <Match when={inventoryQuery.isLoading}>
{/* Loading skeleton */} {/* Loading skeleton */}
<div> <div>
<div class="card card-side m-2 bg-base-100 shadow-lg"> <div class="card card-side m-2 bg-base-100 shadow-lg">
@@ -104,20 +106,20 @@ export const MachineListView: Component = () => {
</Match> </Match>
<Match <Match
when={ when={
!isLoadingInventory && !inventoryQuery.isLoading &&
unpackedMachines().length === 0 && inventoryMachines().length === 0 &&
nixOnlyMachines()?.length === 0 nixOnlyMachines()?.length === 0
} }
> >
No machines found No machines found
</Match> </Match>
<Match when={!isLoadingInventory}> <Match when={!inventoryQuery.isLoading}>
<ul> <ul>
<For each={unpackedMachines()}> <For each={inventoryMachines()}>
{([name, info]) => <MachineListItem name={name} info={info} />} {([name, info]) => <MachineListItem name={name} info={info} />}
</For> </For>
<For each={nixOnlyMachines()}> <For each={nixOnlyMachines()}>
{(name) => <MachineListItem name={name} />} {(name) => <MachineListItem name={name} nixOnly={true} />}
</For> </For>
</ul> </ul>
</Match> </Match>

View File

@@ -1,10 +1,4 @@
import { callApi } from "@/src/api"; import { callApi } from "@/src/api";
import {
createForm,
required,
setValue,
SubmitHandler,
} from "@modular-forms/solid";
import { import {
activeURI, activeURI,
clanList, clanList,
@@ -12,15 +6,7 @@ import {
setClanList, setClanList,
setRoute, setRoute,
} from "@/src/App"; } from "@/src/App";
import { import { createSignal, For, Match, Setter, Show, Switch } from "solid-js";
createEffect,
createSignal,
For,
Match,
Setter,
Show,
Switch,
} from "solid-js";
import { createQuery } from "@tanstack/solid-query"; import { createQuery } from "@tanstack/solid-query";
import { useFloating } from "@/src/floating"; import { useFloating } from "@/src/floating";
import { autoUpdate, flip, hide, offset, shift } from "@floating-ui/dom"; import { autoUpdate, flip, hide, offset, shift } from "@floating-ui/dom";
@@ -156,6 +142,9 @@ const ClanDetails = (props: ClanDetailsProps) => {
</div> </div>
<div class="stat-title">{clan_dir}</div> <div class="stat-title">{clan_dir}</div>
<Show when={details.isLoading}>
<div class="skeleton h-12 w-80" />
</Show>
<Show when={details.isSuccess}> <Show when={details.isSuccess}>
<div class="stat-value">{details.data?.name}</div> <div class="stat-value">{details.data?.name}</div>
</Show> </Show>