Database-BI
view release on metacpan or search on metacpan
templates/web/en-us/canvas.html.tt view on Meta::CPAN
var y = st.y;
if (e.key === 'ArrowRight') x = e.shiftKey ? maxX : clampSpan(x + 1, 1, maxX);
else if (e.key === 'ArrowLeft') x = e.shiftKey ? 1 : clampSpan(x - 1, 1, maxX);
else if (e.key === 'ArrowDown') y = e.shiftKey ? gridBottom() : y + 1;
else if (e.key === 'ArrowUp') y = e.shiftKey ? 1 : Math.max(1, y - 1);
else return;
e.preventDefault();
if (x === st.x && y === st.y) return;
commitMove(card, { x: x, y: y, w: st.w, h: st.h }, true);
}
/* One row past the last card on the canvas: below everything, which is where a
* card sent to the end belongs. */
function gridBottom() {
var bottom = 1;
Array.from(grid.querySelectorAll('.visual-card')).forEach(function (card) {
var sp = spanOf(card);
if (sp.y + sp.h > bottom) bottom = sp.y + sp.h;
});
return bottom;
}
function initMoveHandles(root) {
if (!grid || !anaId) return;
var scope = root || grid;
scope.querySelectorAll('.visual-card-header').forEach(function (header) {
header.addEventListener('pointerdown', onMoveStart);
});
scope.querySelectorAll('.drag-handle').forEach(function (handle) {
handle.addEventListener('keydown', onMoveKey);
handle.addEventListener('blur', flushSave);
});
}
initMoveHandles();
function saveLayout() {
if (!anaId) return;
/* The layout is what the canvas is showing, read back out of the rendered
* grid: x and y are the cell the user dragged a card to, w and h the size
* they dragged its corner to. Nothing is packed or re-derived here - a card
* put in row 4 stays in row 4, with a gap above it if that is where it was
* put - and nothing is written that the server would reject (see
* _validate_layout: inside the grid, and no two cards sharing a cell).
*
* Only a card carrying a span of its own is written: one the canvas
* placed from the saved layout, or one a move, a resize or a push has
* just placed. A card with no style attribute is placed by the browser,
* and the same way on every visit, so it is left out of the layout
* rather than measured into it - measuring it would freeze whatever the
* render in hand happens to show, which on a cross-filtered or drilled
* canvas is the filtered arrangement and not the one the canvas was
* given. Its position is the browser's to decide until the reader moves
* it themselves. */
var layout = [];
Array.from(grid.querySelectorAll('.visual-card')).forEach(function (c) {
var vid = parseInt(c.getAttribute('data-visual'), 10);
if (isNaN(vid)) return;
if (!c.getAttribute('style')) return;
var sp = spanOf(c);
var x = clampSpan(sp.x, 1, GRID_COLS);
layout.push({
visual : vid,
x : x,
y : Math.max(1, sp.y),
w : clampSpan(sp.w, 1, GRID_COLS - x + 1),
h : clampSpan(sp.h, 1, MAX_ROW_SPAN),
});
});
var body = JSON.stringify({ layout: layout });
fetch('/api/analyses/' + encodeURIComponent(anaId), {
method : 'PATCH',
headers : { 'Content-Type': 'application/json' },
body : body,
}).then(function (r) {
/* The server refuses a layout in which two cards share a cell (see
* _validate_layout), leaving the saved one alone. Saying so is the
* difference between a size that is lost and a size the reader knows
* has to be redone: the change is on screen either way, and only the
* saved arrangement was refused. */
if (!r.ok) {
announce('The layout was not saved: the server refused it (' + r.status + ')');
}
}).catch(function () {
announce('The layout was not saved: the server could not be reached');
});
}
/* ---- grid span helpers (3.2 canvas layout) ---- */
var GRID_COLS = 12;
var MAX_ROW_SPAN = 6;
function clampSpan(n, lo, hi) {
return Math.max(lo, Math.min(hi, isNaN(n) ? lo : n));
}
function gridGap() {
var cs = window.getComputedStyle(grid);
return {
col: parseFloat(cs.columnGap || cs.gap) || 0,
row: parseFloat(cs.rowGap || cs.gap) || 0,
};
}
/* Pixels per grid column, gap included, measured from the rendered grid so
* the drag follows the columns the user can actually see. */
function columnPitch() {
var cs = window.getComputedStyle(grid);
var tracks = (cs.gridTemplateColumns || '').split(/\s+/).filter(function (t) {
return parseFloat(t) > 0;
});
var w = tracks.length ? parseFloat(tracks[0]) : 0;
return (w > 0 ? w : grid.getBoundingClientRect().width / GRID_COLS) + gridGap().col;
}
/* Span and start line for one axis, taken from the computed style rather
* than the style attribute. Two reasons: the browser resolves the
* placement of auto-positioned cards, so a card with no saved position
* still reports where it actually is; and once JavaScript has written the
* two longhands, WebKit re-serialises the attribute as the grid-area
* shorthand ("grid-area: 1 / 1 / span 1 / span 6"), which no
* grid-column-based pattern would match. A span may also come back in
* the start longhand (grid-column: span 6 computes to start="span 6"), so
* both are searched. */
function gridPlacement(cs, axis) {
var start = cs['grid' + axis + 'Start'] || '';
var end = cs['grid' + axis + 'End'] || '';
var span = (start + ' ' + end).match(/span\s+(\d+)/);
var line = parseInt(start, 10);
return { span: span ? parseInt(span[1], 10) : 0, line: isNaN(line) ? 0 : line };
}
function spanOf(card) {
var cs = window.getComputedStyle(card);
var col = gridPlacement(cs, 'Column');
var row = gridPlacement(cs, 'Row');
var gap = gridGap();
var cr = card.getBoundingClientRect();
var gr = grid.getBoundingClientRect();
var y = row.line || rowLineAt(cr.top - gridContentTop());
return {
/* Line 0 means the browser had to auto-place the card (a card with
* no saved position, or a width-only rule): fall back to the
* geometry, which is what the user can see either way. Measuring y
* and h as well as x and w matters once a card can be dragged to a
* chosen cell: the DOM index is not where the card is, and writing it
* as the row would persist a position that collides with a
* neighbor's. Rows are read from the rendered tracks, because a row
* of text is shorter than the others. */
x: col.line || Math.round((cr.left - gr.left) / columnPitch()) + 1,
w: col.span || Math.max(1, Math.round((cr.width + gap.col) / columnPitch())),
y: y,
h: row.span || Math.max(1, rowEndAt(cr.bottom - gridContentTop()) - y + 1),
};
}
function applySpan(card, x, w, y, h) {
card.style.setProperty('grid-column', x + '/span ' + w);
card.style.setProperty('grid-row', y + '/span ' + h);
}
/* ---- rows: what is on screen, not a fixed pitch ----
*
* A row is 15rem at least, except a row of text, which is as tall as its text
* (fitTextRows). So a pixel can only be turned into a row by reading the
* tracks the browser drew. Below the last track the rows do not exist yet, and
* count as new ones of the usual height, so a card can be dragged past the end. */
var TALL_ROW = 'minmax(15rem, auto)';
function gridContentTop() {
var cs = window.getComputedStyle(grid);
return grid.getBoundingClientRect().top + (parseFloat(cs.borderTopWidth) || 0) +
(parseFloat(cs.paddingTop) || 0);
}
function rowTracksTo(px) {
var cs = window.getComputedStyle(grid);
var gap = gridGap().row;
var pitch = parseFloat((cs.gridAutoRows || '').match(/[\d.]+px/)) || 240;
var tracks = [];
var at = 0;
(cs.gridTemplateRows || '').split(/\s+/).forEach(function (t) {
var h = parseFloat(t);
if (isNaN(h) || !/px$/.test(t)) return;
tracks.push({ top: at, bottom: at + h });
at += h + gap;
});
while (at <= px + pitch + gap) {
tracks.push({ top: at, bottom: at + pitch });
at += pitch + gap;
}
return tracks;
}
function nearestTrack(px, edge) {
var best = 1, bestD = Infinity;
rowTracksTo(px).forEach(function (t, i) {
var d = Math.abs(px - t[edge]);
if (d < bestD) { bestD = d; best = i + 1; }
});
return best;
}
/* The row whose top is nearest a height in the grid, and whose bottom is. */
function rowLineAt(px) { return nearestTrack(px, 'top'); }
function rowEndAt(px) { return nearestTrack(px, 'bottom'); }
/* A row holding only one-row text cards is as tall as its text, so a title is
* not a band 15rem high. A text card made two rows high or more keeps the full
* rows, which is how a reader asks for a taller one, and a row with nothing in
* it stays full height, because a gap on a canvas is a gap.
*
* The first pass measures with no template, since a card with no saved position
* can only be found where the browser put it. */
function fitTextRows() {
if (!grid) return;
grid.style.removeProperty('grid-template-rows');
if (!grid.querySelector('.text-card')) return;
var tall = {}, text = {}, last = 0;
Array.from(grid.querySelectorAll('.visual-card')).forEach(function (card) {
var sp = spanOf(card);
var into = (card.classList.contains('text-card') && sp.h === 1) ? text : tall;
for (var r = sp.y; r < sp.y + sp.h; r++) into[r] = 1;
if (sp.y + sp.h - 1 > last) last = sp.y + sp.h - 1;
});
var rows = [];
for (var r = 1; r <= last; r++) rows.push(text[r] && !tall[r] ? 'auto' : TALL_ROW);
grid.style.setProperty('grid-template-rows', rows.join(' '));
}
/* ---- resize handles (3.2 grid span) ----
*
* Each card's bottom-right handle resizes its grid-column span (w) and
* grid-row span (h), snapped to whole columns and rows. The spans are
* written to the card's inline style as the size changes, so the cards
* reflow live, and the complete layout is PATCHed to
* /api/analyses/:id by saveLayout(). A reload renders the same geometry
* server-side, with no JavaScript involved.
*
* A corner drag resizes and does not move: x is left where the header drag put
* it (see "dragging a card to a grid cell"), so the widest a card can be is
* the columns left of it: 1 <= w <= 13 - x.
*
templates/web/en-us/canvas.html.tt view on Meta::CPAN
pushApart(card);
/* A drag changes the same value the keyboard does. */
var handle = card.querySelector('.visual-resize-handle');
if (handle) updateResizeAria(handle, card);
saveLayout();
}
document.addEventListener('pointermove', onResizeMove);
document.addEventListener('pointerup', onResizeEnd);
}
function initResizeHandles(root) {
if (!grid || !anaId) return;
(root || grid).querySelectorAll('.visual-resize-handle').forEach(function (handle) {
handle.addEventListener('pointerdown', onResizeStart);
handle.addEventListener('keydown', onResizeKey);
handle.addEventListener('blur', flushSave);
var card = handle.closest('.visual-card');
if (card) updateResizeAria(handle, card);
});
}
fitTextRows();
initResizeHandles();
/* ---- the size menu (3.2): width and height without a drag ----
*
* Each entry is a width in grid columns or a height in grid rows, applied
* through commitSize, so the menu and the corner grip end in the same layout
* and the same PATCH. Focus stays on the menu after a choice, which is where
* the reader already is: the size can be changed again, or tabbed away from,
* without hunting for the card again. The first option is not a choice but
* the size the card is; it is what the menu shows when the size came from
* somewhere else (a drag, an arrow key, a reload), while a choice made here
* stays selected, so the arrow keys walk the entries one after another
* instead of being pulled back to the top after every one.
*/
function initSizeMenus(root) {
if (!grid || !anaId) return;
(root || grid).querySelectorAll('.visual-size-select').forEach(function (sel) {
var card = sel.closest('.visual-card');
if (!card) return;
updateSizeControls(card);
sel.addEventListener('change', function () {
var raw = sel.value;
var index = sel.selectedIndex;
/* The first option says what the card is, not what it should
* become: choosing it again is not a choice. */
if (!raw) return;
var st = resizeState(card);
var isRow = raw.charAt(0) === 'h';
var value = parseInt(isRow ? raw.slice(1) : raw, 10);
/* Choosing the size the card already is should do nothing rather
* than re-announce itself, and leave the entry selected so the next
* arrow key carries on down the list. */
if (isNaN(value) || value === (isRow ? st.h : st.w)) return;
if (isRow) commitSize(card, st.w, value);
else commitSize(card, value, st.h);
/* The entry that was chosen stays chosen: the commit re-selects the
* summary, and a reader stepping down the list with the arrow keys
* would otherwise be pulled back to the top after every change. */
sel.selectedIndex = index;
});
});
}
initSizeMenus();
/* ---- cross-filter (3.3 URL-stage) ----
*
* Semantics: self-highlighting.
* - Clicking a mark on visual N navigates to ?cf=col:eq:val&cv=N.
* - On reload the server filters every visual except the source (cv=N).
* - The source card gets a blue border (.cf-source) to show it is the
* filter origin and is intentionally shown unfiltered.
* - Multi-select not supported: each click replaces any prior cross-filter.
* - Cross-filter respects each visual's own saved filters because the
* server applies ?cf= on top of them (see canvas_render in Dashboard.pm).
*
* extractCfValue(d) extracts the categorical value from a D3 datum.
* HTML::D3 uses these shapes depending on chart kind:
* bar/treemap : d = [label, value] (positional array)
* pie : d = { data:[label,value], ... } (pie arc datum)
* stacked : d = { cat, seg, val }
* combo/line : d = { x, bar_val, line_val } or { label, value }
* scatter : d = [x, y] -- less useful for CF; skipped when val==NaN
*/
function extractCfValue(d) {
if (d === undefined || d === null) return null;
/* A stacked segment's datum is a position in its group -- [row, column]
* -- carrying the row it came from in .data, so the category has to be
* read before the array is taken as the value: the array holds indexes,
* and the first of them is why every segment used to filter by "0". */
if (d.data && typeof d.data === 'object' && !Array.isArray(d.data)
&& d.data.cat !== undefined) {
return String(d.data.cat);
}
if (Array.isArray(d) && d.length >= 1) {
var v = d[0];
return (v !== null && v !== undefined) ? String(v) : null;
}
if (d.data) {
if (Array.isArray(d.data) && d.data.length >= 1) return String(d.data[0]);
if (d.data.label !== undefined) return String(d.data.label);
/* A treemap hands out a hierarchy node, and the category is the leaf
* it names: the id is the whole path down the tree
* ("Root/Gadget Pro"), so the part after the last slash is the tile. */
if (d.data.id !== undefined) {
var parts = String(d.data.id).split('/');
return parts[parts.length - 1] || null;
}
}
if (d.cat !== undefined) return String(d.cat);
if (d.label !== undefined) return String(d.label);
if (d.x !== undefined) return String(d.x);
return null;
}
/* The URL a cross-filter click asks for: one filter, replacing whatever
* filter is in force, and the card that was clicked named as the source so
* the server draws it in full and marks it. Everything else in the query
* string -- a bound parameter, a calculated column, a drill path -- is kept,
* because a click on a mark says what to filter by, not what to forget.
*
* The value goes in as it is, because searchParams encodes what it is given:
* encoding it here as well turned "Gadget Pro" into Gadget%2520Pro, and the
* canvas then filtered for a value no row has. */
function cfUrl(cfCol, op, val, visId) {
var u = new URL(window.location.href);
u.searchParams.delete('cf');
u.searchParams.delete('cv');
u.searchParams.append('cf', cfCol + ':' + op + ':' + val);
u.searchParams.set('cv', visId);
return u;
}
function initCrossFilters(root) {
if (typeof d3 === 'undefined') return;
var cards = cardsIn(root).filter(function (card) {
return card.hasAttribute('data-cf-col');
});
cards.forEach(function (card) {
var cfCol = card.getAttribute('data-cf-col');
var visId = card.getAttribute('data-visual');
if (!cfCol || visId === null) return;
templates/web/en-us/canvas.html.tt view on Meta::CPAN
option(sel, opts[i].value, opts[i].value);
}
}
}
var allCols = canvasColumns.map(function (c) { return { value: c.name }; });
var numCols = canvasColumns.filter(function (c) { return c.numeric; })
.map(function (c) { return { value: c.name }; });
var choose = [{ value: '', label: 'Choose a column\u2026' }];
var countOpt = [{ value: '__count__', label: 'Count (no column needed)' }];
fill(tableSel, allCols);
fill(catSel, choose.concat(allCols));
fill(seriesSel, choose.concat(allCols));
fill(valueSel, choose.concat(countOpt, allCols));
fill(xSel, choose.concat(allCols));
fill(ySel, choose.concat(numCols));
fill(barSel, choose.concat(numCols));
fill(lineSel, choose.concat(numCols));
fill(histSel, choose.concat(numCols));
fill(wcColSel, choose.concat(allCols));
fill(csColSel, choose.concat(numCols));
/* The two optional columns say "none" first, because a partition and a
* read order are choices a cross-row column can do without. */
fill(csOrderSel,
[{ value: '', label: '\u2014 none \u2014' }].concat(allCols));
fill(csBySel,
[{ value: '', label: '\u2014 the whole view \u2014' }].concat(allCols));
fill(mapLocSel, choose.concat(allCols));
if (mapLoc2Sel) fill(mapLoc2Sel, [{ value: '', label: '\u2014 nothing \u2014' }].concat(allCols));
fill(mapLatSel, choose.concat(numCols));
fill(mapLonSel, choose.concat(numCols));
/* Optional columns, so each says "none" first. */
fill(lineSeriesSel, [{ value: '', label: '\u2014 none \u2014' }].concat(allCols));
fill(scSeriesSel, [{ value: '', label: '\u2014 none \u2014' }].concat(allCols));
fill(scSizeSel, [{ value: '', label: '\u2014 none \u2014' }].concat(numCols));
/* The scheme colors series values and the radii size bubbles, so each
* waits for its column, as on the table page's scatter panel. */
function syncScatter() {
if (scSchemeSel) scSchemeSel.disabled = !(scSeriesSel && scSeriesSel.value);
var hasSize = !!(scSizeSel && scSizeSel.value);
if (scMinRInp) scMinRInp.disabled = !hasSize;
if (scMaxRInp) scMaxRInp.disabled = !hasSize;
}
if (scSeriesSel) scSeriesSel.addEventListener('change', syncScatter);
if (scSizeSel) scSizeSel.addEventListener('change', syncScatter);
/* A treemap's color aggregate and scale wait for its color column. */
fill(tmColorSel, [{ value: '', label: '\u2014 none \u2014' }].concat(allCols));
function syncTreemapColour() {
var on = !!(tmColorSel && tmColorSel.value);
if (tmColorAggSel) tmColorAggSel.disabled = !on;
if (tmColorSchemeSel) tmColorSchemeSel.disabled = !on;
}
if (tmColorSel) tmColorSel.addEventListener('change', syncTreemapColour);
/* A radius as the server takes it: a whole number from 1 to 40. */
function scRadius(inp, dflt) {
var n = parseInt(inp.value, 10);
if (isNaN(n)) n = dflt;
return Math.min(40, Math.max(1, n));
}
/* The views whose value column is aggregated, and so the only ones that
* can use an aggregate function of their own. */
var AGG_KINDS = { bar: 1, pie: 1, stacked: 1, treemap: 1, heatmap: 1, combo: 1 };
/* A percentile is written into the function name -- p95 -- because a card
* stores one key for its aggregate, as a pivot measure does. Reading the
* level back clamps it, so the panel cannot build a name the server would
* have to refuse. */
function percentileLevel(input) {
var n = parseInt(input.value, 10);
if (!isFinite(n)) return 95;
return Math.min(100, Math.max(1, n));
}
function aggregateValue(kind) {
if (!aggSel || !AGG_KINDS[kind]) return '';
if (aggSel.value === 'p') return 'p' + percentileLevel(pctInp);
return aggSel.value; /* '' is the default: sum, or count rows */
}
/* ---- the card's own cross-row columns ----
*
* The page's cs= belongs to the page. A card either inherits it, has
* none (so a canvas full of running totals can hold one card of raw
* numbers), or brings a plan of its own, which the server stores as
* { cs, by, order } on the visual and validates against the columns
* every time the card is drawn.
*
* A plan is a list, so the fields describe one column at a time and Add
* this column puts it in csSpecs, which is drawn as a removable chip per
* column. The list is what the card carries: what is on screen is what
* is sent, and nothing is taken out of it behind the reader's back. With
* no list at all the fields themselves are the single column, so one
* column needs no second click.
*/
var csAliasTouched = false;
var csSpecs = []; /* { spec, alias, label, needsOrder } */
function csMeta() {
var opt = csFnSel ? csFnSel.options[csFnSel.selectedIndex] : null;
return {
arg: !!opt && opt.getAttribute('data-arg') === '1',
order: !!opt && opt.getAttribute('data-order') === '1',
};
}
/* A column name has to be usable in a URL and as a column, and the
* column it comes from may hold anything at all ("Unit price ($)"), so
* the suggestion is reduced to letters, digits and underscores. */
function csSlug(text) {
var s = String(text || '').toLowerCase()
.replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '');
if (!s) return 'value';
if (/^[0-9]/.test(s)) s = 'c_' + s;
return s;
}
templates/web/en-us/canvas.html.tt view on Meta::CPAN
editError.hidden = !message;
};
/* The title is the card's own words, or the server's derived one
* when the card never had a title of its own. Every control that
* names the card in its accessible name follows it. */
var editSetTitle = function (card, title) {
var titleEl = card.querySelector('.visual-card-title');
if (titleEl) titleEl.textContent = title;
var handle = card.querySelector('.drag-handle');
if (handle) handle.setAttribute('aria-label', 'Move ' + title);
var size = card.querySelector('.visual-size-select');
if (size) size.setAttribute('aria-label', 'Size of ' + title);
var dl = card.querySelector('.visual-dl-group');
if (dl) dl.setAttribute('data-title', title);
};
var editFill = function (sel, columns, selected) {
sel.innerHTML = '';
var seen = {};
var add = function (value, label) {
if (seen[value]) return;
seen[value] = 1;
var opt = document.createElement('option');
opt.value = value;
opt.textContent = label;
sel.appendChild(opt);
};
add('', 'Choose a column\u2026');
columns.forEach(function (name) { add(name, name); });
/* A saved column is offered even when the sampler did not call
* it numeric: the server, not this list, decides what a
* coordinate column is, and the card's own value must be
* selectable. */
if (selected && !seen[selected]) add(selected, selected);
sel.value = selected || '';
};
var editPosition = function () {
if (!editTarget) return;
var r = editTarget.btn.getBoundingClientRect();
var w = editPanel.offsetWidth;
var left = Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8));
editPanel.style.left = left + 'px';
editPanel.style.top = (r.bottom + 4) + 'px';
editPanel.style.right = 'auto';
editPanel.style.maxHeight = Math.max(160, window.innerHeight - r.bottom - 12) + 'px';
};
var editClose = function (returnFocus) {
var target = editTarget;
editPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
editTarget = null;
editLoaded = false;
if (returnFocus && target) target.btn.focus();
};
var editOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
/* A second press on the same control closes it, like the other
* panel on this toolbar. */
if (!editPanel.hidden && editTarget && editTarget.card === card) {
editClose(1);
return;
}
if (editTarget) editTarget.btn.setAttribute('aria-expanded', 'false');
editTarget = { card: card, btn: btn, index: index };
btn.setAttribute('aria-expanded', 'true');
editPanel.hidden = false;
editLoaded = false;
editSave.disabled = true;
editSave.textContent = 'Save columns';
editLoc.innerHTML = '<option value="">Loading\u2026</option>';
if (editLoc2) editLoc2.innerHTML = '';
editLat.innerHTML = '';
editLon.innerHTML = '';
editSetError('');
editPosition();
editLoc.focus();
fetch('/api/analyses/' + encodeURIComponent(anaId))
.then(function (r) { return r.json(); })
.then(function (analysis) {
if (!editTarget || editTarget.card !== card) return;
var vis = (analysis && analysis.visuals && analysis.visuals[index]) || null;
if (!vis || vis.kind !== 'map') {
editSetError('This card is no longer a map. Reload the canvas to see its current columns.');
return;
}
var enc = vis.encode || {};
var numeric = canvasColumns.filter(function (c) { return c.numeric; })
.map(function (c) { return c.name; });
var all = canvasColumns.map(function (c) { return c.name; });
var locs = Array.isArray(enc.loc) ? enc.loc : (enc.loc ? [enc.loc] : []);
editFill(editLoc, all, locs[0] || '');
if (editLoc2) {
editFill(editLoc2, all, locs[1] || '');
editLoc2.options[0].textContent = '\u2014 nothing \u2014';
}
editLocRest = locs.slice(2);
editFill(editLat, numeric, enc.lat || '');
editFill(editLon, numeric, enc.lon || '');
editLoaded = true;
editSave.disabled = false;
})
.catch(function () {
if (editTarget && editTarget.card === card) {
editSetError('Could not read the card\u2019s columns. Check the connection and try again.');
}
});
};
/* Delegated: the cards appended in place carry the same button but
* no listener of their own. */
grid.addEventListener('click', function (e) {
var btn = e.target.closest('.visual-edit-btn');
if (!btn) return;
templates/web/en-us/canvas.html.tt view on Meta::CPAN
txFont.value = o.font || '';
txSize.value = o.size || '';
txAlign.value = o.align || 'left';
txColourAuto.checked = !o.colour;
if (o.colour) txColour.value = o.colour;
txBackNone.checked = !o.background;
if (o.background) txBack.value = o.background;
txBold.checked = !!o.bold;
txItalic.checked = !!o.italic;
txPlain.checked = !!o.plain;
};
var txPosition = function () {
var r = txAnchor.getBoundingClientRect();
var w = txPanel.offsetWidth;
var left = Math.max(8, Math.min(r.left, window.innerWidth - w - 8));
var top = Math.max(8, r.bottom + 4);
txPanel.style.left = left + 'px';
txPanel.style.top = top + 'px';
txPanel.style.right = 'auto';
txPanel.style.maxHeight = Math.max(160, window.innerHeight - top - 12) + 'px';
};
var txClose = function (returnFocus, saved) {
if (txPanel.hidden) return;
txPanel.hidden = true;
txAnchor.setAttribute('aria-expanded', 'false');
if (txTarget && !saved) {
var body = txTarget.card.querySelector('.visual-card-body');
if (body) body.innerHTML = txTarget.html;
}
var back = txAnchor;
txTarget = null;
txAnchor = txBtn;
if (returnFocus) back.focus();
};
var txShow = function (anchor) {
txAnchor = anchor;
anchor.setAttribute('aria-expanded', 'true');
txPanel.hidden = false;
txSetError('');
txSave.disabled = false;
txPosition();
txText.focus();
};
txBlank = txRead();
var txOpenAdd = function () {
txHeading.textContent = 'Add text';
txSave.textContent = 'Add to canvas';
txRemove.hidden = true;
txFill(txBlank);
txRefresh();
txShow(txBtn);
};
var txOpenEdit = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
var body = card.querySelector('.visual-card-body');
txClose(0);
txHeading.textContent = 'Edit text';
txSave.textContent = 'Save text';
txRemove.hidden = false;
txShow(btn);
txSave.disabled = true;
fetch('/api/analyses/' + encodeURIComponent(anaId))
.then(function (r) { return r.json(); })
.then(function (analysis) {
if (txPanel.hidden || txAnchor !== btn) return;
var vis = (analysis && analysis.visuals && analysis.visuals[index]) || null;
if (!vis || vis.kind !== 'text') {
txSetError('This card has changed. Reload the canvas to see it.');
return;
}
txFill(vis.options || {});
txTarget = { card: card, btn: btn, index: index, html: body ? body.innerHTML : '' };
txRefresh();
txSave.disabled = false;
txPosition();
})
.catch(function () {
txSetError('Could not read the card. Check the connection and try again.');
});
};
txBtn.addEventListener('click', function () {
if (!txPanel.hidden && !txTarget) txClose(1);
else { txClose(0); txOpenAdd(); }
});
/* Delegated, because a card added in place has no listeners of its own.
* A second press on the same button closes the panel, as on the map card. */
grid.addEventListener('click', function (e) {
var btn = e.target.closest('.visual-text-btn');
if (!btn) return;
var card = btn.closest('.visual-card');
if (!card) return;
if (!txPanel.hidden && txAnchor === btn) txClose(1);
else txOpenEdit(card, btn);
});
grid.addEventListener('dblclick', function (e) {
var body = e.target.closest('.text-card .visual-card-body');
var card = body && body.closest('.visual-card');
var btn = card && card.querySelector('.visual-text-btn');
if (btn) txOpenEdit(card, btn);
});
txForm.addEventListener('input', txRefresh);
txForm.addEventListener('change', txRefresh);
/* Picking a color is choosing one: the box that said otherwise follows. */
txColour.addEventListener('input', function () { txColourAuto.checked = false; txRefresh(); });
txBack.addEventListener('input', function () { txBackNone.checked = false; txRefresh(); });
field('cancel').addEventListener('click', function () { txClose(1); });
txPanel.addEventListener('keydown', function (e) {
if (e.key === 'Escape') { e.preventDefault(); txClose(1); }
});
templates/web/en-us/canvas.html.tt view on Meta::CPAN
});
};
txForm.addEventListener('submit', function (e) {
e.preventDefault();
txSetError('');
var o = txRead();
if (!/\S/.test(o.text)) {
txSetError('Type some text first.');
txText.focus();
return;
}
var base = '/api/analyses/' + encodeURIComponent(anaId) + '/visuals';
var target = txTarget;
txSave.disabled = true;
if (!target) {
txRequest(base, 'POST', { kind: 'text', options: o }).then(function (json) {
txClose(0, true);
appendCard(json);
}).catch(function (err) {
txSetError(err.message);
txSave.disabled = false;
});
return;
}
txRequest(base + '/' + target.index, 'PATCH', { options: o }).then(function (json) {
var card = target.card;
var body = card.querySelector('.visual-card-body');
if (body) body.innerHTML = json.html;
card.classList.toggle('text-card-plain', !!json.plain);
var title = json.title || 'Text';
var titleEl = card.querySelector('.visual-card-title');
if (titleEl) titleEl.textContent = title;
var handle = card.querySelector('.drag-handle');
if (handle) handle.setAttribute('aria-label', 'Move ' + title);
var size = card.querySelector('.visual-size-select');
if (size) size.setAttribute('aria-label', 'Size of ' + title);
target.btn.setAttribute('aria-label', 'Edit ' + title);
txClose(1, true);
fitTextRows();
announce('Text "' + title + '" saved.');
}).catch(function (err) {
txSetError(err.message);
txSave.disabled = false;
});
});
/* The cards after this one are renumbered, so the page is drawn again,
* with a cross-filter's source card moved down to match. */
txRemove.addEventListener('click', function () {
var target = txTarget;
if (!target || !confirm('Remove this text from the canvas?\n\nThis cannot be undone.')) return;
txRemove.disabled = true;
txRequest('/api/analyses/' + encodeURIComponent(anaId) + '/visuals/' + target.index, 'DELETE')
.then(function () {
var u = new URL(window.location.href);
var cv = parseInt(u.searchParams.get('cv'), 10);
if (!isNaN(cv) && cv > target.index) u.searchParams.set('cv', String(cv - 1));
window.location.replace(u.toString());
})
.catch(function (err) {
txSetError(err.message);
txRemove.disabled = false;
});
});
}());
/* ---- editing a card's cross-row plan in place ----
*
* A card's plan is stored data like its columns, so it is repaired where
* the card is: the header button opens this panel with the plan the server
* holds, the reader changes the list of columns, and one PATCH replaces the
* plan while the place in the layout, the size and the title stay. The
* list is the plan, as it is in Add current view, because a plan that names
* a column this canvas no longer has has to be fixable one chip at a time
* rather than rebuilt from nothing.
*/
var crPanel = document.getElementById('cr-panel');
var crForm = document.getElementById('cr-form');
var crMode = document.getElementById('cr-mode');
var crFields = document.getElementById('cr-fields');
var crList = document.getElementById('cr-list');
var crEmpty = document.getElementById('cr-empty');
var crCol = document.getElementById('cr-col');
var crFn = document.getElementById('cr-fn');
var crWinField = document.getElementById('cr-window-field');
var crWin = document.getElementById('cr-window');
var crAlias = document.getElementById('cr-alias');
var crOrder = document.getElementById('cr-order');
var crDir = document.getElementById('cr-dir');
var crBy = document.getElementById('cr-by');
var crAdd = document.getElementById('cr-add');
var crSave = document.getElementById('cr-save');
var crCancel = document.getElementById('cr-cancel');
var crStop = document.getElementById('cr-add-cancel');
var crError = document.getElementById('cr-error');
var crWarning = document.getElementById('cr-warning');
if (crPanel && crForm && crMode && crFields && crList && crCol && crFn
&& crOrder && crBy && crSave && crError) {
var crTarget = null; /* { card, btn, index } */
var crLoaded = false;
var crSpecs = []; /* { spec, alias, label, needsOrder } */
/* The columns this card plots that a plan makes: the names its encode
* points at that its plan produces. Renaming one of those leaves the
* plot pointing at a column no card has. */
var crPlotted = [];
/* The card's columns, when it holds them as a list -- a table does, a
* chart names one column per job. A list is what a stranded column can
* be taken off, so a repair the server would refuse becomes one save. */
var crCardColumns = null;
var crCardEncode = null; /* the card's encode, as it was opened */
/* The aliases of the plan the card had when it was opened, in order:
* a chip renamed where it stands is the same column under a new name,
* and this is what says which new name belongs to which old one. */
var crPlanSaved = null;
var crTouched = false; /* the name box has been edited */
var crEditing = -1; /* the chip the fields are describing, or -1 */
templates/web/en-us/canvas.html.tt view on Meta::CPAN
crSetError('Name the new column with letters, digits and underscores, starting with a letter or underscore.');
crAlias.focus();
return undefined;
}
if (crAliasTaken(alias)) {
crSetError('"' + alias + '" is already a column here. Give this one a name of its own.');
crAlias.focus();
return undefined;
}
var m = crMeta();
var spec = col + ':' + crFn.value + ':' + alias;
if (m.arg) {
var win = parseInt(crWin.value, 10);
if (!(win > 0)) {
crSetError('A moving total needs a window of at least one row.');
crWin.focus();
return undefined;
}
spec += ':' + win;
}
return crSpecEntry(spec);
};
/* The panel is tall - the list, seven fields and the buttons - and the
* card that opened it may be near the foot of the window. It opens
* below the header when there is room there, and above it when there is
* more room above; either way it is never taller than the room it has,
* and scrolls rather than hiding its Save button under the frame. */
var crPosition = function () {
if (!crTarget) return;
var r = crTarget.btn.getBoundingClientRect();
var w = crPanel.offsetWidth;
var left = Math.max(8, Math.min(r.right - w, window.innerWidth - w - 8));
var below = window.innerHeight - r.bottom - 12;
var above = r.top - 12;
var want = crPanel.scrollHeight + 2; /* the height it would like */
var up = below < want && above > below;
var max = Math.max(180, up ? above : below);
var top = up
? Math.max(8, r.top - 4 - Math.min(want, max))
: r.bottom + 4;
crPanel.style.left = left + 'px';
crPanel.style.top = top + 'px';
crPanel.style.right = 'auto';
crPanel.style.maxHeight = max + 'px';
};
var crClose = function (returnFocus) {
var target = crTarget;
crPanel.hidden = true;
if (target) target.btn.setAttribute('aria-expanded', 'false');
crTarget = null;
crLoaded = false;
crEditing = -1;
if (returnFocus && target) target.btn.focus();
};
var crOpen = function (card, btn) {
var index = parseInt(card.getAttribute('data-visual'), 10);
if (isNaN(index)) return;
if (!crPanel.hidden && crTarget && crTarget.card === card) {
crClose(1);
return;
}
if (crTarget) crTarget.btn.setAttribute('aria-expanded', 'false');
crTarget = { card: card, btn: btn, index: index };
crLoaded = false;
crSpecs = [];
crTouched = false;
crEditing = -1;
crOrderSaved = [];
crOrderShown = null;
crPlotted = [];
crCardColumns = null;
crCardEncode = null;
crPlanSaved = null;
crWarning.textContent = '';
crWarning.hidden = true;
crAdd.textContent = 'Add this column';
if (crStop) crStop.hidden = true;
btn.setAttribute('aria-expanded', 'true');
crPanel.hidden = false;
crSave.disabled = true;
crSave.textContent = 'Save columns';
crMode.value = 'inherit';
crFields.hidden = true;
crList.innerHTML = '';
crAlias.value = '';
crEmpty.textContent = 'Loading\u2026';
crEmpty.hidden = false;
crSetError('');
crPosition();
crMode.focus();
var all = canvasColumns.map(function (c) { return c.name; });
var num = canvasColumns.filter(function (c) { return c.numeric; })
.map(function (c) { return c.name; });
fetch('/api/analyses/' + encodeURIComponent(anaId))
.then(function (r) { return r.json(); })
.then(function (analysis) {
if (!crTarget || crTarget.card !== card) return;
var vis = (analysis && analysis.visuals && analysis.visuals[index]) || null;
if (!vis) {
crSetError('This card is no longer on the canvas. Reload it to see its current columns.');
return;
}
var plan = vis.cross_row;
var specs = (plan && typeof plan === 'object' && plan.cs && plan.cs.length) ? plan.cs : [];
crSpecs = specs.map(crSpecEntry);
crOrderSaved = (plan && typeof plan === 'object' && plan.order) ? plan.order : [];
var first = crOrderSaved.length ? String(crOrderSaved[0]).split(':') : null;
crOrderShown = first
? { col: first[0] || '', dir: (first[1] || 'asc').toLowerCase() }
: { col: '', dir: 'asc' };
( run in 1.097 second using v1.01-cache-2.11-cpan-60884a8df76 )