#| '!! shinylive warning !!': |
#| shinylive does not work in self-contained HTML documents.
#| Please set `embed-resources: false` in your metadata.
#| standalone: true
#| viewerHeight: 400
#| viewerWidth: "100%"
suppressPackageStartupMessages(library(shiny))
suppressPackageStartupMessages(library(bslib))
# ── Colonne escluse di default ────────────────────────────────────────────────
DEFAULT_DROP <- c("longitude", "latitude", "altitude", "qual_sat", "etal")
COL_RENAME <- c(
"jj/mm/aaaa" = "date",
"hh:mm:ss" = "time",
"groupe" = "group",
"mesure" = "measure"
)
PARAM_COLS <- c("Chl", "Flav", "Anth", "NBI")
# Colonne descrittive: mai trattate come parametri (né nel formato long né nel grafico)
META_COLS <- c("date", "time", "temp", "group", "treatment", "measure", "face",
"longitude", "latitude", "altitude", "qual_sat", "etal")
APP_VERSION <- "v.1.2"
# ── Dati di esempio sintetici, non misure reali ──────────────────────────────
# Stesso contenuto di tests/data/example_dualex.csv (verificato dai test).
EXAMPLE_DUALEX <- c(
"#Model.......:Dx4.5",
"#SN..........:00_000",
"#version.....:Sci. Flav/Anth",
"#software....:3.0.0",
"#jj/mm/aaaa;hh:mm:ss;longitude;latitude;altitude;qual_sat;temp;groupe;mesure;face;Chl;Flav;Anth;NBI;Etal",
"16/07/2026;09:58:05;;;;;28.07;1;1;sup;34.592;1.443;0.151;23.97;NEW",
"16/07/2026;09:58:11;;;;;28.04;1;2;sup;31.213;1.284;0.195;24.31;",
"16/07/2026;09:58:16;;;;;28.01;1;3;sup;34.665;1.122;0.155;30.90;",
"16/07/2026;09:58:23;;;;;27.98;1;4;sup;36.860;1.092;0.142;NaN;",
"16/07/2026;09:58:32;;;;;27.95;1;5;sup;32.935;1.432;0.164;22.99;",
"16/07/2026;09:58:38;;;;;27.92;1;6;sup;22.679;1.498;0.141;15.14;",
"#Groupe;Chl;Chl_sd;Flav;Flav_sd;Anth;Anth_sd;NBI;NBI_sd",
"1;32.157;5.013;1.312;0.174;0.158;0.020;25.179;6.546",
"",
"#jj/mm/aaaa;hh:mm:ss;longitude;latitude;altitude;qual_sat;temp;groupe;mesure;face;Chl;Flav;Anth;NBI;Etal",
"16/07/2026;09:58:48;;;;;27.89;2;1;sup;41.807;1.458;0.161;28.66;",
"16/07/2026;09:58:57;;;;;27.86;2;2;sup;34.709;1.161;0.097;29.88;",
"16/07/2026;09:59:04;;;;;27.83;2;3;sup;33.152;NaN;0.213;27.50;",
"16/07/2026;09:59:14;;;;;27.80;2;4;sup;39.105;1.109;0.165;35.27;",
"16/07/2026;09:59:20;;;;;27.77;2;5;sup;32.765;1.192;0.167;27.48;",
"16/07/2026;09:59:25;;;;;27.74;2;6;sup;36.108;1.231;0.139;29.33;",
"#Groupe;Chl;Chl_sd;Flav;Flav_sd;Anth;Anth_sd;NBI;NBI_sd",
"2;36.274;3.554;1.226;0.121;0.157;0.038;29.690;2.900",
"",
"#jj/mm/aaaa;hh:mm:ss;longitude;latitude;altitude;qual_sat;temp;groupe;mesure;face;Chl;Flav;Anth;NBI;Etal",
"16/07/2026;09:59:34;;;;;27.71;3;1;sup;42.481;0.899;0.135;47.26;",
"16/07/2026;09:59:46;;;;;27.68;3;2;sup;39.566;1.317;nan;30.05;",
"16/07/2026;09:59:56;;;;;27.65;3;3;sup;42.910;0.983;0.142;43.66;",
"16/07/2026;10:00:06;;;;;27.62;3;4;sup;43.929;1.113;0.158;39.45;",
"16/07/2026;10:00:14;;;;;27.59;3;5;sup;41.644;1.114;0.139;NaN;",
"16/07/2026;10:00:24;;;;;27.56;3;6;sup;40.898;1.128;0.167;36.26;",
"#Groupe;Chl;Chl_sd;Flav;Flav_sd;Anth;Anth_sd;NBI;NBI_sd",
"3;41.905;1.549;1.092;0.143;0.146;0.013;39.012;6.006",
"",
"#jj/mm/aaaa;hh:mm:ss;longitude;latitude;altitude;qual_sat;temp;groupe;mesure;face;Chl;Flav;Anth;NBI;Etal",
"16/07/2026;10:00:29;;;;;27.53;4;1;sup;31.344;1.089;0.158;28.77;",
"16/07/2026;10:00:34;;;;;27.50;4;2;sup;29.116;1.138;0.172;25.58;",
"16/07/2026;10:00:39;;;;;27.47;4;3;sup;21.790;1.116;0.177;19.53;",
"16/07/2026;10:00:45;;;;;27.44;4;4;sup;24.372;1.087;0.173;22.42;",
"16/07/2026;10:00:50;;;;;27.41;4;5;sup;28.275;0.716;0.164;39.50;",
"16/07/2026;10:01:00;;;;;27.38;4;6;sup;26.774;1.013;0.146;26.42;",
"#Groupe;Chl;Chl_sd;Flav;Flav_sd;Anth;Anth_sd;NBI;NBI_sd",
"4;26.945;3.437;1.027;0.158;0.165;0.011;27.038;6.905",
"",
"#jj/mm/aaaa;hh:mm:ss;longitude;latitude;altitude;qual_sat;temp;groupe;mesure;face;Chl;Flav;Anth;NBI;Etal"
)
# ── Valori mancanti e numeri ──────────────────────────────────────────────────
# Il Dualex scrive "NaN"/"nan" quando una misura non è valida: un singolo valore
# di questo tipo non deve far scartare l'intera colonna dai parametri.
MISSING_TOKENS <- c("", "nan", "na", "n/a", "null", "-", "--", "---", "inf", "-inf")
NUM_RE <- "^[+-]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][+-]?[0-9]+)?$"
DATE_LIKE_RE <- "^[0-9]{1,4}[/.-][0-9]{1,2}[/.-][0-9]{1,4}$"
is_missing_val <- function(x) {
x <- trimws(as.character(x))
is.na(x) | tolower(x) %in% MISSING_TOKENS
}
# TRUE se tutti i valori non mancanti sono numeri con punto decimale
is_numeric_col <- function(x, require_value = FALSE) {
v <- trimws(as.character(x))
v <- v[!is_missing_val(v)]
if (!length(v)) return(!require_value)
all(grepl(NUM_RE, v))
}
# Conversione numerica sicura: i valori mancanti o non numerici diventano NA
to_num <- function(x) {
v <- trimws(as.character(x))
out <- rep(NA_real_, length(v))
ok <- !is_missing_val(v) & grepl(NUM_RE, v)
out[ok] <- as.numeric(v[ok])
out
}
# Ordine "naturale" (T2 prima di T10; 3 prima di 10), indipendente dalla lingua del sistema
natural_sort <- function(x) {
x <- unique(as.character(x)); x <- x[!is.na(x)]
key <- vapply(x, function(s) {
parts <- regmatches(s, gregexpr("[0-9]+|[^0-9]+", s))[[1]]
paste(ifelse(grepl("^[0-9]+$", parts),
sprintf("%015.0f", suppressWarnings(as.numeric(parts))),
tolower(parts)), collapse = "|")
}, character(1))
x[order(key, x, method = "radix")]
}
# Testo dell'errore: se è una chiave del dizionario viene tradotta
err_text <- function(tx, msg) {
v <- tx[[msg]]
if (is.character(v) && length(v) == 1) v else msg
}
warn_box <- function(...) {
div(style = "margin-top:.8rem; padding:.7rem 1rem; background:#FEF3C7; border:1px solid #FCD34D; border-radius:6px; font-size:.88rem; color:#92400E;", ...)
}
# ── Dizionario UI bilingue ────────────────────────────────────────────────────
TR <- list(
it = list(
app_subtitle = "Pulizia e visualizzazione dati da",
app_descr = "Sensore ottico portatile per la misura non distruttiva di Chl, Flav, Anth e NBI su foglie intatte — Metos Global.",
privacy_title = "Sicurezza dei Dati & Privacy al 100%",
privacy_body = "Questa applicazione viene eseguita interamente all'interno del tuo browser tramite tecnologia WebAssembly. I tuoi dati non lasciano mai il tuo computer e nessun file viene inviato a server esterni. È utilizzabile anche offline. Nota: il primo avvio potrebbe essere necessario qualche secondo per il caricamento dell'ambiente R.",
status_waiting = "In attesa",
status_loaded = "✓ File caricato",
status_clean = "✓ File pulito",
status_trt = "✓ Trattamenti aggiunti",
status_final = "✓ File finale pronto",
status_error = "✗ Errore",
step1 = "1 — Carica il file",
file_placeholder= "Seleziona il file esportato dal Dualex (.txt o .csv)…",
file_btn = "Sfoglia",
file_info = function(nr, nc) paste0(nr, " misure · ", nc, " colonne rilevate"),
step2 = "2 — Seleziona le colonne da mantenere",
sel_all = "Seleziona tutte",
desel_all = "Deseleziona tutte",
col_meta = "colonne selezionate",
of_word = "di",
step3 = "3 — Genera il file pulito",
btn_clean = "Pulisci",
btn_dl_clean = "Scarica CSV pulito",
summary = "Riepilogo",
renamed_lbl = "Colonne rinominate automaticamente:",
stat_measures = "misure",
stat_cols = "colonne",
stat_groups = "gruppi",
stat_file = "nome file",
preview8 = "Anteprima dati",
step4 = "4 — Assegna i trattamenti ai gruppi",
trt_hint = "Inserisci il nome del trattamento per ciascun gruppo. Se lasciato vuoto, viene usato il numero del gruppo.",
trt_placeholder = "Trattamento per gruppo ",
btn_trt = "Aggiungi trattamento",
trt_preview = "Anteprima con trattamenti",
btn_dl_trt = "Scarica CSV con trattamenti",
step5 = "5 — Formato finale e download",
pivot_label = "Trasponi parametri in formato long",
pivot_sub = "Le colonne dei parametri verranno unite in una colonna 'parameter' con i valori in 'value'",
btn_final = "Genera file finale",
btn_dl_final = "Scarica CSV finale",
stat_rows = "righe",
stat_format = "formato",
final_preview = "Anteprima file finale",
step6 = "6 — Grafico esplorativo",
chart_param_lbl = "Seleziona i parametri da visualizzare:",
chart_hint = "Media ± errore standard (SE) per ciascun trattamento. Solo a scopo di controllo qualità rapido — non sostituisce l'analisi statistica.",
btn_chart = "Genera grafico",
btn_dl_png = "Scarica PNG",
chart_no_params = "Nessun parametro numerico disponibile nel file finale.",
chart_ylab = "Valore medio",
jitter_label = "Mostra punti individuali (jitter)",
jitter_sub = "Visualizza ogni singola misura come puntino, utile per individuare outlier o valutare la distribuzione",
step7 = "7 — Unisci con un file precedente (opzionale)",
merge_hint = "Carica un CSV precedentemente esportato da CleanEX nello stesso formato (wide o long). Le colonne devono corrispondere esattamente. I dati verranno ordinati cronologicamente per data e ora.",
merge_file_ph = "Seleziona un CSV CleanEX precedente…",
merge_file_btn = "Sfoglia",
btn_merge = "Unisci i file",
btn_dl_merge = "Scarica CSV combinato",
merge_ok = function(n1, n2) paste0("✓ Unione completata: ", n1, " + ", n2, " righe = ", n1+n2, " righe totali"),
merge_err_cols = "Errore: le colonne del file caricato non corrispondono al file corrente. Verifica che entrambi i file siano nello stesso formato (wide o long) e abbiano gli stessi parametri.",
merge_err_read = "Errore: impossibile leggere il file. Verifica che sia un CSV esportato da CleanEX (separatore virgola, prima riga con i nomi delle colonne).",
merge_preview_curr = "Anteprima file corrente (prime 5 righe):",
merge_preview_prev = "Anteprima file precedente (prime 5 righe):",
example_btn = "Prova con dati di esempio",
example_note = "Dati di esempio sintetici, non misure reali.",
err_not_dualex = "Il file non sembra un'esportazione Dualex: l'intestazione delle colonne (riga 5) non è stata trovata.",
err_no_data = "Il file non contiene righe di misura.",
err_no_cols = "Nessuna colonna selezionata: seleziona almeno una colonna al passo 2.",
warn_no_group = "La colonna dei gruppi (groupe) non è inclusa: non è possibile assegnare i trattamenti. Selezionala di nuovo al passo 2 e ripeti la pulizia.",
warn_decimal = "Rilevata la virgola decimale nei valori: CleanEX si aspetta il punto decimale, quindi i parametri non verranno riconosciuti. Esporta di nuovo il file dal Dualex o sostituisci la virgola con il punto.",
merge_warn_dup = function(n) paste0("Attenzione: ", n, " righe del file corrente sono già presenti nel file precedente e risultano duplicate. Verifica di non aver caricato due volte lo stesso file."),
credits = list(
pre = "Applicazione creata da ",
bug = " · Segnala problemi su ",
or = " o via ",
mail = "mail"
)
),
en = list(
app_subtitle = "Data cleaning and visualisation from",
app_descr = "Handheld optical sensor for non-destructive measurement of Chl, Flav, Anth and NBI on intact leaves — Metos Global.",
privacy_title = "100% Data Security & Privacy",
privacy_body = "This application runs entirely within your browser using WebAssembly technology. Your data never leaves your computer, and no files are sent to external servers. It can also be used offline. Note: the initial launch may take a few seconds to load the R environment.",
status_waiting = "Waiting",
status_loaded = "✓ File loaded",
status_clean = "✓ File cleaned",
status_trt = "✓ Treatments added",
status_final = "✓ Final file ready",
status_error = "✗ Error",
step1 = "1 — Load file",
file_placeholder= "Select the file exported from the Dualex (.txt or .csv)…",
file_btn = "Browse",
file_info = function(nr, nc) paste0(nr, " measurements · ", nc, " columns detected"),
step2 = "2 — Select columns to keep",
sel_all = "Select all",
desel_all = "Deselect all",
col_meta = "columns selected",
of_word = "of",
step3 = "3 — Generate cleaned file",
btn_clean = "Clean",
btn_dl_clean = "Download cleaned CSV",
summary = "Summary",
renamed_lbl = "Automatically renamed columns:",
stat_measures = "measurements",
stat_cols = "columns",
stat_groups = "groups",
stat_file = "file name",
preview8 = "Data preview",
step4 = "4 — Assign treatments to groups",
trt_hint = "Enter the treatment name for each group. If left blank, the group number will be used.",
trt_placeholder = "Treatment for group ",
btn_trt = "Add treatment",
trt_preview = "Preview with treatments",
btn_dl_trt = "Download CSV with treatments",
step5 = "5 — Final format and download",
pivot_label = "Transpose parameters to long format",
pivot_sub = "Parameter columns will be merged into a 'parameter' column with values in 'value'",
btn_final = "Generate final file",
btn_dl_final = "Download final CSV",
stat_rows = "rows",
stat_format = "format",
final_preview = "Final file preview",
step6 = "6 — Exploratory chart",
chart_param_lbl = "Select parameters to display:",
chart_hint = "Mean ± standard error (SE) for each treatment. For quick quality control only — not a substitute for proper statistical analysis.",
btn_chart = "Generate chart",
btn_dl_png = "Download PNG",
chart_no_params = "No numeric parameters available in the final file.",
chart_ylab = "Mean value",
jitter_label = "Show individual data points (jitter)",
jitter_sub = "Overlay each measurement as a dot, useful to spot outliers or assess distribution",
step7 = "7 — Merge with a previous file (optional)",
merge_hint = "Load a CSV previously exported from CleanEX in the same format (wide or long). Columns must match exactly. Data will be sorted chronologically by date and time.",
merge_file_ph = "Select a previous CleanEX CSV…",
merge_file_btn = "Browse",
btn_merge = "Merge files",
btn_dl_merge = "Download combined CSV",
merge_ok = function(n1, n2) paste0("✓ Merge complete: ", n1, " + ", n2, " rows = ", n1+n2, " total rows"),
merge_err_cols = "Error: columns in the uploaded file do not match the current file. Make sure both files are in the same format (wide or long) and have the same parameters.",
merge_err_read = "Error: the file could not be read. Make sure it is a CSV exported from CleanEX (comma separator, first row with column names).",
merge_preview_curr = "Current file preview (first 5 rows):",
merge_preview_prev = "Previous file preview (first 5 rows):",
example_btn = "Try with example data",
example_note = "Synthetic example data, not real measurements.",
err_not_dualex = "The file does not look like a Dualex export: the column header (line 5) was not found.",
err_no_data = "The file contains no measurement rows.",
err_no_cols = "No column selected: select at least one column in step 2.",
warn_no_group = "The group column (groupe) is not included, so treatments cannot be assigned. Select it again in step 2 and repeat the cleaning.",
warn_decimal = "Decimal comma detected in the values: CleanEX expects a decimal point, so the parameters will not be recognised. Export the file again from the Dualex or replace the comma with a point.",
merge_warn_dup = function(n) paste0("Warning: ", n, " rows of the current file are already present in the previous file and appear duplicated. Make sure you did not load the same file twice."),
credits = list(
pre = "Application developed by ",
bug = " · Report issues on ",
or = " or via ",
mail = "email"
)
),
es = list(
app_subtitle = "Limpieza y visualización de datos de",
app_descr = "Sensor óptico portátil para la medición no destructiva de Chl, Flav, Anth y NBI en hojas intactas, de Metos Global.",
privacy_title = "Seguridad de los datos y privacidad al 100%",
privacy_body = "Esta aplicación se ejecuta completamente en su navegador mediante tecnología WebAssembly. Sus datos nunca salen de su ordenador y no se envía ningún archivo a servidores externos. También puede usarse sin conexión. Nota: el primer inicio puede tardar unos segundos mientras se carga el entorno R.",
status_waiting = "En espera",
status_loaded = "✓ Archivo cargado",
status_clean = "✓ Archivo limpio",
status_trt = "✓ Tratamientos añadidos",
status_final = "✓ Archivo final listo",
status_error = "✗ Error",
step1 = "1 — Cargar el archivo",
file_placeholder= "Seleccione el archivo exportado del Dualex (.txt o .csv)…",
file_btn = "Examinar",
file_info = function(nr, nc) paste0(nr, " mediciones · ", nc, " columnas detectadas"),
step2 = "2 — Seleccionar las columnas que se conservan",
sel_all = "Seleccionar todas",
desel_all = "Deseleccionar todas",
col_meta = "columnas seleccionadas",
of_word = "de",
step3 = "3 — Generar el archivo limpio",
btn_clean = "Limpiar",
btn_dl_clean = "Descargar CSV limpio",
summary = "Resumen",
renamed_lbl = "Columnas renombradas automáticamente:",
stat_measures = "mediciones",
stat_cols = "columnas",
stat_groups = "grupos",
stat_file = "nombre del archivo",
preview8 = "Vista previa de los datos",
step4 = "4 — Asignar los tratamientos a los grupos",
trt_hint = "Introduzca el nombre del tratamiento para cada grupo. Si se deja vacío, se usa el número del grupo.",
trt_placeholder = "Tratamiento del grupo ",
btn_trt = "Añadir tratamiento",
trt_preview = "Vista previa con tratamientos",
btn_dl_trt = "Descargar CSV con tratamientos",
step5 = "5 — Formato final y descarga",
pivot_label = "Transponer los parámetros a formato largo (long)",
pivot_sub = "Las columnas de los parámetros se unirán en una columna 'parameter' con los valores en 'value'",
btn_final = "Generar archivo final",
btn_dl_final = "Descargar CSV final",
stat_rows = "filas",
stat_format = "formato",
final_preview = "Vista previa del archivo final",
step6 = "6 — Gráfico exploratorio",
chart_param_lbl = "Seleccione los parámetros que desea mostrar:",
chart_hint = "Media ± error estándar (EE) para cada tratamiento. Solo para un control de calidad rápido: no sustituye al análisis estadístico.",
btn_chart = "Generar gráfico",
btn_dl_png = "Descargar PNG",
chart_no_params = "No hay parámetros numéricos disponibles en el archivo final.",
chart_ylab = "Valor medio",
jitter_label = "Mostrar puntos individuales (jitter)",
jitter_sub = "Muestra cada medición como un punto, útil para detectar valores atípicos o valorar la distribución",
step7 = "7 — Unir con un archivo anterior (opcional)",
merge_hint = "Cargue un CSV exportado anteriormente desde CleanEX en el mismo formato (wide o long). Las columnas deben coincidir exactamente. Los datos se ordenarán cronológicamente por fecha y hora.",
merge_file_ph = "Seleccione un CSV anterior de CleanEX…",
merge_file_btn = "Examinar",
btn_merge = "Unir archivos",
btn_dl_merge = "Descargar CSV combinado",
merge_ok = function(n1, n2) paste0("✓ Unión completada: ", n1, " + ", n2, " filas = ", n1+n2, " filas en total"),
merge_err_cols = "Error: las columnas del archivo cargado no coinciden con las del archivo actual. Compruebe que ambos archivos tengan el mismo formato (wide o long) y los mismos parámetros.",
merge_err_read = "Error: no se puede leer el archivo. Compruebe que sea un CSV exportado desde CleanEX (separador coma, primera fila con los nombres de las columnas).",
merge_preview_curr = "Vista previa del archivo actual (primeras 5 filas):",
merge_preview_prev = "Vista previa del archivo anterior (primeras 5 filas):",
example_btn = "Probar con datos de ejemplo",
example_note = "Datos de ejemplo sintéticos, no mediciones reales.",
err_not_dualex = "El archivo no parece una exportación del Dualex: no se encontró la cabecera de columnas (línea 5).",
err_no_data = "El archivo no contiene filas de medición.",
err_no_cols = "Ninguna columna seleccionada: seleccione al menos una columna en el paso 2.",
warn_no_group = "La columna de grupos (groupe) no está incluida, por lo que no se pueden asignar tratamientos. Vuelva a seleccionarla en el paso 2 y repita la limpieza.",
warn_decimal = "Se detectó la coma decimal en los valores: CleanEX espera el punto decimal, por lo que los parámetros no se reconocerán. Exporte de nuevo el archivo desde el Dualex o sustituya la coma por un punto.",
merge_warn_dup = function(n) paste0("Atención: ", n, " filas del archivo actual ya están en el archivo anterior y aparecen duplicadas. Compruebe que no ha cargado dos veces el mismo archivo."),
credits = list(
pre = "Aplicación desarrollada por ",
bug = " · Informe de problemas en ",
or = " o por ",
mail = "correo"
)
),
fr = list(
app_subtitle = "Nettoyage et visualisation des données du",
app_descr = "Capteur optique portable pour la mesure non destructive de Chl, Flav, Anth et NBI sur feuilles intactes, par Metos Global.",
privacy_title = "Sécurité des données et confidentialité à 100 %",
privacy_body = "Cette application s'exécute entièrement dans votre navigateur grâce à la technologie WebAssembly. Vos données ne quittent jamais votre ordinateur et aucun fichier n'est envoyé à des serveurs externes. Elle fonctionne aussi hors ligne. Remarque : au premier lancement, le chargement de l'environnement R peut prendre quelques secondes.",
status_waiting = "En attente",
status_loaded = "✓ Fichier chargé",
status_clean = "✓ Fichier nettoyé",
status_trt = "✓ Traitements ajoutés",
status_final = "✓ Fichier final prêt",
status_error = "✗ Erreur",
step1 = "1 — Charger le fichier",
file_placeholder= "Sélectionnez le fichier exporté du Dualex (.txt ou .csv)…",
file_btn = "Parcourir",
file_info = function(nr, nc) paste0(nr, " mesures · ", nc, " colonnes détectées"),
step2 = "2 — Sélectionner les colonnes à conserver",
sel_all = "Tout sélectionner",
desel_all = "Tout désélectionner",
col_meta = "colonnes sélectionnées",
of_word = "sur",
step3 = "3 — Générer le fichier nettoyé",
btn_clean = "Nettoyer",
btn_dl_clean = "Télécharger le CSV nettoyé",
summary = "Récapitulatif",
renamed_lbl = "Colonnes renommées automatiquement :",
stat_measures = "mesures",
stat_cols = "colonnes",
stat_groups = "groupes",
stat_file = "nom du fichier",
preview8 = "Aperçu des données",
step4 = "4 — Attribuer les traitements aux groupes",
trt_hint = "Saisissez le nom du traitement pour chaque groupe. S'il est laissé vide, le numéro du groupe est utilisé.",
trt_placeholder = "Traitement du groupe ",
btn_trt = "Ajouter le traitement",
trt_preview = "Aperçu avec traitements",
btn_dl_trt = "Télécharger le CSV avec traitements",
step5 = "5 — Format final et téléchargement",
pivot_label = "Transposer les paramètres au format long",
pivot_sub = "Les colonnes des paramètres seront regroupées dans une colonne 'parameter', avec les valeurs dans 'value'",
btn_final = "Générer le fichier final",
btn_dl_final = "Télécharger le CSV final",
stat_rows = "lignes",
stat_format = "format",
final_preview = "Aperçu du fichier final",
step6 = "6 — Graphique exploratoire",
chart_param_lbl = "Sélectionnez les paramètres à afficher :",
chart_hint = "Moyenne ± erreur standard (ES) pour chaque traitement. Uniquement pour un contrôle qualité rapide : ne remplace pas l'analyse statistique.",
btn_chart = "Générer le graphique",
btn_dl_png = "Télécharger le PNG",
chart_no_params = "Aucun paramètre numérique disponible dans le fichier final.",
chart_ylab = "Valeur moyenne",
jitter_label = "Afficher les points individuels (jitter)",
jitter_sub = "Affiche chaque mesure sous forme de point, utile pour repérer les valeurs aberrantes ou évaluer la distribution",
step7 = "7 — Fusionner avec un fichier précédent (facultatif)",
merge_hint = "Chargez un CSV exporté précédemment depuis CleanEX dans le même format (wide ou long). Les colonnes doivent correspondre exactement. Les données seront triées chronologiquement par date et heure.",
merge_file_ph = "Sélectionnez un CSV CleanEX précédent…",
merge_file_btn = "Parcourir",
btn_merge = "Fusionner les fichiers",
btn_dl_merge = "Télécharger le CSV combiné",
merge_ok = function(n1, n2) paste0("✓ Fusion terminée : ", n1, " + ", n2, " lignes = ", n1+n2, " lignes au total"),
merge_err_cols = "Erreur : les colonnes du fichier chargé ne correspondent pas à celles du fichier actuel. Vérifiez que les deux fichiers ont le même format (wide ou long) et les mêmes paramètres.",
merge_err_read = "Erreur : impossible de lire le fichier. Vérifiez qu'il s'agit d'un CSV exporté depuis CleanEX (séparateur virgule, première ligne avec les noms des colonnes).",
merge_preview_curr = "Aperçu du fichier actuel (5 premières lignes) :",
merge_preview_prev = "Aperçu du fichier précédent (5 premières lignes) :",
example_btn = "Essayer avec des données d'exemple",
example_note = "Données d'exemple synthétiques, pas de vraies mesures.",
err_not_dualex = "Le fichier ne ressemble pas à un export Dualex : l'en-tête des colonnes (ligne 5) est introuvable.",
err_no_data = "Le fichier ne contient aucune ligne de mesure.",
err_no_cols = "Aucune colonne sélectionnée : sélectionnez au moins une colonne à l'étape 2.",
warn_no_group = "La colonne des groupes (groupe) n'est pas incluse : les traitements ne peuvent pas être attribués. Sélectionnez-la de nouveau à l'étape 2 et refaites le nettoyage.",
warn_decimal = "Virgule décimale détectée dans les valeurs : CleanEX attend un point décimal, les paramètres ne seront donc pas reconnus. Exportez de nouveau le fichier depuis le Dualex ou remplacez la virgule par un point.",
merge_warn_dup = function(n) paste0("Attention : ", n, " lignes du fichier actuel figurent déjà dans le fichier précédent et apparaissent en double. Vérifiez que vous n'avez pas chargé deux fois le même fichier."),
credits = list(
pre = "Application développée par ",
bug = " · Signaler des problèmes sur ",
or = " ou par ",
mail = "e-mail"
)
)
)
# ── Parsing Dualex ────────────────────────────────────────────────────────────
# Logica storica (blocco #Groupe = riga + 3 righe successive): usata solo come
# ripiego se nel file non si riconosce nessuna riga che inizia con una data.
filter_dx_lines_legacy <- function(data_lines) {
skip_next <- 0L
keep_lines <- character(0)
for (line in data_lines) {
if (line == "") { if (skip_next > 0L) skip_next <- skip_next - 1L; next }
if (startsWith(line, "#Groupe")) { skip_next <- 3L; next }
if (startsWith(line, "#")) { if (skip_next > 0L) skip_next <- skip_next - 1L; next }
if (skip_next > 0L) { skip_next <- skip_next - 1L; next }
keep_lines <- c(keep_lines, line)
}
keep_lines
}
parse_dx_raw <- function(filepath) {
raw_bytes <- readBin(filepath, what = "raw", n = file.info(filepath)$size)
raw_bytes <- raw_bytes[raw_bytes != as.raw(0x00)]
# BOM (UTF-8 / UTF-16) rimasti dopo la rimozione dei byte nulli
if (length(raw_bytes) >= 3 && identical(raw_bytes[1:3], as.raw(c(0xEF, 0xBB, 0xBF)))) {
raw_bytes <- raw_bytes[-(1:3)]
} else if (length(raw_bytes) >= 2 &&
(identical(raw_bytes[1:2], as.raw(c(0xFF, 0xFE))) ||
identical(raw_bytes[1:2], as.raw(c(0xFE, 0xFF))))) {
raw_bytes <- raw_bytes[-(1:2)]
}
txt <- rawToChar(raw_bytes)
if (!validUTF8(txt)) txt <- iconv(txt, "latin1", "UTF-8", sub = "") # es. "è" in Latin-1
raw_lines <- trimws(strsplit(txt, "\r\n|\n|\r")[[1]])
if (length(raw_lines) < 5 || !grepl(";", raw_lines[5], fixed = TRUE))
stop("err_not_dualex", call. = FALSE)
header_fields <- trimws(strsplit(sub("^#", "", raw_lines[5]), ";")[[1]])
if (length(header_fields) < 3) stop("err_not_dualex", call. = FALSE)
data_lines <- if (length(raw_lines) >= 6) raw_lines[6:length(raw_lines)] else character(0)
# Riga di misura = non commento e primo campo che sembra una data. Così i blocchi
# riepilogativi "#Groupe…" (e la loro riga di statistiche) non entrano mai nei dati,
# qualunque sia la loro lunghezza o la lingua del firmware.
first_field <- sub(";.*$", "", data_lines)
keep_lines <- data_lines[!startsWith(data_lines, "#") & grepl(DATE_LIKE_RE, first_field)]
if (!length(keep_lines)) keep_lines <- filter_dx_lines_legacy(data_lines)
if (!length(keep_lines)) stop("err_no_data", call. = FALSE)
n_cols <- length(header_fields)
split_rows <- lapply(strsplit(keep_lines, ";"), function(x) {
length(x) <- n_cols; x[is.na(x)] <- ""; x
})
df <- as.data.frame(do.call(rbind, split_rows), stringsAsFactors = FALSE)
colnames(df) <- header_fields
df
}
apply_rename <- function(df) {
for (old in names(COL_RENAME)) {
idx <- which(tolower(colnames(df)) == tolower(old))
if (length(idx)) colnames(df)[idx[1]] <- COL_RENAME[[old]]
}
df
}
# ── Colonne parametro: numeriche e non descrittive (esclude qual_sat, etal, GPS…) ──
# NaN/nan/vuoti sono valori mancanti: non escludono la colonna.
get_param_cols <- function(df) {
cand <- colnames(df)[!tolower(colnames(df)) %in% META_COLS]
cand[vapply(cand, function(c) is_numeric_col(df[[c]], require_value = TRUE), logical(1))]
}
# ── Virgola decimale nei valori dei parametri (il Dualex usa il punto) ────────
has_decimal_comma <- function(df) {
cols <- colnames(df)[!tolower(colnames(df)) %in% META_COLS]
any(vapply(cols, function(c) {
v <- trimws(as.character(df[[c]])); v <- v[!is_missing_val(v)]
length(v) > 0 && mean(grepl("^[+-]?[0-9]+,[0-9]+$", v)) > 0.5
}, logical(1)))
}
pivot_long <- function(df) {
param_cols <- get_param_cols(df)
if (!length(param_cols)) return(df)
id_present <- setdiff(colnames(df), param_cols)
id_data <- df[, id_present, drop = FALSE]
long_rows <- do.call(rbind, lapply(param_cols, function(p) {
tmp <- id_data; tmp$parameter <- p; tmp$value <- df[[p]]; tmp
}))
long_rows <- long_rows[order(rep(seq_len(nrow(df)), length(param_cols))), ]
rownames(long_rows) <- NULL
long_rows
}
# ── Calcolo media + SE per trattamento ────────────────────────────────────────
# Valori numerici + trattamento di un parametro, da formato wide o long.
# Lavorare direttamente sul long evita di ricostruire il wide (che farebbe
# collassare le righe con colonne identificative identiche).
param_values <- function(df, param, trt_col = "treatment") {
if (all(c("parameter", "value") %in% colnames(df)) && !(param %in% colnames(df))) {
s <- df[as.character(df$parameter) == param, , drop = FALSE]
data.frame(trt = as.character(s[[trt_col]]), val = to_num(s$value), stringsAsFactors = FALSE)
} else {
data.frame(trt = as.character(df[[trt_col]]), val = to_num(df[[param]]), stringsAsFactors = FALSE)
}
}
compute_mean_se <- function(df, param, trt_col = "treatment") {
pv <- param_values(df, param, trt_col)
ok <- is.finite(pv$val) & !is.na(pv$trt)
vals <- pv$val[ok]; trt <- pv$trt[ok]
if (!length(vals)) return(NULL)
f <- factor(trt, levels = natural_sort(trt))
agg_mean <- tapply(vals, f, mean)
agg_se <- tapply(vals, f, function(x) {
n <- length(x)
if (n < 2) return(0)
sd(x) / sqrt(n)
})
data.frame(
treatment = levels(f),
mean = as.numeric(agg_mean),
se = as.numeric(agg_se),
stringsAsFactors = FALSE
)
}
# ── Encoder base64 (pura base R, nessuna dipendenza esterna) ─────────────────
base64_encode_raw <- function(raw_bytes) {
alphabet <- strsplit("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", "")[[1]]
n <- length(raw_bytes)
pad <- (3 - n %% 3) %% 3
if (pad > 0) raw_bytes <- c(raw_bytes, raw(pad))
m <- matrix(as.integer(raw_bytes), nrow = 3)
idx <- rbind(
bitwShiftR(m[1, ], 2),
bitwOr(bitwShiftL(bitwAnd(m[1, ], 3L), 4), bitwShiftR(m[2, ], 4)),
bitwOr(bitwShiftL(bitwAnd(m[2, ], 15L), 2), bitwShiftR(m[3, ], 6)),
bitwAnd(m[3, ], 63L)
)
out <- alphabet[idx + 1]
out <- matrix(out, nrow = 4)
if (pad >= 1) out[4, ncol(out)] <- "="
if (pad == 2) out[3, ncol(out)] <- "="
paste(out, collapse = "")
}
# ── Estrae l'unità di misura dal nome colonna, es. "Length(cm)" → "cm" ───────
extract_unit <- function(param_name) {
m <- regmatches(param_name, regexpr("\\(([^)]+)\\)\\s*$", param_name))
if (length(m) == 0 || m == "") return(NULL)
sub("^\\((.+)\\)$", "\\1", m)
}
# ── Rendering grafico a barre con error bar, stile theme_bw, palette ggsci npg ─
draw_bar_chart <- function(df, params, trt_col = "treatment", ylab = "Mean value",
is_dark = FALSE, show_jitter = FALSE) {
pal_npg_base <- c("#E64B35", "#4DBBD5", "#00A087", "#3C5488", "#F39B7F",
"#8491B4", "#91D1C2", "#DC0000", "#7E6148", "#B09C85")
pal <- adjustcolor(pal_npg_base, alpha.f = 0.8)
fg <- "#1A1A1A"
major_gr <- "#E5E5E5"
minor_gr <- "#F0F0F0"
panel_bg <- "#FFFFFF"
plot_bg <- "#FFFFFF"
all_treatments <- natural_sort(df[[trt_col]])
trt_colors <- setNames(pal[((seq_along(all_treatments) - 1) %% length(pal)) + 1],
all_treatments)
par(bg = plot_bg, col.axis = fg, col.lab = fg, col.main = fg, fg = fg,
font.main = 1, cex.main = 1.4, cex.lab = 1.3, cex.axis = 1.2)
n_params <- length(params)
if (n_params > 1) {
n_col <- 2
n_row <- ceiling(n_params / n_col)
par(mfrow = c(n_row, n_col), mar = c(7, 6.5, 3.2, 1.4), mgp = c(4, 0.9, 0))
} else {
par(mfrow = c(1, 1), mar = c(7, 6.5, 3.2, 1.4), mgp = c(4, 0.9, 0))
}
for (i in seq_along(params)) {
p <- params[i]
agg <- compute_mean_se(df, p, trt_col)
if (is.null(agg) || !nrow(agg)) next
bar_cols <- trt_colors[agg$treatment]
n_bars <- nrow(agg)
pv <- param_values(df, p, trt_col)
ok_pts <- is.finite(pv$val) & !is.na(pv$trt)
pts_vals <- pv$val[ok_pts]
pts_trt <- pv$trt[ok_pts]
# Intervallo verticale: include sempre lo 0, le barre di errore e (se attivi) i punti;
# funziona anche con valori negativi o tutti nulli.
hi <- max(agg$mean + agg$se, 0, na.rm = TRUE)
lo <- min(agg$mean - agg$se, 0, na.rm = TRUE)
if (show_jitter && length(pts_vals)) {
hi <- max(hi, pts_vals); lo <- min(lo, pts_vals)
}
ylim_max <- if (hi > 0) hi * 1.18 else 0
ylim_min <- if (lo < 0) lo * 1.18 else 0
if (ylim_max == ylim_min) ylim_max <- 1
plot.new()
plot.window(xlim = c(0.2, n_bars * 1.2 + 0.2), ylim = c(ylim_min, ylim_max))
rect(par("usr")[1], par("usr")[3], par("usr")[2], par("usr")[4],
col = panel_bg, border = NA)
y_major <- pretty(c(ylim_min, ylim_max))
y_major <- y_major[y_major >= ylim_min & y_major <= ylim_max]
y_minor <- (head(y_major, -1) + tail(y_major, -1)) / 2
abline(h = y_minor, col = minor_gr, lwd = 0.7)
abline(h = y_major, col = major_gr, lwd = 1)
bp <- barplot(agg$mean, col = bar_cols, border = "#1A1A1A", lwd = 0.9,
ylim = c(ylim_min, ylim_max), add = TRUE,
ylab = "", main = "", names.arg = rep("", n_bars),
axes = FALSE)
if (show_jitter && length(pts_vals)) {
bar_x <- setNames(as.numeric(bp), agg$treatment)
jx <- bar_x[pts_trt] + runif(length(pts_trt), -0.13, 0.13)
points(jx, pts_vals, pch = 21, bg = adjustcolor("#1A1A1A", alpha.f = 0.45),
col = adjustcolor("#1A1A1A", alpha.f = 0.6), cex = 0.85, lwd = 0.6)
}
has_se <- which(agg$se > 0) # SE nullo (n = 1): nessuna barra di errore
if (length(has_se)) {
arrows(x0 = bp[has_se], y0 = agg$mean[has_se], x1 = bp[has_se], y1 = agg$mean[has_se] + agg$se[has_se],
angle = 90, length = 0.08, col = fg, lwd = 1.6)
arrows(x0 = bp[has_se], y0 = agg$mean[has_se], x1 = bp[has_se], y1 = agg$mean[has_se] - agg$se[has_se],
angle = 90, length = 0.08, col = fg, lwd = 1.6)
}
unit <- extract_unit(p)
ylab_full <- if (!is.null(unit)) paste0(ylab, " [", unit, "]") else ylab
usr <- par("usr")
y_off <- (usr[4] - usr[3]) * 0.03
text(x = bp, y = usr[3] - y_off, labels = agg$treatment,
srt = 30, adj = c(1, 1), xpd = TRUE, cex = 1.2, col = fg)
axis(2, at = y_major, col = fg, col.axis = fg, cex.axis = 1.2, las = 1, mgp = c(4, 0.9, 0))
box(col = fg, lwd = 1)
title(ylab = ylab_full, cex.lab = 1.3, col.lab = fg)
title(main = p, cex.main = 1.4, col.main = fg, font.main = 2)
}
par(mfrow = c(1, 1))
invisible(trt_colors)
}
# ── Serializza un vettore R in array JS di stringhe ───────────────────────────
jsonlite_like_array <- function(x) {
esc <- gsub('"', '\\\\"', x)
paste0("[", paste0('"', esc, '"', collapse = ","), "]")
}
# ── Parametri numerici disponibili per il grafico (wide o long) ──────────────
get_available_chart_params <- function(df) {
if ("parameter" %in% colnames(df) && "value" %in% colnames(df)) {
sort(unique(df$parameter))
} else {
get_param_cols(df)
}
}
# ── CSV con virgolette sulle sole colonne di testo: nomi di trattamento con ──
# ── virgole restano integri, i numeri restano senza virgolette ─────────────────
df_to_csv_string <- function(df, sep = ",") {
# NaN/vuoti non rendono "testo" una colonna numerica (restano senza virgolette)
q <- which(!vapply(df, is_numeric_col, logical(1)))
con <- textConnection("out", "w", local = TRUE)
write.table(df, con, sep = sep, row.names = FALSE, quote = q, na = "",
qmethod = "double")
close(con)
paste(out, collapse = "\n")
}
# ── Lettura di un CSV CleanEX come testo (nessuna conversione dei numeri) ─────
read_cleanex_csv <- function(path) {
df <- read.csv(path, check.names = FALSE, stringsAsFactors = FALSE,
colClasses = "character", na.strings = character(0),
encoding = "UTF-8")
if (!ncol(df)) stop("empty file")
b <- charToRaw(colnames(df)[1]) # BOM UTF-8 eventualmente lasciato da Excel
if (length(b) >= 3 && identical(b[1:3], as.raw(c(0xEF, 0xBB, 0xBF))))
colnames(df)[1] <- rawToChar(b[-(1:3)])
df
}
# ── Data Dualex (gg/mm/aaaa) o ISO → Date; NA se non interpretabile ──────────
parse_dx_date <- function(x) {
x <- trimws(as.character(x))
out <- rep(as.Date(NA), length(x))
# Ogni formato è applicato solo alle stringhe con la forma giusta, così un anno a
# due cifre (CSV risalvato da Excel) non viene letto come anno 0026.
cands <- list(
c("%d/%m/%Y", "^[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}$"),
c("%Y-%m-%d", "^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$"),
c("%d.%m.%Y", "^[0-9]{1,2}[.][0-9]{1,2}[.][0-9]{4}$"),
c("%d-%m-%Y", "^[0-9]{1,2}-[0-9]{1,2}-[0-9]{4}$"),
c("%d/%m/%y", "^[0-9]{1,2}/[0-9]{1,2}/[0-9]{2}$"),
c("%d.%m.%y", "^[0-9]{1,2}[.][0-9]{1,2}[.][0-9]{2}$"),
c("%d-%m-%y", "^[0-9]{1,2}-[0-9]{1,2}-[0-9]{2}$")
)
for (cd in cands) {
idx <- which(is.na(out) & grepl(cd[2], x))
if (length(idx)) out[idx] <- as.Date(x[idx], format = cd[1])
}
out
}
# ── Ordinamento cronologico (data, poi ora). Le righe con data illeggibile vanno in
# ── fondo; se nessuna data è leggibile l'ordine resta invariato ───────────────
sort_chrono <- function(df) {
if (!"date" %in% colnames(df) || !nrow(df)) return(df)
d <- parse_dx_date(df$date)
if (all(is.na(d))) return(df)
tm <- if ("time" %in% colnames(df)) {
p <- strsplit(trimws(as.character(df$time)), ":", fixed = TRUE)
vapply(p, function(z) {
z <- suppressWarnings(as.numeric(z)); z <- c(z, 0, 0, 0)[1:3]
if (anyNA(z)) NA_real_ else sum(z * c(3600, 60, 1))
}, numeric(1))
} else rep(0, nrow(df))
out <- df[order(d, tm, seq_len(nrow(df)), na.last = TRUE), , drop = FALSE]
rownames(out) <- NULL
out
}
# ── UI ───────────────────────────────────────────────────────────────────────
ui <- page_fluid(
title = "CleanEX 🧹",
theme = bs_theme(
version = 5,
base_font = "system-ui",
heading_font = "system-ui",
bg = "#F7F8FA",
fg = "#1A1D23",
primary = "#2D6A4F",
secondary = "#B7D4C6",
border_radius = "6px"
),
tags$head(tags$style(HTML("
html, body { padding: 1rem 1.5rem !important; margin: 0 !important; background: #F7F8FA !important; }
@media (prefers-color-scheme: dark) {
html, body { background: #141A13 !important; color: #D8E8D5 !important; }
}
h1.title { display: none !important; }
.dx-card {
background: #fff; border: 1px solid #E2E6EA; border-radius: 10px;
padding: 1.8rem 2.2rem; margin-bottom: 1.4rem;
box-shadow: 0 1px 4px rgba(0,0,0,.06);
}
.privacy-banner {
background: #F0F9FF; border: 1px solid #BAE6FD; border-radius: 10px;
padding: 1rem 1.4rem; margin-bottom: 1.4rem;
display: flex; align-items: flex-start; gap: .9rem;
}
.privacy-icon { font-size: 1.3rem; flex-shrink: 0; line-height: 1.5; }
.privacy-title { font-size: .82rem; font-weight: 700; color: #0C4A6E; margin-bottom: .2rem; letter-spacing: .03em; text-transform: uppercase; }
.privacy-body { font-size: .82rem; color: #075985; margin: 0; line-height: 1.55; }
.app-title { font-size: 1.75rem; font-weight: 700; letter-spacing: -.3px; color: #1A1D23; margin-bottom: .2rem; }
.app-subtitle { font-size: 1.05rem; color: #6B7280; margin-bottom: 0; }
.section-label { font-size: .88rem; font-weight: 700; letter-spacing: .07em; text-transform: uppercase; color: #6B7280; margin-bottom: .8rem; }
.file-chip { display: inline-block; font-size: .78rem; background: #EAF4EF; border: 1px solid #C6E8D6; border-radius: 4px; padding: .2rem .6rem; color: #2D6A4F; font-weight: 600; margin-top: .5rem; }
.lang-switcher {
display: inline-flex; align-items: center;
border: 1.5px solid #D1D5DB; border-radius: 6px; overflow: hidden;
font-size: .85rem; font-weight: 700;
}
.lang-btn {
padding: .35rem .8rem; cursor: pointer; background: #fff; color: #6B7280;
border: none; border-right: 1px solid #D1D5DB;
transition: all .12s; user-select: none; line-height: 1.4;
}
.lang-btn:last-child { border-right: none; }
.lang-btn.active { background: #2D6A4F; color: #fff; }
.lang-btn:hover:not(.active) { background: #F3F4F6; color: #1A1D23; }
.col-grid { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: 1rem; }
.col-toggle {
display: inline-flex; align-items: center; gap: .4rem; padding: .42rem .9rem;
border-radius: 999px; border: 1.5px solid #D1D5DB; background: #fff;
font-size: .92rem; font-weight: 500; color: #374151;
cursor: pointer; transition: all .12s; user-select: none;
}
.col-toggle.active { border-color: #2D6A4F; background: #EAF4EF; color: #1C4430; }
.col-toggle.active::before { content: '✓'; font-size: .82rem; color: #2D6A4F; font-weight: 700; }
.col-toggle.excluded { border-color: #D1D5DB; background: #F9FAFB; color: #9CA3AF; text-decoration: line-through; }
.toggle-meta { font-size: .9rem; color: #6B7280; margin-top: .4rem; margin-bottom: 0; }
.toggle-actions { display: flex; gap: .8rem; margin-bottom: .9rem; }
.link-btn { background: none; border: none; padding: 0; font-size: .85rem; color: #2D6A4F; font-weight: 600; cursor: pointer; text-decoration: underline; }
.link-btn:hover { color: #1C4430; }
#example_btn { display: inline-block; margin-top: .6rem; font-size: .92rem; font-weight: 600; color: #2D6A4F; }
.badge-idle { background: #E9ECF0; color: #4B5563; }
.badge-ok { background: #D1FAE5; color: #065F46; }
.badge-error { background: #FEE2E2; color: #991B1B; }
.status-badge { display: inline-block; font-size: .92rem; font-weight: 600; padding: .3em .85em; border-radius: 999px; }
.shiny-input-container { width: 100% !important; }
.form-group { margin-bottom: 0; }
.form-control, .input-group-text, .form-select { font-size: .95rem !important; padding: .45rem .75rem !important; }
.input-group { width: 100% !important; }
.input-group .form-control { flex: 1 1 auto; min-width: 0; }
#clean_btn, #trt_btn, #pivot_btn {
border: none; color: #fff; font-weight: 600; font-size: 1rem;
padding: .6rem 1.7rem; border-radius: 6px; transition: background .15s;
}
#clean_btn { background: #2D6A4F; } #clean_btn:hover { background: #245740; }
#trt_btn { background: #1D4ED8; } #trt_btn:hover { background: #1E40AF; }
#pivot_btn { background: #7C3AED; } #pivot_btn:hover { background: #6D28D9; }
#chart_btn {
border: none; color: #fff; font-weight: 700; font-size: .95rem;
padding: .58rem 1.6rem; border-radius: 6px; background: #0E7490; transition: background .15s;
}
#chart_btn:hover { background: #0C5E76; }
.dl-wrap .btn {
border: 1.5px solid #2D6A4F; color: #2D6A4F; background: transparent;
font-weight: 600; font-size: 1rem; padding: .6rem 1.7rem;
border-radius: 6px; transition: all .15s;
}
.dl-wrap .btn:hover { background: #EAF4EF; }
.trt-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: .85rem; margin-bottom: 1.2rem; }
.trt-row { display: flex; align-items: center; gap: .6rem; }
.trt-badge {
flex-shrink: 0; min-width: 2.4rem; text-align: center;
background: #F3F4F6; border: 1px solid #E2E6EA; border-radius: 6px;
padding: .35rem .6rem; font-size: .85rem; font-weight: 700; color: #374151;
}
.trt-input {
flex: 1; border: 1.5px solid #D1D5DB; border-radius: 6px;
padding: .4rem .7rem; font-size: .9rem; color: #1A1D23;
outline: none; transition: border-color .12s;
}
.trt-input:focus { border-color: #2D6A4F; }
.trt-table { width: 100%; border-collapse: collapse; margin-bottom: 1rem; font-size: .86rem; }
.trt-table thead th { background: #F3F4F6; font-weight: 700; color: #374151; border-bottom: 2px solid #D1D5DB; padding: .5rem .8rem; text-align: left; }
.trt-table tbody td { padding: .4rem .8rem; border-bottom: 1px solid #F0F1F3; vertical-align: middle; }
.trt-table tbody tr:last-child td { border-bottom: none; }
.trt-table tbody tr:hover td { background: #FAFBFA; }
.pivot-toggle {
display: flex; align-items: center; gap: .85rem; padding: 1rem 1.2rem;
border-radius: 8px; border: 1.5px solid #E2E6EA; background: #FAFAFA;
margin-bottom: 1.2rem; cursor: pointer; transition: all .12s;
}
.pivot-toggle:hover { border-color: #7C3AED; background: #F5F3FF; }
.pivot-toggle.on { border-color: #7C3AED; background: #F5F3FF; }
.pivot-switch {
width: 2.6rem; height: 1.4rem; border-radius: 999px;
background: #D1D5DB; position: relative; flex-shrink: 0; transition: background .15s;
}
.pivot-toggle.on .pivot-switch { background: #7C3AED; }
.pivot-switch::after {
content: ''; position: absolute; top: .18rem; left: .18rem;
width: 1.04rem; height: 1.04rem; border-radius: 50%;
background: #fff; transition: left .15s;
}
.pivot-toggle.on .pivot-switch::after { left: 1.38rem; }
.pivot-label { font-size: 1rem; font-weight: 600; color: #374151; }
.pivot-sub { font-size: .88rem; color: #6B7280; margin-top: .15rem; }
.chart-param-grid { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: 1rem; }
.chart-param-toggle {
display: inline-flex; align-items: center; gap: .4rem; padding: .4rem .9rem;
border-radius: 999px; border: 1.5px solid #C5D4C2; background: #fff;
font-size: .85rem; font-weight: 500; color: #374151;
cursor: pointer; transition: all .12s; user-select: none;
}
.chart-param-toggle.active { border-color: #0E7490; background: #E0F4F8; color: #0C4A5C; }
.chart-param-toggle.active::before { content: '✓'; font-size: .76rem; color: #0E7490; font-weight: 700; }
.chart-param-toggle.excluded { border-color: #DDE5DB; background: #F9FAF9; color: #9CA3AF; }
.chart-wrap { background: #fff; border-radius: 6px; border: 1px solid #E2E6EA; padding: 1rem; margin-top: 1rem; }
.chart-wrap img { width: 100%; height: auto; display: block; border-radius: 4px; }
.chart-hint { font-size: .82rem; color: #6B7280; margin-bottom: 1rem; }
.stats-strip {
display: flex; flex-wrap: wrap; gap: 2.2rem; padding: 1rem 1.4rem;
background: #F0FBF5; border-radius: 6px; border: 1px solid #C6E8D6; margin-bottom: 1.4rem;
}
.stat-item { display: flex; flex-direction: column; }
.stat-val { font-size: 1.5rem; font-weight: 700; color: #2D6A4F; line-height: 1; }
.stat-lbl { font-size: .85rem; color: #6B7280; margin-top: .25rem; }
.preview-wrap { overflow-x: auto; overflow-y: auto; max-height: 340px; border-radius: 6px; border: 1px solid #E2E6EA; }
.preview-wrap thead th { background: #F3F4F6; font-weight: 700; color: #374151; border-bottom: 2px solid #D1D5DB; padding: .55rem .8rem; position: sticky; top: 0; z-index: 1; }
.preview-wrap table { font-size: .95rem !important; margin-bottom: 0; white-space: nowrap; }
.preview-wrap tbody td { padding: .45rem .8rem; color: #4B5563; border-bottom: 1px solid #F0F1F3; }
.preview-wrap tbody tr:last-child td { border-bottom: none; }
.section-divider { border: none; border-top: 1px dashed #D1D5DB; margin: 1.4rem 0; }
.rename-chips { display: flex; flex-wrap: wrap; gap: .5rem; margin-bottom: .4rem; }
.rename-chip { font-size: .8rem; padding: .25rem .7rem; border-radius: 4px; background: #FFF7ED; border: 1px solid #FED7AA; color: #92400E; font-family: monospace; }
.rename-chip .arr { color: #9CA3AF; margin: 0 .3rem; }
.rename-chip .to { color: #1C4430; font-weight: 700; }
/* ── dark mode ─────────────────────────────────────────────────────────── */
body.dark, body.dark html { background: #141A13 !important; color: #D8E8D5 !important; }
body.dark .dx-card { background: #1E261D; border-color: #334430; box-shadow: 0 1px 6px rgba(0,0,0,.3); }
body.dark .app-title { color: #E8F4E5; }
body.dark .app-subtitle { color: #7A9975; }
body.dark .section-label { color: #7A9975; }
body.dark .section-divider { border-color: #334430; }
body.dark .badge-idle { background: #253023; color: #7A9975; }
body.dark .badge-ok { background: #1A3D22; color: #6FCF7F; }
body.dark .badge-error { background: #3D1A1A; color: #F87171; }
body.dark .lang-switcher { border-color: #334430; }
body.dark .lang-btn { background: #1E261D; color: #7A9975; border-color: #334430; }
body.dark .lang-btn.active { background: #3A6B35; color: #fff; }
body.dark .lang-btn:hover:not(.active) { background: #253023; color: #D8E8D5; }
body.dark .privacy-banner { background: #1A2D1A; border-color: #2A4A2A; }
body.dark .privacy-title { color: #6FCF7F; }
body.dark .privacy-body { color: #7A9975; }
body.dark .file-chip { background: #253023; border-color: #334430; color: #6FCF7F; }
body.dark .col-toggle { background: #1E261D; border-color: #334430; color: #C5D8C2; }
body.dark .col-toggle.active { border-color: #5A9B55; background: #1E3A1A; color: #A8E0A0; }
body.dark .col-toggle.excluded { background: #161E15; color: #4A5E47; }
body.dark .toggle-meta { color: #7A9975; }
body.dark .link-btn { color: #6FCF7F; }
body.dark .link-btn:hover { color: #A8E0A0; }
body.dark #example_btn { color: #6FCF7F; }
body.dark #clean_btn { background: #3A6B35; } body.dark #clean_btn:hover { background: #4A8A44; }
body.dark #trt_btn { background: #1D4ED8; } body.dark #trt_btn:hover { background: #2563EB; }
body.dark #chart_btn { background: #0E7490; } body.dark #chart_btn:hover { background: #155E75; }
body.dark .dl-wrap .btn { border-color: #5A9B55; color: #6FCF7F; }
body.dark .dl-wrap .btn:hover { background: #1E3A1A; }
body.dark .stats-strip { background: #1A2D1A; border-color: #2A4A2A; }
body.dark .stat-val { color: #6FCF7F; }
body.dark .stat-lbl { color: #7A9975; }
body.dark .preview-wrap { border-color: #334430; background: #1E261D; }
body.dark .preview-wrap thead th { background: #253023; color: #C5D8C2; border-color: #334430; }
body.dark .preview-wrap tbody td { background: #1E261D; color: #B8D0B5; border-color: #2A3528; }
body.dark .preview-wrap tbody tr:hover td { background: #243426; }
body.dark .preview-wrap table { background: #1E261D; }
body.dark .rename-chip { background: #2D2010; border-color: #5A3E1A; color: #D4A050; }
body.dark .rename-chip .to { color: #6FCF7F; }
body.dark .trt-table thead th { background: #253023; color: #C5D8C2; border-color: #334430; }
body.dark .trt-table tbody td { border-color: #2A3528; color: #B8D0B5; }
body.dark .trt-table tbody tr:hover td { background: #1E2E1D; }
body.dark .trt-badge { background: #253023; border-color: #334430; color: #B8D0B5; }
body.dark .trt-input { background: #253023; border-color: #334430; color: #D8E8D5; }
body.dark .trt-input:focus { border-color: #5A9B55; }
body.dark .pivot-toggle { background: #1E261D; border-color: #334430; }
body.dark .pivot-toggle:hover, body.dark .pivot-toggle.on { border-color: #7C3AED; background: #1E1A2D; }
body.dark .pivot-switch { background: #334430; }
body.dark .pivot-label { color: #D8E8D5; }
body.dark .pivot-sub { color: #7A9975; }
body.dark .chart-param-toggle { background: #1E261D; border-color: #334430; color: #C5D8C2; }
body.dark .chart-param-toggle.active { border-color: #22B8CF; background: #122A30; color: #67E8F9; }
body.dark .chart-param-toggle.excluded { background: #161E15; color: #4A5E47; }
body.dark .chart-wrap { background: #1E261D; border-color: #334430; }
body.dark .chart-hint { color: #7A9975; }
body.dark .shiny-table-output table,
body.dark table.table,
body.dark table {
background: #1E261D !important;
color: #B8D0B5 !important;
}
body.dark table.table > :not(caption) > * > * { background: #1E261D !important; color: #B8D0B5 !important; }
body.dark .form-control, body.dark .form-select, body.dark input[type=text] {
background: #253023 !important; border-color: #334430 !important; color: #D8E8D5 !important;
}
body.dark .input-group-text { background: #334430 !important; border-color: #3D5438 !important; color: #7A9975 !important; }
"))),
tags$script(HTML("
(function() {
function sendHeight() {
var h = document.body.scrollHeight;
window.parent.postMessage({ type: 'cleanex-resize', height: h }, '*');
}
var ro = new ResizeObserver(function() { sendHeight(); });
ro.observe(document.body);
var mo = new MutationObserver(function() { sendHeight(); });
mo.observe(document.body, { childList: true, subtree: true, attributes: true });
sendHeight();
[100, 300, 600, 1000, 1800, 3000].forEach(function(ms) {
setTimeout(sendHeight, ms);
});
})();
(function() {
var mq = window.matchMedia('(prefers-color-scheme: dark)');
function applyDark(on) { document.body.classList.toggle('dark', on); }
applyDark(mq.matches);
mq.addEventListener('change', function(e) { applyDark(e.matches); });
})();
function setLang(lang) {
document.querySelectorAll('.lang-btn').forEach(function(b) {
b.classList.toggle('active', b.getAttribute('data-lang') === lang);
});
Shiny.setInputValue('ui_lang', lang, {priority: 'event'});
}
Shiny.addCustomMessageHandler('downloadCSV', function(msg) {
var blob = new Blob([msg.content], {type: 'text/csv;charset=utf-8;'});
var link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = msg.filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
Shiny.addCustomMessageHandler('downloadPNG', function(msg) {
var link = document.createElement('a');
link.href = 'data:image/png;base64,' + msg.data;
link.download = msg.filename;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
Shiny.addCustomMessageHandler('updateColMeta', function(msg) {
var el = document.getElementById('col-meta');
if (el) el.textContent = msg.text;
});
function toggleCol(el) { el.classList.toggle('active'); el.classList.toggle('excluded'); updateMeta(); }
function setAll(state) {
document.querySelectorAll('.col-toggle').forEach(function(el) {
el.classList.toggle('active', state); el.classList.toggle('excluded', !state);
});
updateMeta();
}
function updateMeta() {
var active = document.querySelectorAll('.col-toggle.active').length;
var total = document.querySelectorAll('.col-toggle').length;
var sel = [];
document.querySelectorAll('.col-toggle.active').forEach(function(t) { sel.push(t.getAttribute('data-col')); });
Shiny.setInputValue('selected_cols', sel, {priority: 'event'});
Shiny.setInputValue('active_col_count', active, {priority: 'event'});
}
function togglePivot() {
var el = document.getElementById('pivot-toggle');
var on = el.classList.toggle('on');
Shiny.setInputValue('pivot_long', on, {priority: 'event'});
}
function toggleJitter() {
var el = document.getElementById('jitter-toggle');
var on = el.classList.toggle('on');
Shiny.setInputValue('show_jitter', on, {priority: 'event'});
}
function toggleChartParam(el) {
el.classList.toggle('active');
el.classList.toggle('excluded');
var sel = [];
document.querySelectorAll('.chart-param-toggle.active').forEach(function(t) {
sel.push(t.getAttribute('data-param'));
});
Shiny.setInputValue('chart_params', sel, {priority: 'event'});
}
$(document).on('shiny:value', function(e) {
if (e.name === 'col_selector_panel') setTimeout(updateMeta, 50);
});
")),
# ── Header ────────────────────────────────────────────────────────────────
div(class = "dx-card",
div(style = "display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.5rem;",
div(class = "app-title", "CleanEX 🧹"),
div(style = "display:flex; align-items:center; gap:.8rem; flex-wrap:wrap;",
uiOutput("status_badge"),
div(class = "lang-switcher",
tags$button(class = "lang-btn", `data-lang` = "it", onclick = "setLang('it')", "IT"),
tags$button(class = "lang-btn active", `data-lang` = "en", onclick = "setLang('en')", "EN"),
tags$button(class = "lang-btn", `data-lang` = "es", onclick = "setLang('es')", "ES"),
tags$button(class = "lang-btn", `data-lang` = "fr", onclick = "setLang('fr')", "FR")
)
)
),
uiOutput("app_subtitle")
),
uiOutput("privacy_banner"),
uiOutput("step1_panel"),
uiOutput("col_selector_panel"),
uiOutput("step3_panel"),
uiOutput("preview_panel"),
uiOutput("treatment_panel"),
uiOutput("pivot_panel"),
uiOutput("chart_panel"),
uiOutput("merge_panel"),
hr(class = "section-divider"),
div(style = "text-align:center; font-size:.92rem; color:#6B7280; padding:.5rem 0 1.5rem;",
uiOutput("app_credits")
)
)
# ── Server ───────────────────────────────────────────────────────────────────
server <- function(input, output, session) {
rv <- reactiveValues(
df_raw = NULL, df_clean = NULL, df_trt = NULL, df_final = NULL,
groups = NULL, error = NULL, base_name = NULL, chart_png_b64 = NULL,
df_merged = NULL, merge_error = NULL, df_prev_preview = NULL,
sel_cols = NULL, trt_vals = list(), decimal_warn = FALSE, merge_warn = 0L,
is_example = FALSE, file_name = NULL
)
lang <- reactive({ if (is.null(input$ui_lang)) "en" else input$ui_lang })
t <- reactive({ TR[[lang()]] })
output$app_subtitle <- renderUI({
tx <- t()
tagList(
p(class = "app-subtitle", tx$app_subtitle, " ",
tags$a(href = "https://metos.global/en/dualex/",
target = "_blank",
style = "color:#2D6A4F; font-weight:700; text-decoration:underline;",
"Dualex — Metos Global.")),
p(class = "app-subtitle", style = "font-size:.9rem; color:#9CA3AF; margin-top:.1rem;",
tx$app_descr)
)
})
output$privacy_banner <- renderUI({
tx <- t()
div(class = "privacy-banner",
div(class = "privacy-icon", "🔒"),
div(
div(class = "privacy-title", tx$privacy_title),
p(class = "privacy-body", tx$privacy_body)
)
)
})
output$app_credits <- renderUI({
cr <- t()$credits
tagList(
cr$pre,
tags$a(href = "https://www.mauromaver.eu", target = "_blank",
style = "color:#2D6A4F; font-weight:700; text-decoration:underline;", "Mauro Maver"),
" · ",
tags$span(style = "color:#9CA3AF; font-size:.88rem;", APP_VERSION),
cr$bug,
tags$a(href = "https://github.com/Stramon1um", target = "_blank",
style = "color:#2D6A4F; font-weight:600; text-decoration:underline;", "GitHub"),
cr$or,
tags$a(href = "mailto:mauro.maver@univr.it",
style = "color:#2D6A4F; font-weight:600; text-decoration:underline;", cr$mail),
" 😊"
)
})
# ── Step 1 ────────────────────────────────────────────────────────────────
output$step1_panel <- renderUI({
tx <- t()
div(class = "dx-card",
p(class = "section-label", tx$step1),
fileInput("file_in", label = NULL,
accept = c(".txt", ".csv", "text/plain", "text/csv"),
placeholder = tx$file_placeholder, buttonLabel = tx$file_btn),
actionLink("example_btn", tx$example_btn, icon = icon("seedling")),
uiOutput("file_info_chip")
)
})
# Carica un file Dualex (o i dati di esempio) e azzera tutto lo stato a valle
load_data <- function(path, name, is_example = FALSE) {
rv$df_raw <- rv$df_clean <- rv$df_trt <- rv$df_final <- rv$groups <- rv$error <- rv$chart_png_b64 <- NULL
rv$df_merged <- rv$merge_error <- rv$df_prev_preview <- rv$sel_cols <- NULL
rv$trt_vals <- list(); rv$decimal_warn <- FALSE; rv$merge_warn <- 0L
rv$is_example <- is_example; rv$file_name <- name
tryCatch({
rv$df_raw <- parse_dx_raw(path)
rv$base_name <- sub("\\.(csv|txt)$", "", name, ignore.case = TRUE)
rv$decimal_warn <- has_decimal_comma(rv$df_raw)
}, error = function(e) { rv$df_raw <- NULL; rv$error <- conditionMessage(e) })
}
observeEvent(input$file_in, {
load_data(input$file_in$datapath, input$file_in$name)
})
observeEvent(input$example_btn, {
f <- tempfile(fileext = ".csv")
writeLines(EXAMPLE_DUALEX, f)
load_data(f, "example_dualex.csv", is_example = TRUE)
unlink(f)
})
output$file_info_chip <- renderUI({
req(rv$df_raw)
tagList(
div(class = "file-chip",
paste0(rv$file_name, " · ", t()$file_info(nrow(rv$df_raw), ncol(rv$df_raw)))),
if (isTRUE(rv$is_example)) p(class = "chart-hint", style = "margin:.4rem 0 0;", t()$example_note),
if (isTRUE(rv$decimal_warn)) warn_box(icon("triangle-exclamation"), " ", t()$warn_decimal)
)
})
# ── Stato dell'interfaccia conservato al cambio lingua ────────────────────
observeEvent(input$selected_cols, { rv$sel_cols <- input$selected_cols },
ignoreNULL = FALSE, ignoreInit = TRUE)
observeEvent(input$trt_edit, {
vals <- rv$trt_vals
vals[[as.character(input$trt_edit$g)]] <- input$trt_edit$v
rv$trt_vals <- vals
})
current_chart_params <- function(avail) {
sel <- intersect(input$chart_params, avail)
if (length(sel)) sel else avail
}
# ── Step 2: Pill colonne ──────────────────────────────────────────────────
output$col_selector_panel <- renderUI({
req(rv$df_raw)
tx <- t()
all_cols <- colnames(rv$df_raw)
sel <- isolate(rv$sel_cols)
active_v <- if (is.null(sel)) !tolower(all_cols) %in% tolower(DEFAULT_DROP)
else all_cols %in% unlist(sel)
n_active <- sum(active_v)
pills <- lapply(seq_along(all_cols), function(i) {
col <- all_cols[i]
is_active <- active_v[i]
tags$span(
class = paste("col-toggle", if (is_active) "active" else "excluded"),
`data-col` = col,
onclick = "toggleCol(this);",
col
)
})
div(class = "dx-card",
p(class = "section-label", tx$step2),
div(class = "toggle-actions",
tags$button(class = "link-btn", onclick = "setAll(true)", tx$sel_all),
tags$button(class = "link-btn", onclick = "setAll(false)", tx$desel_all)
),
div(class = "col-grid", pills),
p(class = "toggle-meta", id = "col-meta",
paste(n_active, tx$of_word, length(all_cols), tx$col_meta))
)
})
observe({
req(rv$df_raw)
active <- if (!is.null(input$active_col_count)) input$active_col_count
else sum(!tolower(colnames(rv$df_raw)) %in% tolower(DEFAULT_DROP))
session$sendCustomMessage("updateColMeta",
list(text = paste(active, t()$of_word, ncol(rv$df_raw), t()$col_meta)))
})
# ── Step 3: Pulizia + rinomina ────────────────────────────────────────────
output$step3_panel <- renderUI({
req(rv$df_raw)
div(class = "dx-card",
p(class = "section-label", t()$step3),
div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
actionButton("clean_btn", t()$btn_clean, icon = icon("broom")),
div(class = "dl-wrap", uiOutput("dl_ui"))
)
)
})
observeEvent(input$clean_btn, {
req(rv$df_raw)
rv$df_clean <- rv$df_trt <- rv$df_final <- rv$groups <- rv$error <- rv$chart_png_b64 <- NULL
tryCatch({
df <- rv$df_raw
keep <- input$selected_cols
if (is.null(keep)) { # selezione mai toccata: colonne di default
keep <- colnames(df)[!tolower(colnames(df)) %in% tolower(DEFAULT_DROP)]
} else if (!length(keep)) { # "Deseleziona tutte": errore esplicito, non i default
rv$error <- "err_no_cols"
return()
}
df <- df[, colnames(df)[colnames(df) %in% unlist(keep)], drop = FALSE]
df <- apply_rename(df)
grp_col <- grep("^group$", colnames(df), ignore.case = TRUE, value = TRUE)
if (!length(grp_col)) grp_col <- grep("group", colnames(df), ignore.case = TRUE, value = TRUE)
if (length(grp_col)) {
grps <- unique(df[[grp_col[1]]])
nums <- suppressWarnings(as.numeric(grps))
rv$groups <- if (!anyNA(nums)) grps[order(nums)] else sort(grps)
}
rv$df_clean <- df
}, error = function(e) rv$error <- conditionMessage(e))
})
output$dl_ui <- renderUI({
req(rv$df_clean)
div(class = "dl-wrap", actionButton("dl_btn", t()$btn_dl_clean, icon = icon("download")))
})
observeEvent(input$dl_btn, {
req(rv$df_clean)
session$sendCustomMessage("downloadCSV", list(
filename = paste0(rv$base_name, "_clean.csv"),
content = df_to_csv_string(rv$df_clean)
))
})
# ── Anteprima step 3 ─────────────────────────────────────────────────────
output$preview_panel <- renderUI({
tx <- t()
if (!is.null(rv$error) && is.null(rv$df_clean)) {
div(class = "dx-card",
div(style = "color:#991B1B; font-size:.9rem;", icon("circle-exclamation"), " ", err_text(tx, rv$error)))
} else if (!is.null(rv$df_clean)) {
df <- rv$df_clean
grp <- if (!is.null(rv$groups)) length(rv$groups) else "—"
# solo le rinomine delle colonne effettivamente presenti nel file pulito
applied <- COL_RENAME[names(COL_RENAME) %in% tolower(colnames(rv$df_raw)) &
unname(COL_RENAME) %in% colnames(df)]
chips <- lapply(names(applied), function(old)
div(class = "rename-chip", span(old), span(class = "arr", "→"), span(class = "to", applied[[old]]))
)
div(class = "dx-card",
p(class = "section-label", tx$summary),
if (is.null(rv$groups)) warn_box(icon("triangle-exclamation"), " ", tx$warn_no_group),
if (length(chips)) tagList(
p(style = "font-size:.82rem; color:#6B7280; margin-bottom:.4rem;", tx$renamed_lbl),
div(class = "rename-chips", chips),
hr(class = "section-divider")
),
div(class = "stats-strip",
div(class="stat-item", span(class="stat-val", nrow(df)), span(class="stat-lbl", tx$stat_measures)),
div(class="stat-item", span(class="stat-val", ncol(df)), span(class="stat-lbl", tx$stat_cols)),
div(class="stat-item", span(class="stat-val", grp), span(class="stat-lbl", tx$stat_groups)),
div(class="stat-item", span(class="stat-val", paste0(rv$base_name, "_clean.csv")), span(class="stat-lbl", tx$stat_file))
),
p(class = "section-label", tx$preview8),
div(class = "preview-wrap", tableOutput("preview_tbl"))
)
}
})
output$preview_tbl <- renderTable({ req(rv$df_clean); rv$df_clean },
striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")
# ── Step 4: Trattamenti per gruppo (tabella, ogni misura = replica) ──────
output$treatment_panel <- renderUI({
req(rv$df_clean, rv$groups)
tx <- t()
inputs <- lapply(rv$groups, function(g) {
div(class = "trt-row",
div(class = "trt-badge", g),
tags$input(type = "text", class = "trt-input", `data-g` = g,
value = { v <- isolate(rv$trt_vals)[[as.character(g)]]; if (is.null(v)) "" else v },
placeholder = paste0(tx$trt_placeholder, g),
oninput = "Shiny.setInputValue('trt_edit', {g: this.dataset.g, v: this.value}, {priority:'event'})")
)
})
div(class = "dx-card",
p(class = "section-label", tx$step4),
p(style = "font-size:.86rem; color:#6B7280; margin-bottom:1rem;", tx$trt_hint),
div(class = "trt-grid", inputs),
hr(class = "section-divider"),
div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
actionButton("trt_btn", tx$btn_trt, icon = icon("tags")),
div(class = "dl-wrap", uiOutput("dl_trt_ui"))
),
uiOutput("trt_preview_wrap")
)
})
observeEvent(input$trt_btn, {
req(rv$df_clean, rv$groups)
rv$df_trt <- rv$df_final <- rv$error <- rv$chart_png_b64 <- NULL
tryCatch({
df <- rv$df_clean
grp_col <- grep("^group$", colnames(df), ignore.case = TRUE, value = TRUE)
if (!length(grp_col)) grp_col <- grep("group", colnames(df), ignore.case = TRUE, value = TRUE)
grp_col <- grp_col[1]
trt_lab <- vapply(rv$groups, function(g) {
val <- rv$trt_vals[[as.character(g)]]
if (!is.null(val) && trimws(val) != "") trimws(val)
else if (nzchar(g)) as.character(g)
else "(blank)" # riga con gruppo vuoto: mai treatment = NA
}, character(1), USE.NAMES = FALSE)
# lookup per posizione (match), non per nome: funziona anche con gruppo vuoto
df$treatment <- trt_lab[match(df[[grp_col]], rv$groups)]
grp_pos <- which(colnames(df) == grp_col)
rest <- setdiff(colnames(df), c(colnames(df)[seq_len(grp_pos)], "treatment"))
rv$df_trt <- df[, c(colnames(df)[seq_len(grp_pos)], "treatment", rest), drop = FALSE]
}, error = function(e) rv$error <- conditionMessage(e))
})
output$dl_trt_ui <- renderUI({
req(rv$df_trt)
div(class = "dl-wrap", actionButton("dl_trt_btn", t()$btn_dl_trt, icon = icon("download")))
})
observeEvent(input$dl_trt_btn, {
req(rv$df_trt)
session$sendCustomMessage("downloadCSV", list(
filename = paste0(rv$base_name, "_treatments.csv"),
content = df_to_csv_string(rv$df_trt)
))
})
output$trt_preview_wrap <- renderUI({
req(rv$df_trt)
tagList(
hr(class = "section-divider"),
p(class = "section-label", t()$trt_preview),
div(class = "preview-wrap", tableOutput("trt_preview_tbl"))
)
})
output$trt_preview_tbl <- renderTable({ req(rv$df_trt); rv$df_trt },
striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")
# ── Step 5: Pivot long + download finale ─────────────────────────────────
output$pivot_panel <- renderUI({
req(rv$df_trt)
tx <- t()
params_found <- get_param_cols(rv$df_trt)
div(class = "dx-card",
p(class = "section-label", tx$step5),
if (length(params_found))
div(id = "pivot-toggle",
class = paste("pivot-toggle", if (isTRUE(isolate(input$pivot_long))) "on"),
onclick = "togglePivot();",
div(class = "pivot-switch"),
div(
div(class = "pivot-label", tx$pivot_label),
div(class = "pivot-sub", paste(tx$pivot_sub, paste(params_found, collapse = ", ")))
)
),
div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap; margin-top:.5rem;",
actionButton("pivot_btn", tx$btn_final, icon = icon("file-csv")),
uiOutput("dl_final_ui")
),
uiOutput("final_preview_wrap")
)
})
observeEvent(input$pivot_btn, {
req(rv$df_trt)
rv$df_final <- rv$error <- rv$chart_png_b64 <- NULL
tryCatch({
rv$df_final <- if (isTRUE(input$pivot_long)) pivot_long(rv$df_trt) else rv$df_trt
}, error = function(e) rv$error <- conditionMessage(e))
})
output$dl_final_ui <- renderUI({
req(rv$df_final)
div(class = "dl-wrap", actionButton("dl_final_btn", t()$btn_dl_final, icon = icon("download")))
})
observeEvent(input$dl_final_btn, {
req(rv$df_final)
session$sendCustomMessage("downloadCSV", list(
filename = paste0(rv$base_name, "_final.csv"),
content = df_to_csv_string(rv$df_final)
))
})
output$final_preview_wrap <- renderUI({
req(rv$df_final)
tx <- t()
tagList(
hr(class = "section-divider"),
div(class = "stats-strip",
div(class="stat-item", span(class="stat-val", nrow(rv$df_final)), span(class="stat-lbl", tx$stat_rows)),
div(class="stat-item", span(class="stat-val", ncol(rv$df_final)), span(class="stat-lbl", tx$stat_cols)),
div(class="stat-item",
span(class="stat-val", if ("parameter" %in% colnames(rv$df_final)) "long" else "wide"),
span(class="stat-lbl", tx$stat_format)),
div(class="stat-item",
span(class="stat-val", paste0(rv$base_name, "_final.csv")),
span(class="stat-lbl", tx$stat_file))
),
p(class = "section-label", tx$final_preview),
div(class = "preview-wrap", tableOutput("final_preview_tbl"))
)
})
output$final_preview_tbl <- renderTable({ req(rv$df_final); rv$df_final },
striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")
# ── Step 6: Grafico esplorativo ───────────────────────────────────────────
output$chart_panel <- renderUI({
req(rv$df_final)
tx <- t()
if (!"treatment" %in% colnames(rv$df_final)) return(NULL)
avail_params <- get_available_chart_params(rv$df_final)
if (!length(avail_params)) {
return(div(class = "dx-card", p(class = "section-label", tx$step6),
p(style = "font-size:.85rem; color:#9CA3AF;", tx$chart_no_params)))
}
sel_now <- isolate(current_chart_params(avail_params))
pills <- lapply(avail_params, function(p) {
tags$span(class = paste("chart-param-toggle",
if (p %in% sel_now) "active" else "excluded"),
`data-param` = p,
onclick = "toggleChartParam(this);", p)
})
div(class = "dx-card",
p(class = "section-label", tx$step6),
p(class = "chart-hint", tx$chart_hint),
p(style = "font-size:.82rem; color:#6B7280; margin-bottom:.5rem; font-weight:600;", tx$chart_param_lbl),
div(class = "chart-param-grid", pills),
div(id = "jitter-toggle",
class = paste("pivot-toggle", if (isTRUE(isolate(input$show_jitter))) "on"),
onclick = "toggleJitter();",
div(class = "pivot-switch"),
div(
div(class = "pivot-label", tx$jitter_label),
div(class = "pivot-sub", tx$jitter_sub)
)
),
div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap;",
actionButton("chart_btn", tx$btn_chart, icon = icon("chart-column")),
uiOutput("dl_png_ui")
),
uiOutput("chart_render_wrap")
)
})
observeEvent(input$chart_btn, {
req(rv$df_final)
rv$chart_png_b64 <- NULL
sel_params <- current_chart_params(get_available_chart_params(rv$df_final))
if (!length(sel_params)) return(NULL)
# Il grafico lavora direttamente su wide o long (param_values): nessuna
# ricostruzione del wide, quindi nessuna riga persa.
tmpfile <- tempfile(fileext = ".png")
n_p <- length(sel_params)
n_col <- if (n_p > 1) 2 else 1
n_row <- ceiling(n_p / n_col)
png(tmpfile, width = 5.2 * n_col, height = 4.6 * n_row, units = "in", res = 300)
drawn <- tryCatch({
draw_bar_chart(rv$df_final, sel_params, ylab = t()$chart_ylab, is_dark = FALSE,
show_jitter = isTRUE(input$show_jitter))
TRUE
}, error = function(e) {
showNotification(paste(t()$status_error, conditionMessage(e)), type = "error")
FALSE
}, finally = dev.off()) # il device PNG viene chiuso anche in caso di errore
if (!drawn) { unlink(tmpfile); return(NULL) }
raw_bytes <- readBin(tmpfile, "raw", file.info(tmpfile)$size)
rv$chart_png_b64 <- base64_encode_raw(raw_bytes)
unlink(tmpfile)
})
output$chart_render_wrap <- renderUI({
req(rv$chart_png_b64)
div(class = "chart-wrap",
tags$img(src = paste0("data:image/png;base64,", rv$chart_png_b64))
)
})
output$dl_png_ui <- renderUI({
req(rv$chart_png_b64)
div(class = "dl-wrap", actionButton("dl_png_btn", t()$btn_dl_png, icon = icon("image")))
})
observeEvent(input$dl_png_btn, {
req(rv$chart_png_b64)
session$sendCustomMessage("downloadPNG", list(
filename = paste0(rv$base_name, "_chart.png"),
data = rv$chart_png_b64
))
})
# ── Step 7: Merge con file precedente ────────────────────────────────────────
output$merge_panel <- renderUI({
req(rv$df_final)
tx <- t()
div(class = "dx-card",
p(class = "section-label", tx$step7),
p(style = "font-size:.9rem; color:#6B7280; margin-bottom:1rem;", tx$merge_hint),
# ── Anteprima file corrente ───────────────────────────────────────────
p(style = "font-size:.86rem; font-weight:600; color:#374151; margin-bottom:.4rem;",
tx$merge_preview_curr),
div(class = "preview-wrap", style = "margin-bottom:1.2rem;",
tableOutput("merge_curr_tbl")),
hr(class = "section-divider"),
# ── Caricamento file precedente ───────────────────────────────────────
fileInput("merge_file_in", label = NULL, accept = c(".csv", "text/csv", "text/plain"),
placeholder = tx$merge_file_ph, buttonLabel = tx$merge_file_btn),
uiOutput("merge_prev_preview_ui"),
# ── Pulsanti ─────────────────────────────────────────────────────────
div(style = "display:flex; gap:.8rem; align-items:center; flex-wrap:wrap; margin-top:.5rem;",
actionButton("merge_btn", tx$btn_merge, icon = icon("object-group"),
style = "border:none;color:#fff;font-weight:600;font-size:1rem;padding:.6rem 1.7rem;border-radius:6px;background:#0E7490;"),
uiOutput("dl_merge_ui")
),
uiOutput("merge_status_ui")
)
})
output$merge_curr_tbl <- renderTable({
req(rv$df_final)
head(rv$df_final, 5)
}, striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")
# Carica preview file precedente appena viene scelto il file
observeEvent(input$merge_file_in, {
rv$df_prev_preview <- rv$df_merged <- rv$merge_error <- NULL
rv$merge_warn <- 0L
tryCatch({
rv$df_prev_preview <- read_cleanex_csv(input$merge_file_in$datapath)
}, error = function(e) rv$merge_error <- t()$merge_err_read)
})
output$merge_prev_preview_ui <- renderUI({
req(rv$df_prev_preview)
tx <- t()
tagList(
p(style = "font-size:.86rem; font-weight:600; color:#374151; margin-bottom:.4rem;",
tx$merge_preview_prev),
div(class = "preview-wrap", style = "margin-bottom:1.2rem;",
tableOutput("merge_prev_tbl"))
)
})
output$merge_prev_tbl <- renderTable({
req(rv$df_prev_preview)
head(rv$df_prev_preview, 5)
}, striped = FALSE, hover = TRUE, bordered = FALSE, spacing = "xs", na = "")
observeEvent(input$merge_btn, {
req(rv$df_final, rv$df_prev_preview)
rv$df_merged <- rv$merge_error <- NULL
rv$merge_warn <- 0L
tryCatch({
df_prev <- rv$df_prev_preview
cols_curr <- colnames(rv$df_final)
cols_prev <- colnames(df_prev)
if (!identical(sort(cols_curr), sort(cols_prev))) {
rv$merge_error <- t()$merge_err_cols
return()
}
df_prev <- df_prev[, cols_curr, drop = FALSE]
df_curr <- rv$df_final
df_curr[] <- lapply(df_curr, function(x) ifelse(is.na(x), "", as.character(x)))
# righe del file corrente già presenti (identiche) nel file precedente
row_key <- function(d) do.call(paste, c(unname(as.list(d)), sep = "\001"))
rv$merge_warn <- sum(row_key(df_curr) %in% row_key(df_prev))
rv$df_merged <- sort_chrono(rbind(df_prev, df_curr))
}, error = function(e) {
rv$merge_error <- t()$merge_err_read
})
})
output$merge_status_ui <- renderUI({
if (!is.null(rv$merge_error)) {
div(style = "margin-top:.8rem; padding:.7rem 1rem; background:#FEE2E2; border:1px solid #FECACA; border-radius:6px; font-size:.9rem; color:#991B1B;",
icon("circle-exclamation"), " ", rv$merge_error)
} else if (!is.null(rv$df_merged)) {
n1 <- nrow(rv$df_final)
n2 <- nrow(rv$df_merged) - n1
tagList(
div(style = "margin-top:.8rem; padding:.7rem 1rem; background:#D1FAE5; border:1px solid #6EE7B7; border-radius:6px; font-size:.9rem; color:#065F46;",
t()$merge_ok(n2, n1)),
if (rv$merge_warn > 0L) warn_box(icon("triangle-exclamation"), " ", t()$merge_warn_dup(rv$merge_warn))
)
}
})
output$dl_merge_ui <- renderUI({
req(rv$df_merged)
div(class = "dl-wrap",
actionButton("dl_merge_btn", t()$btn_dl_merge, icon = icon("download")))
})
observeEvent(input$dl_merge_btn, {
req(rv$df_merged)
session$sendCustomMessage("downloadCSV", list(
filename = paste0(rv$base_name, "_combined.csv"),
content = df_to_csv_string(rv$df_merged)
))
})
# ── Badge stato ───────────────────────────────────────────────────────────
output$status_badge <- renderUI({
tx <- t()
if (!is.null(rv$error)) div(class="status-badge badge-error", tx$status_error)
else if (!is.null(rv$df_final)) div(class="status-badge badge-ok", tx$status_final)
else if (!is.null(rv$df_trt)) div(class="status-badge badge-ok", tx$status_trt)
else if (!is.null(rv$df_clean)) div(class="status-badge badge-ok", tx$status_clean)
else if (!is.null(rv$df_raw)) div(class="status-badge badge-ok", tx$status_loaded)
else div(class="status-badge badge-idle", tx$status_waiting)
})
}
shinyApp(ui, server)