Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Manage forms as svelte component #107

Merged
merged 16 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"plugins": [
"prettier-plugin-svelte"
]
}
31 changes: 29 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@
"esbuild-svelte": "^0.8.0",
"jest": "^29.7.0",
"obsidian": "^1.4.11",
"prettier": "^3.0.3",
"prettier-plugin-svelte": "^3.0.3",
"svelte": "^4.2.0",
"svelte-check": "^3.5.2",
"svelte-preprocess": "^5.0.4",
Expand Down
3 changes: 2 additions & 1 deletion src/API.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { App } from "obsidian";

import { MigrationError, type FormDefinition, type FormOptions } from "./core/formDefinition";
import { type FormDefinition, type FormOptions } from "./core/formDefinition";
import { MigrationError } from "./core/formDefinitionSchema";
import FormResult from "./core/FormResult";
import { exampleModalDefinition } from "./exampleModalDefinition";
import ModalFormPlugin from "./main";
Expand Down
102 changes: 102 additions & 0 deletions src/core/findInputDefinitionSchema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import { A, NonEmptyArray, ParsingFn, parse, pipe } from "@std";
import * as E from "fp-ts/Either";
import { ValiError, BaseSchema } from "valibot";
import { FieldMinimal, FieldMinimalSchema, InputTypeToParserMap } from "./formDefinitionSchema";
import { AllFieldTypes } from "./formDefinition";

function stringifyIssues(error: ValiError): NonEmptyArray<string> {
return error.issues.map((issue) => `${issue.path?.map((i) => i.key)}: ${issue.message} got ${issue.input}`) as NonEmptyArray<string>;
}
export class InvalidInputTypeError {
static readonly _tag = "InvalidInputTypeError" as const;
readonly path: string = 'input.type';
constructor(readonly field: FieldMinimal, readonly inputType: unknown) { }
toString(): string {
return `InvalidInputTypeError: ${this.getFieldErrors()[0]}`;
}
getFieldErrors(): NonEmptyArray<string> {
return [`"input.type" is invalid, got: ${JSON.stringify(this.inputType)}`]
}
}
export class InvalidInputError {
static readonly _tag = "InvalidInputError" as const;
readonly path: string;
constructor(readonly field: FieldMinimal, readonly error: ValiError) {
this.path = error.issues[0].path?.map((i) => i.key).join('.') ?? '';
}
toString(): string {
return `InvalidInputError: ${stringifyIssues(this.error).join(', ')}`;
}

getFieldErrors(): NonEmptyArray<string> {
return stringifyIssues(this.error)
}
}

export class InvalidFieldError {
static readonly _tag = "InvalidFieldError" as const;
readonly path: string;
constructor(public field: unknown, readonly error: ValiError) {
this.path = error.issues[0].path?.map((i) => i.key).join('.') ?? '';
}
toString(): string {
return `InvalidFieldError: ${stringifyIssues(this.error).join(', ')}`;
}
getFieldErrors(): string[] {
return stringifyIssues(this.error)
}
static of(field: unknown) {
return (error: ValiError) => new InvalidFieldError(field, error);
}
}

function isValidInputType(input: unknown): input is AllFieldTypes {
return 'string' === typeof input && input in InputTypeToParserMap;
}
/**
* Finds the corresponding schema to the provided unparsed field.
* It uses the most basic schema to parse the field because we only need
* the input type to find the corresponding schema.
* This is function is usually needed when you know that the field parsing has failed,
* but you need the right input schema to get the specific error.
* This is again due to a limitation of valibot.
* @param fieldDefinition a field definition to find the input schema for
* @returns a tuple of the basic field definition and the input schema
*/
export function findInputDefinitionSchema(fieldDefinition: unknown): E.Either<InvalidFieldError | InvalidInputTypeError, [FieldMinimal, ParsingFn<BaseSchema>]> {
return pipe(
parse(FieldMinimalSchema, fieldDefinition),
E.mapLeft(InvalidFieldError.of(fieldDefinition)),
E.chainW((field) => {
const type = field.input.type;
if (isValidInputType(type)) return E.right([field, InputTypeToParserMap[type]]);
else return E.left(new InvalidInputTypeError(field, type));
})
);
}
/**
* Given an array of fields that have failed to parse,
* this function tries to find the corresponding input schema
* and then parses the input with that schema to get the specific errors.
* The result is an array of field errors.
* This is needed because valibot doesn't provide a way to get the specific error of union types
*/
export function findFieldErrors(fields: unknown[]) {
return pipe(
fields,
A.map((fieldUnparsed) => {
return pipe(
findInputDefinitionSchema(fieldUnparsed),
E.chainW(([field, parser]) => pipe(
parser(field.input),
E.bimap(
(error) => new InvalidInputError(field, error),
() => field
)),
))
}),
// A.partition(E.isLeft),
// Separated.right,
);

}
30 changes: 15 additions & 15 deletions src/core/formDefinition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,40 +5,40 @@ import {
isInputSelectFixed,
isInputSlider,
isSelectFromNotes,
MultiselectSchema,
} from "./formDefinition";
import { MultiselectSchema } from "./formDefinitionSchema";
import { parse } from "valibot";

describe("isDataViewSource", () => {
it("should return true for valid inputDataviewSource objects", () => {
expect(
isDataViewSource({ type: "dataview", query: "some query" })
isDataViewSource({ type: "dataview", query: "some query" }),
).toBe(true);
});

it("should return false for invalid inputDataviewSource objects", () => {
expect(isDataViewSource({ type: "dataview" })).toBe(false);
expect(isDataViewSource({ type: "dataview", query: 123 })).toBe(false);
expect(isDataViewSource({ type: "select", query: "some query" })).toBe(
false
false,
);
});
});

describe("isInputNoteFromFolder", () => {
it("should return true for valid inputNoteFromFolder objects", () => {
expect(
isInputNoteFromFolder({ type: "note", folder: "some folder" })
isInputNoteFromFolder({ type: "note", folder: "some folder" }),
).toBe(true);
});

it("should return false for invalid inputNoteFromFolder objects", () => {
expect(isInputNoteFromFolder({ type: "note" })).toBe(false);
expect(isInputNoteFromFolder({ type: "note", folder: 123 })).toBe(
false
false,
);
expect(
isInputNoteFromFolder({ type: "select", folder: "some folder" })
isInputNoteFromFolder({ type: "select", folder: "some folder" }),
).toBe(false);
});
});
Expand All @@ -50,27 +50,27 @@ describe("isInputSelectFixed", () => {
type: "select",
source: "fixed",
options: [{ value: "1", label: "Option 1" }],
})
}),
).toBe(true);
});

it("should return false for invalid inputSelectFixed objects", () => {
expect(isInputSelectFixed({ type: "select", source: "fixed" })).toBe(
false
false,
);
expect(
isInputSelectFixed({
type: "select",
source: "fixed",
options: [{ value: "1", label: 123 }],
})
}),
).toBe(false);
expect(
isInputSelectFixed({
type: "select",
source: "notes",
options: [{ value: "1", label: "Option 1" }],
})
}),
).toBe(false);
});
});
Expand All @@ -83,7 +83,7 @@ describe("isInputSlider", () => {
it("should return false for invalid inputSlider objects", () => {
expect(isInputSlider({ type: "slider" })).toBe(false);
expect(isInputSlider({ type: "slider", min: "0", max: 10 })).toBe(
false
false,
);
expect(isInputSlider({ type: "select", min: 0, max: 10 })).toBe(false);
});
Expand All @@ -96,19 +96,19 @@ describe("isSelectFromNotes", () => {
type: "select",
source: "notes",
folder: "some folder",
})
}),
).toBe(true);
});

it("should return false for invalid selectFromNotes objects", () => {
expect(isSelectFromNotes({ type: "select", source: "notes" })).toBe(
false
false,
);
expect(
isSelectFromNotes({ type: "select", source: "notes", folder: 123 })
isSelectFromNotes({ type: "select", source: "notes", folder: 123 }),
).toBe(false);
expect(isSelectFromNotes({ type: "note", folder: "some folder" })).toBe(
false
false,
);
});
});
Expand Down
Loading