npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

addv-questionnaire

v0.1.10

Published

Reusable questionnaire filler, question types, validation, auto-calculation and Redux slice for ADDV projects.

Downloads

1,363

Readme

addv-questionnaire

Centralized, reusable questionnaire engine for ADDV projects. Ships the full patient questionnaire flow — every question type, validation, auto-calculation (date-range → days, BMI, BP classification), a Redux slice, and journey orchestration — as a single source of truth so changes flow to every consumer app from one package.

  • Framework: React 18+/19, Next.js 14+ (App Router friendly)
  • Source-only package: ships src/** as-is. Consumers transpile the package via their bundler (see Consumer setup).
  • Styling: Tailwind + SCSS Modules. Host app must support both.

Contents


Install

npm install addv-questionnaire
# or
pnpm add addv-questionnaire
# or
yarn add addv-questionnaire

Then install the peer dependencies your app is missing.


Consumer setup

The package is source-only and has three wiring requirements. Do all four steps once at app startup.

1. Next.js transpile config

The package ships JS/JSX/SCSS source — your bundler must compile it. In Next.js:

// next.config.ts
import type { NextConfig } from "next";

const config: NextConfig = {
  transpilePackages: ["addv-questionnaire"],
};
export default config;

For Vite / webpack consumers, ensure node_modules/addv-questionnaire/** is included by your JSX + SCSS loaders.

2. Register the Redux store

Call setStoreRef(store) immediately after configureStore — before any component that uses the slice mounts. Include questionnaireReducer and localStore in your root reducer.

// store/index.ts
import { configureStore, combineReducers } from "@reduxjs/toolkit";
import { persistReducer, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import {
  questionnaireReducer,
  localStore,
  setStoreRef,
} from "addv-questionnaire";

const rootReducer = combineReducers({
  questionnaire: questionnaireReducer,
  localStore,
  // ...your other reducers
});

const persistedReducer = persistReducer(
  { key: "root", storage, whitelist: ["questionnaire"] },
  rootReducer,
);

export const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({ serializableCheck: false }),
});

setStoreRef(store); // ← register BEFORE persistStore / any mount

export const persistor = persistStore(store);

⚠️ If you forget this step you'll see: [addv-questionnaire] Tried to access store.dispatch before setStoreRef(store) was called.

3. Inject external dependencies (setGlobalDeps)

The heavy journey components (QuestionnaireFillUpTokenNew, QuestionnaireFromPINVerification) were extracted with thousands of call-sites to app-specific APIs, toasts and constants. Rather than rewriting all of them, the package proxies these through setGlobalDeps. Call it once from a top-level client component.

// app/providers.tsx
"use client";

import { useRef } from "react";
import { Provider as ReduxProvider } from "react-redux";
import { setGlobalDeps } from "addv-questionnaire";

import { store } from "@/store";
import { addItemToCart } from "@/store/slices/cartSlice";
import { GET_DEV_CORPORATE_ID, GET_PROD_CORPORATE_ID } from "@/lib/constants";
import { sendMailAfterAssessmentNextAPI } from "@/lib/services/NextServices/NextJSApis";
import {
  errorToast,
  successToast,
  getErrorObject,
} from "@/lib/utils/utilities/utils";
import {
  submitQuestionAnswersAPI,
  submitQuestionAnswersAPIProduct,
  submitHypertensionAnswers,
  createPreconsultation,
  createPreconsultationForMedication,
  shareConsentAfterPreConsult,
  checkPatientQuestionnaireAuthorization,
  checkTokenValidity,
  fetchQuestionnaireTypes,
} from "@/lib/services/patientQuestionnaire";

export function Providers({ children }: { children: React.ReactNode }) {
  const inited = useRef(false);
  if (!inited.current) {
    setGlobalDeps({
      store,
      addItemToCart,
      GET_DEV_CORPORATE_ID,
      GET_PROD_CORPORATE_ID,
      sendMailAfterAssessmentNextAPI,
      errorToast,
      successToast,
      getErrorObject,
      submitQuestionAnswersAPI,
      submitQuestionAnswersAPIProduct,
      submitHypertensionAnswers,
      createPreconsultation,
      createPreconsultationForMedication,
      shareConsentAfterPreConsult,
      checkPatientQuestionnaireAuthorization,
      checkTokenValidity,
      fetchQuestionnaireTypes,
    });
    inited.current = true;
  }

  return <ReduxProvider store={store}>{children}</ReduxProvider>;
}

Full list of injectable deps

| Name | Signature | Purpose | | --- | --- | --- | | store | Redux store | Internal store.dispatch(...) / store.getState() (also handled by setStoreRef) | | addItemToCart | (item) => void | Adds a medication to the host cart after a product outcome | | GET_DEV_CORPORATE_ID | () => string | Corporate id for non-prod env | | GET_PROD_CORPORATE_ID | () => string | Corporate id for prod env | | errorToast | (msg) => void | Error notification | | successToast | (msg) => void | Success notification | | getErrorObject | (err) => { message, code? } | Normalises backend error payloads | | sendMailAfterAssessmentNextAPI | (payload) => Promise<void> | Emails the outcome summary | | submitQuestionAnswersAPI | (payload) => Promise<Response> | Submit answers (condition flow) | | submitQuestionAnswersAPIProduct | (payload) => Promise<Response> | Submit answers (product flow) | | submitHypertensionAnswers | (payload) => Promise<Response> | Hypertension-specific submit | | createPreconsultation | (payload) => Promise<Response> | Create pre-consult for condition | | createPreconsultationForMedication | (payload) => Promise<Response> | Create pre-consult for medication | | shareConsentAfterPreConsult | (payload) => Promise<Response> | Share consent form | | checkPatientQuestionnaireAuthorization | (token) => Promise<Response> | Token-gated authorization check | | checkTokenValidity | (token) => Promise<Response> | Generic JWT validity check | | fetchQuestionnaireTypes | (params) => Promise<Response> | Loads the list of questionnaire templates |

4. Wrap questionnaire routes with QuestionnaireProvider

QuestionnaireProvider carries React-native props the package needs — primarily fetchDropdownOptions (for drug / pharmacy / snomed search dropdowns) — plus config and callbacks.

"use client";
import { QuestionnaireProvider } from "addv-questionnaire";
import { getDrugsApiForPatient } from "@/lib/services/...";
import { generateTokenFromJWT } from "addv-questionnaire";

export function QuestionnairePageWrapper({ children }: { children: React.ReactNode }) {
  const services = {
    fetchDropdownOptions: async ({ apiEndpoint, search, page, extraParams }) => {
      const token = generateTokenFromJWT({ /* ... */ }, process.env.NEXT_PUBLIC_JWT_SECRET);
      const res = await getDrugsApiForPatient({
        endpoint: apiEndpoint,
        search,
        page,
        token,
        ...extraParams,
      });
      return { data: res.data?.items ?? [], pagination: res.data?.pagination };
    },
    // Optional:
    // sendMailAfterAssessment: async (payload) => { ... },
    // addItemToCart: (item) => dispatch(addItemToCart(item)),
  };

  const config = {
    apiBaseUrl: process.env.NEXT_PUBLIC_API_BASE_URL,
    jwtSecret: process.env.NEXT_PUBLIC_JWT_SECRET,
    corporateIds: { dev: "...", prod: "..." },
    branding: { primaryColor: "#0c4f4a", logoUrl: "/logo.svg", corporateName: "Paydens" },
    routes: { onSuccess: "/booking/success", onCancel: "/", signIn: "/sign-in" },
    featureFlags: { enableNHS: true, enableReviewScreen: true, isPrivateBooking: false },
  };

  return (
    <QuestionnaireProvider
      services={services}
      config={config}
      callbacks={{
        onJourneyChange: (step) => {},
        onSubmitSuccess: (result) => {},
        onError: (err) => {},
      }}
      patientContext={{ token: undefined, dob: undefined, gender: undefined }}
    >
      {children}
    </QuestionnaireProvider>
  );
}

What the package exports

All exports come from the root (import { X } from "addv-questionnaire").

Constants

DATE_FORMAT, DATE_TIME_FORMAT, HH_HOUR_MIN_FORMAT, H_HOUR_MIN_FORMAT,
SPLIT_SYMBOL, BLOOD_PRESSURE, MASKED_BP, DROP_DOWN_APIS,
HealthlabelMap, healthUnits, healthUnitsMinMax, desiredOrderBiometrics,
BmiQuestion, bpQuestions, biometricPressureClassifications

Utilities

calculateDaysDifference, applyDateCalculation,      // date math
classifyBloodPressure,                               // BP → category
normalizeLabel, labelsEqual,                         // string compare
buildHealthUnitsMinMax, getRangeForGender,           // biometrics ranges
capitalizeFirstLetter, verifyObject,
generateTokenFromJWT,                                // JWT helper
resetInlineStyleFromEditerContainer,
cn, handleErrors, getColorTint, hexToRgb

Validation

ValidateFillUpAnswer(data, handleErrors, gender)
// Validates a questionnaire payload. `handleErrors` is invoked as
// (message, question, child?, grandchild?) for every error.

Context / Provider

QuestionnaireProvider,
useQuestionnaireContext,
useQuestionnaireServices,
useQuestionnaireConfig

Global DI

setGlobalDeps(deps),   // register external functions / store
setStoreRef(store),    // register Redux store
getStore()             // read the registered store

Redux slice + actions

questionnaireReducer,           // default export — mount as `questionnaire` in rootReducer
localStore,                     // second reducer — mount as `localStore`
actionTypes,                    // plain action-type constants
setHeaderConditionData,
setFooterHeight,
// plus every action creator from the questionnaire slice (21 actions)

Hooks

useMediaQuery,
useWindowWidth,
useLeavePageConfirm

Question type components

Every renderable question variant:

CheckAgreeQuestion, CheckAgreeQuestionAnswer,
CheckboxChoiceQuestionAnswer, CheckboxGroupQuestion,
CustomDropDown, CustomDropDownItem,
DatePickerItem, DatePickerQuestion, DateRangeQuestion,
FileInputQuestion, FileInputTypeItem,
HealthDataPointInputItem, HealthDataPointQuestion,
InformationTextItem, InformationTextQuestion,
NumericalItem, NumericalQuestion,
QuestionTitle, RangePickerItem,
SingleChoiceQuestion, SingleChoiceQuestionAnswer,
TextAreaQuestion, TextAreaQuestionInput,
TextBoxInputItem, TextBoxQuestion

Wrapper / sibling components

QuestionsChildren, QuestionsChildOfChild, QuestionsAdditionalInformation,
InformationTextItemSibling, InformationTextQuestionSibling,
AnswerItem, AnswerReview, MaskDateInputPicker,
PatientDataForQuestionnaire, QuestionnaireFillUpItem,
QuestionnaireWizardItem, WizardFooter, WizardStep

Journey components

Higher-level orchestrators you'll typically mount directly:

QuestionnaireFillUpTokenNew          // token-based deep-link entry (main filler)
QuestionnaireFromPINVerification     // PIN / OTP entry variant
QuestionnaireWizard                  // multi-step wizard wrapper
OutComeScreen, PatientSpecificOutComeScreen, SuccessScreen,
PageExpired, ConditionNotFound,
PrivateConditionDisabledMessageScreen,
ProgressContent, DummySection

Peer dependencies

The package declares these as peers — install them in your app:

  • react ≥ 18, react-dom ≥ 18, next ≥ 14
  • @reduxjs/toolkit ≥ 1.9, react-redux ≥ 8
  • antd ≥ 5, @ant-design/icons ≥ 5
  • @mui/x-date-pickers ≥ 5
  • react-use-wizard ≥ 2, react-albus ≥ 2, framer-motion ≥ 10
  • axios ≥ 1, dayjs ≥ 1.11, moment ≥ 2.29, lodash ≥ 4
  • jsonwebtoken ≥ 8, nanoid ≥ 3, uuid ≥ 9
  • clsx ≥ 2, tailwind-merge ≥ 2
  • values.js ≥ 2, sass ≥ 1

@mona-health/react-input-mask and react-imask used to be optional peers. They are now bundled as regular dependencies — npm installs them automatically when you add addv-questionnaire, because the package's source unconditionally imports them from the health-data-point inputs.


End-to-end example

// app/(appointmentFlow)/questionnaire/page.tsx
import { QuestionnaireFillUpTokenNew } from "addv-questionnaire";
import { QuestionnairePageWrapper } from "@/components/QuestionnairePageWrapper";

export default function Page() {
  return (
    <QuestionnairePageWrapper>
      <QuestionnaireFillUpTokenNew />
    </QuestionnairePageWrapper>
  );
}

Prerequisites satisfied:

  1. next.config.ts has transpilePackages: ["addv-questionnaire"]
  2. store/index.ts calls setStoreRef(store) right after configureStore
  3. app/providers.tsx calls setGlobalDeps({ ... }) once
  4. QuestionnairePageWrapper wraps with <QuestionnaireProvider services={{ fetchDropdownOptions }} ... />

Versioning & publishing

Semver:

  • patch — bug fix, no API change
  • minor — new export / additive feature
  • major — removed export, renamed prop, changed action payload

Publish flow:

cd packages/questionnaire
# bump version in package.json
npm publish

License

UNLICENSED — internal ADDV use only.