Files
function/templates/dashboard/http_functions/client.html
Peter Stockings 5ec8bba9e8 Refactor HTTP function editor with Mithril components and new API endpoints
- Add new Mithril components for editor (editor.js), response view (responseView.js), and alerts (alert.js)
- Create new API endpoints for creating, updating, and deleting HTTP functions
- Update templates to use new Mithril editor component
- Improve header navigation with more consistent styling and active state indicators
- Remove old edit form route and template
- Add new dedicated editor route and template

cursor.ai
2025-02-14 00:40:45 +11:00

248 lines
13 KiB
HTML

{% extends 'dashboard.html' %}
{% block page %}
{{ render_partial('dashboard/http_functions/header.html', user_id=user_id, function_id=function_id,
active_tab='client',
show_edit_form=True,
show_logs=True,
show_client=True,
show_history=True,
edit_url=url_for('http_function_editor', function_id=function_id),
cancel_url=url_for('dashboard_http_functions')) }}
<div class="mx-auto w-full pt-4" id="client-u{{ user_id }}-f{{ function_id }}">
</div>
<script>
function formatTime(milliseconds) {
if (milliseconds < 1000) {
return `${milliseconds.toFixed(2)} ms`; // Display milliseconds directly if less than 1 second
}
const seconds = milliseconds / 1000;
if (seconds < 60) {
return `${seconds.toFixed(2)} s`; // Display seconds if less than 1 minute
}
const minutes = seconds / 60;
if (minutes < 60) {
return `${minutes.toFixed(2)} min`; // Display minutes if less than 1 hour
}
const hours = minutes / 60;
return `${hours.toFixed(2)} h`; // Display hours for longer durations
}
function formatSize(bytes) {
if (bytes < 1024) {
return `${bytes} bytes`;
} else if (bytes < 1024 * 1024) {
return `${(bytes / 1024).toFixed(2)} KB`;
} else if (bytes < 1024 * 1024 * 1024) {
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
} else {
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
}
}
var KeyValueList = (initialVnode) => {
return {
view: (vnode) => {
return m("div.px-4.py-4.rounded-b-lg.border.border-t-0.border-gray-300", [
m("div", [
m("div.flex-col.space-y-2.mb-3", vnode.attrs.list.map(({ key, value }, index) => m('div.flex', [
m("input.px-4.py-1.5.w-full.border.border-gray-300.rounded-md.hover:border-orange-500.focus:outline-orange-500", {
placeholder: "Key",
value: key,
oninput: (e) => vnode.attrs.list[index].key = e.target.value
}),
m("input.ml-3.px-4.py-1.5.w-full.border.border-gray-300.rounded-md.hover:border-orange-500.focus:outline-orange-500", {
placeholder: "Value",
value: value,
oninput: (e) => vnode.attrs.list[index].value = e.target.value
}),
m("button.ml-4.px-4.rounded-md.text-red-500.border.border-red-300.hover:bg-red-100", {
onclick: () => vnode.attrs.list.splice(index, 1)
}, "Remove")
]))),
m("button.px-6.py-1.rounded-md.text-orange-600.border.border-orange-400.hover:bg-orange-100", {
onclick: () => vnode.attrs.list.push({ key: '', value: '' })
}, "Add")
])
])
}
}
}
var TabContent = (activeTab, queryParams, hearders, body) => {
var tabMappings = {
'Query Params': m(KeyValueList, { list: this.queryParams }),
'Headers': m(KeyValueList, { list: this.headers }),
'Body': m("textarea", {
oninput: (e) => this.body = e.target.value,
value: this.body,
rows: 4,
class: "block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300"
})
}
return tabMappings[this.activeTab];
}
var RequestClient = {
// Initialize component state
init: function () {
this.isLoading = false;
this.method = 'GET';
this.url = "{{ url_for('execute_http_function', user_id=user_id, function=name) }}";
this.body = '{}';
this.response = '';
this.duration = 0;
this.status = 0;
this.responseHeaders = [];
this.responseSize = 0;
this.activeTab = 'Query Params';
this.activeResponseTab = 'Browser Preview'
this.headers = [{ key: 'Content-Type', value: 'application/json' }, { key: '', value: '' }];
this.queryParams = [{ key: '', value: '' }];
},
sendRequest: function () {
this.isLoading = true;
let startTime = performance.now();
let url = this.url;
const query = this.queryParams.filter(p => p.key && p.value)
.map(p => `${encodeURIComponent(p.key)}=${encodeURIComponent(p.value)}`)
.join('&');
if (query) {
url += '?' + query;
}
const headers = this.headers.reduce((acc, { key, value }) => {
if (key && value) acc[key] = value;
return acc;
}, {});
fetch(url, {
method: this.method,
body: !['GET', 'HEAD'].includes(this.method) ? this.body : undefined,
headers
})
.then(response => {
this.isLoading = false;
let endTime = performance.now();
this.duration = endTime - startTime;
this.status = response.status;
this.responseHeaders = [...response.headers].map(([key, value]) => ({ key, value }));
return response.text().then(text => {
this.response = text;
return text;
});
})
.then(text => {
this.responseSize = new Blob([text]).size; // This approach will give the size of the response body
this.response = text;
m.redraw();
});
},
view: function () {
return m("div.mx-auto.w-full.pt-4", [
m("form.flex", [
m("select.px-4.py-2.border.rounded-md.border-gray-300.hover:border-orange-500.focus:outline-none.bg-gray-100", {
onchange: (e) => this.method = e.target.value,
value: this.method
}, ["GET", "POST", "PUT", "PATCH", "DELETE"].map(method =>
m("option", { value: method }, method)
)),
m("input.ml-3.w-full.px-4.py-2.border.rounded-md.border-gray-300.hover:border-orange-500.focus:outline-orange-500", {
onchange: (e) => this.url = e.target.value,
value: this.url,
placeholder: "URL"
}),
m("button.ml-3.px-6.py-2.rounded-md.font-semibold.text-white.bg-orange-500.hover:bg-orange-600", {
type: "button",
onclick: () => this.sendRequest(),
disabled: this.isLoading
}, this.isLoading
? m("svg", { class: "animate-spin h-5 w-5 text-white", viewBox: "0 0 24 24" },
m("circle", { class: "opacity-25", cx: "12", cy: "12", r: "10", stroke: "currentColor", "stroke-width": "4", fill: "none" }),
m("path", { class: "opacity-75", fill: "currentColor", d: "M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" })
)
: "Send")
]),
// Tabs for query params, headers, and body
m("div", [
// Tab headers
m("ul.flex.mt-5.border.border-gray-300.rounded-t-lg", [
[
{ name: "Query Params", count: this.queryParams.filter(p => p.key && p.value).length },
{ name: "Headers", count: this.headers.filter(p => p.key && p.value).length },
{ name: "Body", count: null }
].map(({ name, count }, index) =>
m("li.mr-3.py-2.px-4.border-orange-400.focus:outline-none.hover:text-orange-500.cursor-pointer", {
class: this.activeTab === name ? "border-b-2 text-orange-600" : "",
onclick: () => this.activeTab = name
}, `${name}${count ? ` (${count})` : ``}`))
]),
// Tab content
this.activeTab === 'Query Params' ? m(KeyValueList, { list: this.queryParams }) : '',
this.activeTab === 'Headers' ? m(KeyValueList, { list: this.headers }) : '',
this.activeTab === 'Body' ? m("textarea", {
oninput: (e) => this.body = e.target.value,
value: this.body,
rows: 4,
class: "block p-2.5 w-full text-sm text-gray-900 bg-gray-50 rounded-lg border border-gray-300"
}) : ''
]),
this.response ? m("div.my-4.p-4.shadow.rounded-lg", [
m("div.flex.items-center.mb-4.justify-between", [
m("ul.flex.border.border-gray-300.rounded-t-lg", [{ name: 'Browser Preview', count: null }, { name: 'Headers', count: this.responseHeaders.length }, { name: 'Body', count: null }].map(({ name, count }) =>
m("li.mr-3.py-2.px-4.border-orange-400.focus:outline-none.hover:text-orange-500.cursor-pointer", {
class: this.activeResponseTab === name ? "border-b-2 text-orange-600" : "",
onclick: () => this.activeResponseTab = name
}, `${name}${count ? ` (${count})` : ``}`))),
m("svg", { class: "h-6 w-6 cursor-pointer", viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", onclick: () => this.response = '' },
m("path", { "stroke-linecap": "round", "stroke-linejoin": "round", "stroke-width": "2", d: "M6 18L18 6M6 6l12 12" })
)
]),
this.activeResponseTab == 'Headers' ? m("div.relative.overflow-x-auto.shadow-md.sm:rounded-lg", [
m("table.w-full.text-sm.text-left.rtl:text-right.text-gray-500.dark:text-gray-400", [
m("thead.text-xs.text-gray-700.uppercase.bg-gray-50.dark:bg-gray-700.dark:text-gray-400", [
m("tr", [
m("th.px-6.py-3", "Key"),
m("th.px-6.py-3", "Value")
])
]),
m("tbody",
this.responseHeaders.map(({ key, value }) =>
m("tr.bg-white.dark:bg-gray-900.border-b.dark:border-gray-700", [
m("th.scope.row.px-6.py-4.font-medium.text-gray-900.dark:text-white", key),
m("td.px-6.py-4", value)
])
)
)
])
]) : null,
this.activeResponseTab == 'Body' ? m("div.overflow-auto.max-h-64.bg-gray-100.p-2.rounded-lg", [
m("pre.text-sm", this.response)
]) : null,
this.activeResponseTab == 'Browser Preview' ? m("div.p-2.rounded-lg", m.trust(this.response)) : null,
m("div.flex", [
m("div.grow", ""),
m("div.flex.space-x-2.pt-1", [{ key: 'Status', value: this.status }, { key: 'Time', value: formatTime(this.duration) }, { key: 'Size', value: formatSize(this.responseSize) }].map(({ key, value }) =>
m("div.flex.items-center.justify-between", [
m("span.text-gray-600", `${key}:`),
m("span.font-semibold.pl-1.text-green-400", value)
])))
])
]) : null
]);
}
};
RequestClient.init();
m.mount(document.getElementById('client-u{{ user_id }}-f{{ function_id }}'), RequestClient);
</script>
{% endblock %}