@mccaskie-labs/workbench-ask 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,124 @@
1
+ // workbench/ask.json: the project's answers for the question box
2
+ // (capabilities/ask.json's offer). Checked here, by the CLI before it builds
3
+ // the knowledge and by createAsk before it answers anything.
4
+ import { AskError } from "./errors.js";
5
+ export const ASK_LANGUAGES = ["match", "en", "tl", "taglish"];
6
+ /** The Workbench voices (capabilities/ai.json), so the box can name one without depending on workbench-ai. */
7
+ export const ASK_VOICES = ["casual", "conversational", "plain", "formal", "strict-formal"];
8
+ export const ASK_SPELLINGS = ["en-AU", "en-PH", "en-GB", "en-US"];
9
+ const MAX_NOTES = 12;
10
+ const MAX_FAQ = 200;
11
+ /** What's wrong with an answers file, as plain lines. Empty when it is fine. */
12
+ export function askSettingsProblems(input) {
13
+ const out = [];
14
+ if (typeof input !== "object" || input === null || Array.isArray(input))
15
+ return ["workbench/ask.json must be a JSON object"];
16
+ const s = input;
17
+ const known = new Set(["format", "business", "sources", "pages_root", "exclude", "faq", "model", "voice", "spelling", "language", "notes", "handover", "keep", "keep_days", "where", "$schema"]);
18
+ for (const k of Object.keys(s))
19
+ if (!known.has(k))
20
+ out.push(`${k}: not a setting`);
21
+ if (s["format"] !== 1)
22
+ out.push("format: must be 1");
23
+ if (typeof s["business"] !== "string" || s["business"].trim().length === 0 || s["business"].length > 100)
24
+ out.push("business: the business's name, 1 to 100 characters");
25
+ const strings = (key, max, each) => {
26
+ const v = s[key];
27
+ if (v === undefined)
28
+ return;
29
+ if (!Array.isArray(v) || v.length > max || v.some((x) => typeof x !== "string" || x.trim().length === 0 || x.length > each))
30
+ out.push(`${key}: a list of up to ${max} texts, each up to ${each} characters`);
31
+ };
32
+ strings("sources", 50, 200);
33
+ strings("exclude", 50, 200);
34
+ strings("notes", MAX_NOTES, 300);
35
+ for (const key of ["sources", "exclude"]) {
36
+ const v = s[key];
37
+ if (Array.isArray(v) && v.some((x) => typeof x === "string" && (x.startsWith("/") || x.split(/[\\/]/).includes(".."))))
38
+ out.push(`${key}: paths are relative to the project and stay inside it`);
39
+ }
40
+ if (s["pages_root"] !== undefined && (typeof s["pages_root"] !== "string" || s["pages_root"].length === 0 || s["pages_root"].includes("..")))
41
+ out.push("pages_root: a folder inside the project, such as public");
42
+ if (s["faq"] !== undefined) {
43
+ const faq = s["faq"];
44
+ if (!Array.isArray(faq) || faq.length > MAX_FAQ)
45
+ out.push(`faq: a list of up to ${MAX_FAQ} questions and answers`);
46
+ else
47
+ faq.forEach((f, i) => {
48
+ const e = f;
49
+ if (typeof f !== "object" || f === null)
50
+ return out.push(`faq.${i}: { "q": ..., "a": ... }`);
51
+ if (typeof e["q"] !== "string" || e["q"].trim().length === 0 || e["q"].length > 300)
52
+ out.push(`faq.${i}.q: the question, 1 to 300 characters`);
53
+ if (typeof e["a"] !== "string" || e["a"].trim().length === 0 || e["a"].length > 2000)
54
+ out.push(`faq.${i}.a: the answer, 1 to 2000 characters`);
55
+ if (e["url"] !== undefined && (typeof e["url"] !== "string" || !/^(\/[^\s]*|https:\/\/[^\s]+)$/.test(e["url"])))
56
+ out.push(`faq.${i}.url: a path such as /contact, or an https address`);
57
+ for (const k of Object.keys(e))
58
+ if (!["q", "a", "url"].includes(k))
59
+ out.push(`faq.${i}.${k}: not a field`);
60
+ });
61
+ }
62
+ if (s["model"] !== undefined && (typeof s["model"] !== "string" || !/^[a-z0-9][a-z0-9.-]{0,63}$/.test(s["model"])))
63
+ out.push("model: a Workbench alias such as claude-fast");
64
+ if (s["voice"] !== undefined && !ASK_VOICES.includes(s["voice"]))
65
+ out.push(`voice: one of ${ASK_VOICES.join(", ")}`);
66
+ if (s["spelling"] !== undefined && !ASK_SPELLINGS.includes(s["spelling"]))
67
+ out.push(`spelling: one of ${ASK_SPELLINGS.join(", ")}`);
68
+ if (s["language"] !== undefined && !ASK_LANGUAGES.includes(s["language"]))
69
+ out.push(`language: one of ${ASK_LANGUAGES.join(", ")}`);
70
+ const h = s["handover"];
71
+ if (typeof h !== "object" || h === null || typeof h["email"] !== "boolean" || typeof h["app"] !== "boolean" || Object.keys(h).some((k) => k !== "email" && k !== "app")) {
72
+ out.push('handover: { "email": true or false, "app": true or false }');
73
+ }
74
+ if (s["keep"] !== undefined && s["keep"] !== "none" && s["keep"] !== "app")
75
+ out.push("keep: none or app");
76
+ if (s["keep_days"] !== undefined && (!Number.isInteger(s["keep_days"]) || s["keep_days"] < 1 || s["keep_days"] > 365))
77
+ out.push("keep_days: whole days, 1 to 365");
78
+ if (s["where"] !== undefined && s["where"] !== "every_page" && s["where"] !== "chosen_pages")
79
+ out.push("where: every_page or chosen_pages");
80
+ const sources = Array.isArray(s["sources"]) ? s["sources"] : ["public"];
81
+ if (sources.length === 0 && (!Array.isArray(s["faq"]) || s["faq"].length === 0))
82
+ out.push("sources and faq: the box needs something to answer from");
83
+ return out;
84
+ }
85
+ /** Checks the answers file and fills in its defaults. Throws bad_config naming every problem. */
86
+ export function resolveAskSettings(input) {
87
+ const problems = askSettingsProblems(input);
88
+ if (problems.length > 0)
89
+ throw new AskError("bad_config", `workbench/ask.json: ${problems.join("; ")}`);
90
+ const s = input;
91
+ return {
92
+ format: 1,
93
+ business: s.business.trim(),
94
+ sources: s.sources ?? ["public"],
95
+ pages_root: s.pages_root ?? "public",
96
+ exclude: s.exclude ?? [],
97
+ faq: s.faq ?? [],
98
+ model: s.model ?? "claude-fast",
99
+ voice: s.voice ?? "conversational",
100
+ spelling: s.spelling ?? "en-AU",
101
+ language: s.language ?? "match",
102
+ notes: s.notes ?? [],
103
+ handover: { email: s.handover.email, app: s.handover.app },
104
+ keep: s.keep ?? "none",
105
+ keep_days: s.keep_days ?? 30,
106
+ where: s.where ?? "every_page",
107
+ };
108
+ }
109
+ /** The starter answers file `npx workbench-ask init` writes. */
110
+ export const STARTER_ASK = {
111
+ format: 1,
112
+ business: "Demo Co",
113
+ sources: ["public"],
114
+ pages_root: "public",
115
+ faq: [{ q: "How do I get in touch?", a: "Use the contact form on the Contact page and we'll reply within one working day.", url: "/contact" }],
116
+ model: "claude-fast",
117
+ voice: "conversational",
118
+ spelling: "en-AU",
119
+ language: "match",
120
+ notes: [],
121
+ handover: { email: true, app: false },
122
+ keep: "none",
123
+ where: "every_page",
124
+ };
@@ -0,0 +1,33 @@
1
+ /** One CSS custom property the rules read, with its default. */
2
+ export interface StyleVariable {
3
+ /** `--wb-<tool>-<what>`. */
4
+ name: string;
5
+ value: string;
6
+ about: string;
7
+ }
8
+ /** A rule for a class in another state, or for an element inside it. */
9
+ export interface StyleState {
10
+ selector: string;
11
+ about: string;
12
+ css: string;
13
+ }
14
+ /** One class the tool puts on an element, with its default rule. */
15
+ export interface StyleClass {
16
+ name: string;
17
+ element: string;
18
+ about: string;
19
+ css: string;
20
+ states?: readonly StyleState[];
21
+ }
22
+ /** Every class and variable the tool draws with. */
23
+ export interface ToolStyles {
24
+ format: 1;
25
+ tool: string;
26
+ package: string;
27
+ title: string;
28
+ prefix: string;
29
+ variables: readonly StyleVariable[];
30
+ classes: readonly StyleClass[];
31
+ }
32
+ /** The style hooks of the question box (renderAskWidget, ASK_SCRIPT). */
33
+ export declare const ASK_STYLES: ToolStyles;
package/dist/styles.js ADDED
@@ -0,0 +1,79 @@
1
+ // The look the question box starts with (docs/capabilities-manifest.md §10).
2
+ // Every element renderAskWidget and ASK_SCRIPT draw carries one of these
3
+ // classes, and every class has a default rule here, so the box looks finished
4
+ // out of the box and a project restyles it from its own CSS by the same names.
5
+ // `npx workbench-ui styles` writes these into the project's
6
+ // public/styles/workbench.css inside `@layer workbench`. The names are public:
7
+ // renaming one is a breaking change.
8
+ const v = (name) => `var(--wb-ask-${name})`;
9
+ const hidden = { selector: "[hidden]", about: "Hidden until it's needed", css: "display:none" };
10
+ const focus = { selector: ":focus-visible", about: "Has focus", css: `outline:none;box-shadow:0 0 0 3px ${v("focus")}` };
11
+ const disabled = { selector: ":disabled", about: "Waiting for an answer", css: "opacity:.6;cursor:wait" };
12
+ const button = `display:inline-flex;align-items:center;justify-content:center;min-height:2.75rem;padding:0 1rem;font:inherit;font-weight:600;border-radius:${v("radius")};cursor:pointer`;
13
+ const field = `width:100%;box-sizing:border-box;min-height:2.75rem;padding:.5rem .75rem;font:inherit;color:${v("text")};background:${v("sunk")};border:1px solid ${v("line")};border-radius:${v("radius")}`;
14
+ const visuallyHidden = "position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0";
15
+ /** The style hooks of the question box (renderAskWidget, ASK_SCRIPT). */
16
+ export const ASK_STYLES = {
17
+ format: 1,
18
+ tool: "ask",
19
+ package: "@mccaskie-labs/workbench-ask",
20
+ title: "Website question box",
21
+ prefix: "wb-ask-",
22
+ variables: [
23
+ { name: "--wb-ask-text", value: "var(--wb-text, #1f2937)", about: "Text: answers, questions, labels" },
24
+ { name: "--wb-ask-muted", value: "var(--wb-muted, #5b6472)", about: "Quieter text: the privacy line, waiting" },
25
+ { name: "--wb-ask-surface", value: "var(--wb-surface, #f7f8f8)", about: "Background of the panel" },
26
+ { name: "--wb-ask-sunk", value: "color-mix(in srgb, var(--wb-background, #ffffff), var(--wb-text, #1f2937) 3%)", about: "Background of the chat and the fields" },
27
+ { name: "--wb-ask-line", value: "var(--wb-line, #d7d8db)", about: "Borders" },
28
+ { name: "--wb-ask-bot", value: "color-mix(in srgb, var(--wb-surface, #f7f8f8), var(--wb-text, #1f2937) 7%)", about: "Background of the box's answers" },
29
+ { name: "--wb-ask-visitor", value: "var(--wb-accent, #2563eb)", about: "Background of the visitor's questions" },
30
+ { name: "--wb-ask-on-visitor", value: "var(--wb-on-accent, #ffffff)", about: "Text on the visitor's questions" },
31
+ { name: "--wb-ask-accent", value: "var(--wb-accent, #2563eb)", about: "The button in the corner, Send, links" },
32
+ { name: "--wb-ask-on-accent", value: "var(--wb-on-accent, #ffffff)", about: "Text on the main buttons" },
33
+ { name: "--wb-ask-focus", value: "var(--wb-focus, rgba(37,99,235,0.4))", about: "The ring round a control with focus" },
34
+ { name: "--wb-ask-radius", value: "var(--wb-radius, 8px)", about: "Corner rounding" },
35
+ { name: "--wb-ask-shadow", value: "0 12px 32px rgba(0,0,0,.35)", about: "The panel's shadow when it floats" },
36
+ { name: "--wb-ask-z", value: "1000", about: "How far above the page the button and panel sit" },
37
+ ],
38
+ classes: [
39
+ { name: "wb-ask", element: "div", about: "The whole box: the button in the corner and its panel", css: `position:fixed;right:1rem;bottom:1rem;z-index:${v("z")};display:flex;flex-direction:column;align-items:flex-end;gap:.5rem;color:${v("text")};font-size:1rem;line-height:1.45` },
40
+ { name: "wb-ask-inline", element: "div", about: "The box placed in the page (open: true), not floating", css: "position:static;align-items:stretch;z-index:auto" },
41
+ { name: "wb-ask-launcher", element: "button", about: "The button in the corner that opens the panel", css: `${button};order:2;color:${v("on-accent")};background:${v("accent")};border:0;box-shadow:${v("shadow")}`, states: [focus] },
42
+ {
43
+ name: "wb-ask-panel",
44
+ element: "section",
45
+ about: "The chat panel",
46
+ css: `display:flex;flex-direction:column;gap:.5rem;width:min(24rem,calc(100vw - 2rem));max-height:min(36rem,calc(100vh - 6rem));overflow-y:auto;padding:.75rem;box-sizing:border-box;background:${v("surface")};border:1px solid ${v("line")};border-radius:${v("radius")};box-shadow:${v("shadow")}`,
47
+ states: [hidden],
48
+ },
49
+ { name: "wb-ask-header", element: "header", about: "The panel's title row", css: "display:flex;align-items:center;justify-content:space-between;gap:.5rem" },
50
+ { name: "wb-ask-title", element: "h2", about: "\"Ask\" and the business's name", css: "margin:0;font-size:1.05rem;font-weight:600" },
51
+ { name: "wb-ask-close", element: "button", about: "Closes the panel", css: `${button};padding:0;width:2.75rem;color:${v("muted")};background:transparent;border:0;font-size:1.4rem`, states: [focus] },
52
+ { name: "wb-ask-log", element: "ol", about: "The chat so far", css: `flex:1 1 auto;list-style:none;margin:0;padding:.5rem;display:flex;flex-direction:column;gap:.5rem;overflow-y:auto;min-height:7rem;background:${v("sunk")};border-radius:${v("radius")}` },
53
+ { name: "wb-ask-message", element: "li", about: "One question or answer", css: `flex:none;max-width:85%;padding:.5rem .75rem;border-radius:${v("radius")}` },
54
+ { name: "wb-ask-message-visitor", element: "li", about: "A question the visitor asked", css: `align-self:flex-end;color:${v("on-visitor")};background:${v("visitor")}` },
55
+ { name: "wb-ask-message-bot", element: "li", about: "An answer, or what the box says when it can't answer", css: `align-self:flex-start;background:${v("bot")}` },
56
+ { name: "wb-ask-thinking", element: "li", about: "Looking it up", css: `color:${v("muted")};font-style:italic` },
57
+ { name: "wb-ask-text", element: "p", about: "The words of a question or answer", css: "margin:0;white-space:pre-wrap;overflow-wrap:anywhere" },
58
+ { name: "wb-ask-sources", element: "ul", about: "The pages an answer came from", css: "list-style:none;margin:.4rem 0 0;padding:0;display:flex;flex-wrap:wrap;gap:.25rem .75rem;font-size:.9rem" },
59
+ { name: "wb-ask-source-item", element: "li", about: "One page", css: "margin:0" },
60
+ { name: "wb-ask-source", element: "a", about: "A link to a page the answer came from", css: `color:${v("accent")};text-decoration:underline`, states: [focus] },
61
+ { name: "wb-ask-offer", element: "button", about: "Ask a person: opens the form that sends the question to the owner", css: `${button};margin-top:.5rem;min-height:2.5rem;color:${v("accent")};background:transparent;border:1px solid ${v("accent")}`, states: [focus] },
62
+ { name: "wb-ask-form", element: "form", about: "The question field and Send", css: "display:flex;gap:.5rem;align-items:flex-end", states: [hidden] },
63
+ { name: "wb-ask-form-label", element: "label", about: "The question field's label, for screen readers only", css: visuallyHidden },
64
+ { name: "wb-ask-input", element: "textarea", about: "Where the visitor types a question", css: `${field};flex:1;resize:none`, states: [focus] },
65
+ { name: "wb-ask-send", element: "button", about: "Sends the question", css: `${button};color:${v("on-accent")};background:${v("accent")};border:0`, states: [focus, disabled] },
66
+ { name: "wb-ask-handover", element: "form", about: "The form that sends the question to the owner", css: `display:grid;gap:.5rem;padding:.75rem;background:${v("sunk")};border-radius:${v("radius")}`, states: [hidden] },
67
+ { name: "wb-ask-handover-offer", element: "p", about: "\"Would you like someone to answer you by email?\"", css: "margin:0;font-weight:600" },
68
+ { name: "wb-ask-field", element: "label", about: "One field of the form, with its label", css: "display:grid;gap:.25rem" },
69
+ { name: "wb-ask-label", element: "span", about: "A field's label", css: `font-size:.9rem;color:${v("muted")}` },
70
+ { name: "wb-ask-handover-input", element: "input", about: "Name, email and question fields", css: field, states: [focus] },
71
+ { name: "wb-ask-trap", element: "label", about: "A field only bots fill in, kept out of sight", css: visuallyHidden },
72
+ { name: "wb-ask-handover-buttons", element: "div", about: "Send and Not now", css: "display:flex;flex-wrap:wrap;gap:.5rem" },
73
+ { name: "wb-ask-handover-send", element: "button", about: "Sends the question to the owner", css: `${button};color:${v("on-accent")};background:${v("accent")};border:0`, states: [focus, disabled] },
74
+ { name: "wb-ask-handover-cancel", element: "button", about: "Closes the form without sending", css: `${button};color:${v("muted")};background:transparent;border:1px solid ${v("line")}`, states: [focus] },
75
+ { name: "wb-ask-handover-status", element: "p", about: "Sent, or what went wrong", css: "margin:0;font-size:.95rem" },
76
+ { name: "wb-ask-privacy", element: "p", about: "Where answers come from, and that questions aren't stored", css: `margin:0;font-size:.8rem;color:${v("muted")}` },
77
+ { name: "wb-ask-words", element: "script", about: "The box's words for its script (never shown)", css: "display:none" },
78
+ ],
79
+ };
@@ -0,0 +1,21 @@
1
+ import { type AskWordsLang, type Words } from "./words.ts";
2
+ export interface AskWidgetOptions {
3
+ /** The app's route that hands requests to Ask.handle, e.g. `/api/ask`. */
4
+ endpoint: string;
5
+ /** The business's name, as in workbench/ask.json (`ask.settings.business`). */
6
+ business: string;
7
+ /** The project's strings lookup (`ui.wbask.*`). */
8
+ t?: Words;
9
+ /** The words' language when `t` has none. Default en. */
10
+ lang?: AskWordsLang;
11
+ /** Start with the panel open (a Help page), instead of the button in the corner. */
12
+ open?: boolean;
13
+ /** Whether the box offers to hand questions on (`ask.settings.handover`: email or app). Default true. */
14
+ handover?: boolean;
15
+ /** With keep: app, how many days the app keeps questions (`ask.settings.keep_days`), so the box says so. */
16
+ keepDays?: number;
17
+ }
18
+ /** The box's HTML. Put it once in the page's body, with ASK_SCRIPT after it. */
19
+ export declare function renderAskWidget(o: AskWidgetOptions): string;
20
+ /** The box's script, for a `<script>` tag after renderAskWidget's HTML (or a file the page loads). */
21
+ export declare const ASK_SCRIPT: string;
package/dist/widget.js ADDED
@@ -0,0 +1,173 @@
1
+ // The question box on the project's pages: a button in the corner that opens
2
+ // a small chat panel, and a form that hands a question to the owner. Plain
3
+ // HTML from renderAskWidget plus one small script (ASK_SCRIPT, no libraries),
4
+ // which posts to the app's endpoint (Ask.handle). Every element carries a
5
+ // wb-ask-* class (ASK_STYLES); the script only ever puts text in with
6
+ // textContent, and only links to the site's own paths or https addresses.
7
+ import { ASK_LIMITS } from "./ask.js";
8
+ import { ASK_WORD_KEYS, wordsFor } from "./words.js";
9
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
10
+ /** The box's HTML. Put it once in the page's body, with ASK_SCRIPT after it. */
11
+ export function renderAskWidget(o) {
12
+ if (!/^\/[^\s"'<>]*$/.test(o.endpoint))
13
+ throw new TypeError("endpoint must be a path on the site, such as /api/ask");
14
+ const w = wordsFor(o, { business: o.business, max: ASK_LIMITS.questionChars, days: o.keepDays ?? 0 });
15
+ const words = Object.fromEntries(ASK_WORD_KEYS.filter((k) => !k.startsWith("email.")).map((k) => [k, w(k)]));
16
+ const json = JSON.stringify(words).replace(/</g, "\\u003c");
17
+ const open = o.open === true;
18
+ const handover = o.handover !== false;
19
+ return [
20
+ `<div class="wb-ask${open ? " wb-ask-inline" : ""}" data-wb-ask data-endpoint="${esc(o.endpoint)}" data-handover="${handover ? "yes" : "no"}">`,
21
+ open ? "" : `<button class="wb-ask-launcher" type="button" aria-expanded="false" aria-controls="wbask-panel">${esc(words.open)}</button>`,
22
+ `<section class="wb-ask-panel" id="wbask-panel" aria-label="${esc(words.title)}"${open ? "" : " hidden"}>`,
23
+ `<header class="wb-ask-header"><h2 class="wb-ask-title">${esc(words.title)}</h2>${open ? "" : `<button class="wb-ask-close" type="button" aria-label="${esc(words.close)}">×</button>`}</header>`,
24
+ `<ol class="wb-ask-log" aria-live="polite"><li class="wb-ask-message wb-ask-message-bot"><p class="wb-ask-text">${esc(words.greeting)}</p></li></ol>`,
25
+ `<form class="wb-ask-form"><label class="wb-ask-form-label" for="wbask-question">${esc(words.placeholder)}</label>`,
26
+ `<textarea class="wb-ask-input" id="wbask-question" name="question" rows="2" maxlength="${ASK_LIMITS.questionChars}" placeholder="${esc(words.placeholder)}" required></textarea>`,
27
+ `<button class="wb-ask-send" type="submit">${esc(words.send)}</button></form>`,
28
+ handover
29
+ ? [
30
+ `<form class="wb-ask-handover" hidden><p class="wb-ask-handover-offer">${esc(words["handover.offer"])}</p>`,
31
+ `<label class="wb-ask-field"><span class="wb-ask-label">${esc(words["handover.name"])}</span><input class="wb-ask-handover-input" name="name" maxlength="${ASK_LIMITS.nameChars}" autocomplete="name"></label>`,
32
+ `<label class="wb-ask-field"><span class="wb-ask-label">${esc(words["handover.email"])}</span><input class="wb-ask-handover-input" name="email" type="email" maxlength="254" autocomplete="email" required></label>`,
33
+ `<label class="wb-ask-field"><span class="wb-ask-label">${esc(words["handover.message"])}</span><textarea class="wb-ask-handover-input" name="message" rows="3" maxlength="${ASK_LIMITS.messageChars}" required></textarea></label>`,
34
+ `<label class="wb-ask-trap" aria-hidden="true">Website<input name="website" tabindex="-1" autocomplete="off"></label>`,
35
+ `<div class="wb-ask-handover-buttons"><button class="wb-ask-handover-send" type="submit">${esc(words["handover.send"])}</button><button class="wb-ask-handover-cancel" type="button">${esc(words["handover.cancel"])}</button></div>`,
36
+ `<p class="wb-ask-handover-status" role="status"></p></form>`,
37
+ ].join("")
38
+ : "",
39
+ `<p class="wb-ask-privacy">${esc(o.keepDays ? words.privacy_kept : words.privacy)}</p>`,
40
+ `</section>`,
41
+ `<script type="application/json" class="wb-ask-words">${json}</script>`,
42
+ `</div>`,
43
+ ].join("");
44
+ }
45
+ /** The box's script, for a `<script>` tag after renderAskWidget's HTML (or a file the page loads). */
46
+ export const ASK_SCRIPT = `(() => {
47
+ for (const root of document.querySelectorAll("[data-wb-ask]")) {
48
+ if (root.dataset.wbAskReady) continue;
49
+ root.dataset.wbAskReady = "yes";
50
+ const words = JSON.parse(root.querySelector(".wb-ask-words").textContent);
51
+ const endpoint = root.dataset.endpoint;
52
+ const canHandOver = root.dataset.handover === "yes";
53
+ const panel = root.querySelector(".wb-ask-panel");
54
+ const launcher = root.querySelector(".wb-ask-launcher");
55
+ const closer = root.querySelector(".wb-ask-close");
56
+ const log = root.querySelector(".wb-ask-log");
57
+ const form = root.querySelector(".wb-ask-form");
58
+ const input = root.querySelector(".wb-ask-input");
59
+ const send = root.querySelector(".wb-ask-send");
60
+ const hand = root.querySelector(".wb-ask-handover");
61
+ const history = [];
62
+ let lastQuestion = "";
63
+ const el = (tag, cls, text) => { const e = document.createElement(tag); e.className = cls; if (text !== undefined) e.textContent = text; return e; };
64
+ const scroll = () => { log.scrollTop = log.scrollHeight; };
65
+ const toggle = (show) => {
66
+ panel.hidden = !show;
67
+ if (launcher) launcher.setAttribute("aria-expanded", show ? "true" : "false");
68
+ if (show) input.focus(); else if (launcher) launcher.focus();
69
+ };
70
+ if (launcher) launcher.addEventListener("click", () => toggle(panel.hidden));
71
+ if (closer) closer.addEventListener("click", () => toggle(false));
72
+ root.addEventListener("keydown", (e) => { if (e.key === "Escape" && launcher && !panel.hidden) toggle(false); });
73
+ const post = async (body) => {
74
+ const res = await fetch(endpoint, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), credentials: "same-origin" });
75
+ return { status: res.status, body: await res.json().catch(() => ({})) };
76
+ };
77
+ const offer = (item) => {
78
+ if (!canHandOver || !hand) return;
79
+ const b = el("button", "wb-ask-offer", words["handover.start"]);
80
+ b.type = "button";
81
+ b.addEventListener("click", () => {
82
+ hand.hidden = false;
83
+ form.hidden = true;
84
+ hand.querySelector(".wb-ask-handover-status").textContent = "";
85
+ hand.elements.message.value = lastQuestion;
86
+ hand.scrollIntoView({ block: "nearest" });
87
+ hand.elements.email.focus();
88
+ });
89
+ item.appendChild(b);
90
+ };
91
+ const say = (who, text) => {
92
+ const item = el("li", "wb-ask-message wb-ask-message-" + who);
93
+ item.appendChild(el("p", "wb-ask-text", text));
94
+ log.appendChild(item);
95
+ scroll();
96
+ return item;
97
+ };
98
+ const safe = (url) => typeof url === "string" && (/^\\/(?!\\/)/.test(url) || /^https:\\/\\//.test(url));
99
+ form.addEventListener("submit", async (e) => {
100
+ e.preventDefault();
101
+ const question = input.value.trim();
102
+ if (!question) return;
103
+ if (question.length > ${ASK_LIMITS.questionChars}) { say("bot", words.too_long); return; }
104
+ say("visitor", question);
105
+ lastQuestion = question;
106
+ input.value = "";
107
+ send.disabled = true;
108
+ const wait = say("bot wb-ask-thinking", words.thinking);
109
+ let r;
110
+ try {
111
+ r = await post({ action: "ask", question, history: history.slice(-6), page: location.pathname });
112
+ } catch {
113
+ r = { status: 0, body: {} };
114
+ }
115
+ wait.remove();
116
+ send.disabled = false;
117
+ history.push({ who: "visitor", text: question });
118
+ const b = r.body || {};
119
+ if (r.status === 429) { say("bot", words.limited); return; }
120
+ if (r.status !== 200 || typeof b.status !== "string") { offer(say("bot", words.error)); return; }
121
+ if (b.status === "answered" && typeof b.text === "string") {
122
+ const item = say("bot", b.text);
123
+ history.push({ who: "bot", text: b.text });
124
+ const links = (Array.isArray(b.sources) ? b.sources : []).filter((s) => s && safe(s.url));
125
+ if (links.length) {
126
+ const list = el("ul", "wb-ask-sources");
127
+ list.setAttribute("aria-label", words.sources);
128
+ for (const s of links) {
129
+ const li = el("li", "wb-ask-source-item");
130
+ const a = el("a", "wb-ask-source", s.title || words.sources);
131
+ a.href = s.url;
132
+ li.appendChild(a);
133
+ list.appendChild(li);
134
+ }
135
+ item.appendChild(list);
136
+ }
137
+ if (b.handover) offer(item);
138
+ return;
139
+ }
140
+ const item = say("bot", words[b.status] || words.error);
141
+ if (b.handover) offer(item);
142
+ });
143
+ if (hand) hand.querySelector(".wb-ask-handover-cancel").addEventListener("click", () => {
144
+ hand.hidden = true;
145
+ form.hidden = false;
146
+ input.focus();
147
+ });
148
+ if (hand) hand.addEventListener("submit", async (e) => {
149
+ e.preventDefault();
150
+ const status = hand.querySelector(".wb-ask-handover-status");
151
+ const email = hand.elements.email.value.trim();
152
+ if (!/^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/.test(email)) { status.textContent = words["handover.bad_email"]; return; }
153
+ const button = hand.querySelector(".wb-ask-handover-send");
154
+ button.disabled = true;
155
+ let r;
156
+ try {
157
+ r = await post({ action: "handover", email, name: hand.elements.name.value.trim(), question: hand.elements.message.value.trim(), page: location.pathname, website: hand.elements.website.value });
158
+ } catch {
159
+ r = { status: 0, body: {} };
160
+ }
161
+ button.disabled = false;
162
+ if (r.status === 200 && r.body && r.body.ok) {
163
+ hand.hidden = true;
164
+ hand.reset();
165
+ form.hidden = false;
166
+ say("bot", words["handover.sent"]);
167
+ } else {
168
+ status.textContent = r.status === 400 ? words["handover.bad_email"] : r.status === 429 ? words.limited : words["handover.failed"];
169
+ }
170
+ });
171
+ }
172
+ })();
173
+ `;
@@ -0,0 +1,11 @@
1
+ export declare const ASK_WORD_KEYS: readonly ["open", "close", "title", "greeting", "placeholder", "send", "thinking", "you", "bot", "sources", "unsure", "refused", "paused", "error", "limited", "too_long", "handover.offer", "handover.start", "handover.name", "handover.email", "handover.message", "handover.send", "handover.cancel", "handover.sent", "handover.failed", "handover.bad_email", "privacy", "privacy_kept", "email.subject", "email.intro", "email.page", "email.reply"];
2
+ export type AskWordKey = (typeof ASK_WORD_KEYS)[number];
3
+ export type AskWordsLang = "en" | "tl" | "taglish";
4
+ export declare const ASK_WORDS: Readonly<Record<AskWordsLang, Readonly<Record<AskWordKey, string>>>>;
5
+ /** The project's strings lookup: `t('ui.wbask.send')`. Undefined falls back to the words of `lang`. */
6
+ export type Words = (key: string, params?: Readonly<Record<string, string | number>>) => string | undefined;
7
+ /** One lookup: the project's `t` first, then this package's words. */
8
+ export declare function wordsFor(o: {
9
+ t?: Words;
10
+ lang?: AskWordsLang;
11
+ }, base?: Readonly<Record<string, string | number>>): (key: AskWordKey, params?: Readonly<Record<string, string | number>>) => string;
package/dist/words.js ADDED
@@ -0,0 +1,131 @@
1
+ // The question box's words, keyed as the project's strings catalogue keys them
2
+ // (`ui.wbask.*`), in English, Tagalog and Taglish. A project copies them into
3
+ // its catalogue (or keeps its own) and passes its `t`; a word the catalogue
4
+ // lacks falls back to the English here. The Tagalog and Taglish are starter
5
+ // words: have a fluent reader check them before a visitor sees them.
6
+ export const ASK_WORD_KEYS = [
7
+ "open",
8
+ "close",
9
+ "title",
10
+ "greeting",
11
+ "placeholder",
12
+ "send",
13
+ "thinking",
14
+ "you",
15
+ "bot",
16
+ "sources",
17
+ "unsure",
18
+ "refused",
19
+ "paused",
20
+ "error",
21
+ "limited",
22
+ "too_long",
23
+ "handover.offer",
24
+ "handover.start",
25
+ "handover.name",
26
+ "handover.email",
27
+ "handover.message",
28
+ "handover.send",
29
+ "handover.cancel",
30
+ "handover.sent",
31
+ "handover.failed",
32
+ "handover.bad_email",
33
+ "privacy",
34
+ "privacy_kept",
35
+ "email.subject",
36
+ "email.intro",
37
+ "email.page",
38
+ "email.reply",
39
+ ];
40
+ const en = {
41
+ open: "Ask a question",
42
+ close: "Close",
43
+ title: "Ask {business}",
44
+ greeting: "Hi! Ask me anything about {business}. If I'm not sure, I'll pass your question on.",
45
+ placeholder: "Type your question",
46
+ send: "Send",
47
+ thinking: "Looking that up…",
48
+ you: "You",
49
+ bot: "{business}",
50
+ sources: "Read more",
51
+ unsure: "I'm not sure about that one, and I'd rather not guess.",
52
+ refused: "Sorry, I can't help with that here.",
53
+ paused: "The question box is resting for now.",
54
+ error: "Something went wrong on our side.",
55
+ limited: "That's a lot of questions at once. Please wait a minute and try again.",
56
+ too_long: "Please keep your question under {max} characters.",
57
+ "handover.offer": "Would you like someone from {business} to answer you by email?",
58
+ "handover.start": "Ask a person",
59
+ "handover.name": "Your name (optional)",
60
+ "handover.email": "Your email",
61
+ "handover.message": "Your question",
62
+ "handover.send": "Send to {business}",
63
+ "handover.cancel": "Not now",
64
+ "handover.sent": "Sent. {business} will reply to your email.",
65
+ "handover.failed": "That didn't send. Please try again, or use the contact page.",
66
+ "handover.bad_email": "Please check your email address.",
67
+ privacy: "Answers come from this site's own pages and may be wrong. Your questions aren't stored.",
68
+ privacy_kept: "Answers come from this site's own pages and may be wrong. {business} keeps your questions for {days} days.",
69
+ "email.subject": "Website question from {who}",
70
+ "email.intro": "{who} asked a question on the website that the question box couldn't answer. Reply to this email to answer them.",
71
+ "email.page": "Asked on: {page}",
72
+ "email.reply": "Their email: {email}",
73
+ };
74
+ const tl = {
75
+ open: "Magtanong",
76
+ close: "Isara",
77
+ title: "Magtanong sa {business}",
78
+ greeting: "Kumusta! Magtanong tungkol sa {business}. Kung hindi ako sigurado, ipapasa ko ang tanong mo.",
79
+ placeholder: "Isulat ang tanong mo",
80
+ send: "Ipadala",
81
+ thinking: "Hinahanap ko…",
82
+ you: "Ikaw",
83
+ bot: "{business}",
84
+ sources: "Basahin pa",
85
+ unsure: "Hindi ako sigurado diyan, at ayokong manghula.",
86
+ refused: "Pasensya na, hindi ako makakatulong diyan dito.",
87
+ paused: "Pahinga muna ang tanungan.",
88
+ error: "May nangyaring mali sa amin.",
89
+ limited: "Ang dami ng tanong nang sabay. Maghintay ng isang minuto at subukan ulit.",
90
+ too_long: "Pakiikliin ang tanong sa {max} na titik pababa.",
91
+ "handover.offer": "Gusto mo bang sagutin ka ng taga-{business} sa email?",
92
+ "handover.start": "Magtanong sa tao",
93
+ "handover.name": "Pangalan mo (hindi kailangan)",
94
+ "handover.email": "Email mo",
95
+ "handover.message": "Tanong mo",
96
+ "handover.send": "Ipadala sa {business}",
97
+ "handover.cancel": "Huwag muna",
98
+ "handover.sent": "Naipadala na. Sasagot ang {business} sa email mo.",
99
+ "handover.failed": "Hindi naipadala. Subukan ulit, o gamitin ang contact page.",
100
+ "handover.bad_email": "Pakitingnan ulit ang email mo.",
101
+ privacy: "Galing sa mga pahina ng site na ito ang mga sagot at maaaring mali. Hindi itinatago ang mga tanong mo.",
102
+ privacy_kept: "Galing sa mga pahina ng site na ito ang mga sagot at maaaring mali. Itinatago ng {business} ang mga tanong mo nang {days} araw.",
103
+ "email.subject": en["email.subject"],
104
+ "email.intro": en["email.intro"],
105
+ "email.page": en["email.page"],
106
+ "email.reply": en["email.reply"],
107
+ };
108
+ const taglish = {
109
+ ...en,
110
+ open: "Ask a question",
111
+ greeting: "Hi! Ask lang about {business}. Kung hindi ako sure, ipapasa ko yung question mo.",
112
+ thinking: "Hinahanap ko…",
113
+ unsure: "Hindi ako sure diyan, ayokong manghula.",
114
+ refused: "Sorry, hindi ako makakatulong diyan dito.",
115
+ limited: "Ang dami ng questions nang sabay. Wait lang ng isang minute then try ulit.",
116
+ "handover.offer": "Gusto mo bang sagutin ka ng taga-{business} sa email?",
117
+ "handover.sent": "Sent na. Magre-reply ang {business} sa email mo.",
118
+ "handover.failed": "Hindi na-send. Try ulit, o gamitin ang contact page.",
119
+ };
120
+ export const ASK_WORDS = { en, tl, taglish };
121
+ function fill(text, params = {}) {
122
+ return text.replace(/\{(\w+)\}/g, (m, k) => (Object.hasOwn(params, k) ? String(params[k]) : m));
123
+ }
124
+ /** One lookup: the project's `t` first, then this package's words. */
125
+ export function wordsFor(o, base = {}) {
126
+ const words = ASK_WORDS[o.lang ?? "en"] ?? ASK_WORDS.en;
127
+ return (key, params = {}) => {
128
+ const all = { ...base, ...params };
129
+ return o.t?.(`ui.wbask.${key}`, all) ?? fill(words[key], all);
130
+ };
131
+ }
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@mccaskie-labs/workbench-ask",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "A question box for a Workbench project's website: answers visitors from the project's own pages and questions-and-answers through the Gateway, says so when it isn't sure, and hands the question to the owner by email or to the app. Workbench keeps no visitor's words.",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/mccaskie-labs/workbench.git",
10
+ "directory": "packages/ask"
11
+ },
12
+ "engines": {
13
+ "node": ">=24"
14
+ },
15
+ "sideEffects": false,
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ },
21
+ "./styles": {
22
+ "types": "./dist/styles.d.ts",
23
+ "default": "./dist/styles.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "bin": {
28
+ "workbench-ask": "./dist/cli.js"
29
+ },
30
+ "files": [
31
+ "dist",
32
+ "README.md",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "scripts": {
39
+ "typecheck": "tsc -p tsconfig.check.json && tsc -p test/tsconfig.json",
40
+ "test": "vitest run",
41
+ "build": "node scripts/build.mjs",
42
+ "prepack": "node scripts/build.mjs"
43
+ },
44
+ "devDependencies": {
45
+ "@types/node": "24.19.2",
46
+ "vitest": "^5.1.0"
47
+ }
48
+ }