Explorer

html-ui.tool-script

description
(en) The small JavaScript of the forms made by html-ui.tool-form: sends the named fields of the form as the arguments of the MCP tool data-tool to POST /api/<tool>, then goes to data-then ({name} is replaced by that argument) or shows the result
type
String
expression
"const setPath = (target, path, value) => {\n  const keys = path.split(\".\");\n  let node = target;\n  for (let i = 0; i < keys.length - 1; i++) {\n    node = node[keys[i]] ??= /^\\d+$/.test(keys[i + 1]) ? [] : {};\n  }\n  node[keys.at(-1)] = value;\n};\nconst getPath = (target, path) => path.split(\".\").reduce((node, key) => node?.[key], target);\nfor (const form of document.querySelectorAll(\"form[data-tool]:not([data-bound])\")) {\n  form.dataset.bound = \"1\";\n  form.addEventListener(\"submit\", async (e) => {\n    e.preventDefault();\n    if (form.dataset.confirm && !confirm(form.dataset.confirm)) return;\n    const out = form.querySelector(\".out\");\n    const button = form.querySelector(\"button\");\n    const show = (text, error) => {\n      out.textContent = text;\n      out.className = error ? \"out error\" : \"out\";\n    };\n    const args = {};\n    for (const el of form.elements) {\n      if (!el.name || (el.value === \"\" && !el.hasAttribute(\"data-keep-empty\"))) continue;\n      setPath(args, el.name, el.hasAttribute(\"data-json\") ? JSON.parse(el.value) : el.value);\n    }\n    button.disabled = true;\n    show(document.documentElement.dataset.busy);\n    try {\n      const response = await fetch(\"/api/\" + form.dataset.tool, {\n        method: \"POST\",\n        headers: { \"content-type\": \"application/json\" },\n        body: JSON.stringify(args),\n      });\n      const text = await response.text();\n      if (!response.ok) {\n        let message = text;\n        try {\n          message = JSON.parse(text).message ?? text;\n        } catch {}\n        throw new Error(message);\n      }\n      const then = form.dataset.then;\n      if (then) {\n        location.href = then.replace(/\\{([\\w.]+)\\}/g, (_, k) => encodeURIComponent(getPath(args, k) ?? \"\"));\n        return;\n      }\n      show(text);\n    } catch (err) {\n      show(String(err.message ?? err), true);\n    } finally {\n      button.disabled = false;\n    }\n  });\n}\n"
visibility
public
html-ui.tool-script (project html-ui, branch fly-deploy, snapshot 0Ue3_1jyxE9mDRrGURvDDqJnMSZOw0QEkXWqWUKOuZY)
id: tDX5h_jm83mg3_iAtOMb3rVpiaxXUce2L16fdliDSx8
content hash: 27LDJ7R7W27uT6uxphWzyvIlfATNQxIqeVP_353YhbM