Skip to content

Commit

Permalink
Adding label check en uitzonderingen
Browse files Browse the repository at this point in the history
  • Loading branch information
uittenbroekrobbert committed Feb 19, 2025
1 parent 2db7975 commit ffa853e
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 65 deletions.
49 changes: 45 additions & 4 deletions docs/javascripts/filtering.js
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,14 @@ function filterTable() {

var labelsInput = document.getElementById("labelsInput").value.split(",").map(item => item.trim()).filter(item => item !== "");

for (var i = 1; i < tr.length; i++) { // Skip header row
var dataLabels = []
for (let i = 1; i < tr.length; i++) { // Skip header row
var dataLabels = ""
if (tr[i].hasAttribute("data-labels")) {
dataLabels = tr[i].getAttribute("data-labels").split(",");
dataLabels = tr[i].getAttribute("data-labels")
}
var uitzonderingExpressions = [];
if (tr[i].hasAttribute("data-uitzondering")) {
uitzonderingExpressions = tr[i].getAttribute("data-uitzondering").split(",").map(item => item.trim()).filter(item => item !== "");
}

var td = tr[i].getElementsByTagName("td")[1]; // Maatregelen column (td[0])
Expand All @@ -167,7 +171,12 @@ function filterTable() {
var roleMatch = selectedRoles.every(role => txtValue2.toUpperCase().indexOf(role) > -1);
var lcMatch = selectedLevenscyclus.every(lc => txtValue3.toUpperCase().indexOf(lc) > -1);
var onderwerpMatch = selectedOnderwerpen.every(onderwerp => txtValue4.toUpperCase().indexOf(onderwerp) > -1);
var labelMatch = labelsInput.length === 0 || dataLabels.length === 0 || dataLabels.some(element => labelsInput.includes(element));
var labelMatch = dataLabels === "" || labelsInput.length === 0 || evaluateLabelExpression(dataLabels, labelsInput);
var uitzonderingMatch = labelsInput.length > 0 && anyExpressionMatches(uitzonderingExpressions, labelsInput);

if (uitzonderingMatch && labelMatch) {
labelMatch = false
}

if (txtValue.toUpperCase().indexOf(filter) > -1 && roleMatch && lcMatch && onderwerpMatch && labelMatch) {
tr[i].style.display = "";
Expand All @@ -180,3 +189,35 @@ function filterTable() {
// Trigger contentUpdated to reinitialize Choices.js after filtering
document.dispatchEvent(new Event('contentUpdated'));
}

/*
Given an expression like: ("ai-systeem-voor-algemene-doeleinden" || "ai-systeem") && "open-source" && "geen-transparantieverplichting" && "geen-hoog-risico-ai-systeem"
and an array of labels, evaluates the expression and returns true or false.
*/
function evaluateLabelExpression(expression, labels) {
// replace the string with function calls to hasLabel so we get true / false values
const transformedExpression = expression.replace(/["']?([a-zA-Z0-9-_]+)["']?/g, "hasLabel('$1')");

// create the function that executes our expression
const functionBody =
'const hasLabel = (label) => labels.includes(labelMapper.find(label).label);' +
'return ' + transformedExpression + ';';

try {
return new Function('labels', functionBody)(labels);
} catch (error) {
console.error('Error evaluating expression:', error);
return false;
}
}

/**
* Given a list of expressions and the current labels, returns true if any expression matches with the given labels, else false
* @param expressions a list of expressions, like:
* ["uitzondering-van-toepassing", ("ai-systeem-voor-algemene-doeleinden" || "ai-systeem") && "open-source" && "geen-transparantieverplichting" && "geen-hoog-risico-ai-systeem"]
* @param labels the labels the test against, like ["ai-systeem","uitzondering-van-toepassing"]
* @returns true if any expression matches with the given labels, else false
*/
function anyExpressionMatches(expressions, labels) {
return expressions.some(expression => evaluateLabelExpression(expression, labels));
}
55 changes: 0 additions & 55 deletions docs/javascripts/modal.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ function showModal(event, modalId) {
} else if (modalId === "beslishulp") {
document.getElementById("modal-content").innerHTML = "<iframe style=\"display: block; width: 100%; height: 100%; border: 0; padding: 0; margin: 0; overflow: hidden;\" src=\"../../html/beslishulp.html\"></iframe>"
document.getElementById("modal-content-container").classList.remove("model-content-auto-size");
// TODO: remove monitor when new beslishulp is released
// monitor.start();
}
document.getElementById("modal").classList.remove("display-none");
}
Expand Down Expand Up @@ -133,59 +131,6 @@ function appendQueryParams(params) {
window.history.replaceState(null, document.title, url.toString()); // Update URL without reload
}

class SessionStorageMonitor {
constructor(key, targetValue, callback, interval = 1000) {
this.key = key;
this.targetValue = targetValue;
this.callback = callback;
this.interval = interval;
this.timerId = null;
this.hasValueChanged = false;
}

start() {
// Check initial value
const initialValue = sessionStorage.getItem(this.key);

// If initial value matches target, we'll wait for it to change first
this.hasValueChanged = initialValue !== this.targetValue;

this.timerId = setInterval(() => {
const currentValue = sessionStorage.getItem(this.key);

// If value is different from target, mark that a change has occurred
if (currentValue !== this.targetValue) {
this.hasValueChanged = true;
}

// Only trigger callback if we've seen a change AND current value matches target
if (this.hasValueChanged && currentValue === this.targetValue) {
this.callback(currentValue);
this.stop();
}
}, this.interval);
}

stop() {
if (this.timerId) {
clearInterval(this.timerId);
this.timerId = null;
}
}
}

const monitor = new SessionStorageMonitor(
'currentquestion', // key to monitor
"null", // target value to watch for
(value) => {
console.log('currentquestion changed to null after having a different value');
const jsonObject = JSON.parse(sessionStorage.getItem("labels"))
const labels = convertLabels(Object.values(jsonObject).flatMap(v => Array.isArray(v) ? v : [v]).filter(v => v !== "")).map(obj => obj.label)
updateLabels(labels);
}
);


/**
* Given any key, display value or list of synonyms, return an object with a label and display_value.
* Used to map between different input for labels, but always get the right combination.
Expand Down
16 changes: 10 additions & 6 deletions src/overrides/hooks/lists.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,12 +66,16 @@ def _create_table_row_2(file: File, filter_options: Dict[str, bool], current_fil
rol_ai_act = file.page.meta.get('rol-ai-act', [])
transparantieverplichting = file.page.meta.get('transparantieverplichting', [])
systeemrisico = file.page.meta.get('systeemrisico', [])
all_labels = soort_toepassing + risicogroep + rol_ai_act + transparantieverplichting + systeemrisico

labels_data_html_attribute = ""
if all_labels:
labels_data_html_attribute = "data-labels=\"" + ",".join(all_labels) + "\""
# categorie = file.page.meta.get('categorie', [])
# create match expression for labels
label_match_expression = []
for arr in [soort_toepassing, risicogroep, rol_ai_act, transparantieverplichting, systeemrisico]:
if arr:
label_match_expression.append("(" + " || ".join(arr) + ")")
label_match_expression_str = " && ".join(label_match_expression) if label_match_expression else ""

data_html_attribute = "data-labels=\"" + label_match_expression_str + "\""
data_html_attribute += "data-uitzondering=\"" + ",".join(expr.replace('"', "'") for expr in file.page.meta.get('uitzondering', [])) + "\""

rollen_chips = ''.join(_create_chip(rol, 'rol', current_file, config) for rol in rollen) if filter_options.get("rol", True) else ""
levenscyclus_chips = ''.join(_create_chip(lc, 'levenscyclus', current_file, config) for lc in levenscyclus) if filter_options.get("levenscyclus", True) else ""
Expand All @@ -81,7 +85,7 @@ def _create_table_row_2(file: File, filter_options: Dict[str, bool], current_fil

return "".join(
[
f"<tr {labels_data_html_attribute}>",
f"<tr {data_html_attribute}>",
f'<td><a href="{relative_link}">{vereiste_id}</a></td>' if filter_options.get("id", True) else "",
f'<td><a href="{relative_link}">{file.page.title}</a></td>',
# f"<td>{categorie_chips}</td>" if filter_options.get("categorie", True) else "",
Expand Down

0 comments on commit ffa853e

Please sign in to comment.