Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 53 additions & 11 deletions public/js/modules/AfTableQuestion.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,20 +34,18 @@ export class AfTableQuestion {

#table;
#body;
#template;
#addBtn;
#minRows;
#maxRows;

constructor(tableElement) {
this.#table = tableElement;
this.#body = tableElement.querySelector('[data-af-table-body]');
this.#template = tableElement.querySelector('[data-af-table-row-template]');
this.#addBtn = tableElement.querySelector('[data-af-table-add-row]');
this.#minRows = parseInt(tableElement.dataset.afMinRows, 10) || 1;
this.#maxRows = parseInt(tableElement.dataset.afMaxRows, 10) || 50;

if (!this.#body || !this.#template || !this.#addBtn) {
if (!this.#body || !this.#addBtn) {
return;
}

Expand Down Expand Up @@ -232,18 +230,62 @@ export class AfTableQuestion {
control.closest('td')?.querySelector('[data-af-cell-error]')?.remove();
}

addRow() {
async addRow() {
const rowCount = this.#rowCount();
if (rowCount >= this.#maxRows) {
if (rowCount >= this.#maxRows || this.#addBtn.getAttribute('aria-busy') === 'true') {
return;
}
const clone = this.#template.content.cloneNode(true);
clone.querySelectorAll('[name]').forEach(el => {
el.name = el.name.replace('__ROW__', rowCount);

const questionId = parseInt(this.#table.dataset.afQuestionId, 10) || 0;
if (questionId <= 0) {
return;
}

this.#addBtn.setAttribute('aria-busy', 'true');
this.#addBtn.classList.add('opacity-25', 'pe-none');

try {
const url = new URL(`${CFG_GLPI.root_doc}/plugins/advancedforms/TableQuestionRow`, window.location.origin);
url.searchParams.set('questions_id', String(questionId));
url.searchParams.set('row_index', String(rowCount));
url.searchParams.set('render_identity', `dynamic-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);

const response = await fetch(url, { credentials: 'same-origin' });
if (!response.ok) {
return;
}

const html = await response.text();
if (html.trim() === '') {
return;
}

this.#appendServerRenderedRow(html);
this.#initSelectsInRow(this.#body.lastElementChild);
} finally {
this.#addBtn.removeAttribute('aria-busy');
this.#updateButtonStates();
}
}

#appendServerRenderedRow(html) {
if (window.$) {
const nodes = window.$.parseHTML(html, document, true);
window.$(this.#body).append(nodes);
return;
}

const template = document.createElement('template');
template.innerHTML = html;
template.content.querySelectorAll('script').forEach(oldScript => {
const script = document.createElement('script');
Array.from(oldScript.attributes).forEach(attribute => {
script.setAttribute(attribute.name, attribute.value);
});
script.textContent = oldScript.textContent;
oldScript.replaceWith(script);
});
this.#body.appendChild(clone);
this.#initSelectsInRow(this.#body.lastElementChild);
this.#updateButtonStates();
this.#body.appendChild(template.content);
}

#initSelectsInRow(row) {
Expand Down
180 changes: 180 additions & 0 deletions public/js/modules/AfTableQuestionConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ export class AfTableQuestionConfig {
container.querySelectorAll('[data-af-table-column]').forEach(row => {
AfTableQuestionConfig.#bindItemtypeVisibility(row);
AfTableQuestionConfig.#bindPatternVisibility(row);
AfTableQuestionConfig.#bindEmbeddedQuestionConfig(row);
});

if (addBtn && template) {
Expand All @@ -84,6 +85,7 @@ export class AfTableQuestionConfig {
AfTableQuestionConfig.#initNewColumnSelect(newSelect, container.dataset.afTableColumnsContainer);
AfTableQuestionConfig.#bindItemtypeVisibility(newRow);
AfTableQuestionConfig.#bindPatternVisibility(newRow);
AfTableQuestionConfig.#bindEmbeddedQuestionConfig(newRow, true);
}

static #initNewColumnSelect(select, rand) {
Expand Down Expand Up @@ -166,6 +168,184 @@ export class AfTableQuestionConfig {
update();
}

static #bindEmbeddedQuestionConfig(columnRow, loadImmediately = false) {
const typeSelect = columnRow.querySelector('select[name*="[question_type]"]');
const target = columnRow.querySelector('[data-af-column-question-config-container]');
if (!typeSelect || !target) { return; }

const setLayoutState = () => {
const hasConfig = target.querySelector('[name]') !== null;
target.classList.toggle('d-none', !hasConfig);
columnRow.classList.toggle('af-has-embedded-config', hasConfig);
};

const cancelPendingRequest = () => {
target.dataset.afEmbeddedRequestId = String(
Number(target.dataset.afEmbeddedRequestId || 0) + 1,
);
};

const clearConfig = () => {
cancelPendingRequest();
target.replaceChildren();
target.classList.add('d-none');
columnRow.classList.remove('af-has-embedded-config');
};

const reload = async ({ keepBlock = false } = {}) => {
const container = columnRow.closest('[data-af-table-columns-container]');
const rows = Array.from(container?.querySelectorAll('[data-af-table-column]') ?? []);
const columnIndex = Math.max(0, rows.indexOf(columnRow));
const requestId = String(Number(target.dataset.afEmbeddedRequestId || 0) + 1);
target.dataset.afEmbeddedRequestId = requestId;

const payload = new FormData();
payload.append('type', typeSelect.value);
payload.append('column_index', String(columnIndex));

if (keepBlock) {
const block = target.querySelector('[name$="[block_id]"]');
if (block) {
payload.append('question_extra_data[block_id]', block.value);
}
}

target.setAttribute('aria-busy', 'true');
try {
let html;

if (window.$?.ajax) {
// GLPI configures jQuery globally to add the current CSRF
// token to POST requests. Native fetch does not receive that
// configuration and is rejected by the firewall with 403.
html = await window.$.ajax({
url: `${CFG_GLPI.root_doc}/plugins/advancedforms/TableColumnQuestionConfig`,
method: 'POST',
data: payload,
processData: false,
contentType: false,
dataType: 'html',
});
} else {
const response = await fetch(
`${CFG_GLPI.root_doc}/plugins/advancedforms/TableColumnQuestionConfig`,
{
method: 'POST',
body: payload,
credentials: 'same-origin',
},
);

if (!response.ok) {
clearConfig();
return;
}

html = await response.text();
}

if (target.dataset.afEmbeddedRequestId !== requestId) { return; }

target.innerHTML = html;
setLayoutState();
AfTableQuestionConfig.#bindEmbeddedQuestionConfig(columnRow);
} catch {
clearConfig();
} finally {
if (target.dataset.afEmbeddedRequestId === requestId) {
target.removeAttribute('aria-busy');
}
}
};

const triggerAutosave = control => {
if (!control) { return; }
control.dataset.afEmbeddedCommit = '1';
if (window.$) {
window.$(control).trigger('change');
} else {
control.dispatchEvent(new Event('change', { bubbles: true }));
}
};

const onTypeChange = async event => {
if (typeSelect.dataset.afEmbeddedCommit === '1') {
delete typeSelect.dataset.afEmbeddedCommit;
return;
}

const container = columnRow.closest('[data-af-table-columns-container]');
const columnIndex = Array.from(
container?.querySelectorAll('[data-af-table-column]') ?? [],
).indexOf(columnRow);

event.preventDefault();
event.stopImmediatePropagation();
clearConfig();
await reload();

// GLPI may replace the complete question editor during autosave.
// Start observing before triggering autosave so the replacement
// cannot happen between those two operations.
const questionEditor = columnRow.closest(
'[data-glpi-form-editor-question]',
) ?? container;

if (!questionEditor) {
triggerAutosave(typeSelect);
return;
}

const selectedType = typeSelect.value;
const observer = new MutationObserver(() => {
const currentContainer = questionEditor.querySelector(
'[data-af-table-columns-container]',
);
const currentRows = Array.from(
currentContainer?.querySelectorAll('[data-af-table-column]') ?? [],
);
const currentRow = currentRows[columnIndex];
if (!currentRow || currentRow === columnRow) {
return;
}

const currentType = currentRow.querySelector(
'select[name*="[question_type]"]',
);
if (!currentType || currentType.value !== selectedType) {
return;
}

observer.disconnect();
AfTableQuestionConfig.#bindEmbeddedQuestionConfig(currentRow, true);
});

observer.observe(questionEditor, {
childList: true,
subtree: true,
});

triggerAutosave(typeSelect);

// Avoid leaving an observer alive if autosave fails or is cancelled.
window.setTimeout(() => observer.disconnect(), 10000);
};

const $type = window.$ ? window.$(typeSelect) : null;
if ($type) {
$type.off('.afEmbeddedType');
$type.on('change.afEmbeddedType', onTypeChange);
} else if (!typeSelect.dataset.afEmbeddedNativeBound) {
typeSelect.dataset.afEmbeddedNativeBound = '1';
typeSelect.addEventListener('change', onTypeChange, { capture: true });
}

setLayoutState();
if (loadImmediately && typeSelect.value && !target.querySelector('[name]')) {
void reload();
}
}

static #initItemtypeSelect(select, rand) {
if (!select || !window.setupAdaptDropdown) { return; }
if (!select.id) {
Expand Down
54 changes: 54 additions & 0 deletions src/Controller/TableColumnQuestionConfigController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

/**
* -------------------------------------------------------------------------
* advancedforms plugin for GLPI
* -------------------------------------------------------------------------
*
* MIT License
* -------------------------------------------------------------------------
* @copyright Copyright (C) 2025 by the advancedforms plugin team.
* @license MIT https://opensource.org/licenses/mit-license.php
* @link https://github.com/pluginsGLPI/advancedforms
* -------------------------------------------------------------------------
*/

namespace GlpiPlugin\Advancedforms\Controller;

use Glpi\Controller\AbstractController;
use Glpi\Http\Firewall;
use Glpi\Security\Attribute\SecurityStrategy;
use GlpiPlugin\Advancedforms\Model\QuestionType\TableQuestion;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

final class TableColumnQuestionConfigController extends AbstractController
{
#[SecurityStrategy(Firewall::STRATEGY_AUTHENTICATED)]
#[Route(
path: 'TableColumnQuestionConfig',
name: 'table_column_question_config',
methods: ['POST'],
)]
public function __invoke(Request $request): Response
{
$type = (string) $request->request->get('type', '');
$column_index = $request->request->getInt('column_index', 0);
$payload = $request->request->all();
$extra_data = $payload['question_extra_data'] ?? [];

$renderer = new TableQuestion();
$html = $renderer->renderEmbeddedQuestionConfiguration(
$type,
max(0, $column_index),
is_array($extra_data) ? $extra_data : [],
);

return new Response(
$html,
Response::HTTP_OK,
['Content-Type' => 'text/html; charset=UTF-8'],
);
}
}
Loading