Skip to content

Commit

Permalink
chore: call properly the parse function
Browse files Browse the repository at this point in the history
  • Loading branch information
danielo515 committed Dec 20, 2023
1 parent 4321d39 commit 3e1cbea
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 104 deletions.
9 changes: 4 additions & 5 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
{
"plugins": [
"prettier-plugin-svelte"
],
"plugins": ["prettier-plugin-svelte"],
"arrowParens": "always",
"editorconfig": true,
"svelteAllowShorthand": true,
"trailingComma": "all"
}
"trailingComma": "all",
"printWidth": 120
}
116 changes: 36 additions & 80 deletions src/FormModal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,7 @@ import type { FormDefinition, FormOptions } from "./core/formDefinition";
import { FileSuggest } from "./suggesters/suggestFile";
import { DataviewSuggest } from "./suggesters/suggestFromDataview";
import { SvelteComponent } from "svelte";
import {
executeSandboxedDvQuery,
sandboxedDvQuery,
} from "./suggesters/SafeDataviewQuery";
import { executeSandboxedDvQuery, sandboxedDvQuery } from "./suggesters/SafeDataviewQuery";
import { A, E, flow, parseFunctionBody, pipe, throttle } from "@std";

Check failure on line 13 in src/FormModal.ts

View workflow job for this annotation

GitHub Actions / build

'flow' is defined but never used
import { log_error, log_notice } from "./utils/Log";
import { FieldValue, FormEngine, makeFormEngine } from "./store/formStore";
Expand All @@ -21,16 +18,9 @@ import { FolderSuggest } from "./suggesters/suggestFolder";

export type SubmitFn = (formResult: FormResult) => void;

const notify = throttle(
(msg: string) =>
log_notice("⚠️ The form has errors ⚠️", msg, "notice-warning"),
2000,
);
const notify = throttle((msg: string) => log_notice("⚠️ The form has errors ⚠️", msg, "notice-warning"), 2000);
const notifyError = (title: string) =>
throttle(
(msg: string) => log_notice(`🚨 ${title} 🚨`, msg, "notice-error"),
2000,
);
throttle((msg: string) => log_notice(`🚨 ${title} 🚨`, msg, "notice-error"), 2000);

export class FormModal extends Modal {
svelteComponents: SvelteComponent[] = [];
Expand All @@ -44,10 +34,7 @@ export class FormModal extends Modal {
options?: FormOptions,
) {
super(app);
this.initialFormValues = formDataFromFormDefaults(
modalDefinition.fields,
options?.values ?? {},
);
this.initialFormValues = formDataFromFormDefaults(modalDefinition.fields, options?.values ?? {});
this.formEngine = makeFormEngine((result) => {
this.onSubmit(new FormResult(result, "ok"));
this.close();
Expand All @@ -59,8 +46,7 @@ export class FormModal extends Modal {
const { contentEl } = this;
// This class is very important for scoped styles
contentEl.addClass("modal-form");
if (this.modalDefinition.customClassname)
contentEl.addClass(this.modalDefinition.customClassname);
if (this.modalDefinition.customClassname) contentEl.addClass(this.modalDefinition.customClassname);
contentEl.createEl("h1", { text: this.modalDefinition.title });
this.modalDefinition.fields.forEach((definition) => {
const fieldBase = new Setting(contentEl)
Expand All @@ -73,12 +59,10 @@ export class FormModal extends Modal {
const type = fieldInput.type;
const initialValue = this.initialFormValues[definition.name];
const fieldStore = this.formEngine.addField(definition);
const subToErrors = (
input: HTMLInputElement | HTMLTextAreaElement,
) => {
const subToErrors = (input: HTMLInputElement | HTMLTextAreaElement) => {
this.subscriptions.push(
fieldStore.errors.subscribe((errs) => {
console.log("errors", errs);
errs.length > 0 ? console.log("errors", errs) : void 0;
errs.forEach(notify);
input.setCustomValidity(errs.join("\n"));
}),
Expand All @@ -94,8 +78,7 @@ export class FormModal extends Modal {
textEl.setValue(initialValue);
}
textEl.inputEl.rows = 6;
if (Platform.isIosApp)
textEl.inputEl.style.width = "100%";
if (Platform.isIosApp) textEl.inputEl.style.width = "100%";
else if (Platform.isDesktopApp) {
textEl.inputEl.rows = 10;
}
Expand All @@ -110,8 +93,7 @@ export class FormModal extends Modal {
text.inputEl.type = type;
subToErrors(text.inputEl);
text.onChange(fieldStore.value.set);
initialValue !== undefined &&
text.setValue(String(initialValue));
initialValue !== undefined && text.setValue(String(initialValue));
});
case "number":
return fieldBase.addText((text) => {
Expand All @@ -122,14 +104,12 @@ export class FormModal extends Modal {
fieldStore.value.set(Number(val) + "");
}
});
initialValue !== undefined &&
text.setValue(String(initialValue));
initialValue !== undefined && text.setValue(String(initialValue));
});
case "datetime":
return fieldBase.addText((text) => {
text.inputEl.type = "datetime-local";
initialValue !== undefined &&
text.setValue(String(initialValue));
initialValue !== undefined && text.setValue(String(initialValue));
subToErrors(text.inputEl);
text.onChange(fieldStore.value.set);
});
Expand Down Expand Up @@ -179,21 +159,15 @@ export class FormModal extends Modal {
source == "fixed"
? fieldInput.multi_select_options
: source == "notes"
? pipe(
get_tfiles_from_folder(
fieldInput.folder,
this.app,
),
E.map(A.map((file) => file.basename)),
E.getOrElse((err) => {
log_error(err);
return [] as string[];
}),
)
: executeSandboxedDvQuery(
sandboxedDvQuery(fieldInput.query),
this.app,
);
? pipe(
get_tfiles_from_folder(fieldInput.folder, this.app),
E.map(A.map((file) => file.basename)),
E.getOrElse((err) => {
log_error(err);
return [] as string[];
}),
)
: executeSandboxedDvQuery(sandboxedDvQuery(fieldInput.query), this.app);
fieldStore.value.set(initialValue ?? []);
this.svelteComponents.push(
new MultiSelect({
Expand All @@ -210,9 +184,7 @@ export class FormModal extends Modal {
return;
}
case "tag": {
const options = Object.keys(
this.app.metadataCache.getTags(),
).map((tag) => tag.slice(1)); // remove the #
const options = Object.keys(this.app.metadataCache.getTags()).map((tag) => tag.slice(1)); // remove the #
fieldStore.value.set(initialValue ?? []);
this.svelteComponents.push(
new MultiSelect({
Expand Down Expand Up @@ -242,35 +214,22 @@ export class FormModal extends Modal {
case "fixed":
return fieldBase.addDropdown((element) => {
fieldInput.options.forEach((option) => {
element.addOption(
option.value,
option.label,
);
element.addOption(option.value, option.label);
});
fieldStore.value.set(element.getValue());
element.onChange(fieldStore.value.set);
});

case "notes":
return fieldBase.addDropdown((element) => {
const files = get_tfiles_from_folder(
fieldInput.folder,
this.app,
);
const files = get_tfiles_from_folder(fieldInput.folder, this.app);
pipe(
files,
E.map((files) =>
files.reduce(
(
acc: Record<string, string>,
option,
) => {
acc[option.basename] =
option.basename;
return acc;
},
{},
),
files.reduce((acc: Record<string, string>, option) => {
acc[option.basename] = option.basename;
return acc;
}, {}),
),
E.mapLeft((err) => {
log_error(err);
Expand All @@ -290,10 +249,10 @@ export class FormModal extends Modal {
}
case "document_block": {
const functionBody = fieldInput.body;
const functionParsed = parseFunctionBody<
[Record<string, FieldValue>],
string
>("form", functionBody);
const functionParsed = parseFunctionBody<[Record<string, FieldValue>], string>(
functionBody,
"form",
);
const domNode = fieldBase.infoEl.createDiv();
const sub = this.formEngine.subscribe((form) => {
pipe(
Expand All @@ -306,10 +265,10 @@ export class FormModal extends Modal {
),
),
E.match(
flow(
String,
notifyError("Error in document block"),
),
(error) => {
console.error(error);
notifyError("Error in document block")(String(error));
},
(newText) => domNode.setText(newText),
),
);
Expand All @@ -323,10 +282,7 @@ export class FormModal extends Modal {
});

new Setting(contentEl).addButton((btn) =>
btn
.setButtonText("Submit")
.setCta()
.onClick(this.formEngine.triggerSubmit),
btn.setButtonText("Submit").setCta().onClick(this.formEngine.triggerSubmit),
);

const submitEnterCallback = (evt: KeyboardEvent) => {
Expand Down
25 changes: 6 additions & 19 deletions src/std/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,20 +102,13 @@ type ParseOpts = Parameters<typeof parse>[2];
export function parseC<S extends BaseSchema>(schema: S, options?: ParseOpts) {
return (input: unknown) => parse(schema, input, options);
}
export type ParsingFn<S extends BaseSchema> = (
input: unknown,
) => Either<ValiError, Output<S>>;
export type ParsingFn<S extends BaseSchema> = (input: unknown) => Either<ValiError, Output<S>>;
/**
* Concatenates two parsing functions that return Either<ValiError, B> into one.
* If the first function returns a Right, the second function is not called.
*/
class _EFunSemigroup<A extends BaseSchema, B extends BaseSchema>
implements Semigroup<ParsingFn<A>>
{
concat(
f: ParsingFn<A>,
g: ParsingFn<B>,
): (i: unknown) => Either<ValiError, unknown> {
class _EFunSemigroup<A extends BaseSchema, B extends BaseSchema> implements Semigroup<ParsingFn<A>> {
concat(f: ParsingFn<A>, g: ParsingFn<B>): (i: unknown) => Either<ValiError, unknown> {
return (i) => {
const fRes = f(i);
if (isRight(fRes)) return fRes;
Expand All @@ -130,10 +123,7 @@ export const EFunSemigroup = new _EFunSemigroup();
* Takes an array of schemas and returns a function
* that tries to parse the input with each schema.
*/
export function trySchemas<S extends BaseSchema>(
schemas: NonEmptyArray<S>,
options?: ParseOpts,
) {
export function trySchemas<S extends BaseSchema>(schemas: NonEmptyArray<S>, options?: ParseOpts) {
const [first, ...rest] = schemas;
return pipe(
rest,
Expand Down Expand Up @@ -178,15 +168,12 @@ function ensureError(e: unknown): Error {
* we often know what the function input types should be, but
* we can't trust the function body to return the correct type, so by default1t it will be unknown
*/
export function parseFunctionBody<Args extends unknown[], T>(
body: string,
...args: string[]
) {
export function parseFunctionBody<Args extends unknown[], T>(body: string, ...args: string[]) {
const fnBody = `"use strict";
${body}`;
try {
const fn = new Function(...args, fnBody) as (...args: Args) => T;
return pipe(tryCatchK(fn, ensureError), right);
return right(tryCatchK(fn, ensureError));
} catch (e) {
return left(ensureError(e));
}
Expand Down

0 comments on commit 3e1cbea

Please sign in to comment.