formal-ai 0.205.0

Formal symbolic AI implementation with OpenAI-compatible APIs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
// formal-ai shared site chrome (issue #479).
//
// The landing page (/) and the documentation hub (/docs/) are structurally the
// same page: a top bar (brand + language/theme switchers), a hero, a grid of
// "chooser" cards, and a footer. Rather than duplicate that machinery, both
// pages provide a small config object to `createChooser()` here.
//
// This module reuses the exact `data-theme` contract and the same
// Links-Notation-backed `formal-ai.preferences.v1` storage (via preferences.js)
// that download.js and the chat app use, so a visitor's theme/locale choice is
// shared across /, /app/, /docs/ and /download/. It makes no network calls.
//
// The proven download.js helpers (h/segmentedControl/locale+theme resolution)
// are intentionally re-implemented here verbatim rather than imported, so the
// heavily-tested download page stays an independent island while the two new
// pages share one source of truth.

(function (global) {
  "use strict";

  var SUPPORTED_LOCALES = ["en", "ru", "zh", "hi"];

  // Chrome labels shared by every page (switchers + footer). Page-specific copy
  // (heading/eyebrow/summary/card text) overrides these via `config.copy`.
  var LABELS = {
    en: {
      language: "Language",
      theme: "Theme",
      themeAuto: "Auto",
      themeLight: "Light",
      themeDark: "Dark",
      footerVersion: "Version",
      footerSource: "Source on GitHub",
      sourceEyebrow: "Open source",
    },
    ru: {
      language: "Язык",
      theme: "Тема",
      themeAuto: "Авто",
      themeLight: "Светлая",
      themeDark: "Тёмная",
      footerVersion: "Версия",
      footerSource: "Исходный код на GitHub",
      sourceEyebrow: "Открытый код",
    },
    zh: {
      language: "语言",
      theme: "主题",
      themeAuto: "自动",
      themeLight: "浅色",
      themeDark: "深色",
      footerVersion: "版本",
      footerSource: "GitHub 源代码",
      sourceEyebrow: "开源",
    },
    hi: {
      language: "भाषा",
      theme: "थीम",
      themeAuto: "ऑटो",
      themeLight: "लाइट",
      themeDark: "डार्क",
      footerVersion: "संस्करण",
      footerSource: "GitHub पर सोर्स कोड",
      sourceEyebrow: "ओपन सोर्स",
    },
  };

  // ---------------------------------------------------------------------------
  // Locale detection (identical contract to download.js)
  // ---------------------------------------------------------------------------

  function normalizeLocale(tag) {
    var lower = String(tag || "").toLowerCase();
    for (var i = 0; i < SUPPORTED_LOCALES.length; i += 1) {
      if (lower === SUPPORTED_LOCALES[i] || lower.indexOf(SUPPORTED_LOCALES[i] + "-") === 0) {
        return SUPPORTED_LOCALES[i];
      }
    }
    if (lower.indexOf("zh") === 0) return "zh";
    return undefined;
  }

  function detectLocaleFromBrowser() {
    var nav = typeof navigator !== "undefined" ? navigator : {};
    var languages = nav.languages || (nav.language ? [nav.language] : ["en"]);
    for (var i = 0; i < languages.length; i += 1) {
      var match = normalizeLocale(languages[i]);
      if (match) return match;
    }
    return "en";
  }

  function resolveLocale(localePreference) {
    var normalized = normalizeLocale(localePreference);
    if (normalized) return normalized;
    return detectLocaleFromBrowser();
  }

  function resolveTheme(themePreference) {
    if (themePreference === "dark") return "dark";
    if (themePreference === "light") return "light";
    if (
      typeof global.matchMedia === "function" &&
      global.matchMedia("(prefers-color-scheme: dark)").matches
    ) {
      return "dark";
    }
    return "light";
  }

  // ---------------------------------------------------------------------------
  // Preference round-trip (shared with the chat app via preferences.js)
  // ---------------------------------------------------------------------------

  function readPreferences() {
    if (global.FormalAiPreferences && typeof global.FormalAiPreferences.load === "function") {
      return global.FormalAiPreferences.load({});
    }
    return {};
  }

  function writePreference(key, value) {
    if (!global.FormalAiPreferences || typeof global.FormalAiPreferences.save !== "function") {
      return;
    }
    var current = global.FormalAiPreferences.load({});
    current[key] = value;
    global.FormalAiPreferences.save(current);
  }

  function readVersion() {
    if (typeof document === "undefined") return "";
    var meta = document.querySelector('meta[name="formal-ai-version"]');
    var content = meta && meta.getAttribute("content");
    // The Pages stamp pipeline replaces __FORMAL_AI_VERSION__ with a real
    // semver; if the placeholder survives (un-stamped local build) we omit the
    // label rather than print the placeholder.
    if (!content || content.indexOf("__") === 0 || !/^v?\d/.test(content)) return "";
    return content.charAt(0).toLowerCase() === "v" ? content.slice(1) : content;
  }

  // ---------------------------------------------------------------------------
  // Tiny hyperscript helper (identical to download.js)
  // ---------------------------------------------------------------------------

  function h(tag, props) {
    var el = document.createElement(tag);
    if (props) {
      Object.keys(props).forEach(function (key) {
        var value = props[key];
        if (value == null || value === false) return;
        if (key === "class") {
          el.className = value;
        } else if (key === "text") {
          el.textContent = value;
        } else if (key.indexOf("on") === 0 && typeof value === "function") {
          el.addEventListener(key.slice(2).toLowerCase(), value);
        } else if (value === true) {
          el.setAttribute(key, "");
        } else {
          el.setAttribute(key, String(value));
        }
      });
    }
    for (var i = 2; i < arguments.length; i += 1) {
      appendChild(el, arguments[i]);
    }
    return el;
  }

  function appendChild(parent, child) {
    if (child == null || child === false) return;
    if (Array.isArray(child)) {
      child.forEach(function (item) {
        appendChild(parent, item);
      });
      return;
    }
    if (typeof child === "string" || typeof child === "number") {
      parent.appendChild(document.createTextNode(String(child)));
      return;
    }
    parent.appendChild(child);
  }

  function segmentedControl(options, activeValue, onSelect, ariaLabel, className) {
    return h(
      "div",
      { class: className, role: "group", "aria-label": ariaLabel },
      options.map(function (option) {
        return h("button", {
          type: "button",
          class: activeValue === option.value ? "active" : "",
          "aria-pressed": activeValue === option.value ? "true" : "false",
          "data-value": option.value,
          text: option.label,
          onClick: function () {
            onSelect(option.value);
          },
        });
      }),
    );
  }

  // ---------------------------------------------------------------------------
  // Chooser page factory (landing + docs)
  // ---------------------------------------------------------------------------
  //
  // config = {
  //   rootId:       string  — id of the <main> to render into
  //   topbarClass:  string  — class for the <header> top bar
  //   brandHref:    string  — where the brand link points (home)
  //   repoUrl:      string  — hero "Source on GitHub" big-button target
  //   exposeAs:     string  — window global to publish the api on (for e2e)
  //   destinations: [{ id, href, external?, icon, titleKey, descKey, actionKey }]
  //   copy:         { <locale>: { heading, eyebrow, summary, ...cardKeys } }
  // }

  function createChooser(config) {
    var state = { locale: "en", themePreference: "auto" };

    function text(locale, key) {
      var c = config.copy || {};
      return (
        (c[locale] && c[locale][key]) ||
        (c.en && c.en[key]) ||
        (LABELS[locale] && LABELS[locale][key]) ||
        LABELS.en[key] ||
        key
      );
    }

    function applyDocumentChrome() {
      if (typeof document === "undefined") return;
      document.documentElement.setAttribute("data-theme", resolveTheme(state.themePreference));
      document.documentElement.lang = state.locale;
    }

    function navCard(locale, destination) {
      var props = {
        class: "nav-card",
        href: destination.href,
        "data-testid": "nav-" + destination.id,
      };
      // External links open in a new tab with safe rel; in-site routes stay in
      // the same tab so theme/locale (in localStorage) carry over seamlessly.
      if (destination.external) {
        props.target = "_blank";
        props.rel = "noopener noreferrer";
      }
      return h(
        "a",
        props,
        h("span", { class: "nav-card-icon", "aria-hidden": "true", text: destination.icon }),
        h("span", { class: "nav-card-title", text: text(locale, destination.titleKey) }),
        h("span", { class: "nav-card-desc", text: text(locale, destination.descKey) }),
        h("span", { class: "nav-card-action", text: text(locale, destination.actionKey) }),
      );
    }

    function render() {
      var root = document.getElementById(config.rootId);
      if (!root) return;
      var locale = state.locale;
      root.textContent = "";

      var topbar = h(
        "header",
        { class: config.topbarClass || "landing-topbar" },
        h(
          "a",
          { class: "brand", href: config.brandHref || "./", "data-testid": "brand-home" },
          h("span", { class: "brand-mark", "aria-hidden": "true", text: "" }),
          h("span", { text: "formal-ai" }),
        ),
        h(
          "div",
          { class: "topbar-controls" },
          segmentedControl(
            SUPPORTED_LOCALES.map(function (value) {
              return { value: value, label: value.toUpperCase() };
            }),
            locale,
            function (value) {
              state.locale = value;
              writePreference("uiLanguage", value);
              applyDocumentChrome();
              render();
            },
            text(locale, "language"),
            "locale-switch",
          ),
          segmentedControl(
            [
              { value: "auto", label: text(locale, "themeAuto") },
              { value: "light", label: text(locale, "themeLight") },
              { value: "dark", label: text(locale, "themeDark") },
            ],
            state.themePreference,
            function (value) {
              state.themePreference = value;
              writePreference("theme", value);
              applyDocumentChrome();
              render();
            },
            text(locale, "theme"),
            "theme-switch",
          ),
        ),
      );

      // The source-code entry point is a big, prominent call-to-action button in
      // the hero (issue #479: the maintainer asked that "the source code on the
      // landing is a big button", not a small footer link). It reuses the exact
      // <span>(action) + <strong>(label) shape of the /download page's
      // .primary-download button, mirroring how vk-bot-desktop surfaces its
      // primary action, and opens the repository in a new tab.
      var sourceCta = config.repoUrl
        ? h(
            "a",
            {
              class: "source-cta",
              href: config.repoUrl,
              target: "_blank",
              rel: "noopener noreferrer",
              "data-testid": "source-cta",
            },
            h("span", { class: "source-cta-icon", "aria-hidden": "true", text: "</>" }),
            h(
              "span",
              { class: "source-cta-text" },
              h("span", { class: "source-cta-eyebrow", text: text(locale, "sourceEyebrow") }),
              h("strong", { class: "source-cta-label", text: text(locale, "footerSource") }),
            ),
          )
        : null;

      var hero = h(
        "section",
        { class: "hero" },
        h("p", { class: "eyebrow", text: text(locale, "eyebrow") }),
        h("h1", { text: text(locale, "heading") }),
        h("p", {
          class: "summary",
          "data-testid": config.rootId + "-summary",
          text: text(locale, "summary"),
        }),
        sourceCta,
      );

      var cards = h(
        "section",
        { class: "nav-cards", "data-testid": "nav-cards" },
        (config.destinations || []).map(function (destination) {
          return navCard(locale, destination);
        }),
      );

      // The footer no longer carries a small "Source on GitHub" text link — the
      // source code is surfaced as the big .source-cta button in the hero above
      // (issue #479). The footer keeps only the stamped version label.
      var version = readVersion();
      var footer = h(
        "footer",
        { class: "landing-footer" },
        version
          ? h("span", {
              class: "landing-version",
              "data-testid": "landing-version",
              text: text(locale, "footerVersion") + " " + version,
            })
          : null,
      );

      root.appendChild(topbar);
      root.appendChild(hero);
      root.appendChild(cards);
      root.appendChild(footer);
    }

    function init() {
      var prefs = readPreferences();
      state.themePreference =
        prefs.theme === "dark" || prefs.theme === "light" ? prefs.theme : "auto";
      state.locale = resolveLocale(prefs.uiLanguage);

      applyDocumentChrome();
      render();

      // Follow OS theme changes while in "auto".
      if (typeof global.matchMedia === "function") {
        var media = global.matchMedia("(prefers-color-scheme: dark)");
        var onChange = function () {
          if (state.themePreference === "auto") {
            applyDocumentChrome();
            render();
          }
        };
        if (typeof media.addEventListener === "function") {
          media.addEventListener("change", onChange);
        } else if (typeof media.addListener === "function") {
          media.addListener(onChange);
        }
      }
    }

    var api = {
      config: config,
      state: state,
      text: text,
      render: render,
      init: init,
      applyDocumentChrome: applyDocumentChrome,
      resolveLocale: resolveLocale,
      resolveTheme: resolveTheme,
      SUPPORTED_LOCALES: SUPPORTED_LOCALES,
    };

    if (config.exposeAs) {
      global[config.exposeAs] = api;
    }

    if (typeof document !== "undefined") {
      if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", init);
      } else {
        init();
      }
    }

    return api;
  }

  global.FormalAiSiteChrome = {
    SUPPORTED_LOCALES: SUPPORTED_LOCALES,
    LABELS: LABELS,
    normalizeLocale: normalizeLocale,
    detectLocaleFromBrowser: detectLocaleFromBrowser,
    resolveLocale: resolveLocale,
    resolveTheme: resolveTheme,
    readPreferences: readPreferences,
    writePreference: writePreference,
    readVersion: readVersion,
    h: h,
    appendChild: appendChild,
    segmentedControl: segmentedControl,
    createChooser: createChooser,
  };
})(typeof window !== "undefined" ? window : globalThis);