docs
/
AI skills

Put a form on a website page

Every way to put a CRM form on an Appmint site — the platform's own form at /form, a site page tied to a form, or a page of your own design posting through the site's /api — with what each access setting does to the visitor, where the answers land, which emails go out and where their links point.

A CRM form can reach a site three ways. Pick one before building anything, because each one changes which address the visitor uses, what the page looks like, and where the form's emails send people.

A. The platform formB. A page tied to a formC. A page of your own
What it isThe built-in form, one question per screen, at /form?form=<name>A site page with data.formName set. The form renders between the page's two screens.Your own HTML and JS that posts to the form's endpoints through the site's /api
Needs Forms switched on in Site FeaturesYes. Off, /form is a 404.Yes. Off, the page shows as itself, with no form.No
LooksFixed platform designFixed platform design inside your header and footerAnything
Code gates, magic links, invitationsBuilt in: the gate screens, "Send me the link", invitation linksBuilt in, the same as AYou write each step (request the code, ask for it, show each refusal)
Emails' "Open the form" linkOpens itOpens the platform form at /form or the Forms page, not this pageStill points at /form or the Forms page, never at your page (see the warning in way C)
Embed in another website?embed=true?embed=trueNot built in
Use whenA form should just work, a share link, invitationsA form that should sit inside the site's design at its own addressA custom design or flow, e.g. a multi-step registration wizard

Default to A. Use B when the owner wants the form at its own address inside their page. Use C only when the design or flow can't be the platform form. A site built this way (PhaZZer's /registration) is a 7-step wizard of its own design that posts to a code-gated CRM form, with Forms switched off.

Related skills: Shared form from a collection builds the collection and the form. Registration that creates the customer adds a unique email and an automation that creates the account. How a site's addresses route covers features, pages and 404s. Page building: Build a website page. The API by hand: Collect form submissions.

Ask first

  • Which form, and does it exist? Its name, or what it should ask. If it doesn't exist, build it first with Shared form from a collection.
  • Who may fill it in? Anyone, anyone with a shared code, people who prove their email, invited people, or signed-in customers. This sets authenticationType (see Who gets in).
  • Where on the site, and how should it look? The platform's own form (A), inside one of their pages (B), or a page of their own design (C). Which address? Never guess an address: it may already belong to a page or a feature.
  • Is Forms switched on for the site? If not, may it be? Ways A and B need it, and switching it on changes what /form shows.
  • Who is told of each answer? A staff address (email on the form), and whether the visitor gets a confirmation (they do, whenever they give an email).

How it works

The form record (crm_form)

The fields that change what a visitor sees on a site. Model: @jaclight/dbsdk models/crm/crm-form.d.ts. Behaviour: appengine src/crm/crm-form.service.ts and src/util/access-gate.ts.

FieldWhat it does on the site
nameThe form's address: /form?form=<name>, /form/<name>, POST /client/forms/<name>/…. Lowercase letters, numbers, _ and -; unique.
title / descriptionShown above the questions and on the gate screens. Email subjects use title.
collectionThe collection whose records the answers become. Its schema is the questions. Empty: the form's own schema is the questions and each answer is a form_submission. See Where answers land.
schemaThe questions when there's no collection. JSON schema; the builder keeps page 1's fields at the root and later pages in schema.pages[i].properties.
authenticationTypeWho gets in: none, email, code, magic-link, password. The model's default is email, and Studio's too. See below.
accessCodeThe shared code for authenticationType: "code". Compared trimmed and case-insensitive.
participants[{ email, name, accessCode, role }]. When not empty, only these people get in, whatever the type. Each one's accessCode is their own key, carried in their invitation link. The engine adds invitedAt, inviteCount, submittedAt.
statusclosed, cancelled, expired or failed refuse readers and answers with 403 closed. new, sent, open (or none) are open.
startDate / endDateBefore the start: 403 not-open-yet (with opensAt). After the end: 403 closed (with closedAt).
permission{ read: [...], create: [...] }. Left out, the form is open. A read list without Guest gives 403 "This form is not available for public access"; a create list without Guest gives 403 "This form does not accept public submissions". Studio's Access tab "Public" switch writes these.
submitMessageThe thank-you screen of the platform form (HTML is reduced to text). Before it: the page's data.thankYou, then the site's data.forms.thankYou, then "Thank you — that's everything." (base-app SchemaFormRoute.tsx 280). Way C shows its own.
emailThe staff address. Every answer sends it a "New submission: " email with each answer, unless it's the visitor's own address (<code>crm-form.service.ts</code> 1504, <code>notifyTeam</code> 1539).</td></tr><tr><td><code>invitationTemplate</code></td><td>The template for invitations and access emails. Empty: the built-in <code>form-invitation</code>.</td></tr><tr><td><code>templates</code>, <code>emailTemplate</code>, <code>smsTemplate</code></td><td>Extra messages sent with each answer to the visitor's address (<code>templates</code> are template names; the other two are inline bodies).</td></tr><tr><td><code>workflow</code></td><td>A workflow definition, by name, that each answer is handed to (<code>crm-form.service.ts</code> 1421).</td></tr><tr><td><code>signing</code></td><td>A document to sign. Signing links (<code>?sign=<token></code>) open their own signer view; not covered here.</td></tr></tbody></table></div><div class="cal cal-info"><div class="cal-b"><p>The model describes <code>email</code> as "where a submission notification is sent when the submitter did not supply an address". The code sends the team email for every answer, whatever the visitor gave. Tested: a form with <code>email: "team@test.local"</code> sent both the visitor's confirmation and "New submission: Skilltest File" to the team address.</p> </div></div> <h3 id="who-gets-in-authenticationtype">Who gets in (<code>authenticationType</code>)</h3><p>One setting decides who sees the questions. It's checked when the form is read <strong>and</strong> when answers are sent, so a page can't skip it.</p> <div class="tw"><table><thead><tr><th><code>authenticationType</code></th><th>What the visitor does</th><th>What the server checks</th><th>Refusals</th></tr></thead><tbody><tr><td><code>none</code></td><td>Nothing. The questions open.</td><td>Nothing.</td><td>—</td></tr><tr><td><code>email</code></td><td>Types an address before the questions (platform form), or sends one.</td><td>Only that an address is there. It's <strong>not verified</strong>: any address is accepted.</td><td>401 <code>email-required</code></td></tr><tr><td><code>code</code> with an <code>accessCode</code></td><td>Types the shared code, or opens a link with <code>?code=</code>.</td><td>The code, trimmed, ignoring case. A participant's own code also works.</td><td>401 <code>code-required</code>; 403 <code>code-wrong</code></td></tr><tr><td><code>code</code> with participants and no <code>accessCode</code></td><td>Opens their own invitation link (<code>?code=<their code></code>).</td><td>The code must be a participant's.</td><td>403 <code>invitation-required</code> (no code); 403 <code>not-a-participant</code> (unknown code)</td></tr><tr><td><code>code</code> with <strong>no</strong> <code>accessCode</code> and <strong>no</strong> participants</td><td>Gives an email, is emailed a <strong>6-digit code</strong>, types it in.</td><td>Treated as <code>magic-link</code> that emails a code (<code>access-gate.ts</code> 52, <code>emailsCode</code> 57).</td><td>401 <code>link-required</code>, <code>code-wrong</code>, <code>link-expired</code>, <code>already-submitted</code></td></tr><tr><td><code>magic-link</code></td><td>Gives an email, is emailed a link (32-character token), opens it.</td><td>The token must match a pending submission for this form, under 72 hours old. The address is read off that record, never from the request.</td><td>Same as above</td></tr><tr><td><code>password</code></td><td>Signs in as a customer first.</td><td>A signed-in customer (and on the list, if there is one).</td><td>401 <code>signin-required</code></td></tr></tbody></table></div><p>Records saved with the old <code>accessMode</code> of <code>code</code> or <code>participants</code> and a type of <code>none</code> or <code>email</code> are read as <code>code</code> (<code>access-gate.ts</code> 47–54).</p> <div class="cal cal-info"><div class="cal-b"><ul> <li><strong><code>code</code> means two different things.</strong> With an <code>accessCode</code> or participants, it's a code you hand out. With neither, the server emails each visitor their own 6-digit code. That second one is what a registration page wants. A form with <code>code</code> and nothing else set never answers <code>misconfigured</code>.</li> <li><strong><code>email</code> proves nothing.</strong> Use the emailed code or <code>magic-link</code> when the address must be real.</li> <li><strong>A wrong shared code is 403, not 401.</strong> Tested: <code>code-wrong</code> on a <code>code</code> form came back 403; <code>code-wrong</code> on an emailed-code form came back 401. Read <code>reason</code>, not the status.</li> </ul> </div></div> <h3 id="endpoints">Endpoints</h3><p>All are public: no admin token. From a site page, call them as <code>/api/<path></code> (see <a href="#the-site-s-api">The site's /api</a>). Directly they need the <code>orgid</code> header.</p> <div class="tw"><table><thead><tr><th>Call</th><th>Body / query</th><th>Answer</th></tr></thead><tbody><tr><td><code>GET /client/forms/<name></code> (also <code>GET /crm/form/<name></code>)</td><td><code>?code=</code>, <code>?email=</code>, <code>?token=</code>, <code>?sign=</code></td><td><code>{ form: { sk, data: { name, title, description, submitMessage, authenticationType, status, startDate, endDate, schema } }, collection, schema, authenticationType, authentication: { required, type, satisfied }, submitter, participant, session, displayName, logo, lookupOptions }</code>. The form's notify address, participants and author are left out (<code>toPublicReply</code> 118).</td></tr><tr><td><code>POST /client/forms/<name>/access</code> (also <code>/crm/form/<name>/access</code>)</td><td><code>{ "email": "…" }</code></td><td><code>{ "sent": true, "email": "<lowercased>", "via": "code" | "magic-link", "session": "<pending submission sk>" }</code>. Makes a pending <code>form_submission</code> and emails the code or link. Only for emailed-code and <code>magic-link</code> forms; any other gives 400 "This form does not send links or codes." A form with participants only sends to them (403 <code>not-a-participant</code>).</td></tr><tr><td><code>POST /client/forms/<name>/submit</code></td><td>Answers as the body. Query: <code>?token=</code>, <code>?code=</code>, <code>?email=</code></td><td>The saved record, or <code>true</code> when it completes a pending submission (inline <code>magic-link</code> form). This is what the platform form posts to.</td></tr><tr><td><code>POST /crm/form/submit/<name></code> and <code>/crm/form/submit/<name>/<email></code></td><td>Answers as the body. Query: <code>?token=</code>, <code>?code=</code></td><td>The saved record. The visitor's email is the <strong>path</strong> segment, not <code>?email=</code>.</td></tr></tbody></table></div><p>The code or token can be in the body (<code>accessCode</code>, <code>token</code>), the query (<code>?code=</code>, <code>?token=</code>) or a header (<code>x-form-code</code>, <code>x-form-token</code>). It's removed before the answers are checked and never stored with them (<code>crm-form.service.ts</code> 1110–1119). Through the site's <code>/api</code>, only the body and query reach the engine.</p> <div class="cal cal-warn"><div class="cal-b"><p><strong><code>?email=</code> is ignored by <code>/crm/form/submit/<name></code>.</strong> That route reads the email from the path. Tested on an <code>email</code> form: <code>POST /crm/form/submit/<name>?email=q@test.local</code> gave 401 <code>email-required</code>, while <code>/client/forms/<name>/submit?email=q@test.local</code> and <code>/crm/form/submit/<name>/p@test.local</code> let the visitor in. For an emailed-code form it doesn't matter, because the address comes from the code's own record. Put the email in the body too.</p> </div></div> <h3 id="refusal-reasons">Refusal reasons</h3><div class="tw"><table><thead><tr><th>Status</th><th><code>reason</code></th><th>When</th><th>What the page should do</th></tr></thead><tbody><tr><td>400</td><td>—</td><td>"Form data is required" (empty body); "Please fill in Your name, Email." (missing required, by field title); "Topic: must be equal to one of the allowed values"</td><td>Show the message; it names the field.</td></tr><tr><td>400</td><td>—</td><td>"A valid email address is required" (access request)</td><td>Ask for a full address.</td></tr><tr><td>401</td><td><code>email-required</code></td><td><code>email</code> form, no address</td><td>Ask for one.</td></tr><tr><td>401</td><td><code>code-required</code></td><td><code>code</code> form, no code</td><td>Ask for the code.</td></tr><tr><td>403</td><td><code>code-wrong</code></td><td><code>code</code> form, wrong shared code</td><td>"That code isn't right."</td></tr><tr><td>401</td><td><code>link-required</code></td><td>emailed-code or <code>magic-link</code> form, nothing sent</td><td>Ask for the email and request a code.</td></tr><tr><td>401</td><td><code>code-wrong</code></td><td>emailed-code or <code>magic-link</code> form, unknown code or token</td><td>"That code isn't right." Offer a new one.</td></tr><tr><td>401</td><td><code>link-expired</code></td><td>the code or link is over 72 hours old</td><td>Offer a new one.</td></tr><tr><td>401</td><td><code>already-submitted</code></td><td>the link already completed its submission (inline <code>magic-link</code> forms only)</td><td>Say it's been sent.</td></tr><tr><td>403</td><td><code>email-not-verified</code></td><td>the answers' email differs from the one the code was sent to</td><td>Send the verified email.</td></tr><tr><td>403</td><td><code>invitation-required</code> / <code>not-a-participant</code></td><td>a participants form, opened without their link</td><td>"Open it from the link you were sent."</td></tr><tr><td>401</td><td><code>signin-required</code></td><td><code>password</code> form, not signed in</td><td>Send them to <code>/login?redirect=…</code>.</td></tr><tr><td>403</td><td><code>closed</code> / <code>not-open-yet</code></td><td><code>status</code> or the dates</td><td>Say so; nothing to fix.</td></tr><tr><td>403</td><td><code>not-published</code></td><td>the org reviews forms before publishing and this one isn't approved</td><td>Publish it in Studio.</td></tr><tr><td>403</td><td>—</td><td>"This form is not available for public access" / "does not accept public submissions"</td><td>Fix <code>permission</code> on the form.</td></tr><tr><td>404</td><td>—</td><td>"No form or collection found with name <name>"</td><td>Check the name.</td></tr><tr><td>409</td><td><code>duplicate</code> (with <code>field</code>)</td><td>a unique field already has this value in the collection</td><td>"An application from this email already exists."</td></tr></tbody></table></div><h3 id="where-answers-land">Where answers land</h3><div class="tw"><table><thead><tr><th>The form</th><th>The answer is saved as</th><th>Marked</th><th>Notes</th></tr></thead><tbody><tr><td>No <code>collection</code></td><td>a <code>form_submission</code>: <code>{ formId, values: {…answers}, status: "new", authentication: { method, status: "used", email, admittedBy, verified, submittedAt, client } }</code></td><td><code>data.formId</code> = the form's sk</td><td>An inline <code>magic-link</code> answer completes the pending row the link was made for, so the proof and the answers are one record.</td></tr><tr><td>With <code>collection</code></td><td>a record <strong>of that collection</strong>, the answers as its fields, plus <code>data.authentication: { admittedBy }</code></td><td><code>owner = { datatype: "crm_form", id: "<form name>" }</code></td><td>The collection's unique fields and schema apply. The pending <code>form_submission</code> from the code stays <code>pending</code>.</td></tr></tbody></table></div><p><code>admittedBy</code> says which door was used: <code>open</code>, <code>email</code>, <code>form-code</code>, <code>participant-code</code>, <code>link-session</code>, <code>signed-in</code>, <code>staff</code>.</p> <p>Tested. A participant's answer is filed under the participant's own address, whatever email the body carried, and the form's <code>participants[i].submittedAt</code> is set. A collection-bound form saves records even when the collection's own <code>permission.create</code> is <code>["User"]</code> only: the form's permission decides, not the collection's.</p> <div class="cal cal-warn"><div class="cal-b"><p><strong>Don't put <code>Guest</code> in the bound collection's <code>permission</code>.</strong> A collection with <code>Guest</code> in <code>create</code> (or <code>read</code>) is a public form in its own right, under its own name. It skips the CRM form's code. Tested: with <code>Guest</code> added to the test collection, <code>/form?collection=<collection></code> opened its questions and <code>POST /api/client/forms/<collection>/submit</code> saved a record with <strong>no code</strong>, <code>admittedBy: "open"</code> and <strong>no owner</strong>, so an automation filtered on <code>owner.id</code> never saw it. With <code>create: ["User"]</code>, the same call gave 403 "This collection is not shared publicly". The bound form needs nothing on the collection.</p> </div></div> <p>To act on each answer: for a form with no collection, trigger <code>form_submitted</code>. For one with a collection, trigger <code>database_change</code> on the collection with <code>whereField: "owner.id"</code>, <code>whereValue: "<form name>"</code>. See <a href="../ai-skills/registration-that-creates-a-customer.html">Registration that creates the customer</a> step 3. Every answer also raises <code>crm.form.submitted</code>, which AI employees listening to forms hear (<code>crm-form.service.ts</code> 1410).</p> <h3 id="the-emails">The emails</h3><div class="tw"><table><thead><tr><th>Email</th><th>Sent when</th><th>To</th><th>Template</th><th>Link in it</th></tr></thead><tbody><tr><td>Access code or link</td><td><code>POST …/access</code></td><td>the address given</td><td><code>invitationTemplate</code>, else <code>form-invitation</code> (<code>variant: "code"</code> shows the 6-digit code)</td><td><strong>Open the form</strong> → <code><forms page>?form=<name>&token=<code or token></code> (<code>sendFormAccess</code>, <code>crm-form.service.ts</code> 454–460)</td></tr><tr><td>Invitation</td><td>Studio's Send invitation, <code>POST /crm/form/<name>/invite</code> (staff)</td><td>each participant, or those in <code>emails</code></td><td>the same</td><td><strong>Open the form</strong> → <code><forms page>?form=<name>&code=<their code></code> (<code>inviteParticipants</code> 521–549). A resend is marked as a reminder and keeps their code.</td></tr><tr><td>Confirmation</td><td>each answer, if the visitor gave an address (the door's email, the form's email question, or <code>email</code> in the body)</td><td>the visitor</td><td><code>form-submission</code>, plus <code>templates</code>, <code>emailTemplate</code>, <code>smsTemplate</code></td><td>none</td></tr><tr><td>Team alert</td><td>each answer, when the form has <code>email</code></td><td>that address only</td><td>built inline: "New submission: <title>", each answer by its field title</td><td>none</td></tr></tbody></table></div><p><code><forms page></code> is <code>featurePageUrl(orgId, "forms")</code> (appengine <code>site.service.ts</code> 1498–1515), read from the org's <strong>default</strong> site (<code>data.isDefault</code>, else the oldest site):</p> <ul> <li>a <code>forms</code> <strong>row</strong> that is on → <code>https://<site host>/<row.page></code>;</li> <li>a bare <code>"forms"</code> in the list → <code>https://<site host>/<site.data.forms.page or "form"></code>;</li> <li>Forms off, or no row → <code>null</code>, and the emails fall back to <code><site origin>/form</code>.</li> </ul> <p><code>GET /site/base-url?feature=forms</code> gives the same answer, or <code>{ "url": null, "reason": "Enable Forms in Site Features on your default site, then refresh this link." }</code> when it's off. Studio's form Setup tab builds its share link from it: <code><that url>?form=<name></code>.</p> <div class="cal cal-warn"><div class="cal-b"><p><strong>The engine's emails always link to the platform form, never to a page of your own.</strong> Tested with the site's Forms off: the code email for the test form linked to <code>http://<site>/form?form=skilltest-form-otp&token=363946</code>, and <code>/form</code> on that site is a 404. With Forms on, the same link opens the <strong>platform</strong> form with the code already applied, and the visitor can answer there instead of on your page. For way C, tell the person their visitors get an "Open the form" button that 404s (Forms off) or opens a different form (Forms on). The code itself is printed in the email too, which is what a way C page asks for. To change the button, give the form an <code>invitationTemplate</code> of its own whose text doesn't link.</p> </div></div> <h2 id="steps">Steps</h2><h3 id="1-crm-forms-the-form">1. CRM Forms: the form</h3><p>Find the form: <code>repo_find</code> on <code>crm_form</code> with <code>{ "data.name": "<name>" }</code>, then <code>repo_find_one</code> for the whole record. If it doesn't exist, make it with <a href="../ai-skills/shared-form-from-collection.html">Shared form from a collection</a> (with a collection) or <code>repo_create</code> on <code>crm_form</code> (inline <code>schema</code>). A minimal working record:</p> <div class="codewrap"><pre><code>{ "name": "contact", "title": "Contact us", "status": "open", "authenticationType": "none", "email": "office@example.com", "submitMessage": "Thanks, we'll be in touch.", "schema": { "type": "object", "required": ["name", "email"], "properties": { "name": { "type": "string", "title": "Your name" }, "email": { "type": "string", "format": "email", "title": "Email" }, "topic": { "type": "string", "title": "Topic", "enum": ["sales", "support"], "enumNames": ["Sales", "Support"] }, "message": { "type": "string", "maxLength": 500, "title": "Message" } } } }</code></pre></div><p>A registration-style form, bound to a collection and emailing each visitor a code:</p> <div class="codewrap"><pre><code>{ "name": "apply", "title": "Apply", "status": "open", "authenticationType": "code", "collection": "applications", "email": "office@example.com", "submitMessage": "Application received" }</code></pre></div><p>Set <code>authenticationType</code> from <strong>Ask first</strong> and the <a href="#who-gets-in-authenticationtype">table above</a>. Studio sets it on CRM → Forms (<code>/crm-form</code>) → the form → <strong>Access</strong>, which offers Nothing, Magic link, Access code, Username & password, and Email only (<code>crm-form-detail.tsx</code> 89–95).</p> <p><strong>Hands on:</strong> the form's <strong>name</strong> and its <code>authenticationType</code>. <strong>Check:</strong> <code>call_appengine</code> <code>GET /client/forms/<name></code> without anything: <code>none</code> answers 200 with the <code>schema</code>. The others answer the refusal in the table (e.g. 401 <code>link-required</code> for an emailed-code form). Open the form in Studio at <code>/crm-form?uid=<sk></code>.</p> <h3 id="2-site-config-forms-ways-a-and-b-only">2. Site Config: Forms (ways A and B only)</h3><p>Read the default site (<code>repo_find</code> on <code>site</code>, then <code>repo_find_one</code>) and look at <code>data.features</code>. Forms is on if the list has <code>"forms"</code>, or a row <code>{ "feature": "forms" }</code> that isn't <code>enabled: false</code>.</p> <div class="tw"><table><thead><tr><th>Setting</th><th><code>/form</code> and <code>/form/<name></code></th><th>The chosen page's address</th><th>What wraps the form</th><th>Emails link to</th></tr></thead><tbody><tr><td>Off</td><td>404 (correct: Forms is optional)</td><td>its own page</td><td>—</td><td><code><site>/form</code> (a 404)</td></tr><tr><td>On, no page chosen</td><td>the form</td><td>—</td><td><code>account-layout</code></td><td><code><site>/form</code></td></tr><tr><td>On, page <code>X</code> chosen</td><td>the form</td><td><code>/X?form=<name></code> is the form too</td><td>page <code>X</code>: first screen above, second below, at <strong>both</strong> addresses</td><td><code><site>/X</code></td></tr></tbody></table></div><p>Tested with page <code>skilltest-form-frame</code> chosen: <code>/form?form=<name></code>, <code>/form/<name></code> and <code>/skilltest-form-frame?form=<name></code> all drew the form between that page's two screens. <code>/skilltest-form-frame</code> with no form named showed "This form isn't available. No form was named in this link." <code>GET /site/base-url?feature=forms</code> gave <code><site>/skilltest-form-frame</code>. The routing rules are in <a href="../ai-skills/site-page-routing.html">How a site's addresses route</a> (Forms row and Exceptions).</p> <p>To switch it on, follow <a href="../ai-skills/site-page-routing.html">How a site's addresses route</a> step 3: the <strong>whole</strong> list, <code>repo_update</code> with <code>patch</code>, or <code>update-partial</code> with the dot-path key <code>data.features</code>. Read the list again right before writing it.</p> <p><strong>Stop:</strong> switching Forms on gives <code>/form</code> to the form feature, and choosing a page makes that page the frame for every form at both addresses. Its own content stops showing. Tell the person which addresses change, then wait for yes.</p> <p><strong>Hands on:</strong> the forms page's address (<code>/form</code>, or the chosen page). <strong>Check:</strong> <code>GET /site/base-url?feature=forms</code> gives a <code>url</code>. <code>curl -s -o /dev/null -w "%{http_code}" <site>/form</code> is 200.</p> <h3 id="3-way-a-the-platform-form-at-form">3. Way A: the platform form at <code>/form</code></h3><p>Nothing to build. The links:</p> <div class="tw"><table><thead><tr><th>Link</th><th>Opens</th></tr></thead><tbody><tr><td><code>/form?form=<name></code> or <code>/form/<name></code></td><td>the form (the query wins over the segment)</td></tr><tr><td><code>/form?collection=<collection></code></td><td>a collection shared publicly in its own right (see the warning in <a href="#where-answers-land">Where answers land</a>)</td></tr><tr><td><code>…&code=<code></code></td><td>a <code>code</code> form with the code applied, or a participant's own link</td></tr><tr><td><code>…&token=<token></code></td><td>an emailed-code or <code>magic-link</code> form opened from its email. The questions open at once, and the form's email question is answered with the verified address and skipped.</td></tr><tr><td><code>…&email=<address></code></td><td>an <code>email</code> form with the address given</td></tr><tr><td><code>…&mode=group</code></td><td>one screen per schema <code>group</code> (fields with no group go under "General") instead of one per question</td></tr><tr><td><code>…&embed=true</code> (or <code>=1</code>)</td><td>the form alone for another site's iframe: no header, footer, cart, search or audio player; transparent background (<code>components/embed/EmbedFrame.tsx</code>, <code>is-embed.ts</code>)</td></tr></tbody></table></div><p>What the visitor sees. Every row except <code>password</code> was tested on the local site; <code>password</code> is from the code (<code>SchemaFormRoute.tsx</code> 209–222).</p> <div class="tw"><table><thead><tr><th>Form</th><th>Screen</th></tr></thead><tbody><tr><td><code>none</code>, or the gate passed</td><td>"Skilltest Open · 1 of 6 · Your name*", one question at a time, then <strong>Check your answers</strong>, then the thank-you</td></tr><tr><td><code>code</code>, no code</td><td>"Enter your access code" with <strong>Open form</strong>. A wrong code: "That access code is not right."</td></tr><tr><td>emailed code / <code>magic-link</code>, no token</td><td>"What is your email address?" with <strong>Send me the link</strong>. It calls <code>POST /api/client/forms/<name>/access</code> and says "Check your email".</td></tr><tr><td><code>email</code></td><td>"What is your email address?" with <strong>Continue</strong>; the address goes into the link as <code>?email=</code></td></tr><tr><td>participants, no code</td><td>"This form is by invitation. Open it from the link you were sent."</td></tr><tr><td><code>password</code></td><td>"Sign in to open this form" → <code>/login?redirect=<this link></code></td></tr><tr><td>closed, unknown name</td><td>"This form isn't available" with the server's reason ("This form is closed.", "No form or collection found with name …")</td></tr></tbody></table></div><p>How the questions are drawn, from the schema (base-app <code>components/schema-form/SchemaForm.tsx</code> <code>kindOf</code> 146, <code>collect</code> 253, <code>toSteps</code> 281):</p> <div class="tw"><table><thead><tr><th>Schema</th><th>Control</th></tr></thead><tbody><tr><td><code>enum</code> / <code>oneOf</code> with <code>const</code> / <code>options</code></td><td>lettered choice buttons (press A, B, C…); an array type picks several</td></tr><tr><td><code>boolean</code></td><td>Yes / No</td></tr><tr><td><code>integer</code> with <code>minimum</code> and <code>maximum</code> up to 10 apart, or <code>x-control: rating</code></td><td>a 1–N scale</td></tr><tr><td><code>format</code>: <code>email</code>, <code>date</code>, <code>date-time</code>, <code>time</code>, <code>uri</code>, <code>tel</code>, <code>color</code>, <code>password</code></td><td>the matching input. A <code>date-time</code> answer is sent as a full timestamp.</td></tr><tr><td><code>x-control</code>: <code>textarea</code>, <code>richtext</code>, <code>markdown</code>, or <code>maxLength</code> over 180</td><td>a paragraph box</td></tr><tr><td><code>x-control</code>: <code>file</code> / <code>image</code></td><td>a file picker (see the warning)</td></tr><tr><td><code>x-control: signature</code></td><td>draw or type, with consent</td></tr><tr><td><code>type: "null"</code> or <code>x-control: paragraph</code> / <code>label</code> / <code>notice</code></td><td>a statement showing <code>x-content</code>; nothing to answer</td></tr><tr><td>a nested <code>object</code> with <code>properties</code> (up to 3 deep)</td><td>its fields asked one by one, folded back into the object on submit</td></tr><tr><td><code>hidden</code>, <code>readOnly</code>, <code>disabled</code>, <code>const</code>, and <code>id</code>, <code>sk</code>, <code>pk</code>, <code>datatype</code>, <code>author</code>, <code>createdate</code>, <code>modifydate</code>, <code>version</code>, <code>state</code>, <code>search</code></td><td>not asked</td></tr><tr><td><code>schema.pages</code> with more than one page</td><td>one screen per page, its fields together, titled by the page</td></tr></tbody></table></div><p><code>required</code> (or <code>inputRequired: true</code> on the field), <code>minLength</code> / <code>maxLength</code>, <code>minimum</code> / <code>maximum</code>, <code>pattern</code>, <code>errorMessage</code> and a <code>validations</code> list are checked on each screen before moving on. The server checks the schema again on submit.</p> <div class="cal cal-warn"><div class="cal-b"><p><strong>An uploaded file goes into the record itself.</strong> The platform form reads it as a data URL and sends <code>{ name, type, size, data: "data:…;base64,…" }</code> in the JSON (<code>SchemaForm.tsx</code> 711–717). The engine saves it as it came. Tested: the test answer's <code>values.doc.data</code> held the base64 file. Large files bloat records and can hit the API's body limit. For documents, use a page that uploads to the file manager first (way C), or keep files small.</p> </div></div> <p><strong>Hands on:</strong> the link to share: <code>GET /site/base-url?feature=forms</code> + <code>?form=<name></code>. Add <code>&embed=true</code> for an iframe. <strong>Check:</strong> open the link in a browser. The first question (or the gate) shows inside the site's header and footer. Answer it once with a <code>@test.local</code> address and see the thank-you. Find the answer (<a href="#where-answers-land">Where answers land</a>) and delete it.</p> <h3 id="4-way-b-a-site-page-tied-to-a-form">4. Way B: a site page tied to a form</h3><p>A page whose <code>data.formName</code> names a form <strong>is</strong> that form while Forms is on, at its own address (<code>SchemaFormRoute.tsx</code> <code>isSchemaFormRoute</code> 103). The page's first screen is drawn above the form and its second below, like a chosen Forms page. Use it for a form at its own address, e.g. <code>/contact</code>, inside the site's design.</p> <p>Make the page with <a href="../ai-skills/build-a-website-page.html">Build a website page</a>, with <strong>two screens</strong> (the part above the form, the part below), then set <code>formName</code>:</p> <div class="codewrap"><pre><code>{ "name": "contact", "slug": "contact", "site": "<site name>", "appType": "web", "title": "Contact us", "formName": "contact", "screens": [ { "id": "top", "name": "Top", "slug": "top", "order": 0, "html": "<!DOCTYPE html>…<section class=\"intro\">…</section>…", "attributes": {}, "config": {} }, { "id": "bottom", "name": "Bottom", "slug": "bottom", "order": 1, "html": "<!DOCTYPE html>…<section class=\"faq\">…</section>…", "attributes": {}, "config": {} } ], "activeScreenId": "top", "html": "<the first screen's document>" }</code></pre></div><p>On an existing page, add only the field: <code>repo_update</code> on <code>page</code> with <code>patch: { "formName": "<form name>" }</code>, or <code>update-partial</code> with <code>{ "data.formName": "…", "data.name": "…", "data.site": "…", "data.slug": "…" }</code>.</p> <div class="cal cal-info"><div class="cal-b"><p><strong>Build Studio has no field for <code>formName</code>.</strong> The page schema doesn't have it, so Page settings never shows it. Set it with <code>repo_update</code>. A page that has it opens in Build Studio like any other.</p> </div></div> <p>Tested on the local site:</p> <ul> <li>Forms on: <code>/skilltest-form-wrap</code> drew "SKILLTEST TOP SCREEN", the form, then "SKILLTEST BOTTOM SCREEN", inside the site's own header and footer.</li> <li>Forms off: the same address showed only the page's first screen. No form, no error.</li> <li><code>/skilltest-form-wrap?form=skilltest-form-code</code> drew a <strong>different</strong> form, the code-gated one. <code>?form=</code> beats <code>formName</code>.</li> <li>An ordinary page with <code>?form=</code> (<code>/news?form=…</code>) stays itself. Only <code>/form</code>, the chosen Forms page and <code>formName</code> pages take <code>?form=</code>.</li> </ul> <p>There is no form component or preset to drop a form into a normal page. <code><wm-form></code> exists only in Content Studio posts (the Content Player renders it). The site's page renderer leaves it as an empty tag. The page runtime's <code>form.*</code> only serializes, validates and resets a <code><form></code>; it doesn't submit to a CRM form. A form inside a page's own content is way C.</p> <p><strong>Hands on:</strong> the page's address. <strong>Check:</strong> open it. The form sits between the two screens. The emails still link to <code>/form</code> (step 2), not to this page.</p> <h3 id="5-way-c-a-page-of-your-own-posting-through-api">5. Way C: a page of your own, posting through <code>/api</code></h3><p>The page is ordinary HTML in its screens. Its script goes in <strong>Page settings → Style → JavaScript</strong> (<code>style.javascript</code>), guarded by <code>data-design-mode</code>, as in <a href="../ai-skills/build-a-website-page.html">Build a website page</a> step 4. Forms can stay off.</p> <h4 id="the-site-s-api">The site's <code>/api</code></h4><p><code>fetch('/api/<path>')</code> on the same site goes to the engine with the org and the site's app token added (base-app <code>app/api/[...slug]/route.ts</code>).</p> <ul> <li><strong>Only the body, the query string and <code>Authorization</code> get through.</strong> Custom headers like <code>x-form-token</code> or <code>x-form-code</code> are dropped. Put the code in the query (<code>?token=</code>) or the body. A signed-in visitor's <code>Authorization</code> goes on as <code>x-client-authorization</code>, which makes them the customer (route.ts 72–74, <code>lib/appmint-client.ts</code> 234–237).</li> <li><strong>Errors come back wrapped:</strong> <code>{ "error": { "reason": "duplicate", "field": "email", "statusCode": 409, "error": "A … with email \"…\" already exists.", "path": "…", "method": "POST", "timeStamp": "…" }, "status": 409 }</code>, with the engine's HTTP status. The message is <code>error.error</code>, the reason <code>error.reason</code> (route.ts 131–138). Tested for every refusal above.</li> <li>The query string is also copied into the body as <code>clientQuery</code>; the form endpoints remove it. A body that holds nothing else is refused: "Form data is required".</li> <li>The proxy adds the visitor's IP, host and agent as <code>x-client-info</code>; the answer stores it as <code>client</code>.</li> </ul> <h4 id="the-flow-for-a-form-that-emails-a-code">The flow, for a form that emails a code</h4><ol> <li>Collect the answers in your own steps.</li> <li><code>POST /api/client/forms/<name>/access</code> with <code>{ email }</code>, where <code>email</code> is trimmed and lowercased. Show "We sent a 6-digit code to …", a code box, <strong>Send a new code</strong> (the same call; each call makes a new pending code, and every unexpired one works) and <strong>Change email</strong>.</li> <li><code>POST /api/crm/form/submit/<name>?token=<code></code> with the answers. Send <strong>the same email</strong> in the answers; another address is refused with 403 <code>email-not-verified</code>.</li> <li>Show each <code>reason</code> from <a href="#refusal-reasons">Refusal reasons</a>. Show success only on a 2xx.</li> </ol> <p>For a plain form (<code>none</code>), skip 2 and post the answers. For a shared code, send <code>?code=<code></code>.</p> <h4 id="a-complete-page-tested">A complete page (tested)</h4><p>The screen's HTML:</p> <div class="codewrap"><pre><code><!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> .st-apply { max-width: 520px; margin: 48px auto; padding: 0 16px; } .st-apply label { display: block; margin: 12px 0 4px; font-weight: 600; } .st-apply input, .st-apply select { width: 100%; padding: 10px; } .st-msg[data-tone="error"] { color: #b91c1c; } </style> </head> <body> <main class="st-apply" id="st-apply"> <h1>Apply</h1> <form id="st-details" novalidate> <label for="st-name">Full name</label> <input id="st-name" name="full_name" required> <label for="st-email">Work email</label> <input id="st-email" name="email" type="email" required> <label for="st-team">Team</label> <select id="st-team" name="team"><option>Red</option><option>Blue</option></select> <button type="submit">Send me a code</button> </form> <form id="st-code" hidden novalidate> <p id="st-sent"></p> <label for="st-code-input">6-digit code</label> <input id="st-code-input" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6"> <button type="submit">Submit application</button> <button type="button" id="st-resend">Send a new code</button> </form> <div id="st-done" hidden><h2>Application received</h2></div> <p class="st-msg" id="st-msg" role="status"></p> </main> </body> </html></code></pre></div><p>Its <code>style.javascript</code>:</p> <div class="codewrap"><pre><code>(function boot() { // Never run inside Build Studio's canvas. if (document.body && document.body.getAttribute('data-design-mode') === 'true') return; var app = document.getElementById('st-apply'); if (!app) return void setTimeout(boot, 30); if (app.dataset.bound) return; app.dataset.bound = '1'; var FORM = 'skilltest-form-otp'; var details = document.getElementById('st-details'); var codeForm = document.getElementById('st-code'); var msg = document.getElementById('st-msg'); var answers = null; function say(text, tone) { msg.textContent = text || ''; msg.setAttribute('data-tone', tone || ''); } // POST through the site's own /api. Errors come back as { error: { reason, error, statusCode }, status }. function api(path, body) { return fetch('/api/' + path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), credentials: 'same-origin' }).then(function (r) { return r.json().catch(function () { return null; }).then(function (j) { if (r.ok) return j; var e = (j && typeof j.error === 'object' && j.error) || j || {}; var err = new Error(typeof e.error === 'string' ? e.error : (e.message || 'Request failed')); err.status = r.status; err.reason = e.reason || ''; throw err; }); }); } function requestCode() { return api('client/forms/' + FORM + '/access', { email: answers.email }).then(function () { document.getElementById('st-sent').textContent = 'We sent a 6-digit code to ' + answers.email + '.'; details.hidden = true; codeForm.hidden = false; say(''); }); } details.addEventListener('submit', function (ev) { ev.preventDefault(); var f = new FormData(details); answers = { full_name: String(f.get('full_name') || '').trim(), // The unique index compares exact text: lowercase before saving. email: String(f.get('email') || '').trim().toLowerCase(), team: String(f.get('team') || '') }; if (!answers.full_name || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(answers.email)) return say('Fill in your name and a full email address.', 'error'); requestCode().catch(function (e) { say(e.message, 'error'); }); }); document.getElementById('st-resend').addEventListener('click', function () { requestCode().then(function () { say('A new code is on its way.'); }).catch(function (e) { say(e.message, 'error'); }); }); codeForm.addEventListener('submit', function (ev) { ev.preventDefault(); var code = String(document.getElementById('st-code-input').value || '').trim(); // The code rides in the query string: the site's /api does not pass custom headers on. var path = 'crm/form/submit/' + FORM + '?token=' + encodeURIComponent(code) + '&email=' + encodeURIComponent(answers.email); api(path, answers).then(function () { codeForm.hidden = true; document.getElementById('st-done').hidden = false; say(''); }).catch(function (e) { if (e.reason === 'code-wrong') return say('That code is not right. Check the email and try again.', 'error'); if (e.reason === 'link-expired') return say('That code has expired. Send a new one.', 'error'); if (e.reason === 'link-required') return say('Enter the code from the email.', 'error'); if (e.reason === 'duplicate') return say('An application from this email already exists.', 'error'); if (e.reason === 'email-not-verified') return say('Use the email the code was sent to.', 'error'); say(e.message, 'error'); }); }); })();</code></pre></div><p>Tested in headless Chrome on the local site with Forms off. The form was bound to a collection with <code>unique: true</code> on <code>email</code>, its index built. The steps and what came back:</p> <ol> <li>Typed <code>Custom.Tester@test.local</code>: <code>access</code> gave 200 and the code box showed.</li> <li><code>000000</code>: 401, "That code is not right…"</li> <li>The real code: 200, "Application received". The record was saved with the email lowercased and <code>owner: { datatype: "crm_form", id: "skilltest-form-otp" }</code>.</li> <li>The same email again with a fresh code: 409, "An application from this email already exists."</li> </ol> <h4 id="collection-bound-or-plain">Collection-bound or plain</h4><div class="tw"><table><thead><tr><th></th><th>Plain form (no <code>collection</code>)</th><th>Collection-bound form</th></tr></thead><tbody><tr><td>Questions</td><td>the form's <code>schema</code></td><td>the collection's schema</td></tr><tr><td>Saved as</td><td><code>form_submission</code> (<code>values</code>)</td><td>a collection record, <code>owner</code> = the form</td></tr><tr><td>One per email</td><td>not available</td><td><code>unique: true</code> on the field, then <code>POST /repository/collections/fix</code> (see <a href="../ai-skills/registration-that-creates-a-customer.html">Registration that creates the customer</a> step 1). Tested: 409 <code>duplicate</code>.</td></tr><tr><td>Automation trigger</td><td><code>form_submitted</code></td><td><code>database_change</code> on the collection, <code>owner.id</code> = form name</td></tr><tr><td>Emailed code used twice</td><td>refused for an inline <code>magic-link</code> link (<code>already-submitted</code>)</td><td>accepted for 72 hours (the pending row stays <code>pending</code>)</td></tr></tbody></table></div><div class="cal cal-warn"><div class="cal-b"><ul> <li><strong>Unique fields compare exact text.</strong> Tested: <code>Reg.One@test.local</code> and <code>reg.one@test.local</code> were saved as two records. Lowercase the email in the page.</li> <li><strong>No passwords in a form record.</strong> A password in the answers is stored as plain text in the collection or <code>form_submission</code>, readable by staff and exports. Account creation belongs to an automation; the customer sets a password through <code>/login</code>'s "Forgot password?" or signs in with a magic link. See <a href="../ai-skills/registration-that-creates-a-customer.html">Registration that creates the customer</a>.</li> <li><strong>Don't post to <code>/crm/contact-form/json/<app>/<name></code> from a page.</strong> It is the embed route for a form on an outside website. It hands the answers to the form's own submit, so the form's permission, dates, code, invitation, sign-in and schema all apply, but a <code><name></code> with no form or collection yet creates a new open form from the first post's fields (<code>crm-form.service.ts</code> <code>saveContactFormJSON</code>). A typo makes a stray form. Post to <code>/api/crm/form/submit/<name></code> (or <code>/api/client/forms/<name>/submit</code>) as in the flow above.</li> </ul> </div></div> <p><strong>Stop:</strong> the page is live at its address from its first save on a site that serves drafts. Show the person the address and the flow, and wait for yes. The code emails will carry an "Open the form" link to <code>/form</code> (see <a href="#the-emails">The emails</a>); tell them.</p> <p><strong>Hands on:</strong> the page's address. <strong>Check:</strong> go through it once with a <code>@test.local</code> address. Read the code from the engine instead of an inbox: <code>repo_find</code> on <code>form_submission</code> with <code>{ "data.formId": "<form sk>", "data.authentication.email": "<address>" }</code>, and take <code>data.authentication.token</code>. A wrong code shows the code message, the right one shows success, and the record appears (<a href="#where-answers-land">Where answers land</a>). Delete the test record and the pending <code>form_submission</code>.</p> <h2 id="when-it-s-done">When it's done</h2><p>Tell the person:</p> <ul> <li>the way chosen and the address the form is at;</li> <li>who can fill it in (the <code>authenticationType</code> in their words: "anyone", "people we email a code to");</li> <li>where answers land (the form's Submissions in Studio, or the collection), and who is emailed for each;</li> <li>where the form's emails link, and, for way C, that the "Open the form" link goes to <code>/form</code>, not their page;</li> <li>whether Forms is on, and which addresses that gives to forms.</li> </ul> <p>Open the form in Studio (<code>/crm-form?uid=<sk></code>) and the page on the site.</p> <h2 id="what-it-can-t-do-yet">What it can't do yet</h2><ul> <li><strong>The emails can't link to a page of your own.</strong> <code>sendFormAccess</code> and <code>inviteParticipants</code> always build <code><forms page>?form=…</code>. Way C pages get an "Open the form" button that 404s or opens the platform form.</li> <li><strong>The code doesn't run out on a collection-bound form.</strong> The code stays good for 72 hours and can be used again. A unique field stops a second record under the same email.</li> <li><strong>No "already applied" check before the code.</strong> The visitor learns about the duplicate only when they submit with the code.</li> <li><strong>No upload of files to the file manager from the platform form.</strong> Files go into the record as base64.</li> <li><strong>The confirmation email's subject starts with the site's host, not the business name.</strong> Tested: "phasite-phazzer.localhost:3200 - Skilltest File - Form Submission Received". The submission context has no <code>displayName</code>.</li> <li><strong>The form's SEO tab isn't used by the site.</strong> No code in the site's form route or page metadata reads the form's <code>seo</code>, so share previews of <code>/form</code> show the forms page's own title and image. Not tested.</li> <li><strong>Build Studio can't set <code>formName</code></strong>, and there's no component to place a CRM form inside a page's content.</li> <li><strong>Studio's participant "Their link"</strong> is built as <code><forms page>/form?form=…&code=…</code> (<code>crm-form-detail.tsx</code> 612), so with Forms on <code>/form</code> it reads <code>/form/form?form=…</code>. It still opens, because the query names the form.</li> <li><strong><code>/crm/contact-form/json/<app>/<name></code></strong> creates an open form named <code><name></code> on the first post to a name that has none (see the warning in step 5).</li> </ul> <h2 id="don-ts">Don'ts</h2><ul> <li>Don't create a page named <code>form</code> to "fix" a 404 at <code>/form</code>. Forms is off and the 404 is correct. Switch Forms on, or use way C.</li> <li>Don't choose a page the site uses for something else as the Forms page. Its content becomes the frame around every form.</li> <li>Don't send the code in a header from a site page. Use <code>?token=</code> or <code>?code=</code>.</li> <li>Don't use <code>authenticationType: "email"</code> when the address must be real.</li> <li>Don't put <code>Guest</code> on a bound collection's <code>permission</code>. It opens the collection without the form's gate.</li> <li>Don't put a password field in a form or its collection.</li> <li>Don't post to <code>/crm/contact-form/json/…</code> from a page.</li> <li>Don't read codes from real inboxes in tests. Use <code>@test.local</code> addresses and the pending <code>form_submission</code>.</li> </ul> </article> <nav class="pager"> <a class="pg pg-p" href="../ai-skills/built-in-pages-and-templates.html"><span>Previous</span><b>Built-in pages — turn them off, replace them, or frame them in the site's design</b></a> <a class="pg pg-n" href="../ai-skills/social-post-graphic.html"><span>Next</span><b>Social post graphic</b></a> </nav> </main> <nav class="toc" id="toc"></nav> </div> <script>/* Docs search. Loaded inline into every page by build.mjs. The index (search-index.js) is fetched with a <script> tag on first use, so this also works from disk. search.html?q=... renders the full result list. */ (function () { var q = document.getElementById('q'); if (!q) return; var ROOT = q.getAttribute('data-root') || ''; var wrap = q.parentNode; var pop = document.createElement('div'); pop.className = 'sr-pop'; pop.hidden = true; wrap.appendChild(pop); var list = document.getElementById('sr'); var idx = null, waiting = null, active = -1, hits = []; function load(cb) { if (idx) return cb(); if (waiting) { waiting.push(cb); return; } waiting = [cb]; var s = document.createElement('script'); s.src = ROOT + '/search-index.js'; s.onload = function () { var d = window.DOCS_SEARCH; idx = { pages: d.pages.map(function (p) { return { u: p[0], t: p[1], s: p[2], d: p[3], lt: p[1].toLowerCase(), ls: p[2].toLowerCase() }; }), secs: d.secs.map(function (x) { return { p: x[0], a: x[1], h: x[2], x: x[3], lh: x[2].toLowerCase(), lx: x[3].toLowerCase() }; }) }; var w = waiting; waiting = null; w.forEach(function (f) { f(); }); }; s.onerror = function () { waiting = null; pop.innerHTML = '<div class="sr-empty">Search index not found. Rebuild the docs.</div>'; pop.hidden = false; }; document.head.appendChild(s); } /* Filler words ("how do I refund a card") are dropped unless nothing else is left. */ var STOP = ' a an the to of in on for and or is are how do does i my me we our you your with by at it be can what where when why which this that from as into '; function terms(s) { var all = (s.toLowerCase().match(/[a-z0-9]+/g) || []).filter(function (t, i, a) { return a.indexOf(t) === i; }); var real = all.filter(function (t) { return STOP.indexOf(' ' + t + ' ') === -1; }); return real.length ? real : all; } function count(hay, t) { var n = 0, i = hay.indexOf(t); while (i !== -1 && n < 8) { n++; i = hay.indexOf(t, i + t.length); } return n; } function wordStart(hay, t) { var i = hay.indexOf(t); while (i !== -1) { if (i === 0 || !/[a-z0-9]/.test(hay[i - 1])) return true; i = hay.indexOf(t, i + 1); } return false; } /* Every term must appear somewhere in the section or its page title. Title and heading hits outweigh body hits; whole-word hits outweigh fragments. */ function search(query) { var ts = terms(query); if (!ts.length) return []; var phrase = ts.join(' '); var byPage = {}; idx.secs.forEach(function (s) { var p = idx.pages[s.p], score = 0; for (var i = 0; i < ts.length; i++) { var t = ts[i], hit = 0; if (p.lt.indexOf(t) !== -1) hit += wordStart(p.lt, t) ? 10 : 4; if (s.lh.indexOf(t) !== -1) hit += wordStart(s.lh, t) ? 7 : 3; var c = count(s.lx, t); if (c) hit += (wordStart(s.lx, t) ? 1.5 : 0.6) + Math.min(c, 8) * 0.25; if (p.ls.indexOf(t) !== -1) hit += 0.5; if (!hit) return; score += hit; } if (ts.length > 1) { if (p.lt.indexOf(phrase) !== -1) score += 12; if (s.lh.indexOf(phrase) !== -1) score += 9; else if (s.lx.indexOf(phrase) !== -1) score += 4; } if (!s.a) score += 0.5; var g = byPage[s.p] || (byPage[s.p] = { p: p, score: 0, secs: [] }); g.secs.push({ s: s, score: score }); if (score > g.score) g.score = score; }); var groups = Object.keys(byPage).map(function (k) { return byPage[k]; }); groups.forEach(function (g) { g.secs.sort(function (a, b) { return b.score - a.score; }); g.score += Math.min(g.secs.length - 1, 5) * 0.4; }); groups.sort(function (a, b) { return b.score - a.score; }); return groups.map(function (g) { g.ts = ts; return g; }); } function esc(s) { return s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"'); } function mark(s, ts) { if (!ts.length) return esc(s); return s.split(new RegExp('(' + ts.join('|') + ')', 'gi')).map(function (part, i) { return i % 2 ? '<mark>' + esc(part) + '</mark>' : esc(part); }).join(''); } function snippet(text, ts, len) { var lx = text.toLowerCase(), pos = -1; for (var i = 0; i < ts.length; i++) { var j = lx.indexOf(ts[i]); if (j !== -1 && (pos === -1 || j < pos)) pos = j; } if (pos === -1) return mark(text.slice(0, len), ts) + (text.length > len ? '…' : ''); var start = Math.max(0, pos - 50); var sp = text.lastIndexOf(' ', start); if (start > 0 && sp > start - 20) start = sp + 1; var s = text.slice(start, start + len); return (start > 0 ? '…' : '') + mark(s, ts) + (start + len < text.length ? '…' : ''); } function href(p, a) { return ROOT + '/' + p.u + '.html' + (a ? '#' + a : ''); } function moreHref(v) { return ROOT + '/search.html?q=' + encodeURIComponent(v); } function renderPop() { var v = q.value.trim(); if (!v) { pop.hidden = true; return; } hits = search(v); active = hits.length ? 0 : -1; if (!hits.length) { pop.innerHTML = '<div class="sr-empty">No results for “' + esc(v) + '”.</div>'; } else { pop.innerHTML = hits.slice(0, 8).map(function (g, i) { var s = g.secs[0].s; return '<a class="sr-i' + (i === 0 ? ' on' : '') + '" href="' + href(g.p, s.a) + '">' + '<span class="sr-t">' + mark(g.p.t, g.ts) + (s.h ? ' <span class="sr-h">› ' + mark(s.h, g.ts) + '</span>' : '') + '</span>' + (g.p.s ? '<span class="sr-s">' + esc(g.p.s) + '</span>' : '') + '<span class="sr-x">' + snippet(s.x || g.p.d, g.ts, 160) + '</span></a>'; }).join('') + '<a class="sr-more" href="' + moreHref(v) + '">See all ' + hits.length + ' result' + (hits.length === 1 ? '' : 's') + ' →</a>'; } if (!list) { // Phones: the popup is position:fixed to the screen edges, just under the box. pop.style.top = window.innerWidth <= 900 ? (wrap.getBoundingClientRect().bottom + 8) + 'px' : ''; pop.hidden = false; } } function renderList() { var v = q.value.trim(); if (!v) { list.innerHTML = '<p class="sr-count">Type in the search box to search every page.</p>'; return; } var gs = search(v); list.innerHTML = '<p class="sr-count">' + gs.length + ' page' + (gs.length === 1 ? '' : 's') + ' match “' + esc(v) + '”.</p>' + gs.slice(0, 60).map(function (g) { var top = g.secs[0].s, rest = g.secs.slice(1, 5).filter(function (x) { return x.s.a; }); return '<div class="sr-g"><a href="' + href(g.p, top.a) + '">' + mark(g.p.t, g.ts) + (top.h ? ' › ' + mark(top.h, g.ts) : '') + '</a>' + (g.p.s ? '<span class="sr-s">' + esc(g.p.s) + '</span>' : '') + '<p>' + snippet(top.x || g.p.d, g.ts, 260) + '</p>' + (rest.length ? '<ul class="sr-sub">' + rest.map(function (x) { return '<li><a href="' + href(g.p, x.s.a) + '">' + mark(x.s.h, g.ts) + '</a></li>'; }).join('') + '</ul>' : '') + '</div>'; }).join(''); } function update() { load(function () { if (list) { renderList(); var u = q.value.trim() ? '?q=' + encodeURIComponent(q.value.trim()) : location.pathname.split('/').pop(); try { history.replaceState(null, '', u); } catch (e) {} } else renderPop(); }); } function setActive(i) { var items = pop.querySelectorAll('.sr-i'); if (!items.length) return; active = (i + items.length) % items.length; items.forEach(function (el, k) { el.classList.toggle('on', k === active); }); items[active].scrollIntoView({ block: 'nearest' }); } q.addEventListener('focus', function () { load(function () { if (!list && q.value.trim()) renderPop(); }); }); q.addEventListener('input', update); q.addEventListener('keydown', function (e) { if (e.key === 'ArrowDown') { e.preventDefault(); setActive(active + 1); } else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(active - 1); } else if (e.key === 'Escape') { pop.hidden = true; q.blur(); } else if (e.key === 'Enter') { e.preventDefault(); var v = q.value.trim(); if (!v || list) return; var items = pop.querySelectorAll('.sr-i'); location.href = active >= 0 && items[active] ? items[active].getAttribute('href') : moreHref(v); } }); document.addEventListener('click', function (e) { if (!wrap.contains(e.target)) pop.hidden = true; }); document.addEventListener('keydown', function (e) { var tag = (document.activeElement && document.activeElement.tagName) || ''; var typing = /INPUT|TEXTAREA|SELECT/.test(tag) || (document.activeElement && document.activeElement.isContentEditable); if ((e.key === 'k' && (e.metaKey || e.ctrlKey)) || (e.key === '/' && !typing)) { e.preventDefault(); q.focus(); q.select(); } }); if (list) { var m = /[?&]q=([^&]*)/.exec(location.search); q.value = m ? decodeURIComponent(m[1].replace(/\+/g, ' ')) : ''; update(); if (!q.value) q.focus(); } })(); var mb=document.getElementById('menu'); if(mb){mb.addEventListener('click',function(){document.getElementById('side').classList.toggle('closed');});} if(window.innerWidth<=900){var s=document.getElementById('side'); if(s)s.classList.add('closed');} var art=document.querySelector('.body'), toc=document.getElementById('toc'); if(art&&toc){ var hs=art.querySelectorAll('h2,h3'); if(hs.length>1){ var html='<h4>On this page</h4>'; hs.forEach(function(h,i){ if(!h.id){h.id='s'+i+'-'+h.textContent.toLowerCase().replace(/[^a-z0-9]+/g,'-').replace(/^-|-$/g,'');} html+='<a class="'+h.tagName.toLowerCase()+'" href="#'+h.id+'">'+h.textContent+'</a>'; }); toc.innerHTML=html; var links=toc.querySelectorAll('a'); var obs=new IntersectionObserver(function(es){ es.forEach(function(e){ if(e.isIntersecting){ links.forEach(function(l){l.classList.toggle('on', l.getAttribute('href')==='#'+e.target.id);}); }}); },{rootMargin:'-110px 0px -70% 0px'}); hs.forEach(function(h){obs.observe(h);}); } } </script> </body> </html>