diff --git a/bin/run-all-tests b/bin/run-all-tests index 91d4e7b3..6f40d60b 100755 --- a/bin/run-all-tests +++ b/bin/run-all-tests @@ -3,7 +3,7 @@ # Run every automated test suite in the repository. # # Suites run in this order: -# 1. builder-frontend - Vitest unit tests (npm test) +# 1. builder-frontend - Vitest unit tests, then format and type checks # 2. builder-api - JVM unit/integration tests (mvn test) # 3. library-api - JVM unit/integration tests (mvn test) # 4. examples - Node tests for the CRM examples (node --test) @@ -40,7 +40,7 @@ Runs every automated test suite in the repository. Run it directly or as Devbox on its own. Suites: - builder-frontend builder-frontend Vitest tests (npm test) + builder-frontend builder-frontend Vitest tests, format check, type check builder-api builder-api JVM tests (mvn test) library-api library-api JVM tests (mvn test) examples CRM example Node tests (node --test) @@ -183,7 +183,12 @@ run_builder_frontend_suite() { print_status "Installing builder-frontend dependencies..." npm install fi - npm test + # Run every check so one failure doesn't hide another. + local status=0 + npm test || status=1 + npm run format:check || status=1 + npm run typecheck || status=1 + exit "$status" ) } diff --git a/builder-frontend/README.md b/builder-frontend/README.md index 69d35ee7..5cd0aa6f 100644 --- a/builder-frontend/README.md +++ b/builder-frontend/README.md @@ -23,6 +23,19 @@ It correctly bundles Solid in production mode and optimizes the build for the be The build is minified and the filenames include the hashes.
Your app is ready to be deployed! +### `npm run format` and `npm run format:check` + +Formats `src` with Prettier's defaults, or checks that it is formatted. + +### `npm run typecheck` + +Type-checks `src`, failing only when a file has more errors than +`typecheck-baseline.json` records for it. After fixing type errors, run +`npm run typecheck -- --update` to lower the baseline. + +`devbox run test -- builder-frontend` runs the tests, the format check and the +type check, as CI does. + ## Deployment Learn more about deploying your application with the [documentations](https://vite.dev/guide/static-deploy.html) diff --git a/builder-frontend/package-lock.json b/builder-frontend/package-lock.json index 2e3de3ac..f2689d79 100644 --- a/builder-frontend/package-lock.json +++ b/builder-frontend/package-lock.json @@ -33,6 +33,8 @@ "@tailwindcss/postcss": "^4.1.8", "@tailwindcss/vite": "^4.1.18", "@types/json-schema": "^7.0.15", + "@types/lodash": "^4.17.27", + "@types/lodash.debounce": "^4.0.9", "autoprefixer": "^10.4.21", "jsdom": "^30.0.1", "postcss": "^8.5.4", @@ -3760,6 +3762,23 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/lodash": { + "version": "4.17.27", + "resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.17.27.tgz", + "integrity": "sha512-VenMRv/eKNrspX9v3H4dbmjsrnCOYdYBG3kxXKk3dG6X+urBGcj2Prww3xw1U5K4FV/mE4h5GbWd0szEKf+9ew==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/lodash.debounce": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/@types/lodash.debounce/-/lodash.debounce-4.0.9.tgz", + "integrity": "sha512-Ma5JcgTREwpLRwMM+XwBR7DaWe96nC38uCBDFKZWbNKD+osjVzdpnUSwBcqCptrp16sSOLBAUb50Car5I0TCsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/lodash": "*" + } + }, "node_modules/@types/node": { "version": "24.0.1", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.1.tgz", diff --git a/builder-frontend/package.json b/builder-frontend/package.json index 812db33c..26d18309 100644 --- a/builder-frontend/package.json +++ b/builder-frontend/package.json @@ -7,7 +7,10 @@ "dev": "vite", "build": "vite build", "preview": "vite preview", - "test": "vitest run" + "test": "vitest run", + "format": "prettier --write src", + "format:check": "prettier --check src", + "typecheck": "node scripts/typecheck.mjs" }, "dependencies": { "@bpmn-io/feel-editor": "^2.7.1", @@ -35,6 +38,8 @@ "@tailwindcss/postcss": "^4.1.8", "@tailwindcss/vite": "^4.1.18", "@types/json-schema": "^7.0.15", + "@types/lodash": "^4.17.27", + "@types/lodash.debounce": "^4.0.9", "autoprefixer": "^10.4.21", "jsdom": "^30.0.1", "postcss": "^8.5.4", diff --git a/builder-frontend/scripts/typecheck.mjs b/builder-frontend/scripts/typecheck.mjs new file mode 100644 index 00000000..f8eb998e --- /dev/null +++ b/builder-frontend/scripts/typecheck.mjs @@ -0,0 +1,86 @@ +// Type-check src against a per-file baseline of known errors. +// +// The codebase predates type checking, so `tsc` reports errors in files nobody +// has touched. This fails only when a file has more errors than its baseline, +// so new code is checked without first fixing every old error. After fixing +// errors, run `npm run typecheck -- --update` to lower the baseline. + +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync, writeFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +const root = fileURLToPath(new URL("..", import.meta.url)); +const baselinePath = `${root}typecheck-baseline.json`; +const update = process.argv.includes("--update"); + +let output; +try { + output = execFileSync("node_modules/.bin/tsc", ["--noEmit", "-p", "."], { + cwd: root, + encoding: "utf8", + }); +} catch (error) { + // tsc exits non-zero whenever it reports errors. + if (typeof error.stdout !== "string") throw error; + output = error.stdout; +} + +// Group each error's lines (tsc continues a message on indented lines) by file. +const errors = new Map(); +let current; +for (const line of output.split("\n")) { + const located = line.match(/^(.+?)\(\d+,\d+\): error TS\d+/); + const global = line.match(/^error TS\d+/); + if (located || global) { + const file = located ? located[1] : "(no file)"; + current = [line]; + errors.set(file, [...(errors.get(file) ?? []), current]); + } else if (current && line.startsWith(" ")) { + current.push(line); + } +} + +const counts = Object.fromEntries( + [...errors].map(([file, list]) => [file, list.length]).sort(), +); +const total = Object.values(counts).reduce((sum, count) => sum + count, 0); + +if (update) { + writeFileSync(baselinePath, `${JSON.stringify(counts, null, 2)}\n`); + console.log( + `Recorded ${total} known type errors in typecheck-baseline.json.`, + ); + process.exit(0); +} + +const baseline = existsSync(baselinePath) + ? JSON.parse(readFileSync(baselinePath, "utf8")) + : {}; +const worse = Object.keys(counts).filter( + (file) => counts[file] > (baseline[file] ?? 0), +); +const better = Object.keys(baseline).filter( + (file) => (counts[file] ?? 0) < baseline[file], +); + +for (const file of worse) { + console.error( + `${file}: ${counts[file]} type errors, baseline allows ${baseline[file] ?? 0}`, + ); + for (const lines of errors.get(file)) console.error(lines.join("\n")); +} +if (better.length > 0) { + console.log( + `Fewer type errors than the baseline in ${better.join(", ")}. ` + + "Run `npm run typecheck -- --update` to lock in the improvement.", + ); +} +if (worse.length > 0) { + console.error( + "\nFix the new type errors above. Only lower the baseline, never raise it.", + ); + process.exit(1); +} +console.log( + `Type check passed: ${total} type errors, none beyond the baseline.`, +); diff --git a/builder-frontend/src/api/publishedScreener.ts b/builder-frontend/src/api/publishedScreener.ts index a5d6f808..2aa7347a 100644 --- a/builder-frontend/src/api/publishedScreener.ts +++ b/builder-frontend/src/api/publishedScreener.ts @@ -3,7 +3,9 @@ import { env } from "@/config/environment"; const apiUrl = env.apiUrl; -export const fetchPublishedScreener = async (publishedScreenerId: string): Promise => { +export const fetchPublishedScreener = async ( + publishedScreenerId: string, +): Promise => { const url = apiUrl + "/published/screener/" + publishedScreenerId; try { const response = await fetch(url, { @@ -24,8 +26,10 @@ export const fetchPublishedScreener = async (publishedScreenerId: string): Promi } }; - -export const evaluatePublishedScreener = async (publishedScreenerId: string, inputData: any): Promise => { +export const evaluatePublishedScreener = async ( + publishedScreenerId: string, + inputData: any, +): Promise => { const url = apiUrl + "/published/" + publishedScreenerId + "/evaluate"; try { const response = await fetch(url, { diff --git a/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/CheckJsonEditor.tsx b/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/CheckJsonEditor.tsx index 0a4a9bf3..bbb3b82b 100644 --- a/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/CheckJsonEditor.tsx +++ b/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/CheckJsonEditor.tsx @@ -1,5 +1,12 @@ -import { Accessor, createEffect, onCleanup } from 'solid-js' -import { Content, createJSONEditor, JSONContent, JSONEditorPropsOptional, Mode, OnChange } from 'vanilla-jsoneditor' +import { Accessor, createEffect, onCleanup } from "solid-js"; +import { + Content, + createJSONEditor, + JSONContent, + JSONEditorPropsOptional, + Mode, + OnChange, +} from "vanilla-jsoneditor"; const JSONEditorSolid = (props: JSONEditorPropsOptional) => { let refContainer; @@ -9,16 +16,16 @@ const JSONEditorSolid = (props: JSONEditorPropsOptional) => { // create editor refEditor = createJSONEditor({ target: refContainer, - props: {} + props: {}, }); onCleanup(() => { // destroy editor if (refEditor) { - refEditor.destroy() - refEditor = null + refEditor.destroy(); + refEditor = null; } - }) + }); }); // update props @@ -28,15 +35,21 @@ const JSONEditorSolid = (props: JSONEditorPropsOptional) => { } }); - return
; -} - + return
; +}; -const CheckJsonEditor = ( - { jsonContent, onValidJsonChange }: - { jsonContent?: Accessor, onValidJsonChange: (json: JSONContent) => void } -) => { - const onChange = (updatedContent: Content, previousContent: Content, { contentErrors, patchResult }) => { +const CheckJsonEditor = ({ + jsonContent, + onValidJsonChange, +}: { + jsonContent?: Accessor; + onValidJsonChange: (json: JSONContent) => void; +}) => { + const onChange = ( + updatedContent: Content, + previousContent: Content, + { contentErrors, patchResult }, + ) => { if (contentErrors) { return; } @@ -49,7 +62,7 @@ const CheckJsonEditor = ( jsonContent = { json: JSON.parse(updatedContent.text) }; } onValidJsonChange(jsonContent); - } + }; return (
@@ -61,5 +74,5 @@ const CheckJsonEditor = ( />
); -} +}; export default CheckJsonEditor; diff --git a/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/EligibilityCheckTest.tsx b/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/EligibilityCheckTest.tsx index 5c6e9ea3..13c1dd49 100644 --- a/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/EligibilityCheckTest.tsx +++ b/builder-frontend/src/components/homeScreen/customChecks/customCheckDetail/checkTesting/EligibilityCheckTest.tsx @@ -22,7 +22,7 @@ const EligibilityCheckTest = ({ eligibilityCheck: Accessor; testEligibility: ( checkConfg: CheckConfig, - inputData: Record + inputData: Record, ) => Promise; }) => { const [checkConfig, setCheckConfig] = createSignal({ @@ -56,7 +56,7 @@ const EligibilityCheckTest = ({ onClick={async () => { const result = await testEligibility( checkConfig(), - currentJsonContent().json + currentJsonContent().json, ); if (!result) { return; diff --git a/builder-frontend/src/components/screenerEditor/NextStepsContentModal.test.tsx b/builder-frontend/src/components/screenerEditor/NextStepsContentModal.test.tsx index 8a30b687..30522e06 100644 --- a/builder-frontend/src/components/screenerEditor/NextStepsContentModal.test.tsx +++ b/builder-frontend/src/components/screenerEditor/NextStepsContentModal.test.tsx @@ -22,7 +22,10 @@ it("warns about new benefits, saves only the screener copy, and resets a benefit nextSteps: { eligible: { body: "Benefit instructions" } }, }; const field = { - benefitContent: { food: {}, removed: { eligible: { body: "Ignore removed" } } }, + benefitContent: { + food: {}, + removed: { eligible: { body: "Ignore removed" } }, + }, }; const save = vi.fn(); const container = document.body.appendChild(document.createElement("div")); diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.test.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.test.ts index 29646f6b..2abebb6b 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.test.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.test.ts @@ -1,77 +1,112 @@ // @vitest-environment jsdom -import { afterEach, describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it } from "vitest"; -import { Form } from '@bpmn-io/form-js-viewer'; -import CustomFormFieldsModule from './index'; -import { NONE_OF_THESE_VALUE } from './ChecklistWithNone'; -import { normalizeArrayFieldData } from '@/utils/arrayFieldData'; +import { Form } from "@bpmn-io/form-js-viewer"; +import CustomFormFieldsModule from "./index"; +import { NONE_OF_THESE_VALUE } from "./ChecklistWithNone"; +import { normalizeArrayFieldData } from "@/utils/arrayFieldData"; let form: Form | undefined; afterEach(() => { form?.destroy(); form = undefined; - document.body.innerHTML = ''; + document.body.innerHTML = ""; }); -describe('ChecklistWithNone', () => { +describe("ChecklistWithNone", () => { it.each([ { - source: 'input data', - options: { valuesKey: 'benefitOptions' }, - data: { benefitOptions: [{ label: 'Medicaid', value: 'Medicaid' }] }, + source: "input data", + options: { valuesKey: "benefitOptions" }, + data: { benefitOptions: [{ label: "Medicaid", value: "Medicaid" }] }, }, { - source: 'expression', - options: { valuesExpression: '=[{"label":"Medicaid","value":"Medicaid"}]' }, + source: "expression", + options: { + valuesExpression: '=[{"label":"Medicaid","value":"Medicaid"}]', + }, data: {}, }, - ])('places None last when options come from $source', async ({ options, data }) => { - const schema = { - components: [{ - type: 'checklist_none', - id: 'Field_enrollments', - key: 'enrollments', - label: 'Benefits', - description: 'Choose all that apply.', - ...options, - }], - type: 'default', - id: 'Form_test', - schemaVersion: 18, - }; - const container = document.body.appendChild(document.createElement('div')); - form = new Form({ container, additionalModules: [CustomFormFieldsModule] }); - await form.importSchema(schema, data); + ])( + "places None last when options come from $source", + async ({ options, data }) => { + const schema = { + components: [ + { + type: "checklist_none", + id: "Field_enrollments", + key: "enrollments", + label: "Benefits", + description: "Choose all that apply.", + ...options, + }, + ], + type: "default", + id: "Form_test", + schemaVersion: 18, + }; + const container = document.body.appendChild( + document.createElement("div"), + ); + form = new Form({ + container, + additionalModules: [CustomFormFieldsModule], + }); + await form.importSchema(schema, data); - const optionRows = Array.from(container.querySelectorAll('.fjs-form-field-checklist > .fjs-inline-label')); - expect(optionRows.map((row) => row.textContent?.trim())).toEqual(['Medicaid', 'None of these']); - expect(optionRows[1].nextElementSibling?.textContent).toContain('Choose all that apply.'); - }); + const optionRows = Array.from( + container.querySelectorAll( + ".fjs-form-field-checklist > .fjs-inline-label", + ), + ); + expect(optionRows.map((row) => row.textContent?.trim())).toEqual([ + "Medicaid", + "None of these", + ]); + expect(optionRows[1].nextElementSibling?.textContent).toContain( + "Choose all that apply.", + ); + }, + ); - it('makes None exclusive and preserves the answer across reimport', async () => { + it("makes None exclusive and preserves the answer across reimport", async () => { const schema = { - components: [{ - type: 'checklist_none', - id: 'Field_enrollments', - key: 'enrollments', - label: 'Benefits', - description: 'Choose all that apply.', - values: [{ label: 'SNAP', value: 'SNAP' }], - }], - type: 'default', - id: 'Form_test', + components: [ + { + type: "checklist_none", + id: "Field_enrollments", + key: "enrollments", + label: "Benefits", + description: "Choose all that apply.", + values: [{ label: "SNAP", value: "SNAP" }], + }, + ], + type: "default", + id: "Form_test", schemaVersion: 18, }; - const container = document.body.appendChild(document.createElement('div')); + const container = document.body.appendChild(document.createElement("div")); form = new Form({ container, additionalModules: [CustomFormFieldsModule] }); await form.importSchema(schema, {}); - const checkboxes = () => Array.from(container.querySelectorAll('input[type="checkbox"]')); + const checkboxes = () => + Array.from( + container.querySelectorAll('input[type="checkbox"]'), + ); expect(checkboxes()).toHaveLength(2); - const optionRows = Array.from(container.querySelectorAll('.fjs-form-field-checklist > .fjs-inline-label')); - expect(optionRows.map((row) => row.textContent?.trim())).toEqual(['SNAP', 'None of these']); - expect(optionRows[1].nextElementSibling?.textContent).toContain('Choose all that apply.'); + const optionRows = Array.from( + container.querySelectorAll( + ".fjs-form-field-checklist > .fjs-inline-label", + ), + ); + expect(optionRows.map((row) => row.textContent?.trim())).toEqual([ + "SNAP", + "None of these", + ]); + expect(optionRows[1].nextElementSibling?.textContent).toContain( + "Choose all that apply.", + ); checkboxes()[1].click(); await new Promise((resolve) => setTimeout(resolve, 0)); @@ -82,7 +117,7 @@ describe('ChecklistWithNone', () => { checkboxes()[0].click(); await new Promise((resolve) => setTimeout(resolve, 0)); - expect(form._getState().data.enrollments).toEqual(['SNAP']); + expect(form._getState().data.enrollments).toEqual(["SNAP"]); expect(checkboxes()[1].checked).toBe(false); checkboxes()[1].click(); @@ -90,9 +125,13 @@ describe('ChecklistWithNone', () => { expect(form._getState().data.enrollments).toEqual([NONE_OF_THESE_VALUE]); expect(checkboxes()[0].checked).toBe(false); - expect(normalizeArrayFieldData(schema, form._getState().data).enrollments).toEqual([]); + expect( + normalizeArrayFieldData(schema, form._getState().data).enrollments, + ).toEqual([]); checkboxes()[1].click(); await new Promise((resolve) => setTimeout(resolve, 0)); - expect(normalizeArrayFieldData(schema, form._getState().data).enrollments).toBeNull(); + expect( + normalizeArrayFieldData(schema, form._getState().data).enrollments, + ).toBeNull(); }); }); diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.ts index bd616000..8f382bf7 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone.ts @@ -1,10 +1,15 @@ -import { html } from 'htm/preact'; -import { useContext } from 'preact/hooks'; +import { html } from "htm/preact"; +import { useContext } from "preact/hooks"; -import { Checklist, FormContext, iconsByType, useExpressionEvaluation } from '@bpmn-io/form-js-viewer'; +import { + Checklist, + FormContext, + iconsByType, + useExpressionEvaluation, +} from "@bpmn-io/form-js-viewer"; -export const CHECKLIST_WITH_NONE_TYPE = 'checklist_none'; -export const NONE_OF_THESE_VALUE = '__bdt_none_of_these__'; +export const CHECKLIST_WITH_NONE_TYPE = "checklist_none"; +export const NONE_OF_THESE_VALUE = "__bdt_none_of_these__"; /** * The marker distinguishes an explicit "None" answer from form-js's default @@ -14,23 +19,33 @@ export function ChecklistWithNone(props: any) { const { field, value } = props; const { values, valuesExpression, valuesKey } = field; const { getService } = useContext(FormContext); - const initialData = getService('form')._getState().initialData; + const initialData = getService("form")._getState().initialData; const evaluatedOptions = useExpressionEvaluation(valuesExpression); - const noneSelected = Array.isArray(value) && value.includes(NONE_OF_THESE_VALUE); + const noneSelected = + Array.isArray(value) && value.includes(NONE_OF_THESE_VALUE); // Resolve options in the same order as form-js's Checklist: input data, // static values, then expression. Pass the result back to Checklist as // static values so its built-in renderer places None in the same list. - const options = valuesKey !== undefined - ? initialData?.[valuesKey] - : values !== undefined ? values : evaluatedOptions; - const { valuesKey: _valuesKey, valuesExpression: _valuesExpression, ...fieldWithoutSource } = field; + const options = + valuesKey !== undefined + ? initialData?.[valuesKey] + : values !== undefined + ? values + : evaluatedOptions; + const { + valuesKey: _valuesKey, + valuesExpression: _valuesExpression, + ...fieldWithoutSource + } = field; const fieldWithNone = { ...fieldWithoutSource, values: [ ...(Array.isArray(options) ? options : []).filter( - (option: any) => option?.value !== NONE_OF_THESE_VALUE && option !== NONE_OF_THESE_VALUE + (option: any) => + option?.value !== NONE_OF_THESE_VALUE && + option !== NONE_OF_THESE_VALUE, ), - { label: 'None of these', value: NONE_OF_THESE_VALUE }, + { label: "None of these", value: NONE_OF_THESE_VALUE }, ], }; @@ -40,11 +55,15 @@ export function ChecklistWithNone(props: any) { field=${fieldWithNone} onChange=${({ value: selections }: { value: unknown[] }) => { const selectedNone = selections.includes(NONE_OF_THESE_VALUE); - props.onChange({ value: selectedNone - ? noneSelected - ? selections.filter((selection) => selection !== NONE_OF_THESE_VALUE) - : [NONE_OF_THESE_VALUE] - : selections }); + props.onChange({ + value: selectedNone + ? noneSelected + ? selections.filter( + (selection) => selection !== NONE_OF_THESE_VALUE, + ) + : [NONE_OF_THESE_VALUE] + : selections, + }); }} /> `; @@ -53,9 +72,9 @@ export function ChecklistWithNone(props: any) { ChecklistWithNone.config = { ...Checklist.config, type: CHECKLIST_WITH_NONE_TYPE, - name: 'Checkbox group with None', - label: 'Checkbox group with None', - icon: iconsByType('checklist'), + name: "Checkbox group with None", + label: "Checkbox group with None", + icon: iconsByType("checklist"), // Preserve the internal marker when form-js imports saved answers. sanitizeValue: ({ value, ...options }: any) => Array.isArray(value) && value.includes(NONE_OF_THESE_VALUE) @@ -63,10 +82,16 @@ ChecklistWithNone.config = { : Checklist.config.sanitizeValue({ value, ...options }), create: (options: any = {}) => ({ ...Checklist.config.create(options), - label: 'Checkbox group with None', - ...options + label: "Checkbox group with None", + ...options, }), propertiesPanelEntries: [ - 'key', 'label', 'description', 'values', 'required', 'disabled', 'readonly' - ] + "key", + "label", + "description", + "values", + "required", + "disabled", + "readonly", + ], }; diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/YesNoQuestion.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/YesNoQuestion.ts index a4818006..dda7d659 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/YesNoQuestion.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/YesNoQuestion.ts @@ -2,24 +2,32 @@ * File's contents are an augmented version of Radio.js from the following location: * https://github.com/bpmn-io/form-js/blob/develop/packages/form-js-viewer/src/render/components/form-fields/Radio.js * The Preact component has been modified to create a Yes/No Question form field. - * + * * Helper functions [formFieldClasses(...)] and Preact "HTM" syntax taken from the following location: * https://github.com/bpmn-io/form-js-examples/blob/master/custom-components/app/extension/render/Range.js */ -import { html } from 'htm/preact'; -import { useRef } from 'preact/hooks'; +import { html } from "htm/preact"; +import { useRef } from "preact/hooks"; -import classNames from 'classnames'; -import isEqual from 'lodash/isEqual'; - -import { Radio, Description, Errors, Label } from '@bpmn-io/form-js'; -import { iconsByType } from '@bpmn-io/form-js-viewer'; +import classNames from "classnames"; +import isEqual from "lodash/isEqual"; +import { Radio, Description, Errors, Label } from "@bpmn-io/form-js"; +import { iconsByType } from "@bpmn-io/form-js-viewer"; const YES_NO_TYPE = "yes_no"; export function YesNoQuestion(props: any) { - const { disabled, errors = [], domId, onBlur, onFocus, field, readonly, value } = props; + const { + disabled, + errors = [], + domId, + onBlur, + onFocus, + field, + readonly, + value, + } = props; const { description, label, validate = {} } = field; const { required } = validate; @@ -43,84 +51,85 @@ export function YesNoQuestion(props: any) { /* Handle options */ const onChange = (newValue: boolean) => { - props.onChange({value: newValue}); + props.onChange({ value: newValue }); }; const yesNoOptions = [ - { label: 'Yes', value: true }, - { label: 'No', value: false } + { label: "Yes", value: true }, + { label: "No", value: false }, ]; - return (html` -
- <${Label} label=${label} required=${required} /> - ${yesNoOptions.map((option, index) => { - const itemDomId = `${domId}-${index}`; - const isChecked = isEqual(option.value, value); - return (html` -
- onChange(option.value)} - onBlur=${onRadioBlur} - onFocus=${onRadioFocus} - aria-describedby=${[descriptionId, errorMessageId].join(' ')} - required=${required} - aria-invalid=${errors.length > 0} - /> - <${Label} - htmlFor=${itemDomId} - label=${option.label} - class=${classNames({ 'fjs-checked': isChecked })} - required=${false} - /> -
` - ); - })} - <${Description} description=${description} /> - <${Errors} errors=${errors} /> -
` - ); + return html`
+ <${Label} label=${label} required=${required} /> + ${yesNoOptions.map((option, index) => { + const itemDomId = `${domId}-${index}`; + const isChecked = isEqual(option.value, value); + return html`
+ onChange(option.value)} + onBlur=${onRadioBlur} + onFocus=${onRadioFocus} + aria-describedby=${[descriptionId, errorMessageId].join(" ")} + required=${required} + aria-invalid=${errors.length > 0} + /> + <${Label} + htmlFor=${itemDomId} + label=${option.label} + class=${classNames({ "fjs-checked": isChecked })} + required=${false} + /> +
`; + })} + <${Description} description=${description} /> + <${Errors} errors=${errors} /> +
`; } YesNoQuestion.config = { /* Extend the default configuration of Radio Groups */ ...Radio.config, type: YES_NO_TYPE, - name: 'Yes/No', - label: 'Yes/No question', + name: "Yes/No", + label: "Yes/No question", sanitizeValue: ({ value }: { value: unknown }) => - typeof value === 'boolean' ? value : null, + typeof value === "boolean" ? value : null, icon: iconsByType("radio"), - group: 'selection', + group: "selection", propertiesPanelEntries: [ - 'key', - 'label', - 'description', - 'disabled', - 'readonly' - ] + "key", + "label", + "description", + "disabled", + "readonly", + ], }; -function formFieldClasses(type, { errors = [], disabled = false, readonly = false } = {}) { +function formFieldClasses( + type, + { errors = [], disabled = false, readonly = false } = {}, +) { if (!type) { - throw new Error('type required'); + throw new Error("type required"); } - return classNames( - 'fjs-form-field', - `fjs-form-field-${type}`, - { - 'fjs-has-errors': errors.length > 0, - 'fjs-disabled': disabled, - 'fjs-readonly': readonly - } - ); + return classNames("fjs-form-field", `fjs-form-field-${type}`, { + "fjs-has-errors": errors.length > 0, + "fjs-disabled": disabled, + "fjs-readonly": readonly, + }); } diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/index.js b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/index.js index 8565193e..68923317 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/index.js +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customFormFields/index.js @@ -1,7 +1,7 @@ -import { YesNoQuestion } from './YesNoQuestion'; -import { ChecklistWithNone } from './ChecklistWithNone'; -import { NextSteps } from '../nextSteps/NextSteps'; -import { PrintSummary } from '../printSummary/PrintSummary'; +import { YesNoQuestion } from "./YesNoQuestion"; +import { ChecklistWithNone } from "./ChecklistWithNone"; +import { NextSteps } from "../nextSteps/NextSteps"; +import { PrintSummary } from "../printSummary/PrintSummary"; /* * This is a module definition to register custom @@ -16,9 +16,9 @@ class CustomFormFieldsModule { } } -CustomFormFieldsModule.$inject = ["formFields"] +CustomFormFieldsModule.$inject = ["formFields"]; export default { - __init__: [ 'customFields' ], - customFields: [ 'type', CustomFormFieldsModule ] + __init__: ["customFields"], + customFields: ["type", CustomFormFieldsModule], }; diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/bpmn-io-dependencies.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/bpmn-io-dependencies.ts index 79ff11f0..c6e1bb7e 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/bpmn-io-dependencies.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/bpmn-io-dependencies.ts @@ -1,10 +1,10 @@ /** * WARNING: This Code is rewritten from https://github.com/bpmn-io/properties-panel - * + * * Due to an oddity with using contexts from compiled libraries, * SelectEntry and its context-using dependencies need to be * rewritten here in order for customKeyDropdownProvider.ts to function properly. - * + * * Specific files used here: * - https://github.com/bpmn-io/properties-panel/blob/main/src/components/entries/Select.js * - https://github.com/bpmn-io/properties-panel/blob/main/src/hooks/useError.js @@ -12,17 +12,24 @@ * - https://github.com/bpmn-io/properties-panel/blob/main/src/hooks/useShowEntryEvent.js */ -import classNames from 'classnames'; -import { isFunction } from 'min-dash'; +import classNames from "classnames"; +import { isFunction } from "min-dash"; -import { html } from 'htm/preact'; +import { html } from "htm/preact"; import { - useCallback, useContext, useEffect, useRef, useState -} from 'preact/hooks'; + useCallback, + useContext, + useEffect, + useRef, + useState, +} from "preact/hooks"; import { - useEvent, ErrorsContext, EventContext, PropertiesPanelContext -} from '@bpmn-io/properties-panel'; + useEvent, + ErrorsContext, + EventContext, + PropertiesPanelContext, +} from "@bpmn-io/properties-panel"; export function useEvent(event, callback, eventBus) { const eventContext = useContext(EventContext); @@ -51,7 +58,7 @@ export function useEvent(event, callback, eventBus) { eventBus.off(event, callback); } }; - }, [ callback, event, eventBus ]); + }, [callback, event, eventBus]); } /** @@ -68,15 +75,18 @@ export function useShowEntryEvent(id) { const focus = useRef(false); - const onShowEntry = useCallback((event) => { - if (event.id === id) { - onShow(); + const onShowEntry = useCallback( + (event) => { + if (event.id === id) { + onShow(); - if (!focus.current) { - focus.current = true; + if (!focus.current) { + focus.current = true; + } } - } - }, [ id ]); + }, + [id], + ); useEffect(() => { if (focus.current && ref.current) { @@ -92,7 +102,7 @@ export function useShowEntryEvent(id) { } }); - useEvent('propertiesPanel.showEntry', onShowEntry); + useEvent("propertiesPanel.showEntry", onShowEntry); return ref; } @@ -100,10 +110,12 @@ export function useShowEntryEvent(id) { export function useError(id) { const { errors } = useContext(ErrorsContext); - return errors[ id ]; + return errors[id]; } -{ /* Required to break up imports, see https://github.com/babel/babel/issues/15156 */ } +{ + /* Required to break up imports, see https://github.com/babel/babel/issues/15156 */ +} /** * @typedef { { value: string, label: string, disabled: boolean, children: { value: string, label: string, disabled: boolean } } } Option @@ -129,7 +141,7 @@ function Select(props) { label, onChange, options = [], - value = '', + value = "", disabled, onFocus, onBlur, @@ -137,10 +149,10 @@ function Select(props) { const ref = useShowEntryEvent(id); - const [ localValue, setLocalValue ] = useState(value); - const [ isOpen, setIsOpen ] = useState(false); + const [localValue, setLocalValue] = useState(value); + const [isOpen, setIsOpen] = useState(false); - const flatOptions = options.flatMap(option => option.children || [ option ]); + const flatOptions = options.flatMap((option) => option.children || [option]); const handleInput = ({ target }) => { setLocalValue(target.value); @@ -159,12 +171,12 @@ function Select(props) { }; const handleKeyDown = (event) => { - if (event.key === 'Enter') { + if (event.key === "Enter") { commitValue(); setIsOpen(false); } - if (event.key === 'ArrowDown') { + if (event.key === "ArrowDown") { event.preventDefault(); setIsOpen(true); } @@ -187,64 +199,75 @@ function Select(props) { } setLocalValue(value); - }, [ value ]); - - return (html` -
- -
- - -
- ${isOpen && html` -
- ${flatOptions.map((option, idx) => html` + }, [value]); + + return html`
+ +
+ + +
+ ${isOpen && + html` +
+ ${flatOptions.map( + (option, idx) => html` - `)} -
- `} -
` - ); + aria-selected=${option.value === localValue} + disabled=${option.disabled} + style="display: block; width: 100%; padding: 6px 8px; border: 0; background: ${option.value === + localValue + ? "#eee" + : "white"}; text-align: left;" + onMouseDown=${(event) => event.preventDefault()} + onClick=${() => selectOption(option)} + > + ${option.label} + + `, + )} +
+ `} +
`; } /** @@ -275,14 +298,14 @@ export default function SelectEntry(props) { onFocus, onBlur, validate, - tooltip + tooltip, } = props; const options = getOptions(element); const globalError = useError(id); - const [ localError, setLocalError ] = useState(null); + const [localError, setLocalError] = useState(null); let value = getValue(element); @@ -292,8 +315,7 @@ export default function SelectEntry(props) { setLocalError(newValidationError); } - }, [ value, validate ]); - + }, [value, validate]); const onChange = (newValue) => { let newValidationError = null; @@ -308,26 +330,23 @@ export default function SelectEntry(props) { const error = globalError || localError; - return (html` -
- <${Select} - id=${ id } - label=${ label } - value=${ value } - onChange=${ onChange } - onFocus=${ onFocus } - onBlur=${ onBlur } - options=${ options } - disabled=${ disabled } - element=${ element } /> - ${ error && html`
${ error }
` } -
` - ); + return html`
+ <${Select} + id=${id} + label=${label} + value=${value} + onChange=${onChange} + onFocus=${onFocus} + onBlur=${onBlur} + options=${options} + disabled=${disabled} + element=${element} + /> + ${error && html`
${error}
`} +
`; } export function isEdited(node) { @@ -337,5 +356,5 @@ export function isEdited(node) { // helpers ///////////////// function prefixId(id) { - return `bio-properties-panel-${ id }`; + return `bio-properties-panel-${id}`; } diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/customKeyDropdownProvider.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/customKeyDropdownProvider.ts index fc3ac730..ebdece9b 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/customKeyDropdownProvider.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/customKeyDropdownProvider.ts @@ -1,4 +1,4 @@ -import SelectEntry from './bpmn-io-dependencies'; +import SelectEntry from "./bpmn-io-dependencies"; /** * Custom properties provider that replaces the path entry @@ -7,7 +7,7 @@ class CustomKeyDropdownProvider { private pathOptionsService: any; private modeling: any; - static $inject = ['propertiesPanel', 'pathOptionsService', 'modeling']; + static $inject = ["propertiesPanel", "pathOptionsService", "modeling"]; constructor(propertiesPanel: any, pathOptionsService: any, modeling: any) { this.pathOptionsService = pathOptionsService; @@ -19,40 +19,42 @@ class CustomKeyDropdownProvider { const pathOptionsService = this.pathOptionsService; const modeling = this.modeling; - return function(groups: any[]) { + return function (groups: any[]) { // Find and modify the general group that contains the path entry - const generalGroup = groups.find(g => g.id === 'general'); + const generalGroup = groups.find((g) => g.id === "general"); if (!generalGroup) { return groups; } - // For Group components, just remove the key field entirely (don't add dropdown) - if (field.type === 'group') { + if (field.type === "group") { generalGroup.entries = generalGroup.entries.filter( - (entry: any) => entry.id !== 'path' + (entry: any) => entry.id !== "path", ); } // For Expression components, keep the original free-text key input // (expression keys store computed results, not form input paths) - if (field.type === 'expression') { + if (field.type === "expression") { return groups; } - const curKeyEntry = generalGroup.entries.find((entry: any) => entry.id === 'key'); + const curKeyEntry = generalGroup.entries.find( + (entry: any) => entry.id === "key", + ); // Only replace the Key input with dropdown if it exists if (curKeyEntry) { // Remove the original key entry generalGroup.entries = generalGroup.entries.filter( - (entry: any) => entry.id !== 'key' + (entry: any) => entry.id !== "key", ); // Add our custom dropdown key entry for non-group components generalGroup.entries.unshift({ ...curKeyEntry, - component: (props: any) => CustomKeyDropdown({ ...props, pathOptionsService, modeling }) + component: (props: any) => + CustomKeyDropdown({ ...props, pathOptionsService, modeling }), }); } return groups; @@ -63,37 +65,40 @@ class CustomKeyDropdownProvider { function CustomKeyDropdown(props: any) { const { element: field, id, pathOptionsService, modeling } = props; - const getValue = () => { return field.key || '' }; + const getValue = () => { + return field.key || ""; + }; const setValue = (value: string) => { - return modeling.editFormField(field, 'key', value); + return modeling.editFormField(field, "key", value); }; const getOptions = () => { // Get current field's key so it won't be disabled in the dropdown - const currentKey = field.key || ''; + const currentKey = field.key || ""; // Get the component type to filter compatible options - const componentType = field.type || ''; + const componentType = field.type || ""; // Get options from the injected service, passing current key to exclude from disabling - const options = pathOptionsService?.getOptions(currentKey, componentType) || []; + const options = + pathOptionsService?.getOptions(currentKey, componentType) || []; return options; }; return SelectEntry({ element: field, - id: id || 'key', - label: 'Key', - description: 'Enter any key or select a mapped data path', + id: id || "key", + label: "Key", + description: "Enter any key or select a mapped data path", getValue, setValue, - getOptions + getOptions, }); } // Module definition for didi export const customKeyModule = { - __init__: ['customKeyDropdownProvider'], - customKeyDropdownProvider: ['type', CustomKeyDropdownProvider] + __init__: ["customKeyDropdownProvider"], + customKeyDropdownProvider: ["type", CustomKeyDropdownProvider], }; diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/pathOptionsService.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/pathOptionsService.ts index f4e705cd..744fef26 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/pathOptionsService.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/customKeyDropdown/pathOptionsService.ts @@ -7,23 +7,35 @@ interface PathOption { const TYPE_COMPATIBILITY: Record = { // String types - 'string': ['textfield', 'textarea', 'select', 'radio', 'checklist', 'taglist'], + string: ["textfield", "textarea", "select", "radio", "checklist", "taglist"], // Number types - 'number': ['number'], - 'integer': ['number'], + number: ["number"], + integer: ["number"], // Boolean types: only components that submit real booleans. Other components // submit "true"/"false" strings; builders can still type a boolean key into them. - 'boolean': ['checkbox', 'yes_no'], + boolean: ["checkbox", "yes_no"], // Date/time types - 'date': ['datetime'], - 'date-time': ['datetime'], - 'time': ['datetime'], + date: ["datetime"], + "date-time": ["datetime"], + time: ["datetime"], // Array types (arrays of primitives) - 'array:string': ['checklist', 'checklist_none', 'taglist', 'select'], - 'array:number': ['checklist', 'checklist_none', 'taglist', 'select'], - 'array:boolean': ['checklist', 'checklist_none'], + "array:string": ["checklist", "checklist_none", "taglist", "select"], + "array:number": ["checklist", "checklist_none", "taglist", "select"], + "array:boolean": ["checklist", "checklist_none"], // Fallback for any/unknown types - compatible with all - 'any': ['textfield', 'textarea', 'number', 'checkbox', 'select', 'radio', 'checklist', 'checklist_none', 'taglist', 'datetime', 'yes_no'], + any: [ + "textfield", + "textarea", + "number", + "checkbox", + "select", + "radio", + "checklist", + "checklist_none", + "taglist", + "datetime", + "yes_no", + ], }; interface EventBus { @@ -33,7 +45,10 @@ interface EventBus { /** * Checks if a Form-JS component type is compatible with a JSON Schema type. */ -export function isTypeCompatible(schemaType: string | undefined, componentType: string): boolean { +export function isTypeCompatible( + schemaType: string | undefined, + componentType: string, +): boolean { if (!schemaType) { return true; // If no schema type, allow all } @@ -48,7 +63,7 @@ export function isTypeCompatible(schemaType: string | undefined, componentType: } export default class PathOptionsService { - static $inject = ['eventBus', 'formFieldRegistry']; + static $inject = ["eventBus", "formFieldRegistry"]; private pathOptions: PathOption[] = []; private eventBus: EventBus; @@ -64,7 +79,7 @@ export default class PathOptionsService { setOptions(options: PathOption[]): void { this.pathOptions = options; - this.eventBus.fire('pathOptions.changed', { options }); + this.eventBus.fire("pathOptions.changed", { options }); } /** @@ -96,19 +111,18 @@ export default class PathOptionsService { */ getOptions(currentFieldKey?: string, componentType?: string): PathOption[] { const usedKeys = this.getUsedKeys(); - return this.pathOptions - .filter(option => { - if (option.value !== currentFieldKey && usedKeys.has(option.value)) { - return false; - } - - // If no component type filter, show all options - if (!componentType) { - return true; - } - // Filter by type compatibility - return isTypeCompatible(option.type, componentType); - }); + return this.pathOptions.filter((option) => { + if (option.value !== currentFieldKey && usedKeys.has(option.value)) { + return false; + } + + // If no component type filter, show all options + if (!componentType) { + return true; + } + // Filter by type compatibility + return isTypeCompatible(option.type, componentType); + }); } /** @@ -120,6 +134,6 @@ export default class PathOptionsService { } export const pathOptionsModule = { - __init__: ['pathOptionsService'], - pathOptionsService: ['type', PathOptionsService] + __init__: ["pathOptionsService"], + pathOptionsService: ["type", PathOptionsService], }; diff --git a/builder-frontend/src/components/screenerEditor/formJsExtensions/pathTransform.ts b/builder-frontend/src/components/screenerEditor/formJsExtensions/pathTransform.ts index 1d2a1f21..0c8f7e67 100644 --- a/builder-frontend/src/components/screenerEditor/formJsExtensions/pathTransform.ts +++ b/builder-frontend/src/components/screenerEditor/formJsExtensions/pathTransform.ts @@ -1,14 +1,15 @@ import { CheckConfig } from "@/types"; import { keyComboFromEvent } from "vanilla-jsoneditor"; - export const determinePaths = (checks: CheckConfig[]): String[] => { const inputPaths: String[] = []; for (const check of checks) { let pathPrefix: String = ""; const checkInputPaths: String[] = []; - for (const [parameterKey, parameterValue] of Object.entries(check.parameters)) { + for (const [parameterKey, parameterValue] of Object.entries( + check.parameters, + )) { if (parameterKey == "personId") { if (!parameterValue) { throw Error("Misconfigured Check Params"); @@ -19,10 +20,11 @@ export const determinePaths = (checks: CheckConfig[]): String[] => { } } - for (const [parameterKey, parameterValue] of Object.entries(check.parameters)) { - + for (const [parameterKey, parameterValue] of Object.entries( + check.parameters, + )) { } } - + return inputPaths; -} \ No newline at end of file +}; diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/benefitList/modals/AddNewBenefitModal.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/benefitList/modals/AddNewBenefitModal.tsx index 59e26d0f..735491e2 100644 --- a/builder-frontend/src/components/screenerEditor/manageBenefits/benefitList/modals/AddNewBenefitModal.tsx +++ b/builder-frontend/src/components/screenerEditor/manageBenefits/benefitList/modals/AddNewBenefitModal.tsx @@ -1,25 +1,34 @@ -import { createStore } from "solid-js/store" +import { createStore } from "solid-js/store"; import type { CreateCustomBenefitRequest } from "@/types"; - type NewBenefitValues = { name: string; description: string; -} -const AddNewBenefitModal = ( - { addNewBenefit, closeModal }: - { addNewBenefit: (benefit: CreateCustomBenefitRequest) => Promise; closeModal: () => void } -) => { - const [newBenefit, setNewBenefit] = createStore({ name: "", description: "" }); +}; +const AddNewBenefitModal = ({ + addNewBenefit, + closeModal, +}: { + addNewBenefit: (benefit: CreateCustomBenefitRequest) => Promise; + closeModal: () => void; +}) => { + const [newBenefit, setNewBenefit] = createStore({ + name: "", + description: "", + }); // Styling for the Add button based on whether fields are filled const isAddDisabled = () => { - return newBenefit.name.trim() === "" || newBenefit.description.trim() === ""; - } + return ( + newBenefit.name.trim() === "" || newBenefit.description.trim() === "" + ); + }; const addButtonClasses = () => { - return isAddDisabled() ? "opacity-50 cursor-not-allowed" : "hover:bg-sky-700"; - } + return isAddDisabled() + ? "opacity-50 cursor-not-allowed" + : "hover:bg-sky-700"; + }; return (
@@ -79,5 +88,5 @@ const AddNewBenefitModal = (
); -} +}; export default AddNewBenefitModal; diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts index 4f6b7905..dd618da4 100644 --- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts +++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts @@ -192,10 +192,7 @@ const createScreenerBenefits = ( explanation, ); // A reload could report a failed read as a failed save, and would re-render every row. - if ( - screenerId() === targetScreenerId && - benefitId() === targetBenefitId - ) { + if (screenerId() === targetScreenerId && benefitId() === targetBenefitId) { explanationSaves++; setBenefit( "checks", diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditAliasModal.test.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditAliasModal.test.tsx index 65deadbd..f0e2a1b3 100644 --- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditAliasModal.test.tsx +++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditAliasModal.test.tsx @@ -109,9 +109,8 @@ describe("EditAliasModal", () => { container, ); - const input = container.querySelector( - 'input[type="text"]', - )!; + const input = + container.querySelector('input[type="text"]')!; input.value = "My own alias"; input.dispatchEvent(new InputEvent("input", { bubbles: true })); clickButton(container, "Save"); diff --git a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx index 4d1581a6..c18e46d6 100644 --- a/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx +++ b/builder-frontend/src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx @@ -100,8 +100,14 @@ it("keeps unsaved edits from a backdrop click, but Cancel still discards them", }); it.each([ - [new ApiError("Check not found in benefit", 404), "Check not found in benefit"], - [new ApiError("Could not update check explanation", 500), "Please try again."], + [ + new ApiError("Check not found in benefit", 404), + "Check not found in benefit", + ], + [ + new ApiError("Could not update check explanation", 500), + "Please try again.", + ], [new TypeError("Failed to fetch"), "Please try again."], ])("explains a failed save: %s", async (failure, message) => { dispose = render( diff --git a/builder-frontend/src/components/shared/Modal.tsx b/builder-frontend/src/components/shared/Modal.tsx index 6ee8fc83..00f51ba3 100644 --- a/builder-frontend/src/components/shared/Modal.tsx +++ b/builder-frontend/src/components/shared/Modal.tsx @@ -17,11 +17,7 @@ export const Modal: Component> = (props) => { return ( -
+
e.stopPropagation()} diff --git a/builder-frontend/src/config/environment.ts b/builder-frontend/src/config/environment.ts index 8a777454..b363f1d7 100644 --- a/builder-frontend/src/config/environment.ts +++ b/builder-frontend/src/config/environment.ts @@ -37,9 +37,7 @@ function resolveEnv(): Env { } // Browser-based Codespace: hostname looks like "-.app.github.dev" - const codespaceMatch = hostname.match( - /^(.+)-\d+\.(app\.github\.dev)$/, - ); + const codespaceMatch = hostname.match(/^(.+)-\d+\.(app\.github\.dev)$/); if (codespaceMatch) { const codespaceName = codespaceMatch[1]; const domain = codespaceMatch[2]; diff --git a/builder-frontend/src/firebase/firebase.js b/builder-frontend/src/firebase/firebase.js index 2365af83..74d0e71f 100644 --- a/builder-frontend/src/firebase/firebase.js +++ b/builder-frontend/src/firebase/firebase.js @@ -27,11 +27,13 @@ const app = initializeApp(firebaseConfig); export const auth = getAuth(app); // Connect to emulators in development -if (import.meta.env.MODE === 'development') { +if (import.meta.env.MODE === "development") { try { const prefixes = ["localhost", "127.0.0.1"]; - const isLocalhost = prefixes.some(prefix => AUTH_DOMAIN.startsWith(prefix)); - const protocol = isLocalhost ? 'http' : 'https'; + const isLocalhost = prefixes.some((prefix) => + AUTH_DOMAIN.startsWith(prefix), + ); + const protocol = isLocalhost ? "http" : "https"; const authEmulatorUrl = `${protocol}://${AUTH_DOMAIN}`; connectAuthEmulator(auth, authEmulatorUrl, { disableWarnings: true }); console.log("🔧 Connected to Firebase auth emulator"); diff --git a/builder-frontend/src/integrations/nextSteps.test.ts b/builder-frontend/src/integrations/nextSteps.test.ts index f78c80db..8572e7b4 100644 --- a/builder-frontend/src/integrations/nextSteps.test.ts +++ b/builder-frontend/src/integrations/nextSteps.test.ts @@ -102,25 +102,25 @@ it("does not invent missing content or pass unsafe application links", () => { it("names unmet requirements the way results do", () => { const aliased = structuredClone(results); aliased.food.check_results.a.aliasName = "IncomeLimit"; - expect( - projectNextSteps(aliased, field)!.food.unmetRequirements[0], - ).toBe("Income Limit"); + expect(projectNextSteps(aliased, field)!.food.unmetRequirements[0]).toBe( + "Income Limit", + ); }); it("keeps an author's wording in unmet requirements", () => { const aliased = structuredClone(results); aliased.food.check_results.a.aliasName = "Age 18-64"; - expect( - projectNextSteps(aliased, field)!.food.unmetRequirements[0], - ).toBe("Age 18-64"); + expect(projectNextSteps(aliased, field)!.food.unmetRequirements[0]).toBe( + "Age 18-64", + ); }); it("lists a failed check whose alias is only punctuation", () => { const aliased = structuredClone(results); aliased.food.check_results.a.aliasName = "--"; - expect( - projectNextSteps(aliased, field)!.food.unmetRequirements[0], - ).toBe("--"); + expect(projectNextSteps(aliased, field)!.food.unmetRequirements[0]).toBe( + "--", + ); }); it("uses plain-language explanations for unmet requirements with alias and name fallbacks", () => { diff --git a/builder-frontend/src/testForm.json b/builder-frontend/src/testForm.json index e4bb1e3c..8c642005 100644 --- a/builder-frontend/src/testForm.json +++ b/builder-frontend/src/testForm.json @@ -57,4 +57,4 @@ "version": "1.15.0" }, "schemaVersion": 18 -} \ No newline at end of file +} diff --git a/builder-frontend/src/utils/arrayFieldData.test.ts b/builder-frontend/src/utils/arrayFieldData.test.ts index 736b631e..d722adb8 100644 --- a/builder-frontend/src/utils/arrayFieldData.test.ts +++ b/builder-frontend/src/utils/arrayFieldData.test.ts @@ -1,77 +1,108 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it } from "vitest"; -import { normalizeArrayFieldData } from './arrayFieldData'; -import { NONE_OF_THESE_VALUE } from '@/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone'; +import { normalizeArrayFieldData } from "./arrayFieldData"; +import { NONE_OF_THESE_VALUE } from "@/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone"; const schema = { - components: [{ - type: 'checklist_none', - key: 'people.client.enrollments', - }], + components: [ + { + type: "checklist_none", + key: "people.client.enrollments", + }, + ], }; -describe('normalizeArrayFieldData', () => { - it('distinguishes unanswered, explicit None, and selected values', () => { - expect(normalizeArrayFieldData(schema, { people: { client: {} } })).toEqual({ - people: { client: { enrollments: null } }, - }); - expect(normalizeArrayFieldData(schema, { - people: { client: { enrollments: [] } }, - })).toEqual({ people: { client: { enrollments: null } } }); - expect(normalizeArrayFieldData(schema, { - people: { client: { enrollments: [NONE_OF_THESE_VALUE] } }, - })).toEqual({ people: { client: { enrollments: [] } } }); - expect(normalizeArrayFieldData(schema, { - people: { client: { enrollments: ['SNAP', 'Medicaid'] } }, - })).toEqual({ - people: { client: { enrollments: ['SNAP', 'Medicaid'] } }, +describe("normalizeArrayFieldData", () => { + it("distinguishes unanswered, explicit None, and selected values", () => { + expect(normalizeArrayFieldData(schema, { people: { client: {} } })).toEqual( + { + people: { client: { enrollments: null } }, + }, + ); + expect( + normalizeArrayFieldData(schema, { + people: { client: { enrollments: [] } }, + }), + ).toEqual({ people: { client: { enrollments: null } } }); + expect( + normalizeArrayFieldData(schema, { + people: { client: { enrollments: [NONE_OF_THESE_VALUE] } }, + }), + ).toEqual({ people: { client: { enrollments: [] } } }); + expect( + normalizeArrayFieldData(schema, { + people: { client: { enrollments: ["SNAP", "Medicaid"] } }, + }), + ).toEqual({ + people: { client: { enrollments: ["SNAP", "Medicaid"] } }, }); }); - it('sends null for other empty array fields and does not mutate form-js data', () => { + it("sends null for other empty array fields and does not mutate form-js data", () => { const data = { regular: [] as string[], - tags: ['a'], - name: '', + tags: ["a"], + name: "", people: { client: { enrollments: [NONE_OF_THESE_VALUE] } }, }; - const normalized = normalizeArrayFieldData({ - components: [ - ...schema.components, - { type: 'checklist', key: 'regular' }, - { type: 'taglist', key: 'tags' }, - { type: 'textfield', key: 'name' }, - ], - }, data); + const normalized = normalizeArrayFieldData( + { + components: [ + ...schema.components, + { type: "checklist", key: "regular" }, + { type: "taglist", key: "tags" }, + { type: "textfield", key: "name" }, + ], + }, + data, + ); expect(normalized.regular).toBeNull(); - expect(normalized.tags).toEqual(['a']); - expect(normalized.name).toBe(''); + expect(normalized.tags).toEqual(["a"]); + expect(normalized.name).toBe(""); expect(normalized.people.client.enrollments).toEqual([]); expect(data.people.client.enrollments).toEqual([NONE_OF_THESE_VALUE]); }); - it('does not create missing parent objects or lists', () => { - expect(normalizeArrayFieldData(schema, { people: {} })).toEqual({ people: {} }); - expect(normalizeArrayFieldData({ - components: [{ - type: 'dynamiclist', - path: 'household', - components: [{ type: 'checklist_none', key: 'enrollments' }], - }], - }, {})).toEqual({}); + it("does not create missing parent objects or lists", () => { + expect(normalizeArrayFieldData(schema, { people: {} })).toEqual({ + people: {}, + }); + expect( + normalizeArrayFieldData( + { + components: [ + { + type: "dynamiclist", + path: "household", + components: [{ type: "checklist_none", key: "enrollments" }], + }, + ], + }, + {}, + ), + ).toEqual({}); }); - it('normalizes fields inside repeated groups', () => { - const data = { household: [{ enrollments: [] }, { enrollments: ['SNAP'] }] }; - expect(normalizeArrayFieldData({ - components: [{ - type: 'dynamiclist', - path: 'household', - components: [{ type: 'checklist_none', key: 'enrollments' }], - }], - }, data)).toEqual({ - household: [{ enrollments: null }, { enrollments: ['SNAP'] }], + it("normalizes fields inside repeated groups", () => { + const data = { + household: [{ enrollments: [] }, { enrollments: ["SNAP"] }], + }; + expect( + normalizeArrayFieldData( + { + components: [ + { + type: "dynamiclist", + path: "household", + components: [{ type: "checklist_none", key: "enrollments" }], + }, + ], + }, + data, + ), + ).toEqual({ + household: [{ enrollments: null }, { enrollments: ["SNAP"] }], }); }); }); diff --git a/builder-frontend/src/utils/arrayFieldData.ts b/builder-frontend/src/utils/arrayFieldData.ts index 46598889..8c900ffc 100644 --- a/builder-frontend/src/utils/arrayFieldData.ts +++ b/builder-frontend/src/utils/arrayFieldData.ts @@ -1,12 +1,12 @@ import { CHECKLIST_WITH_NONE_TYPE, NONE_OF_THESE_VALUE, -} from '@/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone'; -import { forEachKeyedField, type FormComponent } from '@/utils/formFields'; -import { isUnsafeObjectKey } from '@/utils/unsafeObjectKeys'; +} from "@/components/screenerEditor/formJsExtensions/customFormFields/ChecklistWithNone"; +import { forEachKeyedField, type FormComponent } from "@/utils/formFields"; +import { isUnsafeObjectKey } from "@/utils/unsafeObjectKeys"; // Field types whose answers are arrays of selected options. -const ARRAY_FIELD_TYPES = ['checklist', 'taglist', CHECKLIST_WITH_NONE_TYPE]; +const ARRAY_FIELD_TYPES = ["checklist", "taglist", CHECKLIST_WITH_NONE_TYPE]; /** * Convert array answers to eligibility input data. form-js uses [] for an @@ -24,7 +24,7 @@ export function normalizeArrayFieldData( target.forEach((item) => normalizeAtPath(item, segments)); return; } - if (target === null || typeof target !== 'object') return; + if (target === null || typeof target !== "object") return; const [segment, ...rest] = segments; if (isUnsafeObjectKey(segment)) return; @@ -36,14 +36,17 @@ export function normalizeArrayFieldData( } const value = target[segment]; - target[segment] = Array.isArray(value) && value.includes(NONE_OF_THESE_VALUE) - ? [] - : Array.isArray(value) && value.length > 0 ? value : null; + target[segment] = + Array.isArray(value) && value.includes(NONE_OF_THESE_VALUE) + ? [] + : Array.isArray(value) && value.length > 0 + ? value + : null; } forEachKeyedField(schema?.components, (component, path) => { - if (ARRAY_FIELD_TYPES.includes(component.type ?? '')) { - normalizeAtPath(result, path.split('.')); + if (ARRAY_FIELD_TYPES.includes(component.type ?? "")) { + normalizeAtPath(result, path.split(".")); } }); return result; diff --git a/builder-frontend/src/utils/formSchemaUtils.ts b/builder-frontend/src/utils/formSchemaUtils.ts index fd632293..ecdf8801 100644 --- a/builder-frontend/src/utils/formSchemaUtils.ts +++ b/builder-frontend/src/utils/formSchemaUtils.ts @@ -19,11 +19,13 @@ interface FormSchema { export function extractFormPaths(schema: FormSchema): string[] { const paths = new Set(); - function traverse(components: FormComponent[], parentPath: string = '') { + function traverse(components: FormComponent[], parentPath: string = "") { for (const component of components) { // Build current path prefix (for groups/lists with path property) const currentPrefix = component.path - ? (parentPath ? `${parentPath}.${component.path}` : component.path) + ? parentPath + ? `${parentPath}.${component.path}` + : component.path : parentPath; // If component has a key, it's a data field - add its full path diff --git a/builder-frontend/src/utils/title_case.test.ts b/builder-frontend/src/utils/title_case.test.ts index eff55535..143e829a 100644 --- a/builder-frontend/src/utils/title_case.test.ts +++ b/builder-frontend/src/utils/title_case.test.ts @@ -3,12 +3,12 @@ import { titleCase } from "./title_case"; describe("titleCase", () => { it("formats endpoint slugs", () => { - expect(titleCase("phl-senior-citizen-tax-freeze")) - .toBe("Phl senior citizen tax freeze"); + expect(titleCase("phl-senior-citizen-tax-freeze")).toBe( + "Phl senior citizen tax freeze", + ); }); it("formats DMN context aliases", () => { - expect(titleCase("NotAlreadyOnHomestead")) - .toBe("Not Already On Homestead"); + expect(titleCase("NotAlreadyOnHomestead")).toBe("Not Already On Homestead"); }); }); diff --git a/builder-frontend/src/utils/title_case.ts b/builder-frontend/src/utils/title_case.ts index 37f4b152..758780a7 100644 --- a/builder-frontend/src/utils/title_case.ts +++ b/builder-frontend/src/utils/title_case.ts @@ -7,4 +7,4 @@ export const titleCase = (str: string) => { return words.length === 0 ? words : words.charAt(0).toUpperCase() + words.slice(1); -} +}; diff --git a/builder-frontend/src/utils/unknownAnswers.test.ts b/builder-frontend/src/utils/unknownAnswers.test.ts index 4c470038..a57e2e98 100644 --- a/builder-frontend/src/utils/unknownAnswers.test.ts +++ b/builder-frontend/src/utils/unknownAnswers.test.ts @@ -1,43 +1,43 @@ -import { describe, expect, it } from 'vitest'; +import { describe, expect, it } from "vitest"; import { findFilledUnknownPaths, keepUnansweredPaths, restoreUnknownAnswers, -} from './unknownAnswers'; +} from "./unknownAnswers"; -describe('unknown prefill answers', () => { +describe("unknown prefill answers", () => { const prefill = { custom: { wantsExtraCash: null, householdIncome: 0 }, simpleChecks: { livesInPhiladelphiaPa: false }, - people: [{ name: 'Alex' }], + people: [{ name: "Alex" }], }; // What form-js holds after importing the prefill. const formData = { - custom: { wantsExtraCash: false, householdIncome: 0, city: '' }, + custom: { wantsExtraCash: false, householdIncome: 0, city: "" }, simpleChecks: { livesInPhiladelphiaPa: false }, - people: [{ name: 'Alex', note: '' }], + people: [{ name: "Alex", note: "" }], }; - it('finds empty values form-js filled in for null or omitted answers', () => { + it("finds empty values form-js filled in for null or omitted answers", () => { expect(findFilledUnknownPaths(prefill, formData)).toEqual([ - ['custom', 'wantsExtraCash'], - ['custom', 'city'], - ['people', '0', 'note'], + ["custom", "wantsExtraCash"], + ["custom", "city"], + ["people", "0", "note"], ]); }); - it('sends unanswered unknowns as null without mutating form data', () => { + it("sends unanswered unknowns as null without mutating form data", () => { const paths = findFilledUnknownPaths(prefill, formData); expect(restoreUnknownAnswers(formData, paths)).toEqual({ custom: { wantsExtraCash: null, householdIncome: 0, city: null }, simpleChecks: { livesInPhiladelphiaPa: false }, - people: [{ name: 'Alex', note: null }], + people: [{ name: "Alex", note: null }], }); expect(formData.custom.wantsExtraCash).toBe(false); }); - it('keeps an answer once the user changes it, even back to the empty value', () => { + it("keeps an answer once the user changes it, even back to the empty value", () => { let paths = findFilledUnknownPaths(prefill, formData); const checked = structuredClone(formData); checked.custom.wantsExtraCash = true; @@ -51,7 +51,7 @@ describe('unknown prefill answers', () => { }); }); - it('does not add paths that are missing from the data', () => { - expect(restoreUnknownAnswers({}, [['custom', 'city']])).toEqual({}); + it("does not add paths that are missing from the data", () => { + expect(restoreUnknownAnswers({}, [["custom", "city"]])).toEqual({}); }); }); diff --git a/builder-frontend/src/utils/unknownAnswers.ts b/builder-frontend/src/utils/unknownAnswers.ts index 3df63456..0d712fd4 100644 --- a/builder-frontend/src/utils/unknownAnswers.ts +++ b/builder-frontend/src/utils/unknownAnswers.ts @@ -1,7 +1,7 @@ type Path = string[]; // form-js's empty values for checkboxes (false) and text fields (''). -const isFilledEmptyValue = (value: unknown) => value === false || value === ''; +const isFilledEmptyValue = (value: unknown) => value === false || value === ""; const valueAt = (data: unknown, path: Path) => path.reduce( @@ -21,7 +21,7 @@ export function findFilledUnknownPaths( if (isFilledEmptyValue(formData)) { return valueAt(prefill, path) == null ? [path] : []; } - if (formData === null || typeof formData !== 'object') return []; + if (formData === null || typeof formData !== "object") return []; return Object.entries(formData).flatMap(([key, value]) => findFilledUnknownPaths(prefill, value, [...path, key]), ); @@ -40,7 +40,7 @@ export function restoreUnknownAnswers(data: T, paths: Path[]): T { const key = path[path.length - 1]; if ( parent && - typeof parent === 'object' && + typeof parent === "object" && isFilledEmptyValue(parent[key]) ) { parent[key] = null; diff --git a/builder-frontend/src/utils/unsafeObjectKeys.ts b/builder-frontend/src/utils/unsafeObjectKeys.ts index 95aee254..077e1107 100644 --- a/builder-frontend/src/utils/unsafeObjectKeys.ts +++ b/builder-frontend/src/utils/unsafeObjectKeys.ts @@ -1,5 +1,5 @@ // Property names that can reach an object's prototype when copied or assigned. -const UNSAFE_OBJECT_KEYS = ['__proto__', 'prototype', 'constructor']; +const UNSAFE_OBJECT_KEYS = ["__proto__", "prototype", "constructor"]; export const isUnsafeObjectKey = (key: string) => UNSAFE_OBJECT_KEYS.includes(key); diff --git a/builder-frontend/tsconfig.json b/builder-frontend/tsconfig.json index 3c78901e..8f3e2bf3 100644 --- a/builder-frontend/tsconfig.json +++ b/builder-frontend/tsconfig.json @@ -24,7 +24,9 @@ "allowSyntheticDefaultImports": true, /* Type Checking */ - "strict": true + "strict": true, + // Library type definitions are their authors' to fix; check only our code. + "skipLibCheck": true }, "include": ["src/**/*"] } diff --git a/builder-frontend/typecheck-baseline.json b/builder-frontend/typecheck-baseline.json new file mode 100644 index 00000000..d0ce1c96 --- /dev/null +++ b/builder-frontend/typecheck-baseline.json @@ -0,0 +1,38 @@ +{ + "src/App.tsx": 3, + "src/components/Header/Header.tsx": 4, + "src/components/auth/AuthForm.test.tsx": 2, + "src/components/homeScreen/ScreenersList.tsx": 4, + "src/components/homeScreen/customChecks/customCheckDetail/ParametersConfiguration.tsx": 7, + "src/components/homeScreen/customChecks/customCheckDetail/PublishCheck.test.tsx": 3, + "src/components/homeScreen/customChecks/customCheckDetail/checkTesting/CheckJsonEditor.tsx": 8, + "src/components/homeScreen/customChecks/customCheckDetail/checkTesting/EligibilityCheckTest.tsx": 3, + "src/components/homeScreen/customChecks/customCheckDetail/customCheckDetailResource.ts": 13, + "src/components/homeScreen/customChecks/modals/CheckModal.tsx": 1, + "src/components/homeScreen/customChecks/modals/RenameCheck.test.tsx": 2, + "src/components/icon/QuestionMarkIcon.tsx": 2, + "src/components/screenerEditor/FormEditorView.bindings.test.tsx": 6, + "src/components/screenerEditor/FormEditorView.tsx": 19, + "src/components/screenerEditor/Publish.tsx": 4, + "src/components/screenerEditor/ScreenerEditor.test.tsx": 5, + "src/components/screenerEditor/ScreenerEditor.tsx": 1, + "src/components/screenerEditor/formJsExtensions/customFormFields/YesNoQuestion.ts": 3, + "src/components/screenerEditor/formJsExtensions/customKeyDropdown/bpmn-io-dependencies.ts": 28, + "src/components/screenerEditor/formJsExtensions/nextSteps/selection.ts": 1, + "src/components/screenerEditor/formJsExtensions/printSummary/PrintSummary.test.ts": 1, + "src/components/screenerEditor/manageBenefits/ManageBenefits.tsx": 2, + "src/components/screenerEditor/manageBenefits/benefitList/BenefitList.tsx": 3, + "src/components/screenerEditor/manageBenefits/configureBenefit/SelectedEligibilityCheck.tsx": 1, + "src/components/screenerEditor/manageBenefits/configureBenefit/benefitResource.ts": 2, + "src/components/screenerEditor/manageBenefits/configureBenefit/modals/EditExplanationModal.test.tsx": 1, + "src/components/screenerEditor/preview/FormRenderer.tsx": 1, + "src/components/screenerEditor/preview/Preview.tsx": 2, + "src/components/shared/CheckExplanation.tsx": 1, + "src/components/shared/ComponentLibrary.tsx": 1, + "src/components/shared/HamburgerMenu/HamburgerMenuPanel.tsx": 1, + "src/components/shared/Modal.tsx": 1, + "src/context/AuthContext.tsx": 9, + "src/index.tsx": 1, + "src/utils/checkName.ts": 2, + "src/utils/unansweredQuestions.ts": 3 +}