Skip to content

Latest commit

 

History

History
212 lines (165 loc) · 8.02 KB

installation-and-setup.md

File metadata and controls

212 lines (165 loc) · 8.02 KB
title Installation and setup
sidebar_position 1.2

Install

npm install @javaabu/forms

Until it is on npm, install it from GitHub. It builds itself when installed:

pnpm add "@javaabu/forms@github:Javaabu/react-forms#next-gen"

With pnpm 10, allow the build scripts of the package and of @javaabu/i18n in your package.json:

{
  "pnpm": { "onlyBuiltDependencies": ["@javaabu/forms", "@javaabu/i18n"] }
}

From pnpm 10.34, packages installed from Git must be allowed by their exact source: pnpm prints the line to add ("@javaabu/forms@https://codeload.github.com/Javaabu/react-forms/tar.gz/<commit>"), or run pnpm approve-builds. This goes away once the package is on npm.

With a script tag

For a page without a bundler (a Blade view, a static page, a quick prototype), load dist/forms.iife.js. It puts everything in @javaabu/forms and the plain HTML adapter on window.JavaabuForms, with React, ReactDOM and @javaabu/i18n bundled in, so nothing else has to load first:

<html lang="dv" dir="rtl">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <script src="https://unpkg.com/@javaabu/forms/dist/forms.iife.js"></script>
</head>
<body>
    <div id="app"></div>
    <script>
        const { h, mount, i18n, Form, Text, Select, Submit } = JavaabuForms

        i18n.setLocale("dv")

        mount(
            "#app",
            h(Form, { action: "/enquiries", model: { name: "ޢަލީ" } },
                h(Text, { name: "name", label: "ނަން", thaana: true, required: true }),
                h(Select, { name: "topic", label: "ބާވަތް", options: { general: "އާންމު", support: "އެހީ" } }),
                h(Submit, null, "ފޮނުވާ"),
            ),
            { errors: {} },
        )
    </script>
</body>
</html>
On JavaabuForms What it is
Every export of @javaabu/forms Form, Text, Select, Table, FormsProvider, fetchRouter, …
html, pageWindow The plain HTML adapter (the default)
h React.createElement: h(Component, props, ...children)
mount(target, node, options?) Renders node into an element or selector inside a FormsProvider with options (any FormsProvider prop); returns the React root
React The bundled React, for hooks
i18n The bundled @javaabu/i18n: i18n.setLocale("dv"), i18n.load(…) for your own strings

The file is about 330 kB (React included), so use it where there's no build step. In an app with a bundler, or a page that already loads React, import the ES modules instead. Until the package is on npm, build the file yourself (pnpm build) and serve it from your app. examples/script-tag.html is a complete page that opens straight from disk.

Choose a UI adapter

Without an adapter, the components render plain HTML. Pick the adapter for your UI kit once, at the root of your app.

Onu

npm install @javaabu/onu
/* resources/css/app.css */
@import "tailwindcss";
@import "@javaabu/onu/tailwind.css";
@import "@javaabu/forms/tailwind.css";
import { OnuProvider, ThemeProvider } from "@javaabu/onu"
import { FormsProvider, mergeAdapters } from "@javaabu/forms"
import { onu } from "@javaabu/forms/onu"
import { onuEditor } from "@javaabu/forms/onu/editor" // only if you use Wysiwyg

const ui = mergeAdapters(onu, onuEditor)

export function Providers({ children }) {
  return (
    <ThemeProvider>
      <OnuProvider>
        <FormsProvider ui={ui}>{children}</FormsProvider>
      </OnuProvider>
    </ThemeProvider>
  )
}

shadcn/ui

See shadcn/ui: you make the adapter from your own components with createShadcnAdapter().

Anything else

Write an adapter for your UI kit, or replace a few components of the HTML adapter. See UI adapters.

FormsProvider

FormsProvider is the counterpart of config/forms.php. Every prop is optional, and nested providers override their parent's.

Prop Type Default What it does
ui FormsAdapter HTML The UI adapter
components Partial<FormsComponents> Replaces single components: { Select: MySelect }
router FormsRouter | null native submit How forms without onSubmit submit: inertia, fetchRouter or your own
translate (text) => string __() Translates generated labels and titles
csrfToken string | null <meta name="csrf-token"> The _token field of non-GET forms
old object | null Old input for every form
errors PageErrors | null Validation errors for every form, flat or by error bag
authorize (ability, argument?, guard?) => boolean fail closed Resolves the can props of ConditionalLink and NoItems
settings Record<string, unknown> per_page: 20, max_upload_file_size: 10240, max_image_file_size: 2048 get_setting() values: upload limits (KB), per_page, default_lat, default_lng, app_timezone (the app's time zone for date fields, e.g. config('app.timezone'))
url string the router's, else the browser's The current page's URL, read by sortable headings, Filter, PerPage, SearchForm, BulkActions and Pagination. Set it when they render on the server without the Inertia router (which reads usePage().url)

Laravel apps

Blade layout with Inertia

<html lang="{{ str_replace('_', '-', app()->getLocale()) }}" dir="{{ app()->getLocale() === 'dv' ? 'rtl' : 'ltr' }}">
<head>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    @viteReactRefresh
    @vite(['resources/css/app.css', 'resources/js/app.tsx'])
    @inertiaHead
</head>

Inertia setup

// resources/js/app.tsx
import { createInertiaApp } from "@inertiajs/react"
import { createRoot } from "react-dom/client"
import { FormsProvider, mergeAdapters } from "@javaabu/forms"
import { inertia, inertiaLinks } from "@javaabu/forms/inertia"
import { onu } from "@javaabu/forms/onu"

const ui = mergeAdapters(onu, inertiaLinks)

createInertiaApp({
  resolve: (name) => import(`./pages/${name}.tsx`),
  setup({ el, App, props }) {
    createRoot(el).render(
      <FormsProvider ui={ui} router={inertia}>
        <App {...props} />
      </FormsProvider>,
    )
  },
})

Errors come from the page props by themselves. See Inertia for useForm(), error bags and visit options.

Sharing settings, permissions and old input

// app/Http/Middleware/HandleInertiaRequests.php
public function share(Request $request): array
{
    return [
        ...parent::share($request),
        'forms' => [
            'settings' => [
                'per_page' => get_setting('per_page'),
                'max_upload_file_size' => get_setting('max_upload_file_size'),
            ],
            'can' => [
                'create_users' => $request->user()?->can('create', User::class),
            ],
        ],
        'old' => fn () => $request->session()->getOldInput(),
    ];
}
const { forms } = usePage().props

<FormsProvider settings={forms.settings} authorize={(ability) => !!forms.can[ability]}>

The Inertia router reads the old prop itself. Without Inertia, pass old and errors to FormsProvider from wherever your page gets them.

Translations

Strings come from @javaabu/i18n and follow <html lang>. English and Dhivehi are built in, and you change them in lang/vendor/forms/{locale}/strings.php. See Translations.

Examples

The repository has a page per integration in examples/ (Onu, shadcn/ui, plain HTML, Inertia and fetch, the last two against a mock Laravel endpoint), each with a Dhivehi version (?dv), and examples/script-tag.html, which uses the <script> tag build with no bundler (run pnpm build, then open the file):

git clone https://github.com/Javaabu/react-forms && cd react-forms
pnpm install && pnpm examples