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
@core.string-concat(
  left: @html-ui.cbor-script,
  right: "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 text = await definyCbor.api(\"/api/\" + form.dataset.tool, args);\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 main, snapshot Daaw3vbJhY15cDW6JsA4JuXvffjj_qFyxoZQMUM8hvQ)
id: tDX5h_jm83mg3_iAtOMb3rVpiaxXUce2L16fdliDSx8
content hash: gbv32Vb0PcX5ztCXw2ATYlp4JPH7braduu4976KfwEg