Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Dec 21, 2023
1 parent 20a33c1 commit 6e1599a
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 118 deletions.
135 changes: 66 additions & 69 deletions src/renderer/src/stories/JSONSchemaForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -218,8 +218,8 @@ export class JSONSchemaForm extends LitElement {
#updateRendered = (force) =>
force || this.#rendered === true
? (this.#rendered = new Promise(
(resolve) => (this.#toggleRendered = () => resolve((this.#rendered = true)))
))
(resolve) => (this.#toggleRendered = () => resolve((this.#rendered = true)))
))
: this.#rendered;

resolved = {}; // Keep track of actual resolved values—not just what the user provides as results
Expand Down Expand Up @@ -412,8 +412,8 @@ export class JSONSchemaForm extends LitElement {
let message = isValid
? ""
: requiredButNotSpecified.length === 1
? `<b>${header(requiredButNotSpecified[0])}</b> is not defined`
: `${requiredButNotSpecified.length} required inputs are not specified properly`;
? `<b>${header(requiredButNotSpecified[0])}</b> is not defined`
: `${requiredButNotSpecified.length} required inputs are not specified properly`;
if (requiredButNotSpecified.length !== nMissingRequired)
console.warn("Disagreement about the correct error to throw...");

Expand All @@ -429,8 +429,9 @@ export class JSONSchemaForm extends LitElement {
message = `<b>${header(schema.title ?? path.join("."))}</b> is not valid`;
} else message = `${flaggedInputs.length} invalid form values`;
}
message += `${this.base.length ? ` in the <b>${this.base.join(".")}</b> section` : ""
}. Please check the highlighted fields.`;
message += `${
this.base.length ? ` in the <b>${this.base.join(".")}</b> section` : ""
}. Please check the highlighted fields.`;
}

if (message) this.throw(message);
Expand Down Expand Up @@ -591,7 +592,7 @@ export class JSONSchemaForm extends LitElement {
controls: this.controls[name],
required: isRequired,
validateEmptyValue: this.validateEmptyValues,
pattern: propertyType === 'pattern' ? name : propertyType ?? undefined,
pattern: propertyType === "pattern" ? name : propertyType ?? undefined,
});

// this.validateEmptyValues ? undefined : (el) => (el.value ?? el.checked) !== ""
Expand All @@ -609,8 +610,8 @@ export class JSONSchemaForm extends LitElement {
<div
id=${encode(localPath.join("-"))}
class="form-section ${isRequired || isConditional ? "required" : ""} ${isConditional
? "conditional"
: ""}"
? "conditional"
: ""}"
>
<label class="guided--form-label"
>${(info.title ? unsafeHTML(info.title) : null) ?? header(name)}</label
Expand Down Expand Up @@ -666,10 +667,10 @@ export class JSONSchemaForm extends LitElement {
};

// Checks missing required properties and throws an error if any are found
onInvalid = () => { };
onLoaded = () => { };
onUpdate = () => { };
onOverride = () => { };
onInvalid = () => {};
onLoaded = () => {};
onUpdate = () => {};
onOverride = () => {};

// #deleteExtraneousResults = (results, schema) => {
// for (let name in results) {
Expand Down Expand Up @@ -722,10 +723,10 @@ export class JSONSchemaForm extends LitElement {
return flattenRecursedValues(res); // Flatten on the last pass
};

validateOnChange = () => { };
onStatusChange = () => { };
onThrow = () => { };
createTable = () => { };
validateOnChange = () => {};
onStatusChange = () => {};
onThrow = () => {};
createTable = () => {};

#getLink = (args) => {
if (typeof args === "string") args = args.split("-");
Expand Down Expand Up @@ -779,25 +780,15 @@ export class JSONSchemaForm extends LitElement {
#isARequiredPropertyString = `is a required property`;

// Assume this is going to return as a Promise—even if the change function isn't returning one
triggerValidation = async (
name,
path = [],
checkLinks = true,
input,
schema,
parent,
hooks = {}
) => {

triggerValidation = async (name, path = [], checkLinks = true, input, schema, parent, hooks = {}) => {
const { onError, onWarning } = hooks;

const localPath = [...path, name].filter(str => typeof str === 'string'); // Ignore row information
const localPath = [...path, name].filter((str) => typeof str === "string"); // Ignore row information
const externalPath = [...this.base, ...localPath];
const pathToValidate = [...this.base, ...path];

const undefinedPathToken = localPath.findIndex((str) => !str && typeof str !== 'number') !== -1;
if (undefinedPathToken) return true // Will be unable to get schema anyways (additionalProperties)

const undefinedPathToken = localPath.findIndex((str) => !str && typeof str !== "number") !== -1;
if (undefinedPathToken) return true; // Will be unable to get schema anyways (additionalProperties)

if (!input) input = this.getInput(localPath);
if (!parent) parent = this.#get(path, this.resolved);
Expand All @@ -811,35 +802,34 @@ export class JSONSchemaForm extends LitElement {
const jsonSchemaErrors =
validateArgs.length === 2
? await v
.validate(...validateArgs)
.errors.map((e) => {
const propName = e.path.slice(-1)[0] ?? name;
const rowName = e.path.slice(-2)[0];

const isRow = typeof rowName === "number"

const resolvedValue = e.path.reduce((acc, token) => acc[token], value)

// ------------ Exclude Certain Errors ------------
// Non-Strict Rule
if (schema.strict === false && e.message.includes("is not one of enum values")) return;

// Allow referring to floats as null (i.e. JSON NaN representation)
if (e.message === "is not of a type(s) number") {
if (resolvedValue === null) return;
}



return {
type: "error",
message: `${typeof propName === "string"
? `${header(propName)}${isRow ? ` on Row ${rowName}` : ""}`
: `Row ${propName}`
} ${e.message}.`,
};
})
.filter((v) => !!v)
.validate(...validateArgs)
.errors.map((e) => {
const propName = e.path.slice(-1)[0] ?? name;
const rowName = e.path.slice(-2)[0];

const isRow = typeof rowName === "number";

const resolvedValue = e.path.reduce((acc, token) => acc[token], value);

// ------------ Exclude Certain Errors ------------
// Non-Strict Rule
if (schema.strict === false && e.message.includes("is not one of enum values")) return;

// Allow referring to floats as null (i.e. JSON NaN representation)
if (e.message === "is not of a type(s) number") {
if (resolvedValue === null) return;
}

return {
type: "error",
message: `${
typeof propName === "string"
? `${header(propName)}${isRow ? ` on Row ${rowName}` : ""}`
: `Row ${propName}`
} ${e.message}.`,
};
})
.filter((v) => !!v)
: [];

const valid = skipValidation ? true : await this.validateOnChange(name, parent, pathToValidate, value);
Expand Down Expand Up @@ -904,8 +894,9 @@ export class JSONSchemaForm extends LitElement {
const regex = new RegExp(schema.pattern);
if (!regex.test(parent[name])) {
errors.push({
message: `${schema.title ?? header(name)} does not match the required pattern (${schema.pattern
}).`,
message: `${schema.title ?? header(name)} does not match the required pattern (${
schema.pattern
}).`,
type: "error",
});
}
Expand All @@ -928,7 +919,6 @@ export class JSONSchemaForm extends LitElement {

const resolvedErrors = errors
.map((e) => {

// Custom Error Transformations
if (this.transformErrors) {
const res = this.transformErrors(e, externalPath, parent[name]);
Expand Down Expand Up @@ -1282,18 +1272,25 @@ export class JSONSchemaForm extends LitElement {
required,
path,
results,
'pattern'
"pattern"
);
});

rendered = [...rendered, ...patternProps];
}

if (hasAdditionalProperties) {
const additionalElement = this.#renderInteractiveElement('', {
title: `Additional Properties`,
...schema
}, required, path, results, 'additional')
if (hasAdditionalProperties) {
const additionalElement = this.#renderInteractiveElement(
"",
{
title: `Additional Properties`,
...schema,
},
required,
path,
results,
"additional"
);
rendered = [...rendered, additionalElement];
}

Expand Down
59 changes: 25 additions & 34 deletions src/renderer/src/stories/JSONSchemaInput.js
Original file line number Diff line number Diff line change
Expand Up @@ -238,30 +238,23 @@ export class JSONSchemaInput extends LitElement {
: [];

if (isEditableObject) {



items = Object.entries(this.value);

const isAdditionalProperties = this.#isAdditionalProperties()
const isAdditionalProperties = this.#isAdditionalProperties();

if (this.#isPatternProperties()) {
const regex = new RegExp(name)
const regex = new RegExp(name);
items = items.filter(([key]) => regex.test(key));
}

else if (isAdditionalProperties) {
const props = Object.keys(schema.properties ?? {})
} else if (isAdditionalProperties) {
const props = Object.keys(schema.properties ?? {});
items = items.filter(([key]) => !props.includes(key));

const patternProps = Object.keys(schema.patternProperties ?? {})
const patternProps = Object.keys(schema.patternProperties ?? {});
patternProps.forEach((key) => {
const regex = new RegExp(key)
items = items.filter(([k]) => !regex.test(k))
})
}

else items.filter(([key]) => key in schema.properties)
const regex = new RegExp(key);
items = items.filter(([k]) => !regex.test(k));
});
} else items.filter(([key]) => key in schema.properties);

items = items.map(([key, value]) => {
return {
Expand Down Expand Up @@ -291,12 +284,12 @@ export class JSONSchemaInput extends LitElement {
#schemaElement;
#modal;

#isPatternProperties(){
return this.pattern && !this.#isAdditionalProperties()
#isPatternProperties() {
return this.pattern && !this.#isAdditionalProperties();
}

#isAdditionalProperties(){
return this.pattern === 'additional'
#isAdditionalProperties() {
return this.pattern === "additional";
}

async #createModal({ key, schema = {}, results, list } = {}) {
Expand All @@ -306,8 +299,8 @@ export class JSONSchemaInput extends LitElement {
// const additionalProperties = Object.keys(results).filter((key) => !schemaProperties.includes(key));
// // const additionalElement = html`<label class="guided--form-label">Additional Properties</label><small>Cannot edit additional properties (${additionalProperties}) at this time</small>`

const isPatternProperties = this.#isPatternProperties()
const isAdditionalProperties = this.#isAdditionalProperties()
const isPatternProperties = this.#isPatternProperties();
const isAdditionalProperties = this.#isAdditionalProperties();
const creatNewPatternProperty = isPatternProperties && createNewObject;

const schemaCopy = structuredClone(schema);
Expand Down Expand Up @@ -401,14 +394,13 @@ export class JSONSchemaInput extends LitElement {
setTimeout(() => this.#modal.toggle(true));
}


#getType = (value = this.value) => Array.isArray(value) ? 'array' : typeof value
#getType = (value = this.value) => (Array.isArray(value) ? "array" : typeof value);

#render() {
const { validateOnChange, schema, path: fullPath } = this;

// Do your best to fill in missing schema values
if (!('type' in schema)) schema.type = this.#getType()
if (!("type" in schema)) schema.type = this.#getType();

const path = typeof fullPath === "string" ? fullPath.split("-") : [...fullPath];
const name = path.splice(-1)[0];
Expand Down Expand Up @@ -436,8 +428,8 @@ export class JSONSchemaInput extends LitElement {
if (isArray || isEditableObject) {
// if ('value' in this && !Array.isArray(this.value)) this.value = [ this.value ]

const isPatternProperties = this.#isPatternProperties()
const isAdditionalProperties = this.#isAdditionalProperties()
const isPatternProperties = this.#isPatternProperties();
const isAdditionalProperties = this.#isAdditionalProperties();

// Provide default item types
if (isArray) {
Expand All @@ -452,7 +444,6 @@ export class JSONSchemaInput extends LitElement {
if (fileSystemFormat) return createFilesystemSelector(fileSystemFormat);
// Create tables if possible
else if (itemSchema?.type === "object" && this.form.createTable) {

const ignore = this.form?.ignore
? getIgnore(this.form?.ignore, [...this.form.base, ...path, name])
: {};
Expand Down Expand Up @@ -485,8 +476,8 @@ export class JSONSchemaInput extends LitElement {
return acc?.properties?.[key] ?? acc?.items?.properties?.[key];
}, baseSchema);

const result = await (validateOnChange ?
(this.onValidate
const result = await (validateOnChange
? this.onValidate
? this.onValidate()
: this.form
? this.form.triggerValidation(
Expand All @@ -505,9 +496,8 @@ export class JSONSchemaInput extends LitElement {
},
}
) // NOTE: No pattern properties support
: "")
: true
);
: ""
: true);

const returnedValue = errors.length ? errors : warnings.length ? warnings : result;

Expand Down Expand Up @@ -583,7 +573,8 @@ export class JSONSchemaInput extends LitElement {

if (isAdditionalProperties) {
addButton.setAttribute("disabled", true);
addButton.title = "Additional properties cannot be added at this time—as they don't have a predictable structure.";
addButton.title =
"Additional properties cannot be added at this time—as they don't have a predictable structure.";
}

return html`
Expand Down
Loading

0 comments on commit 6e1599a

Please sign in to comment.