Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ place in your tree where the form has to live. You ask a question from wherever
you happen to be standing in your code, and you get the answer back.

```ts
import { ask } from 'declarative-forms';

const release = await ask([
{ name: 'title', displayName: 'Release title' },
{ name: 'notes', kind: 'textarea', displayName: 'What changed' },
Expand All @@ -27,8 +29,8 @@ That is the whole integration. No `<Form>`, no `useForm`, no `onChange`, no
`useState`, no layout, no `<div>`. The dialog draws itself, loads its own
options, keeps every field in sync, and resolves.

`ask` is nine lines you write once on top of the public API —
[here it is](https://wolfoo2931.github.io/declarative-forms/guide/asking-for-data#the-ask-helper).
`ask` ships with the library —
[what it takes and what it resolves with](https://wolfoo2931.github.io/declarative-forms/guide/asking-for-data#the-ask-function).

📖 **[Read the documentation](https://wolfoo2931.github.io/declarative-forms/)** ·
🎛 **[Try the live demo](https://wolfoo2931.github.io/declarative-forms/#demo)**
Expand Down Expand Up @@ -121,7 +123,7 @@ No build step is required — the ESM build loads directly in a `<script type="m

## The full API, if you want the object instead of the promise

`ask` is a convenience you own. Underneath, a form is a normal object you can
`ask` is a thin wrapper over the object underneath — a normal object you can
hold on to, embed in a page instead of a dialog, subscribe to, and drive from
code:

Expand Down Expand Up @@ -187,7 +189,7 @@ Plainly, so you can rule it out fast:

## Documentation

- [Asking for data](https://wolfoo2931.github.io/declarative-forms/guide/asking-for-data) — the model, and the `ask` helper
- [Asking for data](https://wolfoo2931.github.io/declarative-forms/guide/asking-for-data) — the model, and `ask`
- [Getting started](https://wolfoo2931.github.io/declarative-forms/guide/getting-started)
- [Field kinds](https://wolfoo2931.github.io/declarative-forms/guide/fields/)
- [Reactivity](https://wolfoo2931.github.io/declarative-forms/guide/reactivity) — `isActive`, `reloadOnChangeOf`, computed fields
Expand Down
22 changes: 17 additions & 5 deletions docs/.vitepress/theme/LiveForm.vue
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { DeclarativeForm, html } from '../../../src/index.js';
import { ask, DeclarativeForm, html } from '../../../src/index.js';
import { askWith } from '../../../src/core/ask.js';
import type { DeclarativeFormOptions, FormValues } from '../../../src/index.js';

const props = withDefaults(
Expand Down Expand Up @@ -65,7 +66,7 @@ function compile(): void {
/**
* Compile a program snippet: statements that construct forms and open them.
*
* `import` lines are stripped and the two bindings they bring in are injected
* `import` lines are stripped and the bindings they bring in are injected
* instead, so the snippet can be written the way it would be in an application
* — including the `openInModal()` call — and still run in the page.
*
Expand All @@ -83,9 +84,14 @@ function compileProgram(): void {
const body = source().replace(/^\s*import .*$/gm, '');
const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor as new (
...args: string[]
) => (form: typeof DeclarativeForm, h: typeof html) => Promise<void>;
) => (form: typeof DeclarativeForm, askFn: typeof ask, h: typeof html) => Promise<void>;

const program = new AsyncFunction('DeclarativeForm', 'html', `"use strict";\n${body}`);
const program = new AsyncFunction(
'DeclarativeForm',
'ask',
'html',
`"use strict";\n${body}`,
);

run = () => {
let isRoot = true;
Expand All @@ -106,9 +112,15 @@ function compileProgram(): void {
}
}

// `ask` builds a `DeclarativeForm` of its own, which the panels below the
// demo would never see. This is the shipped `ask` with the one line that
// constructs the form pointed at the instrumented subclass instead.
const demoAsk: typeof ask = (fields, options = {}) =>
askWith(DemoForm, fields, options);

// The snippet is async now, so a failure inside it surfaces as a rejection
// rather than a throw the caller's try/catch would see.
void program(DemoForm, html).catch((cause) => {
void program(DemoForm, demoAsk, html).catch((cause) => {
error.value = cause instanceof Error ? cause.message : String(cause);
});
};
Expand Down
74 changes: 31 additions & 43 deletions docs/guide/asking-for-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,60 +42,48 @@ const name = prompt('Your name?'); // one string
const release = await ask([...]); // a whole record
```

## The `ask` helper
## The `ask` function

The library ships the form object, not the promise. `ask` is nine lines you
write once, on top of the public API, and then never think about again:
`ask` ships with the library. Import it and call it:

```ts
import { DeclarativeForm } from 'declarative-forms';
import type {
DeclarativeFormOptions,
FieldDescriptor,
FormValues,
} from 'declarative-forms';

/** Open a dialog and resolve with its values, or `undefined` if dismissed. */
export function ask(
import { ask } from 'declarative-forms';

const values = await ask(fields);
```

```ts
function ask(
fields: readonly FieldDescriptor[],
options: Omit<DeclarativeFormOptions, 'fields' | 'onConfirm' | 'onCancel'> = {},
): Promise<FormValues | undefined> {
return new Promise((resolve) => {
new DeclarativeForm({
...options,
fields,
onConfirm: (values) => resolve(values),
onCancel: () => resolve(undefined),
}).openInModal();
});
}
options?: AskOptions,
): Promise<FormValues | undefined>;
```

::: tip Why is this not in the package?
Because the object API underneath does strictly more — it can be embedded in a
page, held, subscribed to, driven from code, and closed by something other than
its own buttons. `ask` is the ninety-percent case expressed in the language of
promises, and it is short enough that you should own it and adapt it. See
[the full API](#when-to-use-the-object-api-instead).
:::
It opens the fields as a dialog and resolves with the values, or with
`undefined` if the user dismissed it. `options` is everything
[`DeclarativeForm`](/reference/api#new-declarativeform-options) accepts, minus
the three keys `ask` owns — `fields`, `onConfirm` and `onCancel` — plus two of
its own:

| Option | Notes |
| ------------- | ------------------------------------------------------------- |
| `modal` | Class names for the dialog chrome, as passed to `openInModal` |
| `dismissable` | `false` removes the ✕ and makes Escape a no-op |

The promise settles only after the dialog is torn down and off the modal stack,
so the loop further down — ask, check, ask again — opens each new dialog on a
clean stack rather than stacking it on the one that just closed.

Declare your own `buttons` and the promise resolves once any button that closes
the dialog has finished its action. A `doNotCloseModal` button (a wizard's
"Next") leaves it pending, because it leaves the dialog open.

Try it. This runs the exact code shown, `ask` helper and all:
Try it. This runs the exact code shown:

<LiveForm mode="program" stage="top" open="Ask for a release">

```ts
import { DeclarativeForm } from 'declarative-forms';

// The nine lines, once, in your own codebase.
const ask = (fields, options = {}) =>
new Promise((resolve) => {
new DeclarativeForm({
...options,
fields,
onConfirm: (values) => resolve(values),
onCancel: () => resolve(undefined),
}).openInModal();
});
import { ask } from 'declarative-forms';

// Pretend this is your API.
const fetchReviewers = async () => {
Expand Down
4 changes: 2 additions & 2 deletions docs/guide/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ to load.
::: tip Read [Asking for data](/guide/asking-for-data) first
It is two minutes, and it explains the one thing that makes this library
different from every other form library: **a form here is a function you call,
not a component you mount.** Most applications only ever need the nine-line
`ask` helper on that page. This page is the object API underneath it.
not a component you mount.** Most applications only ever need the `ask`
function described there. This page is the object API underneath it.
:::

A form is an array of **field descriptors**, plus what should happen when the
Expand Down
9 changes: 5 additions & 4 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ Every other form library gives you a _component to mount_. This one gives you a
_function to call_:

```ts
import { ask } from 'declarative-forms';

const release = await ask([
{ name: 'title', displayName: 'Release title' },
{ name: 'notes', kind: 'textarea', displayName: 'What changed' },
Expand Down Expand Up @@ -34,8 +36,7 @@ answer. Its only flaw is that it asks for exactly one string.
**record** you want, and you get a plain object back.

[**Asking for data →**](/guide/asking-for-data) is the two-minute version of
this idea, including the nine-line `ask` helper. Everything below follows from
it.
this idea, and the full story on `ask`. Everything below follows from it.

## Try it {#demo}

Expand Down Expand Up @@ -321,8 +322,8 @@ Said plainly, so you can rule it out quickly:

## Next

- [Asking for data](/guide/asking-for-data) — **start here**: the model, and the
`ask` helper
- [Asking for data](/guide/asking-for-data) — **start here**: the model, and
`ask`
- [Getting started](/guide/getting-started) — install and build your first form
- [Field kinds](/guide/fields/) — the ten built-in kinds
- [Reactivity](/guide/reactivity) — the part that makes this library worth using
Expand Down
37 changes: 36 additions & 1 deletion docs/reference/api.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,44 @@
# API reference

```ts
import { DeclarativeForm } from 'declarative-forms';
import { ask, DeclarativeForm } from 'declarative-forms';
```

## `ask(fields, options?)`

```ts
function ask(
fields: readonly FieldDescriptor[],
options?: AskOptions,
): Promise<FormValues | undefined>;

interface AskOptions extends Omit<
DeclarativeFormOptions,
'fields' | 'onConfirm' | 'onCancel'
> {
modal?: OpenInModalOptions;
dismissable?: boolean; // default true
}
```

Opens the fields as a modal dialog and resolves with its values, or with
`undefined` when the user dismisses it. See
[Asking for data](/guide/asking-for-data).

| Option | Notes |
| --------------- | ------------------------------------------------------------------- |
| `modal` | Class names for the dialog chrome, as passed to `openInModal` |
| `dismissable` | `false` removes the ✕ and makes Escape a no-op |
| `buttons` | Resolves after any button that closes the dialog has run its action |
| everything else | As on [`DeclarativeFormOptions`](#new-declarativeform-options) |

The promise settles _after_ the dialog is torn down and popped off the modal
stack, so asking again immediately opens a clean, unstacked dialog.

A `doNotCloseModal` button leaves the promise pending, because it leaves the
dialog open. With `dismissable: false`, make sure some button closes the dialog
— nothing else will.

## `new DeclarativeForm(options)`

```ts
Expand Down
15 changes: 15 additions & 0 deletions e2e/docs.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ const BASE = `${DOCS_ORIGIN}/declarative-forms`;

const PAGES = [
'/',
'/guide/asking-for-data',
'/guide/getting-started',
'/guide/fields/text',
'/guide/fields/textarea',
Expand Down Expand Up @@ -104,6 +105,20 @@ test.describe('demos are genuinely interactive', () => {
expect(errors).toEqual([]);
});

test('ask() closes its dialog and resolves with the values', async ({ page }) => {
const errors = await open(page, '/guide/asking-for-data');

await page.click('.live-form__open');
await page.fill('.dl-modal input[name=title]', 'Sunrise 2.0');
await page.click('.dl-modal .low-bar .btn');

// The promise settles only once the dialog is gone.
await expect(page.locator('.dl-modal')).toHaveCount(0);
await expect(page.locator('.live-form__values--ok')).toContainText('Sunrise 2.0');

expect(errors).toEqual([]);
});

test('typing flows into the values panel', async ({ page }) => {
const errors = await open(page, '/guide/fields/text');

Expand Down
Loading
Loading