observablehq / inputs

Better input elements
https://observablehq.com/framework/lib/inputs
ISC License
127 stars 34 forks source link

Table UI does not update when setting value programmatically while multiple=false #217

Open mootari opened 2 years ago

mootari commented 2 years ago

Create the following cells:

data = [{name: "foo"}, {name: "bar"}]
viewof table = Inputs.table(data, {multiple: false})
{
  viewof table.value = data[0];
  viewof table.dispatchEvent(new Event('input'));
}
table

Note that the value is assigned correctly (table would otherwise equal null), but the row is not marked as selected:

image

Expected:

image

mootari commented 2 years ago

Also mentioned here:

This particular case seems to be a bug in Inputs.table() though. With multiple: false, assigning a new value will update the view’s selection, but it won’t update the individual row inputs. (cc @mbostock)

mootari commented 2 years ago

Workaround:

// https://github.com/observablehq/inputs/issues/217#issuecomment-1074222779
setTableIndex = (table, index = -1) => {
  table.querySelector('input[type="radio"]:focus')?.blur();
  if(index >= 0) return table.querySelectorAll('input[type="radio"]')[index]?.onclick({});
  const c = table.querySelector('th input[type="checkbox"]:checked');
  if(!c) return;
  c.checked = false;
  c.onclick({});
}
// unset
setTableIndex(viewof table)
// set
setTableIndex(viewof table, 1)