latest changes
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
(() => {
|
||||
const grid = document.querySelector('#widget-grid');
|
||||
const toggle = document.querySelector('#companion-toggle');
|
||||
if (!grid || !toggle || !window.BrowserCompanion) return;
|
||||
const motion = matchMedia('(prefers-reduced-motion: reduce)');
|
||||
const dark = matchMedia('(prefers-color-scheme: dark)');
|
||||
const name = () => {
|
||||
const theme = document.documentElement.dataset.theme;
|
||||
return theme === 'dark' || (theme !== 'light' && dark.matches) ? 'Dahlia' : 'Pixel';
|
||||
};
|
||||
let companion = null;
|
||||
let refreshFrame = 0;
|
||||
let refreshTimer = 0;
|
||||
let lastRefresh = 0;
|
||||
const refresh = () => {
|
||||
if (refreshTimer || refreshFrame) return;
|
||||
refreshTimer = setTimeout(() => {
|
||||
refreshTimer = 0;
|
||||
refreshFrame = requestAnimationFrame(() => {
|
||||
refreshFrame = 0;
|
||||
lastRefresh = performance.now();
|
||||
companion?.refresh();
|
||||
});
|
||||
}, Math.max(0, 50 - (performance.now() - lastRefresh)));
|
||||
};
|
||||
const setVisible = visible => {
|
||||
if (visible && !companion) companion = new window.BrowserCompanion({
|
||||
root: document.body,
|
||||
surfaces: () => [...grid.querySelectorAll('[data-widget-platform="bottom"]')].flatMap(card => {
|
||||
const body = card.querySelector('.widget-body');
|
||||
const firstLevel = body ? [...body.children] : [];
|
||||
const candidates = [card.querySelector('.widget-card-head'), ...firstLevel];
|
||||
// Structural sections can contain the actual bordered ledges one level down.
|
||||
for (const child of firstLevel) {
|
||||
if (child.tagName === 'SECTION' || child.classList.contains('rain-layout'))
|
||||
candidates.push(...child.children);
|
||||
}
|
||||
// The radar's visible frame is nested in layout wrappers and is a useful ledge.
|
||||
const radarFrames = body ? [...body.querySelectorAll('.rain-radar-frame')] : [];
|
||||
candidates.push(...radarFrames);
|
||||
const cardRect = card.getBoundingClientRect();
|
||||
const tops = [...new Set(candidates)].filter(element => {
|
||||
if (!element || element.matches('button, input, select, textarea, a, [role="button"]')) return false;
|
||||
const rect = element.getBoundingClientRect();
|
||||
return rect.width >= 18 && rect.height >= 12 && rect.top > cardRect.top + 12 && rect.top < cardRect.bottom - 12;
|
||||
}).map(element => ({ element, edge: 'top', card }));
|
||||
return [{ element: card, edge: 'bottom', card, explicit: true }, ...tops,
|
||||
...radarFrames.map(element => ({ element, edge: 'bottom', card })),
|
||||
{ element: card, edge: 'top', card, explicit: true }];
|
||||
}),
|
||||
reducedMotion: () => motion.matches,
|
||||
name,
|
||||
debug: new URLSearchParams(location.search).has('companionDebug'),
|
||||
debugSpeed: new URLSearchParams(location.search).has('companionFast') ? 10 : 1,
|
||||
});
|
||||
if (!visible && companion) { companion.destroy(); companion = null; }
|
||||
toggle.setAttribute('aria-pressed', String(visible));
|
||||
toggle.textContent = visible ? 'Hide companion' : 'Show companion';
|
||||
try { localStorage.setItem('dashboard-companion-visible', String(visible)); } catch (_) { /* Optional preference. */ }
|
||||
};
|
||||
toggle.addEventListener('click', () => setVisible(!companion));
|
||||
const observer = new MutationObserver(refresh);
|
||||
observer.observe(grid, { childList: true, subtree: true, attributes: true, attributeFilter: ['data-span', 'class', 'style', 'hidden'] });
|
||||
const resize = new ResizeObserver(refresh);
|
||||
resize.observe(grid);
|
||||
window.addEventListener('resize', refresh, { passive: true });
|
||||
window.addEventListener('scroll', refresh, { passive: true });
|
||||
motion.addEventListener('change', () => companion?.setReducedMotion(motion.matches));
|
||||
dark.addEventListener('change', () => { companion?.setName(name()); refresh(); });
|
||||
new MutationObserver(() => { companion?.setName(name()); refresh(); }).observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class', 'style'] });
|
||||
document.addEventListener('htmx:afterSwap', refresh);
|
||||
document.addEventListener('dashboard:widget-mounted', refresh);
|
||||
document.addEventListener('dashboard:widget-unmounted', refresh);
|
||||
try { setVisible(localStorage.getItem('dashboard-companion-visible') !== 'false'); }
|
||||
catch (_) { setVisible(true); }
|
||||
})();
|
||||
@@ -0,0 +1,11 @@
|
||||
.companion-box{position:fixed;top:0;left:0;z-index:40;width:18px;height:18px;margin:-18px 0 0 -9px;border:3px solid #155e75;border-radius:3px;background:#ecfeff;pointer-events:none;will-change:transform}
|
||||
.companion-box[hidden]{display:none}
|
||||
.companion-box span{position:absolute;left:50%;bottom:22px;transform:translateX(-50%);white-space:nowrap;padding:2px 6px;border:1px solid var(--border);border-radius:5px;background:var(--surface);color:var(--text);font-size:10px;font-weight:700;box-shadow:var(--shadow)}
|
||||
.companion-box[data-state="walking"]{border-color:#166534}.companion-box[data-state="jumping"]{border-color:#7c3aed}.companion-box[data-state="purring"]{border-color:#be185d}.companion-box[data-state="batting"]{border-color:#b45309}.companion-box[data-state="sleeping"]{border-color:#475569}
|
||||
.companion-box[data-state="climbing"]{border-color:#0f766e}.companion-box[data-state="pulling-up"]{border-color:#a21caf}.companion-box[data-state="climb-hopping"]{border-color:#a16207}.companion-box[data-state="landing"]{border-color:#1d4ed8}
|
||||
.companion-debug{position:fixed;inset:0;pointer-events:none;z-index:39}.companion-debug i{position:absolute;display:block}.companion-debug-surface{border-top:2px solid #1d4ed8}.companion-debug-edge{border-left:2px dashed #a21caf}.companion-debug span{position:fixed;right:8px;bottom:8px;max-width:min(90vw,460px);padding:5px 8px;background:var(--surface);color:var(--text);border:1px solid var(--border);font:11px/1.4 monospace}
|
||||
.companion-debug-route{height:0;border-top:1px dashed #047857;transform-origin:0 0}.companion-debug-rejected{width:6px;height:6px;border:1px solid #b91c1c;border-radius:50%}
|
||||
@media(prefers-color-scheme:dark){.companion-box{background:#172c32;border-color:#67e8f9}.companion-box[data-state="walking"]{border-color:#86efac}.companion-box[data-state="jumping"]{border-color:#c4b5fd}.companion-box[data-state="purring"]{border-color:#f9a8d4}.companion-box[data-state="batting"]{border-color:#fcd34d}.companion-box[data-state="sleeping"]{border-color:#cbd5e1}}
|
||||
[data-theme="dark"] .companion-box{background:#172c32;border-color:#67e8f9}[data-theme="dark"] .companion-box[data-state="walking"]{border-color:#86efac}[data-theme="dark"] .companion-box[data-state="jumping"]{border-color:#c4b5fd}[data-theme="dark"] .companion-box[data-state="purring"]{border-color:#f9a8d4}[data-theme="dark"] .companion-box[data-state="batting"]{border-color:#fcd34d}[data-theme="dark"] .companion-box[data-state="sleeping"]{border-color:#cbd5e1}
|
||||
[data-theme="light"] .companion-box{background:#ecfeff;border-color:#155e75}[data-theme="light"] .companion-box[data-state="walking"]{border-color:#166534}[data-theme="light"] .companion-box[data-state="jumping"]{border-color:#7c3aed}[data-theme="light"] .companion-box[data-state="purring"]{border-color:#be185d}[data-theme="light"] .companion-box[data-state="batting"]{border-color:#b45309}[data-theme="light"] .companion-box[data-state="sleeping"]{border-color:#475569}
|
||||
@media(prefers-reduced-motion:reduce){.companion-box{will-change:auto}}
|
||||
@@ -0,0 +1,578 @@
|
||||
/* Portable companion movement. The host supplies visible surfaces and preferences. */
|
||||
(() => {
|
||||
'use strict';
|
||||
const STATES = ['idle', 'walking', 'jumping', 'landing', 'climbing', 'pulling-up', 'climb-hopping', 'purring', 'batting', 'sleeping'];
|
||||
const DEFAULTS = Object.freeze({ bodySize: 18, maxJumpHorizontalS: 3, maxJumpRiseS: 1.5,
|
||||
maxJumpDropS: 2, preferredJumpHorizontalS: 1.8, maxStepUpS: .3, minClimbHeightS: 1,
|
||||
climbSpeedSPerSec: 1.2, walkSpeedSPerSec: 2, jumpDurationMinMs: 350,
|
||||
jumpDurationMaxMs: 650, pullUpDurationMinMs: 400, pullUpDurationMaxMs: 700,
|
||||
buttWiggleChance: .25, climbHopChance: .15, climbHopMaxDistanceS: .8,
|
||||
minLandingWidthS: .8, edgeClearanceS: .15, centerRightPreference: .7,
|
||||
maxRouteTransitions: 16, stuckTimeoutMs: 4000,
|
||||
idleMinMs: 12000, idleMaxMs: 20000, sleepMinMs: 20000, sleepMaxMs: 45000,
|
||||
emoteMinMs: 2200, emoteMaxMs: 3800, emoteCooldownMs: 16000,
|
||||
sleepCooldownMs: 90000, activeMinTransitions: 2, activeMaxTransitions: 5,
|
||||
activeMovePauseMs: 450, activeChance: .65, sleepChance: .12, emoteChance: .32 });
|
||||
const LIMITS = { bodySize: [8, 80], maxJumpHorizontalS: [.5, 6], maxJumpRiseS: [.2, 3],
|
||||
maxJumpDropS: [.2, 4], preferredJumpHorizontalS: [.3, 4], maxStepUpS: [0, 1],
|
||||
minClimbHeightS: [.3, 4], climbSpeedSPerSec: [.2, 5], walkSpeedSPerSec: [.2, 6],
|
||||
jumpDurationMinMs: [150, 1500], jumpDurationMaxMs: [200, 2000],
|
||||
pullUpDurationMinMs: [150, 1500], pullUpDurationMaxMs: [200, 2000],
|
||||
buttWiggleChance: [0, 1], climbHopChance: [0, 1], climbHopMaxDistanceS: [.1, 2],
|
||||
minLandingWidthS: [.5, 3], edgeClearanceS: [0, .8], centerRightPreference: [0, 1],
|
||||
maxRouteTransitions: [2, 40], stuckTimeoutMs: [500, 15000],
|
||||
idleMinMs: [10000, 120000], idleMaxMs: [10000, 180000],
|
||||
sleepMinMs: [10000, 180000], sleepMaxMs: [10000, 300000],
|
||||
emoteMinMs: [800, 15000], emoteMaxMs: [800, 20000],
|
||||
emoteCooldownMs: [1000, 120000], sleepCooldownMs: [10000, 600000],
|
||||
activeMinTransitions: [1, 12], activeMaxTransitions: [1, 20],
|
||||
activeMovePauseMs: [100, 3000], activeChance: [0, 1],
|
||||
sleepChance: [0, 1], emoteChance: [0, 1] };
|
||||
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
|
||||
function configure(overrides = {}) {
|
||||
if (!overrides || typeof overrides !== 'object') overrides = {};
|
||||
const result = {};
|
||||
for (const [key, value] of Object.entries(DEFAULTS)) {
|
||||
const proposed = overrides[key];
|
||||
result[key] = typeof proposed === 'number' && Number.isFinite(proposed)
|
||||
? clamp(proposed, ...LIMITS[key]) : value;
|
||||
}
|
||||
result.preferredJumpHorizontalS = Math.min(result.preferredJumpHorizontalS, result.maxJumpHorizontalS);
|
||||
result.jumpDurationMaxMs = Math.max(result.jumpDurationMinMs, result.jumpDurationMaxMs);
|
||||
result.pullUpDurationMaxMs = Math.max(result.pullUpDurationMinMs, result.pullUpDurationMaxMs);
|
||||
result.idleMaxMs = Math.max(result.idleMinMs, result.idleMaxMs);
|
||||
result.sleepMaxMs = Math.max(result.sleepMinMs, result.sleepMaxMs);
|
||||
result.emoteMaxMs = Math.max(result.emoteMinMs, result.emoteMaxMs);
|
||||
result.activeMaxTransitions = Math.max(result.activeMinTransitions, result.activeMaxTransitions);
|
||||
return result;
|
||||
}
|
||||
const gap = (a, b) => Math.max(0, b.left - a.right, a.left - b.right);
|
||||
const landingX = (surface, fromX, config) => clamp(fromX, surface.left + config.bodySize / 2 + config.edgeClearanceS * config.bodySize,
|
||||
surface.right - config.bodySize / 2 - config.edgeClearanceS * config.bodySize);
|
||||
function jumpAnchors(source, target, rise, config) {
|
||||
const size = config.bodySize, clearance = size * config.edgeClearanceS;
|
||||
let fromX = landingX(source, (target.left + target.right) / 2, config);
|
||||
if (rise > config.maxStepUpS * size) {
|
||||
const outside = [target.left - size / 2 - clearance, target.right + size / 2 + clearance]
|
||||
.map(x => landingX(source, x, config))
|
||||
.filter(x => x + size / 2 + clearance <= target.left || x - size / 2 - clearance >= target.right);
|
||||
if (!outside.length) return null;
|
||||
fromX = outside.sort((a, b) => Math.abs(a - target.left) - Math.abs(b - target.left))[0];
|
||||
} else if (rise < -config.maxStepUpS * size) {
|
||||
const sides = [source.left + size / 2 + clearance, source.right - size / 2 - clearance];
|
||||
fromX = sides.sort((a, b) => Math.abs(landingX(target, a, config) - a) -
|
||||
Math.abs(landingX(target, b, config) - b))[0];
|
||||
}
|
||||
return { fromX, toX: landingX(target, fromX, config) };
|
||||
}
|
||||
function targetArcClear(source, target, fromX, toX, rise, config) {
|
||||
if (rise <= config.maxStepUpS * config.bodySize) return true;
|
||||
const size = config.bodySize, arc = Math.max(size * .65, rise + size * .5);
|
||||
for (let step = 1; step < 10; step++) {
|
||||
const t = step / 10, x = fromX + (toX - fromX) * t;
|
||||
const y = source.y + (target.y - source.y) * t - Math.sin(Math.PI * t) * arc;
|
||||
if (x + size / 2 > target.rect.left && x - size / 2 < target.rect.right &&
|
||||
y > target.rect.top + .5 && y - size < target.rect.bottom) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
function visibleBorder(style, side) {
|
||||
if (!style || ['none', 'hidden'].includes(style[`border${side}Style`]) ||
|
||||
parseFloat(style[`border${side}Width`]) < 1) return false;
|
||||
const color = style[`border${side}Color`]?.trim().toLowerCase() || '';
|
||||
if (color === 'transparent') return false;
|
||||
const alpha = color.match(/(?:rgba\([^)]*,\s*|rgb\([^)]*\/\s*|color\([^)]*\/\s*)([\d.]+%?)\s*\)$/)?.[1];
|
||||
return alpha === undefined || (alpha.endsWith('%') ? parseFloat(alpha) / 100 : Number(alpha)) > .05;
|
||||
}
|
||||
function visibleRect(element, root) {
|
||||
if (!element?.isConnected) return null;
|
||||
const rect = element.getBoundingClientRect();
|
||||
if (rect.width < 1 || rect.height < 1) return null;
|
||||
let left = rect.left, right = rect.right, top = rect.top, bottom = rect.bottom, opacity = 1;
|
||||
for (let node = element; node && node !== root?.parentElement; node = node.parentElement) {
|
||||
const style = getComputedStyle(node);
|
||||
opacity *= Number(style.opacity);
|
||||
if (style.display === 'none' || style.visibility !== 'visible' || opacity <= .05) return null;
|
||||
if (node !== element && ['hidden', 'clip', 'scroll', 'auto'].includes(style.overflowX)) {
|
||||
const clip = node.getBoundingClientRect(); left = Math.max(left, clip.left); right = Math.min(right, clip.right);
|
||||
}
|
||||
if (node !== element && ['hidden', 'clip', 'scroll', 'auto'].includes(style.overflowY)) {
|
||||
const clip = node.getBoundingClientRect(); top = Math.max(top, clip.top); bottom = Math.min(bottom, clip.bottom);
|
||||
}
|
||||
}
|
||||
return right > left && bottom > top ? { left, right, top, bottom, width: right - left, height: bottom - top } : null;
|
||||
}
|
||||
function discover(entries, root, config) {
|
||||
const surfaces = [], edges = [], rejected = [];
|
||||
for (const [index, raw] of entries.slice(0, 160).entries()) {
|
||||
const entry = raw.element ? raw : { element: raw };
|
||||
const element = entry.element, rect = visibleRect(element, root);
|
||||
if (!rect) { rejected.push({ element, reason: 'hidden or clipped' }); continue; }
|
||||
const explicit = entry.explicit === true;
|
||||
if (!explicit && element.matches?.('button, input, select, textarea, a, [contenteditable], [role="button"]')) {
|
||||
rejected.push({ element, reason: 'interactive control' }); continue;
|
||||
}
|
||||
const style = getComputedStyle(element);
|
||||
const edge = entry.edge === 'bottom' ? 'bottom' : 'top';
|
||||
const native = element.getBoundingClientRect();
|
||||
if ((edge === 'top' && rect.top > native.top + .5) ||
|
||||
(edge === 'bottom' && rect.bottom < native.bottom - .5)) {
|
||||
rejected.push({ element, reason: 'edge clipped' }); continue;
|
||||
}
|
||||
if (!explicit && !visibleBorder(style, edge === 'top' ? 'Top' : 'Bottom')) {
|
||||
rejected.push({ element, reason: 'borderless' }); continue;
|
||||
}
|
||||
const card = entry.card || element;
|
||||
const cardRect = visibleRect(card, root);
|
||||
if (!cardRect) continue;
|
||||
const inset = config.edgeClearanceS * config.bodySize;
|
||||
const left = Math.max(rect.left, cardRect.left + inset);
|
||||
const right = Math.min(rect.right, cardRect.right - inset);
|
||||
const y = edge === 'top' ? rect.top : rect.bottom;
|
||||
if (right - left < config.bodySize * Math.max(1, config.minLandingWidthS) + 2 * inset ||
|
||||
y < rect.top - .5 || y > rect.bottom + .5) {
|
||||
rejected.push({ element, reason: 'too narrow' }); continue;
|
||||
}
|
||||
const surface = { id: `${index}:${edge}`, element, card, edge, rect, left, right, y,
|
||||
anchor: { left: rect.left, top: rect.top }, explicit };
|
||||
surfaces.push(surface);
|
||||
if (edge === 'top') {
|
||||
for (const side of ['Left', 'Right']) {
|
||||
if (!explicit && !visibleBorder(style, side)) continue;
|
||||
const x = side === 'Left' ? rect.left : rect.right;
|
||||
const height = rect.bottom - rect.top;
|
||||
if (height < config.bodySize * config.minClimbHeightS || height > innerHeight * 4) continue;
|
||||
edges.push({ id: `${surface.id}:${side}`, element, card, side: side.toLowerCase(), x,
|
||||
top: rect.top, bottom: rect.bottom, platform: surface.id });
|
||||
}
|
||||
}
|
||||
}
|
||||
return { surfaces, edges, rejected };
|
||||
}
|
||||
function pathClear(a, b, surfaces, config, kind) {
|
||||
const size = config.bodySize, margin = config.edgeClearanceS * size;
|
||||
const left = Math.min(a.x, b.x) - size / 2 - margin;
|
||||
const right = Math.max(a.x, b.x) + size / 2 + margin;
|
||||
const top = Math.min(a.y, b.y) - size - (kind === 'jump' ? size * .55 : 0);
|
||||
const bottom = Math.max(a.y, b.y) - margin;
|
||||
return !surfaces.some(surface => {
|
||||
if (surface.id === a.id || surface.id === b.id || surface.card === a.card && surface.element === a.element) return false;
|
||||
const rect = surface.rect;
|
||||
if (kind === 'drop' && rect.bottom <= a.y) return false;
|
||||
if (rect.right <= left || rect.left >= right || rect.bottom <= top || rect.top >= bottom) return false;
|
||||
// A parent card contains the route; its border is not an obstacle inside it.
|
||||
if (rect.left <= left && rect.right >= right && rect.top <= top && rect.bottom >= bottom) return false;
|
||||
return true;
|
||||
});
|
||||
}
|
||||
function graphFor(surfaces, edges, config) {
|
||||
const graph = new Map(surfaces.map(s => [s.id, []]));
|
||||
const size = config.bodySize;
|
||||
for (const source of surfaces) for (const target of surfaces) {
|
||||
if (source === target) continue;
|
||||
const rise = source.y - target.y, horizontal = gap(source, target);
|
||||
const anchors = jumpAnchors(source, target, rise, config);
|
||||
if (!anchors) continue;
|
||||
const sourceX = anchors.fromX, targetX = anchors.toX;
|
||||
const distance = Math.abs(targetX - sourceX);
|
||||
const departure = { ...source, x: sourceX }, arrival = { ...target, x: targetX };
|
||||
if (Math.abs(rise) <= config.maxStepUpS * size && horizontal <= size * .4 &&
|
||||
pathClear(departure, arrival, surfaces, config, 'walk')) {
|
||||
graph.get(source.id).push({ to: target.id, kind: 'walk', fromX: sourceX, toX: targetX, cost: 1 + distance / size });
|
||||
continue;
|
||||
}
|
||||
if (rise > config.maxJumpRiseS * size || -rise > config.maxJumpDropS * size ||
|
||||
distance > config.maxJumpHorizontalS * size || horizontal > config.maxJumpHorizontalS * size) continue;
|
||||
const kind = rise < -config.maxStepUpS * size ? 'drop' : 'jump';
|
||||
if (!pathClear(departure, arrival, surfaces, config, kind)) continue;
|
||||
if (!targetArcClear(source, target, sourceX, targetX, rise, config)) continue;
|
||||
graph.get(source.id).push({ to: target.id, kind, fromX: sourceX, toX: targetX,
|
||||
cost: (kind === 'drop' ? 3 : 2) + distance / (size * config.preferredJumpHorizontalS) + Math.abs(rise) / size });
|
||||
}
|
||||
for (const edge of edges) {
|
||||
const target = surfaces.find(s => s.id === edge.platform);
|
||||
if (!target) continue;
|
||||
for (const source of surfaces) {
|
||||
if (source.id === target.id || source.y < edge.bottom - size * .45 ||
|
||||
source.y > edge.bottom + size * config.maxJumpRiseS ||
|
||||
Math.abs(landingX(source, edge.x, config) - edge.x) > size * config.maxJumpHorizontalS) continue;
|
||||
const fromX = landingX(source, edge.x, config);
|
||||
if (!pathClear({ ...source, x: fromX }, { ...target, x: landingX(target, edge.x, config) },
|
||||
surfaces.filter(s => s.element !== target.element), config, 'climb')) continue;
|
||||
graph.get(source.id).push({ to: target.id, kind: 'climb', edge, fromX,
|
||||
toX: landingX(target, edge.x, config), attachRise: Math.max(0, source.y - edge.bottom),
|
||||
cost: 2.5 + (edge.bottom - edge.top) / (size * config.climbSpeedSPerSec) +
|
||||
Math.max(0, source.y - edge.bottom) / size });
|
||||
}
|
||||
}
|
||||
return graph;
|
||||
}
|
||||
function routes(graph, start, limit) {
|
||||
const queue = [{ id: start, cost: 0, steps: [] }], best = new Map([[start, 0]]), found = [];
|
||||
while (queue.length && found.length < 100) {
|
||||
queue.sort((a, b) => a.cost - b.cost);
|
||||
const route = queue.shift();
|
||||
if (route.cost > best.get(route.id)) continue;
|
||||
if (route.steps.length) found.push(route);
|
||||
if (route.steps.length >= limit) continue;
|
||||
for (const transition of graph.get(route.id) || []) {
|
||||
const cost = route.cost + transition.cost;
|
||||
if (cost >= (best.get(transition.to) ?? Infinity)) continue;
|
||||
best.set(transition.to, cost);
|
||||
queue.push({ id: transition.to, cost, steps: [...route.steps, transition] });
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
class DebugBoxRenderer {
|
||||
constructor(root) {
|
||||
this.element = document.createElement('div');
|
||||
this.element.className = 'companion-box';
|
||||
this.element.setAttribute('aria-hidden', 'true');
|
||||
this.label = document.createElement('span');
|
||||
this.element.append(this.label); root.append(this.element);
|
||||
}
|
||||
render(position, state, name) {
|
||||
this.element.dataset.state = state;
|
||||
this.element.style.transform = `translate3d(${Math.round(position.x)}px,${Math.round(position.y)}px,0)`;
|
||||
this.label.textContent = `${name} · ${state}`;
|
||||
}
|
||||
destroy() { this.element.remove(); }
|
||||
}
|
||||
class Companion {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
this.root = options.root || document.body;
|
||||
this.config = configure(options.config);
|
||||
this.renderer = options.renderer || new DebugBoxRenderer(this.root);
|
||||
this.reduced = !!options.reducedMotion?.();
|
||||
this.name = options.name?.() || 'Companion';
|
||||
this.position = { x: 0, y: 0 };
|
||||
this.state = 'idle'; this.stateReason = 'initial placement'; this.trace = [];
|
||||
this.platform = null; this.route = []; this.motion = null;
|
||||
this.mode = 'calm'; this.activeRemaining = 0;
|
||||
this.lastSleepAt = performance.now(); this.lastEmoteAt = -Infinity;
|
||||
this.burstsSinceRest = 0; this.burstsSinceEmote = 0;
|
||||
this.debugSpeed = options.debugSpeed ? clamp(Number(options.debugSpeed) || 1, 1, 20) : 1;
|
||||
this.deadline = performance.now() + this.dwell('idle');
|
||||
this.lastTime = 0; this.running = true; this.dirty = true;
|
||||
this.refresh(); this.tick = this.tick.bind(this); this.frame = requestAnimationFrame(this.tick);
|
||||
}
|
||||
dwell(activity) {
|
||||
const min = this.config[`${activity}MinMs`], max = this.config[`${activity}MaxMs`];
|
||||
return (min + Math.random() * (max - min)) / this.debugSpeed;
|
||||
}
|
||||
setState(state, reason, now = performance.now()) {
|
||||
if (this.state === state) { this.stateReason = reason; return; }
|
||||
this.state = state; this.stateReason = reason;
|
||||
this.trace.push({ at: Math.round(now), state, reason });
|
||||
if (this.trace.length > 12) this.trace.shift();
|
||||
}
|
||||
refresh() {
|
||||
const previous = this.platform;
|
||||
const seen = discover(this.options.surfaces(), this.root, this.config);
|
||||
this.surfaces = seen.surfaces; this.edges = seen.edges; this.rejected = seen.rejected;
|
||||
this.graph = graphFor(this.surfaces, this.edges, this.config);
|
||||
this.dirty = true;
|
||||
const same = this.surfaces.find(s => previous && s.element === previous.element && s.edge === previous.edge);
|
||||
if (same) {
|
||||
this.position.x += same.anchor.left - previous.anchor.left;
|
||||
this.position.y += same.anchor.top - previous.anchor.top;
|
||||
this.platform = same;
|
||||
if (this.motion) {
|
||||
this.motion.from.x += same.anchor.left - previous.anchor.left;
|
||||
this.motion.from.y += same.anchor.top - previous.anchor.top;
|
||||
const destination = this.surfaces.find(s => s.element === this.motion.destination.element && s.edge === this.motion.destination.edge);
|
||||
if (destination) {
|
||||
this.motion.to.x += destination.anchor.left - this.motion.destination.anchor.left;
|
||||
this.motion.to.y += destination.anchor.top - this.motion.destination.anchor.top;
|
||||
this.motion.destination = destination;
|
||||
if (this.motion.step) {
|
||||
const updated = (this.graph.get(same.id) || []).find(t =>
|
||||
t.to === destination.id && t.kind === this.motion.step.kind);
|
||||
if (!updated) this.stopAtSafeAnchor();
|
||||
else this.motion.step = updated;
|
||||
}
|
||||
} else this.stopAtSafeAnchor();
|
||||
} else this.position.y = same.y;
|
||||
} else if (previous) this.stopAtSafeAnchor();
|
||||
else if (this.surfaces.length && !this.hasStarted) {
|
||||
this.platform = this.surfaces[0];
|
||||
this.position = { x: landingX(this.platform, this.platform.left + 30, this.config), y: this.platform.y };
|
||||
this.hasStarted = true;
|
||||
} else if (this.surfaces.length) {
|
||||
this.stopAtSafeAnchor();
|
||||
}
|
||||
this.renderer.element.hidden = !this.platform;
|
||||
this.renderer.render(this.position, this.state, this.name);
|
||||
this.drawDebug();
|
||||
}
|
||||
stopAtSafeAnchor() {
|
||||
this.motion = null; this.route = []; this.setState('idle', 'recovering safe anchor');
|
||||
this.mode = 'calm'; this.activeRemaining = 0;
|
||||
this.deadline = performance.now() + this.dwell('idle');
|
||||
const nearby = this.surfaces.filter(s => Math.abs(s.y - this.position.y) < this.config.bodySize &&
|
||||
this.position.x >= s.left && this.position.x <= s.right)
|
||||
.sort((a, b) => Math.abs(a.y - this.position.y) - Math.abs(b.y - this.position.y))[0];
|
||||
this.platform = nearby || null;
|
||||
if (nearby) this.position.y = nearby.y;
|
||||
this.renderer.element.hidden = !nearby;
|
||||
}
|
||||
choose(now) {
|
||||
if (!this.platform || this.reduced) return;
|
||||
if (this.mode !== 'active') {
|
||||
const reachable = routes(this.graph, this.platform.id, this.config.maxRouteTransitions).length > 0;
|
||||
const restReady = now - this.lastSleepAt >= this.config.sleepCooldownMs / this.debugSpeed;
|
||||
const emoteReady = now - this.lastEmoteAt >= this.config.emoteCooldownMs / this.debugSpeed;
|
||||
const restChance = Math.min(1, this.config.sleepChance + this.burstsSinceRest * .2);
|
||||
if (restReady && this.burstsSinceRest >= 4) {
|
||||
this.beginSleep(now); return;
|
||||
} else if (emoteReady && this.burstsSinceEmote >= 2) {
|
||||
this.beginEmote(now, 'brief activity after exploration'); return;
|
||||
} else if (restReady && this.burstsSinceRest >= 2 && Math.random() < restChance) {
|
||||
this.beginSleep(now); return;
|
||||
} else if (reachable && Math.random() < this.config.activeChance) {
|
||||
this.mode = 'active';
|
||||
this.activeRemaining = Math.round(this.config.activeMinTransitions + Math.random() *
|
||||
(this.config.activeMaxTransitions - this.config.activeMinTransitions));
|
||||
this.setState('idle', `active exploration planned (${this.activeRemaining} transitions)`, now);
|
||||
} else if (emoteReady && Math.random() < this.config.emoteChance) {
|
||||
this.beginEmote(now, 'brief grounded activity'); return;
|
||||
} else {
|
||||
this.setState('idle', 'quietly observing', now);
|
||||
this.deadline = now + this.dwell('idle'); return;
|
||||
}
|
||||
}
|
||||
if (this.activeRemaining <= 0) { this.endBurst(now, 'exploration complete'); return; }
|
||||
const candidates = routes(this.graph, this.platform.id, this.config.maxRouteTransitions)
|
||||
.filter(route => route.steps.length <= this.activeRemaining && this.surfaces.some(s => s.id === route.id));
|
||||
if (!candidates.length) {
|
||||
if (this.platform.right - this.platform.left > this.config.bodySize * 2) {
|
||||
const toX = landingX(this.platform, this.position.x +
|
||||
(Math.random() < .3 ? -1 : 1) * this.config.bodySize * (1 + Math.random() * 3), this.config);
|
||||
if (Math.abs(toX - this.position.x) < 2) { this.endBurst(now, 'no reachable route'); return; }
|
||||
this.motion = { phase: 'patrol', destination: this.platform, from: { ...this.position },
|
||||
to: { x: toX, y: this.platform.y }, start: now,
|
||||
duration: Math.abs(toX - this.position.x) /
|
||||
(this.config.walkSpeedSPerSec * this.config.bodySize) * 1000 };
|
||||
this.setState('walking', 'patrolling current platform', now); return;
|
||||
}
|
||||
this.endBurst(now, 'no reachable route'); return;
|
||||
}
|
||||
const immediateJumps = candidates.filter(route => ['jump', 'drop'].includes(route.steps[0]?.kind));
|
||||
const pool = immediateJumps.length && Math.random() < .55 ? immediateJumps : candidates;
|
||||
const weighted = pool.map(route => {
|
||||
const target = this.surfaces.find(s => s.id === route.id);
|
||||
const horizontal = (target.left + target.right) / 2 / Math.max(innerWidth, 1);
|
||||
return { route, weight: (1 + this.config.centerRightPreference * horizontal) /
|
||||
(1 + route.cost * .12) * (1 + Math.random() * .25) };
|
||||
});
|
||||
weighted.sort((a, b) => b.weight - a.weight);
|
||||
this.route = weighted[Math.floor(Math.random() * Math.min(3, weighted.length))].route.steps.slice();
|
||||
this.beginNext(now);
|
||||
}
|
||||
beginSleep(now) {
|
||||
this.mode = 'resting'; this.lastSleepAt = now; this.burstsSinceRest = 0;
|
||||
this.setState('sleeping', 'rest after exploration', now);
|
||||
this.deadline = now + this.dwell('sleep');
|
||||
}
|
||||
beginEmote(now, reason) {
|
||||
this.lastEmoteAt = now; this.burstsSinceEmote = 0;
|
||||
this.setState(Math.random() < .5 ? 'purring' : 'batting', reason, now);
|
||||
this.deadline = now + this.dwell('emote');
|
||||
}
|
||||
endBurst(now, reason) {
|
||||
this.mode = 'calm'; this.activeRemaining = 0; this.route = [];
|
||||
this.burstsSinceRest += 1; this.burstsSinceEmote += 1;
|
||||
this.setState('idle', reason, now);
|
||||
this.deadline = now + this.dwell('idle');
|
||||
}
|
||||
beginNext(now) {
|
||||
const step = this.route.shift();
|
||||
if (!step) { this.setState('idle', 'route complete on platform', now); this.deadline = now + 400; return; }
|
||||
const destination = this.surfaces.find(s => s.id === step.to);
|
||||
if (!destination || !(this.graph.get(this.platform.id) || []).some(e => e.to === step.to && e.kind === step.kind)) {
|
||||
this.route = []; this.setState('idle', 'route invalidated', now); this.deadline = now + 1000; return;
|
||||
}
|
||||
const fromX = landingX(this.platform, step.fromX, this.config);
|
||||
if (Math.abs(this.position.x - fromX) > 2) {
|
||||
this.motion = { phase: 'approach', step, destination, from: { ...this.position },
|
||||
to: { x: fromX, y: this.platform.y }, start: now,
|
||||
duration: Math.abs(fromX - this.position.x) / (this.config.walkSpeedSPerSec * this.config.bodySize) * 1000 };
|
||||
this.setState('walking', 'approach departure point', now); return;
|
||||
}
|
||||
this.startTransition(step, destination, now);
|
||||
}
|
||||
startTransition(step, destination, now) {
|
||||
const current = (this.graph.get(this.platform.id) || []).find(t =>
|
||||
t.to === destination.id && t.kind === step.kind);
|
||||
if (!current) { this.motion = null; this.route = []; this.setState('idle', 'transition invalidated', now); this.deadline = now + 1000; return; }
|
||||
step = current;
|
||||
const size = this.config.bodySize;
|
||||
const duration = step.kind === 'walk' ? Math.abs(step.toX - this.position.x) /
|
||||
(this.config.walkSpeedSPerSec * size) * 1000 :
|
||||
clamp(350 + (Math.abs(step.toX - this.position.x) + Math.abs(destination.y - this.position.y)) * 2,
|
||||
this.config.jumpDurationMinMs, this.config.jumpDurationMaxMs);
|
||||
this.motion = { phase: step.kind, step, destination, from: { ...this.position },
|
||||
to: { x: step.toX, y: destination.y }, start: now, duration: Math.max(duration, 1) };
|
||||
this.setState(step.kind === 'climb' ? 'climbing' : step.kind === 'walk' ? 'walking' : 'jumping',
|
||||
`start ${step.kind}`, now);
|
||||
if (step.kind === 'climb') {
|
||||
this.motion.phase = 'attach';
|
||||
this.motion.to = { x: step.edge.x + (step.edge.side === 'left' ? -size / 2 : size / 2),
|
||||
y: Math.min(this.position.y, step.edge.bottom) };
|
||||
this.motion.duration = Math.max(180, Math.hypot(this.motion.to.x - this.position.x,
|
||||
this.motion.to.y - this.position.y) / (this.config.walkSpeedSPerSec * size) * 1000);
|
||||
if (step.attachRise > this.config.maxStepUpS * size)
|
||||
this.setState('climb-hopping', 'short hop to visible climb edge', now);
|
||||
}
|
||||
}
|
||||
advance(now) {
|
||||
const m = this.motion; if (!m) return;
|
||||
const t = clamp((now - m.start) / m.duration, 0, 1);
|
||||
this.position.x = m.from.x + (m.to.x - m.from.x) * t;
|
||||
this.position.y = m.from.y + (m.to.y - m.from.y) * t;
|
||||
if (m.phase === 'jump' || m.phase === 'drop' || m.phase === 'climb-hop') {
|
||||
const arc = m.phase === 'drop' ? this.config.bodySize * .25 :
|
||||
Math.max(this.config.bodySize * .65, m.from.y - m.to.y + this.config.bodySize * .5);
|
||||
this.position.y -= Math.sin(Math.PI * t) * arc;
|
||||
}
|
||||
if (m.phase === 'attach' && m.to.y < m.from.y)
|
||||
this.position.y -= Math.sin(Math.PI * t) * this.config.bodySize * .3;
|
||||
if (t < 1) return;
|
||||
if (m.phase === 'approach') { this.startTransition(m.step, m.destination, now); return; }
|
||||
if (m.phase === 'attach') {
|
||||
m.phase = 'ascend'; m.from = { ...this.position };
|
||||
m.to = { x: this.position.x, y: m.destination.y + this.config.bodySize * .6 };
|
||||
m.start = now; m.duration = Math.max(1, (m.from.y - m.to.y) /
|
||||
(this.config.climbSpeedSPerSec * this.config.bodySize) * 1000);
|
||||
this.setState('climbing', 'attached to visible side edge', now); return;
|
||||
}
|
||||
if (m.phase === 'ascend') {
|
||||
const hop = Math.random() < this.config.climbHopChance &&
|
||||
Math.abs(m.step.toX - m.step.edge.x) <= this.config.climbHopMaxDistanceS * this.config.bodySize;
|
||||
m.phase = hop ? 'climb-hop' : 'pull-up';
|
||||
this.setState(hop ? 'climb-hopping' : 'pulling-up', hop ? 'short ledge hop' : 'ledge pull-up', now);
|
||||
m.from = { ...this.position }; m.to = { x: m.step.toX, y: m.destination.y };
|
||||
m.start = now;
|
||||
m.duration = clamp(450 + Math.random() * 150, this.config.pullUpDurationMinMs, this.config.pullUpDurationMaxMs);
|
||||
m.wiggle = !hop && Math.random() < this.config.buttWiggleChance;
|
||||
return;
|
||||
}
|
||||
this.platform = m.destination; this.motion = null; this.position.y = this.platform.y;
|
||||
if (this.mode === 'active') this.activeRemaining = Math.max(0, this.activeRemaining - 1);
|
||||
if (['jump', 'drop', 'climb-hop'].includes(m.phase)) {
|
||||
this.setState('landing', `touchdown after ${m.phase}`, now);
|
||||
this.deadline = now + 260;
|
||||
} else {
|
||||
this.setState('idle', `${m.phase} complete on platform`, now);
|
||||
this.deadline = now + this.config.activeMovePauseMs / this.debugSpeed;
|
||||
}
|
||||
}
|
||||
tick(now) {
|
||||
if (!this.running) return;
|
||||
const delta = Math.min(50, Math.max(0, now - (this.lastTime || now)));
|
||||
this.lastTime = now;
|
||||
if (document.hidden) {
|
||||
if (!this.pausedAt) this.pausedAt = now;
|
||||
this.frame = requestAnimationFrame(this.tick); return;
|
||||
}
|
||||
if (this.pausedAt) {
|
||||
const paused = now - this.pausedAt;
|
||||
if (this.motion) this.motion.start += paused;
|
||||
this.deadline += paused;
|
||||
this.pausedAt = 0;
|
||||
}
|
||||
if (this.reduced) {
|
||||
this.frame = requestAnimationFrame(this.tick); return;
|
||||
}
|
||||
if (this.motion && now - this.motion.start > this.motion.duration + this.config.stuckTimeoutMs) {
|
||||
this.stopAtSafeAnchor(); this.deadline = now + 1000;
|
||||
}
|
||||
if (this.motion) this.advance(now);
|
||||
else if (now >= this.deadline) {
|
||||
if (this.state === 'sleeping') {
|
||||
this.mode = 'calm';
|
||||
this.setState('idle', 'woke from rest', now);
|
||||
this.deadline = now + this.dwell('idle');
|
||||
} else if (this.state === 'purring' || this.state === 'batting') {
|
||||
this.setState('idle', 'grounded activity complete', now);
|
||||
this.deadline = now + this.dwell('idle');
|
||||
} else {
|
||||
if (this.state === 'landing') this.setState('idle', 'landing interval complete', now);
|
||||
if (this.mode === 'active' && this.activeRemaining <= 0)
|
||||
this.endBurst(now, 'exploration complete');
|
||||
else if (this.route.length) this.beginNext(now);
|
||||
else this.choose(now);
|
||||
}
|
||||
}
|
||||
if (this.motion?.wiggle && this.motion.phase === 'pull-up')
|
||||
this.position.x += Math.sin(now / 45) * Math.min(delta / 50, 1) * 1.5;
|
||||
this.renderer.render(this.position, this.state, this.name);
|
||||
this.drawDebug();
|
||||
this.frame = requestAnimationFrame(this.tick);
|
||||
}
|
||||
drawDebug() {
|
||||
if (!this.options.debug || !this.renderer.element?.parentNode) return;
|
||||
if (!this.debugElement) {
|
||||
this.debugElement = document.createElement('div'); this.debugElement.className = 'companion-debug';
|
||||
this.root.append(this.debugElement);
|
||||
}
|
||||
this.debugElement.replaceChildren();
|
||||
for (const s of this.surfaces) {
|
||||
const line = document.createElement('i'); line.className = 'companion-debug-surface';
|
||||
line.style.cssText = `left:${s.left}px;top:${s.y}px;width:${s.right - s.left}px`;
|
||||
this.debugElement.append(line);
|
||||
}
|
||||
for (const e of this.edges) {
|
||||
const line = document.createElement('i'); line.className = 'companion-debug-edge';
|
||||
line.style.cssText = `left:${e.x}px;top:${e.top}px;height:${e.bottom - e.top}px`;
|
||||
this.debugElement.append(line);
|
||||
}
|
||||
for (const [fromId, transitions] of this.graph) {
|
||||
const from = this.surfaces.find(s => s.id === fromId);
|
||||
for (const transition of transitions) {
|
||||
const to = this.surfaces.find(s => s.id === transition.to);
|
||||
if (!from || !to) continue;
|
||||
const line = document.createElement('i'); line.className = 'companion-debug-route';
|
||||
const x1 = transition.fromX, x2 = transition.toX, y1 = from.y, y2 = to.y;
|
||||
const length = Math.hypot(x2 - x1, y2 - y1);
|
||||
line.style.cssText = `left:${x1}px;top:${y1}px;width:${length}px;transform:rotate(${Math.atan2(y2-y1,x2-x1)}rad)`;
|
||||
line.title = transition.kind;
|
||||
this.debugElement.append(line);
|
||||
}
|
||||
}
|
||||
for (const rejected of this.rejected.slice(0, 30)) {
|
||||
if (!rejected.element?.isConnected) continue;
|
||||
const rect = rejected.element.getBoundingClientRect();
|
||||
const mark = document.createElement('i'); mark.className = 'companion-debug-rejected';
|
||||
mark.style.cssText = `left:${rect.left}px;top:${rect.top}px`;
|
||||
mark.title = rejected.reason; this.debugElement.append(mark);
|
||||
}
|
||||
const label = document.createElement('span'); label.textContent =
|
||||
`${this.state} · ${this.platform?.id || 'none'} → ${this.motion?.destination?.id || 'none'} · ` +
|
||||
`route ${this.route.map(s => s.kind).join(' → ')} · ` +
|
||||
`mode ${this.mode}, steps ${this.activeRemaining}, next ${Math.max(0, Math.round(this.deadline - performance.now()))}ms, ` +
|
||||
`motion ${this.motion?.phase || 'none'} · reason ${this.stateReason} · ` +
|
||||
`trace ${this.trace.slice(-4).map(t => `${t.at}:${t.state}(${t.reason})`).join(' | ')} · ` +
|
||||
`available jumps ${(this.graph.get(this.platform?.id) || []).filter(t => ['jump', 'drop'].includes(t.kind)).length} · ` +
|
||||
`${this.surfaces.length} ledges, ${this.edges.length} edges, ${this.rejected.length} rejected ` +
|
||||
`(${[...new Set(this.rejected.map(r => r.reason))].join(', ')}) · ` +
|
||||
`S=${this.config.bodySize}, jump≤${this.config.maxJumpHorizontalS}S, rise≤${this.config.maxJumpRiseS}S, drop≤${this.config.maxJumpDropS}S`;
|
||||
this.debugElement.append(label);
|
||||
}
|
||||
setReducedMotion(value) {
|
||||
this.reduced = !!value; this.motion = null; this.route = [];
|
||||
this.mode = 'calm'; this.activeRemaining = 0;
|
||||
this.setState('idle', 'reduced motion preference');
|
||||
this.deadline = performance.now() + this.dwell('idle');
|
||||
if (this.platform) this.position.y = this.platform.y;
|
||||
this.renderer.render(this.position, this.state, this.name);
|
||||
}
|
||||
setName(name) { this.name = name; this.renderer.render(this.position, this.state, this.name); }
|
||||
destroy() { this.running = false; cancelAnimationFrame(this.frame); this.debugElement?.remove(); this.renderer.destroy(); }
|
||||
}
|
||||
const api = { configure, discover, graphFor, routes, visibleBorder, STATES, DEFAULTS };
|
||||
if (typeof module !== 'undefined' && module.exports) module.exports = api;
|
||||
if (typeof window !== 'undefined') { window.BrowserCompanion = Companion; window.BrowserCompanionMovement = api; window.BrowserCompanionStates = STATES; }
|
||||
})();
|
||||
@@ -1,6 +1,6 @@
|
||||
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}">
|
||||
{% extends 'core/base.html' %}{% load static %}{% block content %}<link rel="stylesheet" href="{% static 'dashboard/builder.css' %}"><link rel="stylesheet" href="{% static 'dashboard/open_meteo.css' %}"><link rel="stylesheet" href="{% static 'dashboard/buienradar.css' %}"><link rel="stylesheet" href="{% static 'dashboard/companion.css' %}">
|
||||
<div class="page-heading dashboard-heading"><div><div class="eyebrow"><span class="eyebrow-line"></span> YOUR WORKSPACE</div><h1>{{ title }}<span class="heading-period">.</span></h1><p>Make this space your own with a few useful widgets.</p></div><div class="dashboard-actions"><button class="button secondary" id="catalogue-toggle" type="button" aria-controls="widget-catalogue" aria-expanded="false" aria-label="Open widget catalogue"><i class="bi bi-gear"></i> Widgets</button><button class="button secondary" id="reset-layout" type="button" hidden>Reset</button><button class="button primary" id="edit-layout" type="button">Edit layout</button></div></div>
|
||||
<div id="layout-status" class="layout-status" role="status" aria-live="polite">Layout saved</div>
|
||||
<div id="layout-status" class="layout-status" role="status" aria-live="polite">Layout saved</div><button class="button secondary" id="companion-toggle" type="button" aria-pressed="false">Show companion</button>
|
||||
<div class="dashboard-pages" aria-label="Dashboard pages"><a href="{% url 'dashboard:index' %}" {% if dashboard_page == 'overview' %}aria-current="page"{% endif %}>Overview</a><a href="{% url 'dashboard:page' 'personal' %}" {% if dashboard_page == 'personal' %}aria-current="page"{% endif %}>Personal</a></div>
|
||||
<div id="widget-grid" class="widget-grid" data-page="{{ dashboard_page }}" data-revision="{{ layout.revision }}" data-save-url="{% url 'dashboard:layout' dashboard_page %}">
|
||||
{% for instance in instances %}{% include 'dashboard/widget_card.html' %}{% endfor %}
|
||||
@@ -10,5 +10,5 @@
|
||||
<template id="buienradar-widget-template">{% include 'dashboard/widgets/buienradar.html' %}</template>
|
||||
<aside id="widget-catalogue" class="widget-catalogue" aria-label="Widget catalogue" aria-hidden="true" inert><div class="catalogue-head"><div><span class="eyebrow">BUILD YOUR PAGE</span><h2>Widgets</h2></div><button type="button" id="catalogue-close" class="button ghost" aria-label="Close widget catalogue"><i class="bi bi-x-lg"></i></button></div><label for="widget-search">Search widgets</label><input id="widget-search" type="search" placeholder="Search by name or description"><div class="catalogue-list">{% for widget in catalogue %}<div class="catalogue-entry" draggable="true" data-widget-type="{{ widget.id }}" data-title="{{ widget.title|lower }}" data-description="{{ widget.description|lower }}"><i class="bi {{ widget.icon }}" aria-hidden="true"></i><div><strong>{{ widget.title }}</strong><small>{{ widget.description }}</small></div><button type="button" class="button secondary" data-add="{{ widget.id }}">Add</button></div>{% endfor %}</div><p class="catalogue-hint">Drag onto a dashed slot, or use Add and the Move controls. Changes save when you select Done.</p></aside><div id="catalogue-backdrop" class="catalogue-backdrop" hidden></div>
|
||||
{{ catalogue|length|json_script:"widget-count" }}
|
||||
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/builder.js' %}" defer></script>
|
||||
<script src="{% static 'dashboard/location.js' %}" defer></script><script src="{% static 'dashboard/open_meteo.js' %}" defer></script><script src="{% static 'dashboard/buienradar.js' %}" defer></script><script src="{% static 'dashboard/builder.js' %}" defer></script><script src="{% static 'dashboard/companion.js' %}" defer></script><script src="{% static 'dashboard/companion-dashboard.js' %}" defer></script>
|
||||
{% endblock %}
|
||||
|
||||
@@ -0,0 +1,305 @@
|
||||
<!doctype html>
|
||||
<html lang="en"><meta charset="utf-8"><title>Companion movement checks</title>
|
||||
<body><pre id="results">Running…</pre>
|
||||
<script src="../static/dashboard/companion.js?test=followup-4"></script>
|
||||
<script>
|
||||
(() => {
|
||||
const movement = window.BrowserCompanionMovement;
|
||||
const config = movement.configure();
|
||||
const results = [];
|
||||
function check(label, value) { results.push({ label, passed: !!value }); }
|
||||
function scenario(specification) {
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const entries = specification.map(([x, y, width, height, border = '1px solid black', edge = 'top']) => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:${width}px;height:${height}px;border:${border}`;
|
||||
host.append(element); return { element, edge };
|
||||
});
|
||||
const geometry = movement.discover(entries, document.body, config);
|
||||
const graph = movement.graphFor(geometry.surfaces, geometry.edges, config);
|
||||
host.remove(); return { geometry, graph };
|
||||
}
|
||||
const short = scenario([[10, 200, 100, 20], [130, 187, 100, 20]]);
|
||||
check('short jump up', short.graph.get('0:top').some(step => step.to === '1:top' && step.kind === 'jump'));
|
||||
const long = scenario([[10, 200, 100, 20], [240, 187, 100, 20]]);
|
||||
check('long jump rejected', long.graph.get('0:top').length === 0);
|
||||
const tall = scenario([[10, 200, 100, 20], [10, 50, 100, 150]]);
|
||||
check('tall visible side offers climb', tall.graph.get('0:top').some(step => step.kind === 'climb'));
|
||||
check('tall side is not jumped', !tall.graph.get('0:top').some(step => step.kind === 'jump'));
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = top => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:20px;top:${top}px;width:280px;height:180px;border:1px solid black`;
|
||||
host.append(element); return element;
|
||||
};
|
||||
const upper = make(20), lower = make(216);
|
||||
const entries = [{ element: upper, edge: 'bottom', explicit: true },
|
||||
{ element: upper, edge: 'top', explicit: true },
|
||||
{ element: lower, edge: 'top', explicit: true },
|
||||
{ element: lower, edge: 'bottom', explicit: true }];
|
||||
const geometry = movement.discover(entries, document.body, config);
|
||||
const graph = movement.graphFor(geometry.surfaces, geometry.edges, config);
|
||||
check('first drop has reachable return climb across grid gap',
|
||||
graph.get('0:bottom').some(step => step.kind === 'drop' && step.to === '2:top') &&
|
||||
graph.get('2:top').some(step => step.kind === 'climb' && step.to === '1:top' &&
|
||||
step.attachRise <= config.maxJumpRiseS * config.bodySize));
|
||||
host.remove();
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = top => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:20px;top:${top}px;width:280px;height:180px;border:1px solid black`;
|
||||
host.append(element); return element;
|
||||
};
|
||||
const upper = make(20), lower = make(216);
|
||||
const entries = [{ element: upper, edge: 'bottom', explicit: true },
|
||||
{ element: upper, edge: 'top', explicit: true },
|
||||
{ element: lower, edge: 'top', explicit: true },
|
||||
{ element: lower, edge: 'bottom', explicit: true }];
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => entries,
|
||||
config: { activeMinTransitions: 2, activeMaxTransitions: 2 }, reducedMotion: () => false });
|
||||
companion.mode = 'active'; companion.activeRemaining = 2;
|
||||
const originalRandom = Math.random;
|
||||
Math.random = () => .1;
|
||||
try {
|
||||
const finishMotion = () => {
|
||||
for (let i = 0; i < 7 && companion.motion; i++)
|
||||
companion.advance(companion.motion.start + companion.motion.duration + 1);
|
||||
};
|
||||
companion.choose(100);
|
||||
finishMotion();
|
||||
const dropped = companion.state === 'landing' && companion.platform?.element === lower;
|
||||
companion.tick(companion.deadline + 1); cancelAnimationFrame(companion.frame);
|
||||
const climbing = !!companion.motion && companion.motion.step?.kind === 'climb';
|
||||
const beforeShift = companion.position.y;
|
||||
upper.style.top = '0px'; lower.style.top = '196px';
|
||||
companion.refresh();
|
||||
const attachedAfterShift = !!companion.motion && Math.abs(companion.position.y - beforeShift + 20) < 1;
|
||||
finishMotion();
|
||||
check('first drop continues into return climb', dropped && climbing &&
|
||||
attachedAfterShift &&
|
||||
companion.platform?.element === upper && companion.platform.edge === 'top' &&
|
||||
companion.activeRemaining === 0);
|
||||
} finally { Math.random = originalRandom; companion.destroy(); host.remove(); }
|
||||
}
|
||||
{
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = 'position:absolute;left:10px;top:50px;width:100px;height:150px;border:1px solid black';
|
||||
document.body.append(element);
|
||||
const geometry = movement.discover([{ element, edge: 'bottom' }, { element, edge: 'top' }], document.body, config);
|
||||
const graph = movement.graphFor(geometry.surfaces, geometry.edges, config);
|
||||
check('radar bottom can climb to its top', graph.get('0:bottom').some(step =>
|
||||
step.to === '1:top' && step.kind === 'climb'));
|
||||
element.remove();
|
||||
}
|
||||
const descent = scenario([[10, 50, 100, 20], [10, 80, 100, 20],
|
||||
[10, 110, 100, 20], [10, 140, 100, 20]]);
|
||||
const downRoute = movement.routes(descent.graph, '0:top', 16).find(route => route.id === '3:top');
|
||||
check('descent uses three safe stops', downRoute?.steps.length === 3 && downRoute.steps.every(step => step.kind === 'drop'));
|
||||
const stranded = scenario([[10, 50, 100, 20], [10, 200, 100, 20]]);
|
||||
check('unsafe fall has no route', movement.routes(stranded.graph, '0:top', 16).length === 0);
|
||||
const borderless = scenario([[10, 50, 100, 20], [10, 80, 100, 20, '0']]);
|
||||
check('invisible border rejected', borderless.geometry.surfaces.length === 1 &&
|
||||
borderless.geometry.rejected[0]?.reason === 'borderless');
|
||||
const transparent = scenario([[10, 50, 100, 20, '1px solid rgba(0, 0, 0, 0)']]);
|
||||
check('transparent border rejected', transparent.geometry.surfaces.length === 0);
|
||||
check('config is bounded', movement.configure({ maxJumpHorizontalS: 100, bodySize: -1 }).maxJumpHorizontalS === 6 &&
|
||||
movement.configure({ bodySize: -1 }).bodySize === 8);
|
||||
const button = document.createElement('button'); button.style.cssText =
|
||||
'position:absolute;left:10px;top:250px;width:100px;height:25px;border:0';
|
||||
document.body.append(button);
|
||||
check('borderless button is not a platform', movement.discover([{ element: button }], document.body, config).surfaces.length === 0);
|
||||
button.remove();
|
||||
function climbSequence(hopChance) {
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = (y, height) => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:10px;top:${y}px;width:100px;height:${height}px;border:1px solid black`;
|
||||
host.append(element); return { element, edge: 'top' };
|
||||
};
|
||||
const entries = [make(200, 20), make(50, 150)];
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => entries,
|
||||
config: { climbHopChance: hopChance }, reducedMotion: () => false });
|
||||
const climb = companion.graph.get('0:top').find(step => step.kind === 'climb');
|
||||
companion.startTransition(climb, companion.surfaces[1], 100);
|
||||
const sequence = [companion.state];
|
||||
for (let i = 0; i < 5 && companion.motion; i++) {
|
||||
companion.advance(companion.motion.start + companion.motion.duration + 1);
|
||||
sequence.push(companion.state);
|
||||
}
|
||||
companion.destroy(); host.remove(); return sequence;
|
||||
}
|
||||
const pull = climbSequence(0).join(',');
|
||||
const hop = climbSequence(1).join(',');
|
||||
check(`climb pull-up settles without landing (${pull})`, pull ===
|
||||
'climbing,climbing,pulling-up,idle');
|
||||
check(`short climb hop reaches landing (${hop})`, hop ===
|
||||
'climbing,climbing,climb-hopping,landing');
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = (x, y) => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:100px;height:20px;border:1px solid black`;
|
||||
host.append(element); return { element, edge: 'top' };
|
||||
};
|
||||
const first = make(10, 200), second = make(130, 187);
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => [first, second],
|
||||
name: () => 'Pixel', reducedMotion: () => false });
|
||||
const before = companion.position.y;
|
||||
first.element.style.top = '180px'; second.element.style.top = '167px';
|
||||
companion.refresh();
|
||||
check('position follows moving source element', Math.abs(companion.position.y - before + 20) < 1);
|
||||
const jump = companion.graph.get('0:top').find(step => step.kind === 'jump');
|
||||
companion.startTransition(jump, companion.surfaces[1], 100);
|
||||
second.element.remove(); companion.refresh();
|
||||
check('removed landing cancels motion safely', companion.motion === null &&
|
||||
companion.platform?.element === first.element);
|
||||
companion.setReducedMotion(true);
|
||||
check('reduced motion stops autonomous state', companion.state === 'idle' && companion.motion === null);
|
||||
companion.setName('Dahlia');
|
||||
check('theme name updates without restarting', companion.renderer.label.textContent.startsWith('Dahlia'));
|
||||
companion.destroy(); host.remove();
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = (x, y, height) => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:${x}px;top:${y}px;width:100px;height:${height}px;border:1px solid black`;
|
||||
host.append(element); return { element, edge: 'top' };
|
||||
};
|
||||
const entries = [make(10, 220, 20), make(130, 220, 20), make(-100, 70, 150)];
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => entries, reducedMotion: () => false });
|
||||
const available = companion.graph.get(companion.platform.id);
|
||||
companion.mode = 'active'; companion.activeRemaining = 2;
|
||||
const originalRandom = Math.random;
|
||||
const values = [.1, .5, .5];
|
||||
Math.random = () => values.shift() ?? .5;
|
||||
try {
|
||||
companion.choose(100);
|
||||
check(`safe jump gets selected when climb also exists (${available.map(e=>e.kind).join(',')}; selected ${companion.motion?.step?.kind})`, available.some(edge => edge.kind === 'jump') &&
|
||||
available.some(edge => edge.kind === 'climb') &&
|
||||
(companion.motion?.step?.kind === 'jump'));
|
||||
} finally { Math.random = originalRandom; companion.destroy(); host.remove(); }
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const make = x => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:${x}px;top:250px;width:100px;height:20px;border:1px solid black`;
|
||||
host.append(element); return { element, edge: 'top' };
|
||||
};
|
||||
const entries = [make(10), make(130)];
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => entries, reducedMotion: () => false });
|
||||
companion.mode = 'active'; companion.activeRemaining = 3;
|
||||
const originalRandom = Math.random;
|
||||
Math.random = () => .9;
|
||||
try {
|
||||
const sequence = [];
|
||||
companion.choose(1000);
|
||||
for (let count = 0; count < 3; count++) {
|
||||
while (companion.motion?.phase === 'approach')
|
||||
companion.advance(companion.motion.start + companion.motion.duration + 1);
|
||||
sequence.push(companion.state);
|
||||
companion.advance(companion.motion.start + companion.motion.duration + 1);
|
||||
sequence.push(companion.state);
|
||||
const done = companion.deadline + 1;
|
||||
companion.tick(done); cancelAnimationFrame(companion.frame);
|
||||
sequence.push(companion.state);
|
||||
}
|
||||
check(`three successive legitimate jumps (${sequence.join(',')})`,
|
||||
[0, 3, 6].every(index => sequence[index] === 'jumping' &&
|
||||
sequence[index + 1] === 'landing') && sequence[2] === 'jumping' &&
|
||||
sequence[5] === 'jumping' && sequence[8] === 'idle');
|
||||
check('landing exits once and allows another route', companion.trace.filter(event =>
|
||||
event.reason === 'landing interval complete').length === 3);
|
||||
} finally { Math.random = originalRandom; companion.destroy(); host.remove(); }
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = 'position:absolute;left:10px;top:300px;width:120px;height:20px;border:1px solid black';
|
||||
host.append(element);
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => [{ element, edge: 'top' }],
|
||||
reducedMotion: () => false });
|
||||
companion.beginNext(100);
|
||||
check('empty route finishes idle', companion.state === 'idle');
|
||||
companion.choose(200);
|
||||
if (companion.motion?.phase === 'patrol')
|
||||
companion.advance(companion.motion.start + companion.motion.duration + 1);
|
||||
check('grounded walking never lands', companion.state !== 'landing');
|
||||
const groundedStates = [];
|
||||
for (const now of [1000, 2000, 3000, 4000, 5000]) {
|
||||
companion.tick(now); cancelAnimationFrame(companion.frame);
|
||||
groundedStates.push(companion.state);
|
||||
}
|
||||
check('grounded frames do not retrigger landing', !groundedStates.includes('landing'));
|
||||
companion.destroy(); host.remove();
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = 'position:absolute;left:10px;top:400px;width:120px;height:20px;border:1px solid black';
|
||||
host.append(element);
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => [{ element, edge: 'top' }],
|
||||
config: { idleMinMs: 12000, idleMaxMs: 12000, sleepMinMs: 20000, sleepMaxMs: 20000 },
|
||||
reducedMotion: () => false });
|
||||
const firstIdle = companion.deadline - performance.now();
|
||||
companion.lastSleepAt = -Infinity; companion.burstsSinceRest = 2;
|
||||
const originalRandom = Math.random;
|
||||
Math.random = () => 0;
|
||||
try {
|
||||
const afterIdle = companion.deadline + 1;
|
||||
companion.tick(afterIdle); cancelAnimationFrame(companion.frame);
|
||||
const slept = companion.state === 'sleeping' && companion.deadline - afterIdle >= 20000;
|
||||
const afterSleep = companion.deadline + 1;
|
||||
companion.tick(afterSleep); cancelAnimationFrame(companion.frame);
|
||||
check('normal idle and sleep dwell without flicker', firstIdle >= 11900 && slept &&
|
||||
companion.state === 'idle' && companion.deadline - afterSleep >= 12000);
|
||||
companion.lastSleepAt = companion.deadline;
|
||||
const afterSecondIdle = companion.deadline + 1;
|
||||
companion.tick(afterSecondIdle); cancelAnimationFrame(companion.frame);
|
||||
const emoted = ['purring', 'batting'].includes(companion.state) &&
|
||||
companion.deadline - afterSecondIdle >= companion.config.emoteMinMs;
|
||||
const afterEmote = companion.deadline + 1;
|
||||
companion.tick(afterEmote); cancelAnimationFrame(companion.frame);
|
||||
check('emote completes into calm idle', emoted && companion.state === 'idle' &&
|
||||
companion.deadline - afterEmote >= 12000);
|
||||
} finally { Math.random = originalRandom; companion.destroy(); host.remove(); }
|
||||
}
|
||||
{
|
||||
const host = document.createElement('div'); document.body.append(host);
|
||||
const entries = [10, 130].map(x => {
|
||||
const element = document.createElement('div');
|
||||
element.style.cssText = `position:absolute;left:${x}px;top:550px;width:100px;height:20px;border:1px solid black`;
|
||||
host.append(element); return { element, edge: 'top' };
|
||||
});
|
||||
const originalRandom = Math.random;
|
||||
let seed = 42;
|
||||
Math.random = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296);
|
||||
const companion = new window.BrowserCompanion({ surfaces: () => entries, reducedMotion: () => false });
|
||||
const events = [];
|
||||
const originalSetState = companion.setState.bind(companion);
|
||||
companion.setState = (state, reason, now) => {
|
||||
if (companion.state !== state) events.push({ state, reason, at: now });
|
||||
originalSetState(state, reason, now);
|
||||
};
|
||||
try {
|
||||
let now = performance.now(), start = now;
|
||||
for (let i = 0; i < 500 && now - start < 300000; i++) {
|
||||
const next = companion.motion ? companion.motion.start + companion.motion.duration + 1 : companion.deadline + 1;
|
||||
now = Math.max(now + 1, next);
|
||||
companion.tick(now); cancelAnimationFrame(companion.frame);
|
||||
}
|
||||
const states = new Set(events.map(event => event.state));
|
||||
check('five-minute schedule includes exploration, play and rest', now - start >= 300000 &&
|
||||
['jumping', 'landing', 'idle', 'purring', 'batting', 'sleeping'].every(state => states.has(state)));
|
||||
} finally { Math.random = originalRandom; companion.destroy(); host.remove(); }
|
||||
}
|
||||
const failed = results.filter(result => !result.passed);
|
||||
document.getElementById('results').textContent = results.map(result =>
|
||||
`${result.passed ? 'PASS' : 'FAIL'} ${result.label}`).join('\n');
|
||||
document.documentElement.dataset.testsPassed = String(failed.length === 0);
|
||||
})();
|
||||
</script></body></html>
|
||||
Reference in New Issue
Block a user