Invoice editor

A list of invoices and an editor dialog, with the open invoice kept in the URL.

Mounted

Open an invoice and watch the address bar. Reload on ?invoice=0143, or try ?invoice=9999 to get a new one. The providers nest in the order they read each other.

tsx
<ReactGraftInvoiceEditorListGraft.Provider>
  <ReactGraftInvoiceEditorAlertDiscardGraft.Provider>
    <ReactGraftInvoiceEditorDialogGraft.Provider>
      <ReactGraftInvoiceEditorList />

      {isActive && (
        <ReactGraftInvoiceEditorStepGraft.Provider>
          <ReactGraftInvoiceEditorStoreGraft.Provider>
            <ReactGraftInvoiceEditorDialog />
          </ReactGraftInvoiceEditorStoreGraft.Provider>
        </ReactGraftInvoiceEditorStepGraft.Provider>
      )}
    </ReactGraftInvoiceEditorDialogGraft.Provider>
  </ReactGraftInvoiceEditorAlertDiscardGraft.Provider>
</ReactGraftInvoiceEditorListGraft.Provider>

One graft per concern

The dialog knows if it is open and if the draft has changes. Its close asks before discarding them.

tsx
// react-graft-invoice-editor-dialog.graft.ts
export const ReactGraftInvoiceEditorDialogGraft = createGraft({
  name: "ReactGraftInvoiceEditorDialogGraft",
  graft: useGraft,
  inject: [useInjectUrl, useInjectDeepLink],
});

function useGraft() {
  const discard = ReactGraftInvoiceEditorAlertDiscardGraft.use();
  const dialog = useDialog<Invoice>();

  const [isDirty, setIsDirty] = useState(false);

  const close = useCallback(async (force = false) => {
    if (!force && isDirty && !(await discard.open())) return;

    dialog.close();
  }, [dialog, discard, isDirty]);

  return { ...dialog, close, isDirty, setIsDirty };
}

The invoice draft has its own graft: it starts from the selected invoice and tracks edits separately.

tsx
// react-graft-invoice-editor-store.graft.ts
function useGraft() {
  const invoices = ReactGraftInvoiceEditorListGraft.use();
  const dialog = ReactGraftInvoiceEditorDialogGraft.use();
  const [value, setValue] = useState<Invoice | null>(dialog.storage);

  const edit = useCallback((patch: Partial<Invoice>) => {
    dialog.setIsDirty(true);
    setValue((previous) => (previous ? { ...previous, ...patch } : previous));
  }, [dialog]);

  return { value, setValue, setCustomer, setStatus, save };
}

The URL

Two injected effects keep the URL and dialog in sync: one follows the open invoice, the other opens the invoice named in the URL—or starts a new one if it doesn't exist.

tsx
// the url follows the dialog
function useInjectUrl({ isActive, isNew, storage }: { isActive: boolean; isNew: boolean; storage: Invoice | null }) {
  const navigate = useNavigate();
  const { invoice } = useSearch({ strict: false });

  const target = isNew ? "new" : storage?.id;

  useEffect(() => {
    if (isActive && target && invoice !== target) void navigate({ search: { invoice: target }, replace: true });
    if (!isActive && invoice) void navigate({ search: {}, replace: true });
  }, [invoice, isActive, navigate, target]);
}

// and on arrival, the dialog follows the url
function useInjectDeepLink({ open }: { open: (invoice: Invoice) => void }) {
  const { byId } = ReactGraftInvoiceEditorListGraft.use();
  const { invoice } = useSearch({ strict: false });
  const hasDeepLinked = useRef(false);

  useEffect(() => {
    if (hasDeepLinked.current) return;

    hasDeepLinked.current = true;
    if (!invoice) return;

    const existing = invoice === "new" ? null : byId(invoice);

    open(existing ?? INVOICE_BLANK);
  }, [byId, invoice, open]);
}

The hooks

Each piece is a plain hook; the graft is what shares its state with the rest of the feature.

tsx
// react-graft-invoice-editor-dialog.graft.ts — open, closed, and what it was opened with
function useDialog<T>() {
  const id = useId();
  const [state, setState] = useState<{ isActive: boolean; storage: T | null }>({ isActive: false, storage: null });

  const open = useCallback((storage: T | null = null) => setState({ isActive: true, storage }), []);
  const close = useCallback(() => setState((previous) => ({ ...previous, isActive: false })), []);

  return { id, isActive: state.isActive, storage: state.storage, open, close };
}

// react-graft-invoice-editor-alert-discard.graft.ts — a question that resolves with its answer
function useConfirm() {
  const id = useId();
  const [isActive, setIsActive] = useState(false);
  const resolverRef = useRef<((confirmed: boolean) => void) | null>(null);

  const open = useCallback(
    () =>
      new Promise<boolean>((resolve) => {
        resolverRef.current?.(false);
        resolverRef.current = resolve;
        setIsActive(true);
      }),
    [],
  );

  const close = useCallback((confirmed: boolean) => {
    setIsActive(false);
    resolverRef.current?.(confirmed);
    resolverRef.current = null;
  }, []);

  return { id, isActive, open, onConfirm: () => close(true), onDismiss: () => close(false) };
}