Skip to content

Commit

Permalink
feat: dataview rendering method for FormValue
Browse files Browse the repository at this point in the history
  • Loading branch information
danielo515 committed Dec 28, 2023
1 parent 57f2c1b commit 86839ce
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 16 deletions.
2 changes: 1 addition & 1 deletion src/core/FormResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export default class FormResult {
return value;
}
getValue(key: string): FormValue {
return FormValue.from(this.data[key]);
return FormValue.from(this.data[key], key);
}
// alias
getV = this.getValue;
Expand Down
70 changes: 64 additions & 6 deletions src/core/FormValue.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import { E, O, ensureError, pipe } from "@std";
import { notifyError } from "src/utils/Log";

function _toBulletList(value: Record<string, unknown> | unknown[]) {
if (Array.isArray(value)) {
return value.map((v) => `- ${v}`).join("\n");
Expand All @@ -15,10 +18,13 @@ function isRecord(value: unknown): value is Record<string, unknown> {
* It has some convenience methods to render the value in a way
* that works well with templates.
*/
export class FormValue {
constructor(protected value: unknown) {}
static from(value: unknown) {
return new FormValue(value);
export class FormValue<T = unknown> {
constructor(
protected value: T,
protected name: string,
) {}
static from<U = unknown>(value: U, name: string) {
return new FormValue(value, name);
}
/**
* Returns the value as a string.
Expand All @@ -34,7 +40,6 @@ export class FormValue {
case "string":
return this.value;
case "number":
return this.value.toString();
case "boolean":
return this.value.toString();
case "object":
Expand Down Expand Up @@ -76,7 +81,60 @@ export class FormValue {
}
}
/**
* Alias for `toBulletList`
* Converts the value to a dataview property using the field name as the key.
* If the value is empty or undefined, it will return an empty string and not render anything.
*/
toDataview() {
const value = this.value;
if (value === undefined) return "";
if (Array.isArray(value)) {
return `[${this.name}:: ${JSON.stringify(value).slice(1, -1)}]`;
}
return `[${this.name}:: ${this.toString()}]`;
}
/**
* Transforms the containerd value using the provided function.
* If the value is undefined or null the function will not be called
* and the result will be the same as the original.
* This is useful if you want to apply somme modifications to the value
* before rendering it, for example if none of the existing format methods suit your needs.
* @param {function} fn the function to transform the values
* @returns a new FormValue with the transformed value
**/
map<U>(fn: (value: unknown) => U): FormValue<T | U> {
const safeFn = E.tryCatchK(fn, ensureError);
const unchanged = () => this as FormValue<T | U>;
return pipe(
this.value,
O.fromNullable,
O.map(safeFn),
O.fold(unchanged, (v) =>
pipe(
v,
E.fold(
(e) => {
notifyError("Error in map of " + this.name)(e.message);
return unchanged();
},

(v: U) => FormValue.from(v, this.name),
),
),
),
);
}
/** Alias for `toDataview` */
toDv = this.toDataview;
/** Alias for `toBulletList` */
toBullets = this.toBulletList;
/**
* Convenient getter to get the value as bullets, so you don't need to call `toBulletList` manually.
* example:
* ```ts
* result.getValue("myField").bullets;
* ```
*/
get bullets() {
return this.toBulletList();
}
}
4 changes: 3 additions & 1 deletion src/std/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
none,
fromNullable as fromNullableOpt,
fold as ofold,
chain as ochain,
} from "fp-ts/Option";
import {
isLeft,
Expand Down Expand Up @@ -87,6 +88,7 @@ export const O = {
none,
fold: ofold,
fromNullable: fromNullableOpt,
chain: ochain,
};

export const parse = tryCatchK(parseV, (e: unknown) => e as ValiError);
Expand Down Expand Up @@ -157,7 +159,7 @@ export function tap(msg: string) {
};
}

function ensureError(e: unknown): Error {
export function ensureError(e: unknown): Error {
return e instanceof Error ? e : new Error(String(e));
}

Expand Down
27 changes: 19 additions & 8 deletions src/utils/Log.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
import { Notice } from "obsidian";
import { ModalFormError } from "./ModalFormError";


export function log_notice(title: string, msg: string | DocumentFragment, titleClass?: string, bodyClass?: string): void {
export function log_notice(
title: string,
msg: string | DocumentFragment,
titleClass?: string,
bodyClass?: string,
): void {
const notice = new Notice("", 15000);
const el = notice.noticeEl;
el.empty();
const head = el.createEl('h6', { text: title, cls: titleClass })
head.setCssStyles({ marginTop: '0px' })
const body = el.createEl('div', { text: msg, cls: bodyClass })
const head = el.createEl("h6", { text: title, cls: titleClass });
head.setCssStyles({ marginTop: "0px" });
const body = el.createEl("div", { text: msg, cls: bodyClass });
el.append(head, body);
}

export function log_update(msg: string): void {
log_notice('Modal form update', msg)
log_notice("Modal form update", msg);
}

export function log_error(e: Error | ModalFormError): void {
if (e instanceof ModalFormError && e.console_msg) {
log_notice('Modal from error: ', e.message + "\n" + e.console_msg, 'var(--text-error)')
log_notice("Modal from error: ", e.message + "\n" + e.console_msg, "var(--text-error)");
console.error(`Modal form Error:`, e.message, "\n", e.console_msg);
} else {
log_notice('Modal from error', e.message)
log_notice("Modal from error", e.message);
}
}

/**
* Convenience function to create a function that logs a notice with a title.
* Use it to notify the user about important errors
* @param title
*/
export const notifyError = (title: string) => (msg: string) => log_notice(`🚨 ${title} 🚨`, msg, "notice-error");

0 comments on commit 86839ce

Please sign in to comment.