repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/web/components/dialogs.js.ts

Raw
File outline
export type DialogResponse =
	| { type: "ui_response"; id: string; value: string }
	| { type: "ui_response"; id: string; confirmed: boolean }
	| { type: "ui_response"; id: string; cancelled: true };

export function dialogResponse(
	id: string,
	method: string,
	value: string | boolean | undefined,
): DialogResponse {
	if (value === undefined) return { type: "ui_response", id, cancelled: true };
	if (method === "confirm")
		return { type: "ui_response", id, confirmed: Boolean(value) };
	return { type: "ui_response", id, value: String(value) };
}

export function renderDialogsComponentJs(): string {
	return `function dialogResponse(id, method, value) {
	if (value === undefined) return { type: 'ui_response', id, cancelled: true };
	if (method === 'confirm') return { type: 'ui_response', id, confirmed: Boolean(value) };
	return { type: 'ui_response', id, value: String(value) };
}
function renderUiRequest(row, event) {
	const controls = document.createElement('div');
	controls.className = 'ui-dialog-controls';
	if (event.method === 'select') {
		for (const option of event.options || []) {
			const button = document.createElement('button');
			button.type = 'button';
			button.textContent = option;
			button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, option))));
			controls.append(button);
		}
	} else if (event.method === 'confirm') {
		for (const item of [['YES', true], ['NO', false]]) {
			const button = document.createElement('button');
			button.type = 'button';
			button.textContent = item[0];
			button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, item[1]))));
			controls.append(button);
		}
	} else {
		const field = document.createElement('textarea');
		field.value = event.prefill || '';
		field.placeholder = event.placeholder || '';
		const button = document.createElement('button');
		button.type = 'button';
		button.textContent = 'SEND';
		button.addEventListener('click', () => socket?.send(JSON.stringify(dialogResponse(event.requestId, event.method, field.value))));
		controls.append(field, button);
	}
	row.append(controls);
}
`;
}