blob: 83f997e0c0dfa8de21c95c5705b6d4604a98c08c [file] [log] [blame]
/* Keep large custom definitions in the fragment: they must not exceed server URL limits. */
(function (root) {
'use strict';
const axes = ['x', 'y', 'color'];
function read(url, presets) {
const params = url.searchParams;
const fragment = new URLSearchParams(url.hash.slice(1).split('&').slice(1).join('&'));
if (!axes.some(axis => params.has('sd_' + axis)) && !params.has('sd_layout') && !fragment.has('sd_custom')) return null;
const custom = JSON.parse(fragment.get('sd_custom') || '{}');
const defaults = ['Wohlstand', presets.Valenz ? 'Valenz' : '', 'Gender'];
const rows = axes.map((axis, i) => {
const choice = params.has('sd_' + axis) ? params.get('sd_' + axis) : defaults[i];
if (choice === 'custom') {
const d = custom[axis];
if (!d || typeof d.name !== 'string' || typeof d.pairs !== 'string') throw new Error('Invalid custom dimension: ' + axis);
return {choice:'__custom', name:d.name, pairs:d.pairs};
}
if ((!choice && i === 0) || (choice && !Object.prototype.hasOwnProperty.call(presets, choice))) throw new Error('Unknown dimension: ' + choice);
return {choice, name:choice, pairs:choice ? presets[choice].map(p => p.join('; ')).join('\n') : ''};
});
const layout = params.get('sd_layout') || 'horizontal';
if (!['horizontal','vertical'].includes(layout)) throw new Error('Unknown layout: ' + layout);
return {rows, layout};
}
function write(url, rows, layout, presets) {
const custom = {};
rows.forEach((row,i) => {
const preset = presets[row.choice];
const unchanged = preset && row.name === row.choice && JSON.stringify(row.pairs.split(/\r?\n/).filter(line => line.trim()).map(line => line.split(';').map(word => word.trim()))) === JSON.stringify(preset);
url.searchParams.set('sd_' + axes[i], !row.choice ? '' : unchanged ? row.choice : 'custom');
if (row.choice && !unchanged) custom[axes[i]] = {name:row.name,pairs:row.pairs};
});
url.searchParams.set('sd_layout',layout);
const fragment = new URLSearchParams(url.hash.slice(1).split('&').slice(1).join('&'));
fragment.delete('sd_custom');
if (Object.keys(custom).length) fragment.set('sd_custom',JSON.stringify(custom));
url.hash = (url.hash.slice(1).split('&')[0] || 'semantic-dimensions') + (fragment.size ? '&'+fragment : '');
return url;
}
const api = {read,write};
if (typeof module !== 'undefined') module.exports = api;
else root.semanticDimensionsURL = api;
}(typeof window === 'undefined' ? this : window));